summaryrefslogtreecommitdiff
path: root/check.lua
blob: 8b38144059ca7f4439a112901cdc5b0122f0e44f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
-- Run with `panto lua check.lua`. Use the same Panto binary for the TUI and fake agy.
local uv, json = require('luv'), require('panto').ext.json
local sysname = uv.os_uname().sysname
local is_macos = sysname == 'Darwin'
local panto = assert(uv.fs_realpath(uv.exepath()))
local root = assert(uv.fs_realpath(arg[0])):match('^(.*)/')
local function which(name)
    for dir in (os.getenv('PATH') or '/usr/local/bin:/usr/bin:/bin'):gmatch('[^:]+') do
        local p = dir .. '/' .. name
        if dir:sub(1, 1) == '/' and uv.fs_access(p, 'X') then return assert(uv.fs_realpath(p)) end
    end
end
local function write(path, data)
    local f = assert(io.open(path, 'wb')); assert(f:write(data)); assert(f:close())
end
local function read(path)
    local f = assert(io.open(path, 'rb')); local data = assert(f:read('a')); f:close(); return data
end
local function run(bin, args, opts, timeout)
    opts = opts or {}; opts.args = args; opts.stdio = opts.stdio or {0, 1, 2}
    local proc, timer, code, signal, expired
    proc = assert(uv.spawn(bin, opts, function(c, s)
        code, signal = c, s; proc:close(); if timer then timer:close() end
    end))
    if timeout then
        timer = assert(uv.new_timer()); timer:start(timeout, 0, function() expired = true; proc:kill('sigkill') end)
    end
    uv.run(); assert(not expired and signal == 0, bin .. ' timed out or was killed'); return code
end
local tmp = assert(uv.fs_realpath(uv.os_tmpdir() or '/tmp')):gsub('/+$', '')
if #tmp > 80 then tmp = assert(uv.fs_realpath('/tmp')):gsub('/+$', '') end
local home = assert(uv.fs_mkdtemp(tmp .. '/panto-agy-XXXXXX'))
local function check()
    dofile(root..'/tests/lifecycle.lua')
    local acp_mod=dofile(root..'/acp.lua'); local usage=acp_mod.usage
    local function cut(text,room)
        local head,tail=acp_mod.history_split(text,room)
        assert(head..tail==text and #tail<=math.max(room,0) and utf8.len(head) and utf8.len(tail),'bad history split'); return head,tail
    end
    local entries={}; for i=1,40 do entries[i]=('[User]: line %02d '):format(i)..('\u{E9}'):rep(i % 7) end
    local head,tail=cut(table.concat(entries,'\n\n'),200)
    assert(head:sub(-2)=='\n\n' and tail:sub(1,7)=='[User]:' and #tail>100,'expected an entry-aligned cut')
    assert(#select(2,cut(('\u{754C}'):rep(100),10))==9) -- three-byte characters stay whole
    assert(cut('abc',10)=='' and cut('',10)=='' and cut('abc',0)=='abc' and select(2,cut('[a]\n\n[b]',3))=='[b]')
    local u={inputTokens=155,outputTokens=41,thoughtTokens=8,cachedReadTokens=55,cachedWriteTokens=10,totalTokens=196}
    local v=usage(u); assert(v.input==90 and v.output==41 and v.cache_read==55 and v.cache_write==10 and v.reasoning==8)
    u.totalTokens=261; assert(usage(u).input==155); u.totalTokens=99; assert(not usage(u) and not usage({}) and not usage(nil))
    local cat=dofile(root..'/catalog.lua'); local catalog=cat.catalog
    local wide='a'..('\u{754C}'):rep(8000); local pages=cat.pages(wide) -- no newline to cut at: characters stay whole
    assert(#pages==3 and table.concat(pages)==wide and #cat.pages('abc')==1)
    for i,p in ipairs(pages) do assert(utf8.len(p) and #cat.part(pages,7,i)<=cat.result_bytes) end
    local req={tools={{name='std.read',description='Read',input_schema_json='{"type":"object"}'},
        {name='fixture.echo',description='Echo',input_schema_json='{"type":"object"}'}}}
    local _,none=catalog(req,{}); assert(#none==0)
    local by,one=catalog(req,{'not.offered','std.read'}); assert(#one==1 and one[1].name=='std__read' and by.std__read and not by.fixture__echo)
    local configure=dofile(root..'/extensions/antigravity-acp.lua').configure
    assert(not pcall(configure,{providers={antigravity={protocol='antigravity-acp',save_session=true}}}))
    -- Exercise the non-macOS probe path (no codesign, binary mode check, keyring env forwarding).
    local linux_home = assert(uv.fs_mkdtemp(home .. '/linux-XXXXXX'))
    local linux_bin = linux_home .. '/agy'; write(linux_bin, '#!/bin/sh\n'); assert(uv.fs_chmod(linux_bin, 448))
    local real_uname, real_getenv = uv.os_uname, os.getenv
    local fake_env = {HOME=linux_home, PATH=linux_home, DBUS_SESSION_BUS_ADDRESS='unix:path=/run/user/1/bus',
        XDG_RUNTIME_DIR='/run/user/1', GEMINI_API_KEY='secret'}
    uv.os_uname = function() return {sysname='Linux'} end
    os.getenv = function(k) return fake_env[k] end
    local ok_linux, err_linux = pcall(function()
        local linux_acp = dofile(root..'/acp.lua')
        local got_bin, got_env, got_err
        linux_acp.probe(function(b, _, e) got_bin, got_env = b, e end, function(e) got_err = e end)
        assert(not got_err and got_bin == linux_bin, got_err)
        local joined = '\n' .. table.concat(got_env, '\n') .. '\n'
        assert(joined:find('\nDBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1/bus\n', 1, true)
            and joined:find('\nXDG_RUNTIME_DIR=/run/user/1\n', 1, true)
            and not joined:find('GEMINI_API_KEY', 1, true), 'bad Linux probe env')
        assert(uv.fs_chmod(linux_bin, 464)) -- 0720 group-writable must be rejected
        got_bin, got_err = nil, nil
        linux_acp.probe(function(b) got_bin = b end, function(e) got_err = e end)
        assert(not got_bin and got_err and got_err:find('group/world writable', 1, true), 'writable binary allowed')
    end)
    uv.os_uname, os.getenv = real_uname, real_getenv
    assert(ok_linux, err_linux)
    local cfg, data = home .. '/.panto', home .. '/.local/share/panto'
    assert(run('/bin/mkdir', {'-p', cfg .. '/extensions', data}) == 0)
    local rocks = assert(os.getenv('HOME')) .. '/.local/share/panto/rocks'
    if uv.fs_stat(rocks) then assert(run('/bin/cp', {'-R', rocks, data .. '/rocks'}) == 0) end
    local source = 'paths=[' .. json.encode(root .. '/extensions') .. ']'
    if os.getenv('PANTO_CHECK_ROCK') == '1' then
        assert(run('luarocks', {'--lua-version','5.4','--tree',data .. '/rocks/lua-5.4.7','make','--deps-mode=none'}, {cwd=root}) == 0)
        source = 'rocks=["panto-antigravity"]'
    end
    write(cfg .. '/config.toml', '[extensions]\n' .. source .. [[

[providers.antigravity]
protocol="antigravity-acp"
]])
    write(cfg .. '/models.toml', '[antigravity.fast]\nmodel="gemini-test"\ninput=10.0\noutput=10.0\ncache_read=1.0\ncache_write=10.0\n')
    write(cfg .. '/SYSTEM.md', 'Short answers.')
    local filler={}; for i=1,1900 do filler[i]=('filler line %04d abcdefghij'):format(i) end
    write(cfg .. '/history-filler.txt', table.concat(filler,'\n'))
    write(home .. '/drop.png', '\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\x00\x00\x01\x00\x00\x00\x01\x08\x04\x00\x00\x00\xb5\x1c\x0c\x02\x00\x00\x00\x0b\x49\x44\x41\x54\x78\xda\x63\xfc\xff\x1f\x00\x03\x03\x02\x00\xef\x9a\x5f\x59\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82')
    write(home .. '/drop.pdf', '%PDF-1.7')
    local exe = home .. '/agy'
    assert(uv.fs_symlink(panto, home .. '/panto')) -- short, space-free shebang path
    write(exe, '#!' .. home .. '/panto lua\n' .. read(root .. '/tests/fake-agy.lua'))
    assert(uv.fs_chmod(exe, 448))
    write(cfg .. '/extensions/signature.lua', [[
local uv = require('luv'); local spawn = uv.spawn
uv.spawn = function(bin, opts, cb)
    if bin == '/usr/bin/codesign' and opts.args[4] == os.getenv('HOME') .. '/agy' then
        bin, opts = '/usr/bin/true', {args={}}
    end
    return spawn(bin, opts, cb)
end
return {name='test.signature', activate=function()
    local ext=require('panto').ext
    ext.on('render_thinking_complete',function(e)
        if e.text=='fixture-visible-thinking' then local f=assert(io.open(os.getenv('HOME')..'/thinking-rendered','w')); f:close() end
    end)
    ext.register_command{name='fixture-notice',description='Queue a workflow completion',handler=function()
        ext.agent:submit('[subagents] Workflow fixture completed. Output below: marker')
    end}
    ext.register_tool{name='fixture.echo',description='Return a nested value.',
        schema={type='object',properties={rows={type='array',minItems=1,items={type='object',properties={value={type='integer'}},required={'value'}}}},required={'rows'}},
        handler=function(input)
            local profile=os.getenv('HOME')..'/.local/share/panto-antigravity/google'
            if input.rows[1].value==43 then
                local f=assert(io.open(profile..'/tool-running','w')); f:close()
                local co=coroutine.running(); local timer=uv.new_timer()
                timer:start(10,10,function()
                    if uv.fs_stat(profile..'/return-result') then timer:close(); assert(coroutine.resume(co)) end
                end)
                coroutine.yield()
            elseif not uv.fs_stat(profile..'/usage-failure') then ext.agent:submit('boundary workflow notice') end
            return tostring(input.rows[1].value)
        end}
end}
]])
    local expect_bin = assert(which('expect'), 'expect is required for TUI check')
    local env = {'HOME=' .. home, 'QUOTA_LOG=' .. home .. '/screen', 'TMPDIR=' .. home,
        'TERM=xterm-256color', 'PATH=' .. home .. ':/usr/local/bin:/usr/bin:/bin', 'PANTO=' .. panto}
    local profile = [[(version 1)(allow default)
(deny network-outbound (remote ip "*:*"))(deny network-bind (local ip "*:*"))
(deny process-exec)(allow process-exec (literal (param "PANTO")) (literal (param "FAKE"))
(literal "/usr/bin/true") (literal "/usr/bin/false")
(literal (param "EXPECT")) (literal "/bin/stty"))]]
    local unshare = sysname == 'Linux' and which('unshare')
    if unshare and run(unshare, {'-c', '-n', '--', '/bin/true'}, {stdio={nil, nil, nil}}) ~= 0 then unshare = nil end
    local function sandbox(args, timeout, stdio)
        if is_macos then
            local cmd = {'-D', 'PANTO=' .. panto, '-D', 'FAKE=' .. exe, '-D', 'EXPECT=' .. expect_bin, '-p', profile}
            for _, a in ipairs(args) do cmd[#cmd+1] = a end
            return run('/usr/bin/sandbox-exec', cmd, {cwd=home, env=env, stdio=stdio}, timeout)
        elseif unshare then
            local cmd = {'-c', '-n', '--'}
            for _, a in ipairs(args) do cmd[#cmd+1] = a end
            return run(unshare, cmd, {cwd=home, env=env, stdio=stdio}, timeout)
        end
        local cmd = {}; for i = 2, #args do cmd[#cmd+1] = args[i] end
        return run(args[1], cmd, {cwd=home, env=env, stdio=stdio}, timeout)
    end
    local google = home .. '/.local/share/panto-antigravity/google'
    local function print_check(mode, args, input, diagnostic)
        write(home..'/fixture-mode', mode); write(home..'/stdin', input or '')
        local inf=assert(uv.fs_open(home..'/stdin','r',384))
        local out=assert(uv.fs_open(home..'/stdout','w',384))
        local err=assert(uv.fs_open(home..'/stderr','w',384))
        local cmd={panto, '--incognito', '-p', '-m', 'antigravity:fast', '-r', diagnostic and 'xhigh' or 'low'}
        for _,a in ipairs(args) do cmd[#cmd+1]=a end
        local code=sandbox(cmd, 15000, {inf,out,err})
        uv.fs_close(inf); uv.fs_close(out); uv.fs_close(err)
        local stdout,stderr=read(home..'/stdout'),read(home..'/stderr')
        if diagnostic then
            assert(code~=0 and stderr:find('reasoning level xhigh',1,true) and not stderr:find('error: turn failed: ProviderProtocolFailed',1,true), stderr)
            assert(not stdout:find('reasoning level xhigh',1,true) and not stdout:find('headless-',1,true), stdout)
        else
            assert(code==0 and stdout:find('headless-'..mode..'-ok',1,true), stdout..'\n'..stderr)
        end
    end
    print_check('argv-probe', {'--','argv-probe'}, 'ignored stdin')
    print_check('stdin-probe', {}, 'stdin-probe')
    write(cfg..'/PROMPT.md','rig-probe')
    print_check('rig-probe', {'--rig',cfg}, '')
    assert(uv.fs_unlink(cfg..'/PROMPT.md'))
    print_check('diagnostic', {'--','diagnostic'}, '', true)
    assert(uv.fs_unlink(home..'/fixture-mode'))
    local tui=sandbox({expect_bin, root .. '/tests/tui.exp'}, 65000)
    if tui~=0 then error('TUI check failed: '..read(home..'/screen'):gsub('\27%[[0-9;?]*[A-Za-z]', ''):sub(-3500)) end
    assert(uv.fs_stat(home..'/thinking-rendered'),'ACP thought did not reach the native thinking component')
    local agents = assert(uv.fs_scandir(google .. '/config/agents')); assert(not uv.fs_scandir_next(agents), 'Generated agent left in private profile')
    assert(not uv.fs_stat(data .. '/state.toml') or not read(data .. '/state.toml'):find('antigravity', 1, true), 'state.toml polluted with session checkpoint')
    local screen = read(home .. '/screen'):gsub('\27%[[0-9;?]*[A-Za-z]', '')
    assert(screen:find('1.3k/1M ctx',1,true),'expected ACP context occupancy, not summed turn inputs')
    assert(screen:find('3.4k tok',1,true),'expected primary and steering usage counted exactly once')
    assert(screen:find('agy native: manage_task [completed]',1,true) and not screen:find('agy native: mcp_pantograph_',1,true),'native activity missing or MCP call duplicated')
    assert(screen:find('27%%%s+━'), 'expected 27% used and a filled bar in the rendered footer')
end
local ok, err = xpcall(check, debug.traceback)
assert(run('/bin/rm', {'-rf', home}) == 0)
assert(ok, err)
print('PASS: headless argv/stdin/rig and provider diagnostic, native TUI, quota meter, model alias, primary MCP tool, permissions, native resume, /tree transcript seed, warm follow-up and cold resume')