@jc_stack/ez-agents 0.1.0-beta.48 → 0.1.0-beta.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +8 -6
- package/CHANGELOG.md +24 -0
- package/README.md +9 -5
- package/bin/ez +16 -7
- package/docker/broker-update-smoke.mjs +16 -2
- package/docker/upgrade-smoke.mjs +1 -1
- package/docs/architecture/ai-selection.md +9 -1
- package/docs/docker-runtime.md +46 -2
- package/docs/plugin-guide.md +3 -3
- package/docs/plugins.md +13 -10
- package/docs/scheduling.md +84 -6
- package/docs/setup.md +2 -2
- package/docs/standalone-cli.md +4 -4
- package/docs/upgrades.md +13 -23
- package/package.json +1 -1
- package/src/agent-guidance.ts +2 -2
- package/src/ai-cli.ts +28 -15
- package/src/ai.ts +90 -14
- package/src/application-channel.ts +18 -14
- package/src/auth-profile.ts +53 -0
- package/src/codex-session.ts +14 -3
- package/src/control-state.ts +28 -21
- package/src/delivery-socket.ts +2 -0
- package/src/executor.ts +38 -26
- package/src/host-executor-client.ts +19 -7
- package/src/host-executor.ts +35 -10
- package/src/index.ts +320 -122
- package/src/menu.ts +8 -7
- package/src/plugin-broker.mjs +4 -11
- package/src/plugins/manager.mjs +70 -48
- package/src/runs.ts +74 -5
- package/src/schedule-cli.ts +39 -7
- package/src/scheduled-tasks.ts +42 -8
- package/src/scheduler.ts +9 -4
- package/src/session-close.ts +17 -0
- package/src/setup-fallback.ts +159 -0
- package/src/task-executor.ts +3 -2
- package/src/tools-line.d.mts +1 -0
- package/src/tools-line.mjs +3 -0
- package/src/updates/binding.mjs +4 -10
- package/src/updates/control.mjs +3 -2
- package/src/updates/runtime.mjs +79 -41
- package/src/updates/supervisor.mjs +27 -6
- package/src/workspace.ts +12 -1
- package/test/ai.test.ts +48 -2
- package/test/application-channel.test.ts +24 -0
- package/test/application-controls.test.ts +4 -1
- package/test/auth-profiles.test.ts +187 -0
- package/test/intake-relay.test.ts +63 -2
- package/test/model-policy.test.ts +1 -1
- package/test/plugin-broker.test.mjs +51 -1
- package/test/plugin-manager.test.mjs +76 -38
- package/test/run-handoff.test.ts +132 -0
- package/test/scheduled-tasks.test.ts +24 -2
- package/test/session-close.test.ts +17 -0
- package/test/setup-fallback.test.ts +423 -0
- package/test/updates.test.mjs +77 -15
- package/test/workspace.test.ts +6 -0
|
@@ -7,6 +7,7 @@ import {execFile,spawn} from 'node:child_process';
|
|
|
7
7
|
import {once} from 'node:events';
|
|
8
8
|
import {promisify} from 'node:util';
|
|
9
9
|
import {snapshot,init as initManager,validate,compose,locked,bindToolDiscovery,prepareCommand} from '../src/plugins/manager.mjs';
|
|
10
|
+
import {TOOLS_LINE} from '../src/tools-line.mjs';
|
|
10
11
|
import { ControlStore, ownerId, ownerEpoch } from '../src/control-state.js';
|
|
11
12
|
import { ApplicationBindings } from '../src/application-channel.js';
|
|
12
13
|
import { RunStore } from '../src/runs.js';
|
|
@@ -33,6 +34,16 @@ for(const cleanup of ['success','failure','already-removed']) test(`cancel remov
|
|
|
33
34
|
if(cleanup==='failure')assert.match(stderr,/cleanup failed/);
|
|
34
35
|
assert.deepEqual((await fs.readFile(log,'utf8')).trim().split('\n').map(JSON.parse),[['run'],['container','rm','--force','exact-test-container']]);
|
|
35
36
|
});
|
|
37
|
+
// Compose --rm only removes a container that ran. Compose dying between create
|
|
38
|
+
// and start (signal, broken output pipe, error) must not strand it in Created.
|
|
39
|
+
for(const exit of ['signal','failure','success']) test(`compose exit by ${exit} without manager cancellation ${exit==='success'?'leaves no cleanup call':'removes its created container'}`,async t=>{
|
|
40
|
+
const root=await fs.mkdtemp(path.join(tmpdir(),'ez-exit-'));t.after(()=>fs.rm(root,{recursive:true,force:true}));
|
|
41
|
+
const log=path.join(root,'calls.jsonl');
|
|
42
|
+
await fs.writeFile(path.join(root,'docker'),`#!${process.execPath}\nconst fs=require('fs'),a=process.argv.slice(2);fs.appendFileSync(${JSON.stringify(log)},JSON.stringify(a)+'\\n');if(a[0]==='container')process.exit(0);console.error('Container exact-test-container Created');${exit==='signal'?"process.kill(process.pid,'SIGKILL')":exit==='failure'?'process.exit(1)':'process.exit(0)'}\n`,{mode:0o700});
|
|
43
|
+
const {stdout}=await exec(process.execPath,['--input-type=module','-e',`import {run} from ${JSON.stringify(new URL('../src/plugins/manager.mjs',import.meta.url).href)};console.log((await run(['run'],{container:'exact-test-container',capture:true})).code)`],{env:{...process.env,PATH:root+path.delimiter+process.env.PATH}});
|
|
44
|
+
assert.equal(stdout.trim(),exit==='signal'?'130':exit==='failure'?'1':'0');
|
|
45
|
+
assert.deepEqual((await fs.readFile(log,'utf8')).trim().split('\n').map(JSON.parse),[['run'],...(exit==='success'?[]:[['container','rm','--force','exact-test-container']])]);
|
|
46
|
+
});
|
|
36
47
|
async function fixture(t) {
|
|
37
48
|
const root=await fs.mkdtemp(path.join(tmpdir(),'ez-tools-'));t.after(()=>fs.rm(root,{recursive:true,force:true}));
|
|
38
49
|
const source=path.join(root,'source'),home=path.join(root,'tools'),deploymentDir=path.join(root,'deployment'),workspace=path.join(deploymentDir,'mind'),control=path.join(deploymentDir,'control'),hostConfig=path.join(deploymentDir,'host-executor.json'),fake=path.join(root,'fake');
|
|
@@ -83,56 +94,43 @@ test('catalog paths resolve relative to the catalog and pin each new agent indep
|
|
|
83
94
|
assert.notEqual(first.sample.revision,next.catalog.sample.revision);
|
|
84
95
|
assert.deepEqual(JSON.parse((await f.call('plugins','available')).stdout),first);
|
|
85
96
|
});
|
|
86
|
-
test('native
|
|
87
|
-
const f=await fixture(t),instructions=path.join(f.workspace,'AGENTS.md'),
|
|
88
|
-
await fs.writeFile(instructions,'Owner mandate\n');
|
|
97
|
+
test('init never writes native instructions; the retired footer becomes the static tools line once',async t=>{
|
|
98
|
+
const f=await fixture(t),instructions=path.join(f.workspace,'AGENTS.md'),override=path.join(f.workspace,'AGENTS.override.md');
|
|
89
99
|
await init(f.home,f.workspace);
|
|
90
|
-
await assert.rejects(fs.access(
|
|
91
|
-
const
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
await fs.
|
|
97
|
-
await bindToolDiscovery(f.home,f.workspace);assert.equal(await fs.readFile(
|
|
98
|
-
await fs.writeFile(
|
|
99
|
-
|
|
100
|
+
await assert.rejects(fs.access(instructions),{code:'ENOENT'});
|
|
101
|
+
const footer='<!-- ez tools: begin -->\nUse `/x/bin/ez`.\n<!-- ez tools: end -->';
|
|
102
|
+
await fs.writeFile(instructions,`Owner mandate\n\n${footer}\n\nOwner tail\n`);await fs.writeFile(override,`Override mandate\n${footer}\n`);
|
|
103
|
+
await bindToolDiscovery(f.home,f.workspace);
|
|
104
|
+
const retired=await fs.readFile(instructions,'utf8');
|
|
105
|
+
assert.equal(retired,`Owner mandate\n\n${TOOLS_LINE}\n\nOwner tail\n`);
|
|
106
|
+
assert.equal(await fs.readFile(override,'utf8'),`Override mandate\n${TOOLS_LINE}\n`);
|
|
107
|
+
await bindToolDiscovery(f.home,f.workspace);assert.equal(await fs.readFile(instructions,'utf8'),retired); // once: idempotent
|
|
108
|
+
await fs.writeFile(instructions,`${TOOLS_LINE}\n${footer}\n`);await bindToolDiscovery(f.home,f.workspace);
|
|
109
|
+
assert.equal(await fs.readFile(instructions,'utf8'),`${TOOLS_LINE}\n\n`); // never duplicates the line
|
|
100
110
|
await fs.writeFile(instructions,'<!-- ez tools: begin -->broken');
|
|
101
111
|
await assert.rejects(bindToolDiscovery(f.home,f.workspace),/Malformed/);
|
|
102
112
|
assert.equal(await fs.readFile(instructions,'utf8'),'<!-- ez tools: begin -->broken');
|
|
113
|
+
const notes=path.join(f.workspace,'TOOLS.md');await fs.writeFile(notes,footer);
|
|
103
114
|
await fs.rm(instructions);await fs.symlink(notes,instructions);
|
|
104
115
|
await assert.rejects(bindToolDiscovery(f.home,f.workspace),/regular file/);
|
|
105
|
-
assert.equal(await fs.readFile(notes,'utf8'),
|
|
106
|
-
});
|
|
107
|
-
test('
|
|
108
|
-
const f=await fixture(t)
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
const instructions=await fs.readFile(path.join(f.workspace,'AGENTS.md'),'utf8');assert.match(instructions,/Use `ez`/);assert.match(instructions,/`tools list --details`/);assert.doesNotMatch(instructions,new RegExp(f.home.replace(/[.*+?^${}()|[\]\\]/g,'\\$&')));
|
|
112
|
-
});
|
|
113
|
-
test('discovery rejects an over-budget launcher before rewriting instructions',async t=>{
|
|
114
|
-
const f=await fixture(t),instructions=path.join(f.workspace,'AGENTS.md'),longHome=path.join(f.root,'h'.repeat(200),'n'.repeat(200));
|
|
115
|
-
await fs.mkdir(longHome,{recursive:true});await fs.writeFile(instructions,'Owner mandate\n');
|
|
116
|
-
await assert.rejects(bindToolDiscovery(longHome,f.workspace),/600-byte core budget/);
|
|
117
|
-
assert.equal(await fs.readFile(instructions,'utf8'),'Owner mandate\n');
|
|
118
|
-
});
|
|
119
|
-
test('standalone init rejects over-budget guidance before creating activation state',async t=>{
|
|
120
|
-
const f=await fixture(t),instructions=path.join(f.workspace,'AGENTS.md'),longHome=path.join(f.root,'i'.repeat(200),'j'.repeat(200)),catalog=path.join(f.root,'empty-catalog.json');
|
|
121
|
-
await fs.writeFile(catalog,'{}');await fs.writeFile(instructions,'Owner mandate\n');
|
|
122
|
-
await assert.rejects(initManager(longHome,f.workspace,catalog,undefined,true),/600-byte core budget/);
|
|
123
|
-
assert.deepEqual(await fs.readdir(longHome),[]);
|
|
124
|
-
assert.equal(await fs.readFile(instructions,'utf8'),'Owner mandate\n');
|
|
116
|
+
assert.equal(await fs.readFile(notes,'utf8'),footer);
|
|
117
|
+
});
|
|
118
|
+
test('manifest example is one line starting with a declared command',async t=>{
|
|
119
|
+
const f=await fixture(t),p=await snapshot(f.source);
|
|
120
|
+
assert.doesNotThrow(()=>validate({...f.manifest,example:'sample search "q" --limit 3'},f.deployment,p.files));
|
|
121
|
+
for(const example of ['other --help','sample\nsecond','x'.repeat(161),3]) assert.throws(()=>validate({...f.manifest,example},f.deployment,p.files),/Manifest example/);
|
|
125
122
|
});
|
|
126
123
|
test('installed snippets follow install, upgrade and uninstall without files or Docker reads',async t=>{
|
|
127
124
|
const f=await fixture(t);await init(f.home,f.workspace);
|
|
128
125
|
const details=async()=>JSON.parse((await f.call('tools','list','--details')).stdout);
|
|
129
126
|
assert.deepEqual(await details(),{});
|
|
130
127
|
for(const description of ['Synthetic capability','Updated capability']) {
|
|
131
|
-
|
|
128
|
+
const example=description==='Updated capability'?'sample run --json':undefined;
|
|
129
|
+
await fs.writeFile(path.join(f.source,'ez-plugin.json'),JSON.stringify({...f.manifest,description,example}));
|
|
132
130
|
const p=await snapshot(f.source);
|
|
133
131
|
await f.call('plugins','install','sample','--source',f.source,'--revision',p.revision);
|
|
134
132
|
const before=await fs.readFile(f.log,'utf8'),index=await details();
|
|
135
|
-
assert.equal(index.sample.
|
|
133
|
+
assert.deepEqual(index.sample.aliases,['sample']);assert.equal(index.sample.purpose,description);assert.equal(index.sample.example,`ez ${example??'sample --help'}`);
|
|
136
134
|
assert.equal(await fs.readFile(index.sample.skills[0],'utf8'),'Synthetic');
|
|
137
135
|
assert.deepEqual(index.sample.skillReads,[['ez','tools','skill','sample','SKILL.md']]);
|
|
138
136
|
assert.deepEqual(JSON.parse((await f.call('tools','skill','sample','SKILL.md')).stdout),{plugin:'sample',revision:p.revision,path:'SKILL.md',content:'Synthetic'});
|
|
@@ -278,6 +276,24 @@ test('an unreadable invocation lease pid falls through to container verification
|
|
|
278
276
|
await assert.rejects(locked(f.home,async()=>{}),/Stale command invocation lease/);
|
|
279
277
|
} finally {process.kill=kill0;process.env.PATH=path0;}
|
|
280
278
|
});
|
|
279
|
+
test('a lease from another PID namespace is live while its call container runs, then drains',async t=>{
|
|
280
|
+
const f=await fixture(t);
|
|
281
|
+
const directory=path.join(f.home,'command-invocations');await fs.mkdir(directory,{recursive:true});
|
|
282
|
+
const lease=path.join(directory,'00000000-0000-4000-8000-000000000001.json');
|
|
283
|
+
// Isolated broker lease: its pid means nothing in this namespace (EPERM/ESRCH or an unrelated process).
|
|
284
|
+
await fs.writeFile(lease,JSON.stringify({pid:1,container:'broker-call',pidNamespace:'pid:[4026531999]'}),{mode:0o600});
|
|
285
|
+
const path0=process.env.PATH;process.env.PATH=f.fake+path.delimiter+path0;t.after(()=>{process.env.PATH=path0;});
|
|
286
|
+
const docker=state=>fs.writeFile(path.join(f.fake,'docker'),`#!${process.execPath}\nconst a=process.argv.slice(2);if(a[0]==='container'&&a[1]==='inspect'){${state}}\n`,{mode:0o700});
|
|
287
|
+
await docker(`console.log('true')`);
|
|
288
|
+
await assert.rejects(locked(f.home,async()=>{}),/commands are active/); // never misreported as stale
|
|
289
|
+
let activated=false;const drain=locked(f.home,async()=>{activated=true;},{drainInvocations:true});
|
|
290
|
+
await new Promise(resolve=>setTimeout(resolve,100));assert.equal(activated,false);
|
|
291
|
+
await docker(`console.error('Error: No such object: broker-call');process.exit(1)`);
|
|
292
|
+
await drain;assert.equal(activated,true);await assert.rejects(fs.access(lease),{code:'ENOENT'});
|
|
293
|
+
await fs.writeFile(lease,JSON.stringify({pid:1,container:'broker-call',pidNamespace:'pid:[4026531999]'}),{mode:0o600});
|
|
294
|
+
await docker(`console.log('false')`);
|
|
295
|
+
await assert.rejects(locked(f.home,async()=>{}),/Stale command invocation lease/); // stopped but not removed: inspect first
|
|
296
|
+
});
|
|
281
297
|
test('changed source, symlinks, reserved aliases, arbitrary Docker fields rejected',async t=>{
|
|
282
298
|
const f=await fixture(t),p=await snapshot(f.source);await init(f.home,f.workspace);
|
|
283
299
|
await fs.writeFile(path.join(f.source,'client.mjs'),'changed');await assert.rejects(f.call('plugins','install','sample','--source',f.source,'--revision',p.revision));
|
|
@@ -532,9 +548,7 @@ test('standalone CLI has discoverable setup, independent guidance and status wit
|
|
|
532
548
|
const help=JSON.parse((await exec(process.execPath,[bin,'--help'])).stdout);
|
|
533
549
|
assert.match(help.usage,/--standalone/);
|
|
534
550
|
await exec(process.execPath,[bin,'init','--standalone','--home',f.home,'--workspace',f.workspace],{env:f.env});
|
|
535
|
-
|
|
536
|
-
assert.match(notes,/tools list --details/);
|
|
537
|
-
assert.doesNotMatch(notes,/Finish the main Telegram|ezenciel-agents-message/);
|
|
551
|
+
await assert.rejects(fs.access(path.join(f.workspace,'AGENTS.md')),{code:'ENOENT'}); // instructions stay owner-written
|
|
538
552
|
const launcher=path.join(f.home,'bin','ez');
|
|
539
553
|
const status=JSON.parse((await exec(launcher,['status'],{cwd:f.root,env:f.env})).stdout);
|
|
540
554
|
assert.equal(status.main,null);assert.deepEqual(status.plugins,[]);
|
|
@@ -672,3 +686,27 @@ test('bounded lock admission times out without stealing an interrupted lock',asy
|
|
|
672
686
|
await assert.rejects(locked(f.home,async()=>assert.fail('must not enter'),{waitMs:50}),/Registry busy/);
|
|
673
687
|
assert.equal(await fs.readFile(file,'utf8'),'preserved');
|
|
674
688
|
});
|
|
689
|
+
|
|
690
|
+
|
|
691
|
+
test('cancelled plugin upgrade drain preserves live invocation and releases admission lock',async t=>{
|
|
692
|
+
const f=await fixture(t),controller=new AbortController();
|
|
693
|
+
const directory=path.join(f.home,'command-invocations');await fs.mkdir(directory,{recursive:true});
|
|
694
|
+
const lease=path.join(directory,'00000000-0000-4000-8000-000000000000.json');
|
|
695
|
+
await fs.writeFile(lease,JSON.stringify({pid:process.pid,container:'active-call'}));
|
|
696
|
+
let activated=false;
|
|
697
|
+
const drain=locked(f.home,async()=>{activated=true;},{drainInvocations:true,signal:controller.signal});
|
|
698
|
+
for(let n=0;n<100&&!await fs.access(path.join(f.home,'registry.lock')).then(()=>true,()=>false);n++)await new Promise(resolve=>setTimeout(resolve,10));
|
|
699
|
+
controller.abort();await assert.rejects(drain,{name:'AbortError'});assert.equal(activated,false);
|
|
700
|
+
await fs.access(lease);await assert.rejects(fs.access(path.join(f.home,'registry.lock')),{code:'ENOENT'});
|
|
701
|
+
});
|
|
702
|
+
|
|
703
|
+
|
|
704
|
+
test('native call cancelled while admission is closed never acquires an invocation lease',async t=>{
|
|
705
|
+
const f=await fixture(t),controller=new AbortController();await fs.mkdir(f.home,{recursive:true});
|
|
706
|
+
let entered,release;const ready=new Promise(resolve=>entered=resolve),hold=new Promise(resolve=>release=resolve);
|
|
707
|
+
const activation=locked(f.home,async()=>{entered();await hold;});await ready;
|
|
708
|
+
const call=prepareCommand(f.home,'sample',[],{invocation:true,signal:controller.signal});
|
|
709
|
+
controller.abort();await assert.rejects(call,{name:'AbortError'});
|
|
710
|
+
await assert.rejects(fs.access(path.join(f.home,'command-invocations')),{code:'ENOENT'});
|
|
711
|
+
release();await activation;
|
|
712
|
+
});
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import test from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import { appendFile, mkdir, mkdtemp, readdir, readFile, rename, rm, stat, symlink, writeFile } from 'node:fs/promises'
|
|
4
|
+
import { tmpdir } from 'node:os'
|
|
5
|
+
import { join } from 'node:path'
|
|
6
|
+
import type { Update } from 'grammy/types'
|
|
7
|
+
import { createRelay } from '../src/index.js'
|
|
8
|
+
import { ControlStore } from '../src/control-state.js'
|
|
9
|
+
import { RunStore } from '../src/runs.js'
|
|
10
|
+
import { Scheduler, holdsSchedule } from '../src/scheduler.js'
|
|
11
|
+
import { initialPreset } from '../src/ai.js'
|
|
12
|
+
|
|
13
|
+
const until = async (check: () => Promise<boolean>) => {
|
|
14
|
+
for (let i = 0; i < 400; i++) { if (await check()) return; await new Promise(r => setTimeout(r, 25)) }
|
|
15
|
+
throw new Error('Timed out')
|
|
16
|
+
}
|
|
17
|
+
const config = (controlDir: string, workspace: string) =>
|
|
18
|
+
({ workspace, controlDir, pairingTtlMs: 1000, executorTimeoutMs: 0, executorCli: 'grok', telegramBotToken: 'fixture' })
|
|
19
|
+
|
|
20
|
+
// The test is the host transport: it claims requests, streams events and
|
|
21
|
+
// keeps the heartbeat fresh. A second path to the same control directory gives
|
|
22
|
+
// the next relay an empty memory ledger, as a replacement process would have.
|
|
23
|
+
const fixture = async (t: test.TestContext) => {
|
|
24
|
+
const root = await mkdtemp(join(tmpdir(), 'ez-run-handoff-')), dir = join(root, 'control'), next = join(root, 'next-control')
|
|
25
|
+
const host = join(dir, 'host-executor')
|
|
26
|
+
await mkdir(host, { recursive: true, mode: 0o700 }); await symlink(dir, next)
|
|
27
|
+
const transport = process.env.EZ_EXECUTOR_TRANSPORT
|
|
28
|
+
process.env.EZ_EXECUTOR_TRANSPORT = 'host'
|
|
29
|
+
const beat = setInterval(() => void writeFile(join(host, 'beat.tmp'), JSON.stringify({ at: Date.now() }))
|
|
30
|
+
.then(() => rename(join(host, 'beat.tmp'), join(host, 'heartbeat.json'))).catch(() => {}), 200)
|
|
31
|
+
t.after(async () => {
|
|
32
|
+
clearInterval(beat)
|
|
33
|
+
if (transport === undefined) delete process.env.EZ_EXECUTOR_TRANSPORT; else process.env.EZ_EXECUTOR_TRANSPORT = transport
|
|
34
|
+
await rm(root, { recursive: true, force: true })
|
|
35
|
+
})
|
|
36
|
+
const files = async () => (await readdir(host)).filter(file => file !== 'heartbeat.json' && !file.endsWith('.tmp')).sort()
|
|
37
|
+
const control = new ControlStore(dir, 1000)
|
|
38
|
+
await control.requestPairing(101, 101); await control.approveOwner(101)
|
|
39
|
+
return { root, dir, next, host, files, control, owner: (await control.status()).owner! }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
test('a graceful relay stop hands running host work to the next relay, which records it without relaunching', async t => {
|
|
43
|
+
const { root, dir, next, host, files, control, owner } = await fixture(t)
|
|
44
|
+
const scheduler = new Scheduler(dir), first = new RunStore(dir)
|
|
45
|
+
const execution = await control.captureChoice({ ...initialPreset('grok'), model: 'fixture-model' })
|
|
46
|
+
const due = Date.now() + 1000
|
|
47
|
+
const saved = await scheduler.save({ id: 'long', name: 'Long', text: 'Long work', owner, execution, enabled: true,
|
|
48
|
+
trigger: { everySeconds: 60, start: new Date(due).toISOString() } }, true)
|
|
49
|
+
await scheduler.tick(owner, first, due)
|
|
50
|
+
const foreground = await first.create({ chatId: 101, telegramUserId: 101, texts: ['chat'], execution })
|
|
51
|
+
const before = createRelay(config(dir, root))
|
|
52
|
+
await before.drainSources()
|
|
53
|
+
const scheduled = (await first.list()).find(run => run.scheduled)!
|
|
54
|
+
for (const id of [foreground.id, scheduled.id]) {
|
|
55
|
+
await until(async () => (await files()).includes(id + '.request.json'))
|
|
56
|
+
await rename(join(host, id + '.request.json'), join(host, id + '.running.json'))
|
|
57
|
+
await appendFile(join(host, id + '.events'), JSON.stringify({ stream: 'stdout', text: 'working\n' }) + '\n')
|
|
58
|
+
}
|
|
59
|
+
await before.stop()
|
|
60
|
+
assert.equal((await stat(join(dir, 'run-handoff.json'))).mode & 0o777, 0o600)
|
|
61
|
+
const handoff = JSON.parse(await readFile(join(dir, 'run-handoff.json'), 'utf8'))
|
|
62
|
+
assert.ok(Date.now() - Date.parse(handoff.writtenAt) < 60_000)
|
|
63
|
+
assert.deepEqual(handoff.runs.map((run: { id: string; status: string }) => [run.id, run.status]).sort(),
|
|
64
|
+
[[foreground.id, 'running'], [scheduled.id, 'running']].sort())
|
|
65
|
+
assert.deepEqual(await files(), [foreground.id + '.events', foreground.id + '.running.json', scheduled.id + '.events', scheduled.id + '.running.json'].sort(),
|
|
66
|
+
'the stop must not cancel, finish or resubmit host work')
|
|
67
|
+
|
|
68
|
+
const after = createRelay(config(next, root)), runs = new RunStore(next)
|
|
69
|
+
after.bot.botInfo = { id: 999, is_bot: true, first_name: 'Fixture', username: 'fixture_bot' } as typeof after.bot.botInfo
|
|
70
|
+
after.bot.api.config.use(async () => ({ ok: true, result: { message_id: 42 } }) as never)
|
|
71
|
+
try {
|
|
72
|
+
await after.adoptHandoff()
|
|
73
|
+
await assert.rejects(readFile(join(dir, 'run-handoff.json')), { code: 'ENOENT' })
|
|
74
|
+
assert.deepEqual((await runs.list()).map(run => run.status), ['running', 'running'])
|
|
75
|
+
// The new ledger accepts the run's result delivery and holds its recurring schedule.
|
|
76
|
+
assert.ok(await runs.enqueueMessage(scheduled.id, 'Result after replacement'))
|
|
77
|
+
await scheduler.tick(owner, runs, due + 60_000); await after.drainSources()
|
|
78
|
+
assert.equal((await runs.list()).length, 2, 'the next recurrence waits for the adopted occurrence')
|
|
79
|
+
await new Promise(resolve => setTimeout(resolve, 300))
|
|
80
|
+
assert.ok(!(await files()).some(file => file.endsWith('.request.json') || file.endsWith('.cancel')), 'adoption never resubmits or cancels')
|
|
81
|
+
await appendFile(join(host, foreground.id + '.events'), JSON.stringify({ stream: 'exit', code: 0 }) + '\n')
|
|
82
|
+
await rm(join(host, foreground.id + '.running.json'))
|
|
83
|
+
await until(async () => (await runs.get(foreground.id))?.status === 'completed')
|
|
84
|
+
assert.equal((await new ControlStore(next, 1000).executionSession(execution)).hasStarted, true)
|
|
85
|
+
// /stop reaches the adopted run through the existing cancel path.
|
|
86
|
+
await after.bot.handleUpdate({ update_id: 1, message: { message_id: 1, date: 0, text: '/stop', from: { id: 101, is_bot: false, first_name: 'Owner' }, chat: { id: 101, type: 'private', first_name: 'Owner' } } } as Update)
|
|
87
|
+
await until(async () => (await runs.get(scheduled.id))?.status === 'cancelled')
|
|
88
|
+
assert.ok((await files()).includes(scheduled.id + '.cancel'), 'the host is asked to stop the adopted executor')
|
|
89
|
+
assert.equal(holdsSchedule(saved, (await runs.get(scheduled.id))!), false)
|
|
90
|
+
} finally { await after.stop() }
|
|
91
|
+
})
|
|
92
|
+
|
|
93
|
+
test('adoption fails closed for unknown, invalid, stale or corrupt handoff records and never launches', async t => {
|
|
94
|
+
const { root, dir, files, owner } = await fixture(t)
|
|
95
|
+
const scheduler = new Scheduler(dir)
|
|
96
|
+
const saved = await scheduler.save({ id: 'gone', name: 'Gone', text: 'work', owner, enabled: true, trigger: { everySeconds: 60, start: new Date(Date.now() + 1000).toISOString() },
|
|
97
|
+
execution: { sessionId: '00000000-0000-4000-8000-000000000000', preset: { ...initialPreset('grok'), model: 'fixture-model' } } }, true)
|
|
98
|
+
const lost = { version: 1, id: 'r_schedule_lost', chatId: 101, telegramUserId: 101, texts: ['work'], status: 'running', createdAt: new Date().toISOString(),
|
|
99
|
+
scheduled: { id: saved.id, revision: saved.revision, dueAt: new Date().toISOString(), pairedAt: owner.pairedAt } }
|
|
100
|
+
const write = (runs: unknown[], writtenAt = new Date().toISOString()) => writeFile(join(dir, 'run-handoff.json'), JSON.stringify({ version: 1, writtenAt, runs }))
|
|
101
|
+
await write([lost, { ...lost, id: '../escape' }, { ...lost, id: 'r_done', status: 'completed' }])
|
|
102
|
+
let launches = 0
|
|
103
|
+
const relay = createRelay(config(dir, root), async () => { launches++; throw new Error('Must not launch') }), runs = new RunStore(dir)
|
|
104
|
+
try {
|
|
105
|
+
await relay.adoptHandoff()
|
|
106
|
+
await until(async () => (await runs.get(lost.id))?.status === 'failed')
|
|
107
|
+
const failed = (await runs.get(lost.id))!
|
|
108
|
+
assert.match(failed.failure?.error ?? '', /outcome is unknown/)
|
|
109
|
+
assert.equal(failed.failureReason, 'handoff-outcome-unknown')
|
|
110
|
+
assert.equal(failed.interrupted, true)
|
|
111
|
+
assert.equal(holdsSchedule(saved, failed), true, 'an unknown outcome holds its schedule until an explicit edit')
|
|
112
|
+
assert.deepEqual((await runs.list()).map(run => run.id), [lost.id])
|
|
113
|
+
for (const stale of [() => write([{ ...lost, id: 'r_schedule_stale' }], new Date(Date.now() - 25 * 3600_000).toISOString()), () => writeFile(join(dir, 'run-handoff.json'), '{not json')]) {
|
|
114
|
+
await stale()
|
|
115
|
+
await relay.adoptHandoff()
|
|
116
|
+
await assert.rejects(readFile(join(dir, 'run-handoff.json')), { code: 'ENOENT' })
|
|
117
|
+
}
|
|
118
|
+
await relay.drainSources()
|
|
119
|
+
assert.equal(launches, 0)
|
|
120
|
+
assert.deepEqual((await runs.list()).map(run => run.id), [lost.id])
|
|
121
|
+
assert.deepEqual(await files(), [])
|
|
122
|
+
} finally { await relay.stop() }
|
|
123
|
+
// A relay without host transport removes a record it cannot adopt.
|
|
124
|
+
delete process.env.EZ_EXECUTOR_TRANSPORT
|
|
125
|
+
await write([{ ...lost, id: 'r_schedule_local' }])
|
|
126
|
+
const local = createRelay(config(dir, root))
|
|
127
|
+
try {
|
|
128
|
+
await local.adoptHandoff()
|
|
129
|
+
await assert.rejects(readFile(join(dir, 'run-handoff.json')), { code: 'ENOENT' })
|
|
130
|
+
assert.equal(await runs.get('r_schedule_local'), null)
|
|
131
|
+
} finally { await local.stop() }
|
|
132
|
+
})
|
|
@@ -7,6 +7,7 @@ import { tmpdir } from 'node:os'
|
|
|
7
7
|
import { Scheduler } from '../src/scheduler.js'
|
|
8
8
|
import { scheduledTaskDetailText, scheduledTasksText } from '../src/scheduled-tasks.js'
|
|
9
9
|
import { RunStore } from '../src/runs.js'
|
|
10
|
+
import type { Trigger } from '../src/schedule-time.js'
|
|
10
11
|
|
|
11
12
|
const owner = { telegramUserId: 101, telegramChatId: 101, pairedAt: '2026-09-11T00:00:00.000Z' }
|
|
12
13
|
const execution = { sessionId: randomUUID(), preset: { id: 'fixture', name: 'Fixture', cli: 'codex', model: 'fixture-model' } }
|
|
@@ -40,7 +41,7 @@ test('scheduled task view is read-only, owner-bound, and shows active task promp
|
|
|
40
41
|
const active = await scheduler.listActiveReadOnly(await runs.list())
|
|
41
42
|
const text = scheduledTasksText(active, owner)
|
|
42
43
|
|
|
43
|
-
assert.equal(text, '📅 Scheduled tasks · 1 active\n\
|
|
44
|
+
assert.equal(text, '📅 Scheduled tasks · 1 active\n\nNext/last times UTC. Use /tasks 1 for task details.\n\n1 · Daily report\n ● Active\n Schedule · Weekdays at 09:00 · Asia/Dubai\n Next · Thu, Jan 1 · 05:00 UTC\n Last · ✓ Completed · Thu, Jan 1 · 05:04 UTC\n Execution · codex (default login) · fixture-model · default effort\n Read the ledger and send the owner a concise report.')
|
|
44
45
|
assert.match(scheduledTaskDetailText(active.find(schedule => schedule.id === saved.id)!, 1), /Last run\n✓ Completed · Thu, Jan 1 · 05:04 UTC/)
|
|
45
46
|
assert.doesNotMatch(text, /Other owner task|This must never be visible/)
|
|
46
47
|
assert.equal(await readFile(join(scheduleDir, 'owner-task.json'), 'utf8'), before)
|
|
@@ -118,7 +119,7 @@ test('a legacy invalid selection does not prevent the active menu from rendering
|
|
|
118
119
|
await writeFile(file,JSON.stringify(saved))
|
|
119
120
|
|
|
120
121
|
const active = await scheduler.listActiveReadOnly([])
|
|
121
|
-
assert.match(scheduledTasksText(active,owner),/codex · gpt-5.6-terra · max/)
|
|
122
|
+
assert.match(scheduledTasksText(active,owner),/codex \(default login\) · gpt-5.6-terra · max/)
|
|
122
123
|
})
|
|
123
124
|
|
|
124
125
|
test('detail view truncates long instructions and tolerates invalid timestamps', async t => {
|
|
@@ -135,3 +136,24 @@ test('detail view truncates long instructions and tolerates invalid timestamps',
|
|
|
135
136
|
const broken = {...active.find(schedule => schedule.id === saved.id)!,nextAt:'not-a-date',lastRun:{status:'completed',at:'also-bad',currentRevision:true}} as never
|
|
136
137
|
assert.doesNotMatch(scheduledTaskDetailText(broken,1,1),/NaN/)
|
|
137
138
|
})
|
|
139
|
+
|
|
140
|
+
test('frequency describes saved rules without inventing a uniform interval for arbitrary cron', async t => {
|
|
141
|
+
const dir=await mkdtemp(join(tmpdir(),'ez-schedule-frequency-'));t.after(()=>rm(dir,{recursive:true,force:true}))
|
|
142
|
+
const scheduler=new Scheduler(dir),start='2027-01-01T00:00:00Z',timezone='America/New_York'
|
|
143
|
+
const cases:[Trigger,string][]=[
|
|
144
|
+
[{at:start},'Once'],[{everySeconds:60,start},'Every minute'],[{everySeconds:90,start},'Every 90 seconds'],
|
|
145
|
+
[{everySeconds:3600,start},'Every hour'],[{everySeconds:172800,start},'Every 2 days'],
|
|
146
|
+
[{cron:'*/15 * * * *',timezone,start},'Every 15 minutes · America/New_York'],
|
|
147
|
+
[{cron:'*/30 * * * *',timezone,start},'Every 30 minutes · America/New_York'],
|
|
148
|
+
[{cron:'15 * * * *',timezone,start},'Hourly at :15 · America/New_York'],
|
|
149
|
+
[{cron:'30 9 * * *',timezone,start},'Daily at 09:30 · America/New_York'],
|
|
150
|
+
[{cron:'*/7 * * * *',timezone,start},'Cron */7 * * * * · America/New_York'],
|
|
151
|
+
[{cron:'0 9 1 * 1',timezone,start},'Cron 0 9 1 * 1 · America/New_York'],
|
|
152
|
+
]
|
|
153
|
+
for(const [i,[trigger,label]] of cases.entries()){
|
|
154
|
+
const saved=await scheduler.save({id:`t-${i}`,name:`Task ${i}`,text:'Inspect saved work.',owner,execution,enabled:true,trigger})
|
|
155
|
+
const active=(await scheduler.listActiveReadOnly([])).find(s=>s.id===saved.id)!
|
|
156
|
+
assert.ok(scheduledTasksText([active],owner).includes(`Schedule · ${label}\n`))
|
|
157
|
+
assert.ok(scheduledTaskDetailText(active,1).includes(`Schedule\n${label}\n`))
|
|
158
|
+
}
|
|
159
|
+
})
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import assert from 'node:assert/strict'
|
|
2
|
+
import test from 'node:test'
|
|
3
|
+
import { queueSessionClose } from '../src/session-close.js'
|
|
4
|
+
import type { RunStore } from '../src/runs.js'
|
|
5
|
+
import type { Owner, SessionState } from '../src/control-state.js'
|
|
6
|
+
|
|
7
|
+
test('a private application scope never gets an owner-authority close turn', async () => {
|
|
8
|
+
const created: unknown[] = []
|
|
9
|
+
const runs = { create: async (input: unknown) => { created.push(input); return input } } as unknown as RunStore
|
|
10
|
+
const owner = { id: 'owner', telegramUserId: 42, pairedAt: new Date(0).toISOString() } as Owner
|
|
11
|
+
const session: SessionState = { sessionId: 'scoped', hasStarted: true, preset: { id: 'p', cli: 'codex', model: 'm' } as SessionState['preset'], applicationScope: 'a'.repeat(64) }
|
|
12
|
+
assert.equal(await queueSessionClose(runs, owner, session), undefined)
|
|
13
|
+
assert.equal(created.length, 0)
|
|
14
|
+
const { applicationScope: _, ...ownerSession } = session
|
|
15
|
+
assert.ok(await queueSessionClose(runs, owner, ownerSession))
|
|
16
|
+
assert.equal(created.length, 1)
|
|
17
|
+
})
|