teimmo 0.0.0-stage → 0.7.8

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/evidence.mjs ADDED
@@ -0,0 +1,58 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import {assert,digest,relativeFile} from './artifacts.mjs';
4
+
5
+ export function validateEvidence(check) {
6
+ assert(check.kind===undefined||['command','behavior'].includes(check.kind),'Unknown check kind');
7
+ if(check.kind==='command') {assert(typeof check.purpose==='string'&&check.purpose.trim(),'Command check needs purpose');assert(check.evidence===undefined,'Generic command checks cannot declare behavioral evidence');return;}
8
+ const e=check.evidence;
9
+ assert(e&&['node-tap','json'].includes(e.format),'Check '+check.id+' needs structured evidence (node-tap/json); exit zero alone is not acceptance. Replan legacy checks.');
10
+ assert(Array.isArray(e.tests)&&e.tests.length,'Evidence requires named tests: '+check.id);
11
+ const ids=new Set(),names=new Set();
12
+ for(const t of e.tests){
13
+ assert(typeof t.id==='string'&&t.id&&!ids.has(t.id),'Duplicate/empty test ID');ids.add(t.id);
14
+ assert(typeof t.name==='string'&&t.name&&!names.has(t.name),'Duplicate/empty test name');names.add(t.name);
15
+ assert(Array.isArray(t.criteria)&&t.criteria.length&&t.criteria.every(x=>/^AC-\d+$/.test(x)),'Test criteria required');
16
+ assert(t.cases===undefined||Array.isArray(t.cases)&&t.cases.every(x=>typeof x==='string'),'Test cases must be IDs');
17
+ }
18
+ }
19
+ export function parseEvidence(check,text) {
20
+ if(check.kind==='command')return {level:'command-only',tests:[],valid:true,gaps:[]};
21
+ validateEvidence(check);
22
+ let observed=[];
23
+ const gaps=[];
24
+ if(check.evidence.format==='json') {
25
+ const entries=text.split(/\r?\n/).flatMap(line=>{try{const x=JSON.parse(line);return x.teimmoEvidence===1?[x]:[];}catch{return [];}});
26
+ if(entries.length!==1||!Array.isArray(entries[0]?.tests))return {level:'unverified',valid:false,tests:[],gaps:['Expected exactly one teimmoEvidence:1 result']};
27
+ observed=entries[0].tests;
28
+ } else {
29
+ // Deliberately supports flat node:test TAP. Nested suites require a JSON adapter.
30
+ if(!/^TAP version 13\s*$/m.test(text))gaps.push('Missing TAP header');
31
+ for(const line of text.split(/\r?\n/)) {
32
+ const m=line.match(/^(not ok|ok) (\d+) - (.*?)(?:\s+#\s*(SKIP|TODO)\b.*)?$/i);
33
+ if(m)observed.push({id:m[3],name:m[3],status:m[4]?'skipped':m[1]==='ok'?'passed':'failed'});
34
+ }
35
+ const count=text.match(/^# tests (\d+)\s*$/m),plan=text.match(/^1\.\.(\d+)\s*$/m);
36
+ if(!count||!plan||Number(count[1])!==observed.length||Number(plan[1])!==observed.length)gaps.push('Incomplete or nested TAP; use flat tests or JSON adapter');
37
+ for(const metric of ['fail','cancelled','skipped','todo'])if(Number(text.match(new RegExp('^# '+metric+' (\\d+)\\s*$','m'))?.[1]||0)>0)gaps.push('TAP '+metric+' is nonzero');
38
+ }
39
+ const seen=new Set();
40
+ for(const t of observed){if(!t||typeof t.id!=='string'||seen.has(t.id)||!['passed','failed','skipped'].includes(t.status)){gaps.push('Malformed or duplicate test result');continue;}seen.add(t.id);if(t.status!=='passed')gaps.push('Test not passed: '+t.id);}
41
+ if(!observed.length)gaps.push('Zero tests executed');
42
+ const tests=check.evidence.tests.map(t=>{
43
+ const key=check.evidence.format==='node-tap'?t.name:t.id;
44
+ const result=observed.find(x=>x?.id===key);
45
+ if(!result||result.status!=='passed')gaps.push('Required test not passed: '+t.id);
46
+ return {...t,status:result?.status||'not-run'};
47
+ });
48
+ return {level:gaps.length?'unverified':'named-tests-executed',valid:gaps.length===0,tests,observedCount:observed.length,gaps,notice:'Execution evidence is not proof of assertion quality or complete business coverage.'};
49
+ }
50
+ export function environmentFingerprint(root,config={}) {
51
+ const files=['package-lock.json','pnpm-lock.yaml','yarn.lock','uv.lock','poetry.lock','Cargo.lock','go.sum',...(config.evidenceInputs||[])];
52
+ const entries=[...new Set(files)].sort().map(name=>{const file=relativeFile(root,name);return [name,fs.existsSync(file)?digest(fs.readFileSync(file)):null];});
53
+ return digest(JSON.stringify({node:process.version,platform:process.platform,arch:process.arch,inputs:entries}));
54
+ }
55
+ export function evidenceFor(root,check,result){
56
+ if(result.error||result.timedOut||result.code===null)return {valid:false,level:'unverified',tests:[],gaps:['Execution unavailable']};
57
+ return parseEvidence(check,fs.readFileSync(path.join(root,result.stdout),'utf8'));
58
+ }
@@ -0,0 +1,49 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import {spawnSync} from 'node:child_process';
4
+ import {assert,digest,inventory,relativeFile} from './artifacts.mjs';
5
+
6
+ const omitted = name => name.split('/').some(p=>['.git','.harness','node_modules','.cache','.codex','.aws','.ssh'].includes(p.toLowerCase())) || /(^|\/)\.env(?:\.|$)|\.(pem|key|p12|pfx)$|(^|\/)id_(rsa|ed25519)$/i.test(name);
7
+ const fingerprint = file => {const s=fs.lstatSync(file);assert(s.isFile(),'Native workspace requires ordinary files');return digest(fs.readFileSync(file))+':'+(s.mode&0o111);};
8
+
9
+ // An independent snapshot, never a checkout/reset/commit in the user's repository.
10
+ export function prepareWorkspace(root,destination,required=[]) {
11
+ relativeFile(root,path.relative(root,destination).replaceAll('\\','/'));
12
+ assert(!fs.existsSync(destination),'Native workspace already exists');
13
+ fs.mkdirSync(destination,{recursive:true});
14
+ const names=new Set([...inventory(root),...required]);
15
+ const spec=path.join(root,'harness-spec');
16
+ if(fs.existsSync(spec))for(const name of fs.readdirSync(spec))names.add('harness-spec/'+name);
17
+ const baseline={},excluded=[];
18
+ for(const name of [...names].sort()){
19
+ if(omitted(name)){assert(!required.includes(name),'Required native input excluded: '+name);excluded.push(name);continue;}
20
+ const source=relativeFile(root,name);
21
+ if(!fs.existsSync(source))continue;
22
+ const target=relativeFile(destination,name),stat=fs.lstatSync(source);
23
+ assert(stat.isFile(),'Native snapshot requires ordinary files: '+name);
24
+ fs.mkdirSync(path.dirname(target),{recursive:true});fs.copyFileSync(source,target);fs.chmodSync(target,stat.mode);
25
+ baseline[name]=fingerprint(target);
26
+ }
27
+ assert(spawnSync('git',['init','-q'],{cwd:destination,windowsHide:true}).status===0,'Native git init failed');
28
+ return {directory:destination,baseline,excluded};
29
+ }
30
+
31
+ export function collectWorkspace(workspace,{allowed,frozen=[]}){
32
+ assert(Array.isArray(allowed)&&allowed.length,'Native execution requires approved task files');
33
+ const root=workspace.directory,files=[];
34
+ // Existing files and approved paths are inspected even if the worker changes ignore rules.
35
+ const names=new Set([...Object.keys(workspace.baseline),...inventory(root),...allowed]);
36
+ for(const name of [...names].sort()){
37
+ const file=relativeFile(root,name),before=workspace.baseline[name];
38
+ assert(!before||fs.existsSync(file),'Native deletions are not supported: '+name);
39
+ if(!fs.existsSync(file))continue;
40
+ const after=fingerprint(file);if(before===after)continue;
41
+ assert(!name.startsWith('harness-spec/')&&!frozen.some(x=>x.toLowerCase()===name.toLowerCase()),'Frozen acceptance contract changed in native workspace: '+name);
42
+ assert(allowed.includes(name),'File outside approved task boundary: '+name);
43
+ const data=fs.readFileSync(file);assert(data.length<=4*1024*1024&&!data.includes(0),'Native output must be text under 4 MiB');
44
+ const content=new TextDecoder('utf-8',{fatal:true}).decode(data);
45
+ if(before)assert(before.split(':').at(-1)===after.split(':').at(-1),'Native mode changes are not supported: '+name);
46
+ files.push({path:name,content});
47
+ }
48
+ return files;
49
+ }
@@ -0,0 +1,35 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import {assert,readJson,write,testDigest,digest} from './artifacts.mjs';
4
+
5
+ export function obligations(root){
6
+ const file=path.join(root,'harness-spec/obligations.json');
7
+ if(!fs.existsSync(file))return [];
8
+ const data=readJson(file);assert(data.version===1&&Array.isArray(data.items),'Unsupported obligations registry');
9
+ const ids=new Set();
10
+ for(const item of data.items){assert(item&&typeof item.id==='string'&&!ids.has(item.id),'Duplicate obligation');ids.add(item.id);assert(['active','retired'].includes(item.status),'Invalid obligation status');assert(item.check&&Array.isArray(item.check.files)&&typeof item.testHash==='string','Invalid obligation check');if(item.status==='retired')assert(item.retirement?.reason?.trim(),'Retirement needs a reason');}
11
+ return data.items;
12
+ }
13
+ export function inheritedChecks(root){
14
+ return obligations(root).filter(x=>x.status==='active').map(x=>({...x.check,id:x.id,inherited:true}));
15
+ }
16
+ export function checkObligations(root){
17
+ for(const item of obligations(root).filter(x=>x.status==='active'))assert(testDigest(root,[item.check])===item.testHash,'Inherited acceptance file changed: '+item.id+'. Restore it or explicitly retire the obligation during planning.');
18
+ }
19
+ export function carryObligations(root,checks,revision){
20
+ const items=obligations(root);
21
+ for(const check of checks){
22
+ if(check.inherited)continue;
23
+ const testHash=testDigest(root,[check]);
24
+ const signature=digest(JSON.stringify({argv:check.argv,evidence:check.evidence,testHash}));
25
+ if(items.some(x=>x.signature===signature&&x.status==='active'))continue;
26
+ items.push({id:'accepted-'+digest(signature+revision).slice(0,20),status:'active',origin:revision,signature,testHash,check});
27
+ }
28
+ return {version:1,items};
29
+ }
30
+ export function retireObligation(root,id,reason){
31
+ assert(reason?.trim(),'Retirement requires explicit impact rationale');
32
+ const items=obligations(root),item=items.find(x=>x.id===id);assert(item&&item.status==='active','Active obligation not found');
33
+ item.status='retired';item.retirement={reason,at:new Date().toISOString(),mechanism:'explicit-cli-action',identityVerified:false};
34
+ write(path.join(root,'harness-spec/obligations.json'),JSON.stringify({version:1,items},null,2));return item;
35
+ }
package/package.json CHANGED
@@ -1,6 +1,64 @@
1
1
  {
2
2
  "name": "teimmo",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.7.8",
4
+ "description": "TeImMo - The Immortal Moon: durable business context, chat skills and verified delivery loops",
5
+ "type": "module",
6
+ "engines": {
7
+ "node": ">=22"
8
+ },
9
+ "bin": {
10
+ "teimmo": "cli.mjs",
11
+ "sddh": "cli.mjs"
12
+ },
13
+ "files": [
14
+ "cli.mjs",
15
+ "artifacts.mjs",
16
+ "runtime.mjs",
17
+ "native-workspace.mjs",
18
+ "regression-supersession.mjs",
19
+ "dashboard-state.mjs",
20
+ "dashboard-ui.mjs",
21
+ "dashboard.mjs",
22
+ "README.md",
23
+ "NOTICE",
24
+ "domain.mjs",
25
+ "skillpack.mjs",
26
+ "evidence.mjs",
27
+ "context.mjs",
28
+ "obligations.mjs",
29
+ "LICENSE",
30
+ "replan.mjs",
31
+ "workspace-layout.mjs",
32
+ "runners/unittest_evidence.py"
33
+ ],
34
+ "scripts": {
35
+ "test": "node --test tests/*.test.mjs",
36
+ "check:release": "node scripts/check-release.mjs",
37
+ "test:package": "node scripts/package-smoke.mjs",
38
+ "test:oracle": "node scripts/dashboard-oracle.mjs"
39
+ },
40
+ "license": "Apache-2.0",
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "git+https://github.com/VinhTimoon/TeImMo.git"
44
+ },
45
+ "bugs": {
46
+ "url": "https://github.com/VinhTimoon/TeImMo/issues"
47
+ },
48
+ "homepage": "https://github.com/VinhTimoon/TeImMo#readme",
49
+ "publishConfig": {
50
+ "access": "public",
51
+ "registry": "https://registry.npmjs.org/"
52
+ },
53
+ "keywords": [
54
+ "ai",
55
+ "agent",
56
+ "harness",
57
+ "spec-driven-development",
58
+ "codex",
59
+ "antigravity"
60
+ ],
61
+ "devDependencies": {
62
+ "cc-sdd": "3.1.0"
63
+ }
64
+ }
@@ -0,0 +1,65 @@
1
+ import {assert,digest} from './artifacts.mjs';
2
+ import path from 'node:path';
3
+
4
+ export function deriveRegressionCommand(base,file){
5
+ assert(base,'Unknown base check');
6
+ const entries=base.files.filter(name=>base.argv.includes(name));
7
+ if(entries.length===1)return {argv:base.argv.map(arg=>arg===entries[0]?file:arg),entry:entries[0]};
8
+ const runner=base.argv.findIndex(arg=>path.basename(arg)==='unittest_evidence.py');
9
+ const pattern=base.argv.indexOf('--pattern');
10
+ const directory=base.argv[runner+1];
11
+ if(runner>=0&&pattern>runner+1&&directory&&base.argv[pattern+1]){
12
+ const entry=path.posix.join(directory.replaceAll('\\','/'),base.argv[pattern+1]);
13
+ assert(base.files.includes(entry),'Unittest pattern must name one frozen test file');
14
+ const argv=[...base.argv];argv[runner+1]=path.posix.dirname(file);argv[pattern+1]=path.posix.basename(file);
15
+ return {argv,entry};
16
+ }
17
+ throw new Error('Base check must name exactly one test entrypoint in argv');
18
+ }
19
+
20
+ export function activeRegressionChecks(state) {
21
+ const checks=state.regressionChecks||[];
22
+ const superseded=new Set((state.regressionSupersessions||[]).map(item=>item.from));
23
+ return checks.filter(check=>!superseded.has(check.id));
24
+ }
25
+
26
+ export function carryableChecks(state,checks){
27
+ validateRegressionSupersessions(state);
28
+ const retired=new Set((state.regressionSupersessions||[]).map(item=>item.from));
29
+ return checks.filter(check=>!retired.has(check.id));
30
+ }
31
+
32
+ export function validateRegressionSupersessions(state) {
33
+ const checks=state.regressionChecks||[];
34
+ const byId=new Map(checks.map(check=>[check.id,check]));
35
+ const entries=state.regressionSupersessions||[];
36
+ assert(Array.isArray(entries),'Invalid regression supersession record');
37
+ const seen=new Set();
38
+ for(const item of entries){
39
+ assert(item&&typeof item==='object'&&typeof item.from==='string'&&typeof item.to==='string'&&typeof item.reason==='string'&&item.reason.trim().length>=20,'Invalid regression supersession');
40
+ assert(!seen.has(item.from),'Regression superseded twice: '+item.from);seen.add(item.from);
41
+ const from=byId.get(item.from),to=byId.get(item.to);
42
+ assert(from&&to&&from.id!==to.id,'Supersession requires two registered regression checks');
43
+ assert(!entries.some(other=>other.from===item.to),'Replacement regression cannot also be superseded');
44
+ assert(from.criteria.every(id=>to.criteria.includes(id)),'Replacement must cover every original criterion');
45
+ assert(item.fromDigest===digest(JSON.stringify(from))&&item.toDigest===digest(JSON.stringify(to)),'Regression supersession points to changed check metadata');
46
+ }
47
+ return entries;
48
+ }
49
+
50
+ export function supersedeRegression(state,fromId,toId,reason,sourceHash){
51
+ assert(typeof reason==='string'&&reason.trim().length>=20,'Explain precisely why the original check is vacuous');
52
+ validateRegressionSupersessions(state);
53
+ assert(!state.regressionSupersessions?.some(item=>item.from===fromId),'Regression already superseded');
54
+ const from=state.regressionChecks?.find(check=>check.id===fromId),to=state.regressionChecks?.find(check=>check.id===toId);
55
+ assert(from&&to&&fromId!==toId,'Supersession requires two registered regression checks');
56
+ assert(from.criteria.every(id=>to.criteria.includes(id)),'Replacement must cover every original criterion');
57
+ assert(!state.regressionSupersessions?.some(item=>item.from===toId),'Replacement is already superseded');
58
+ assert(state.verifiedHash===sourceHash,'Run verification on unchanged source before superseding');
59
+ const result=state.checks?.find(check=>check.id===toId);
60
+ assert(result&&result.code===0&&result.evidence?.valid===true&&result.evidence?.tests?.length>0,'Replacement must have passing named evidence');
61
+ const entry={from:fromId,to:toId,reason:reason.trim(),at:new Date().toISOString(),mechanism:'explicit-cli-action',identityVerified:false,fromDigest:digest(JSON.stringify(from)),toDigest:digest(JSON.stringify(to)),sourceHash};
62
+ state.regressionSupersessions=[...(state.regressionSupersessions||[]),entry];
63
+ validateRegressionSupersessions(state);
64
+ return entry;
65
+ }
package/replan.mjs ADDED
@@ -0,0 +1,48 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import {randomUUID} from 'node:crypto';
4
+ import {assert,readJson,write,relativeFile} from './artifacts.mjs';
5
+ import {carryObligations} from './obligations.mjs';
6
+
7
+ export function planReviewContext(root,state){
8
+ const history=state.history||[];
9
+ const boundary=history.findLastIndex(item=>item.stage==='plan'&&item.status==='REOPENED');
10
+ const lessons=history.slice(boundary+1).filter(item=>item.stage.startsWith('review-')&&item.status==='FAIL').slice(-12);
11
+ const archives=history.filter(item=>item.stage==='plan'&&item.status==='REOPENED'&&/^replan-[a-f0-9-]{36}$/.test(item.detail));
12
+ const superseded=[];
13
+ for(const entry of archives){
14
+ const file=relativeFile(root,`.harness/replans/${entry.detail}.json`);
15
+ if(!fs.existsSync(file))continue;
16
+ const prior=readJson(file).state;
17
+ for(const record of prior?.regressionSupersessions||[])superseded.push({revision:entry.detail,reason:record.reason,original:prior.regressionChecks?.find(c=>c.id===record.from),replacement:prior.regressionChecks?.find(c=>c.id===record.to)});
18
+ }
19
+ return {lessons,superseded};
20
+ }
21
+
22
+ export function recoverReplan(root){
23
+ const journal=relativeFile(root,'.harness/pending-replan.json');
24
+ if(!fs.existsSync(journal))return false;
25
+ const data=readJson(journal);
26
+ assert(data.version===1&&/^replan-[a-f0-9-]{36}$/.test(data.id)&&data.state?.phase==='discussion'&&data.obligations?.version===1,'Invalid replan journal');
27
+ // Fixed destinations and idempotent writes permit recovery after any write boundary.
28
+ for(const [name,value] of [[`.harness/replans/${data.id}.json`,data.archive],['harness-spec/obligations.json',data.obligations],['.harness/state.json',data.state]])write(relativeFile(root,name),JSON.stringify(value,null,2));
29
+ fs.unlinkSync(journal);return true;
30
+ }
31
+
32
+ export function reopenPlan(root,state,checks){
33
+ const id='replan-'+randomUUID(),at=new Date().toISOString();
34
+ const documents={};
35
+ const spec=relativeFile(root,'harness-spec');
36
+ for(const name of fs.readdirSync(spec)){
37
+ const file=relativeFile(root,'harness-spec/'+name);
38
+ if(fs.lstatSync(file).isFile())documents[name]=fs.readFileSync(file,'utf8');
39
+ }
40
+ const tests={};
41
+ for(const file of new Set(checks.flatMap(check=>check.files)))tests[file]=fs.readFileSync(relativeFile(root,file),'utf8');
42
+ const next=structuredClone(state);
43
+ Object.assign(next,{phase:'discussion',status:'REOPENED',contractHash:null,testsHash:null,taskRuns:null,approvalReceipt:null,verifiedHash:null,verifiedEnvironmentHash:null,regressionChecks:[],regressionSupersessions:[],regressionHash:null,findings:[],checks:[],contextCarry:null,noProgress:0});
44
+ next.history.push({at,stage:'plan',status:'REOPENED',detail:id});
45
+ const data={version:1,id,archive:{state:structuredClone(state),documents,tests},obligations:carryObligations(root,checks,id),state:next};
46
+ write(relativeFile(root,'.harness/pending-replan.json'),JSON.stringify(data,null,2));
47
+ recoverReplan(root);return next;
48
+ }
@@ -0,0 +1,59 @@
1
+ """Emit TeImMo JSON evidence from Python unittest; run with -B to avoid bytecode changes."""
2
+ import argparse
3
+ import json
4
+ import sys
5
+ import unittest
6
+ from pathlib import Path
7
+
8
+ class EvidenceResult(unittest.TextTestResult):
9
+ def __init__(self, *args, **kwargs):
10
+ super().__init__(*args, **kwargs)
11
+ self.records = {}
12
+
13
+ def record(self, test, status):
14
+ if self.records.get(test.id()) != 'failed':
15
+ self.records[test.id()] = status
16
+
17
+ def addSuccess(self, test):
18
+ super().addSuccess(test)
19
+ self.record(test, 'passed')
20
+
21
+ def addFailure(self, test, err):
22
+ super().addFailure(test, err)
23
+ self.record(test, 'failed')
24
+
25
+ def addError(self, test, err):
26
+ super().addError(test, err)
27
+ self.record(test, 'failed')
28
+
29
+ def addSkip(self, test, reason):
30
+ super().addSkip(test, reason)
31
+ self.record(test, 'skipped')
32
+
33
+ def addExpectedFailure(self, test, err):
34
+ super().addExpectedFailure(test, err)
35
+ self.record(test, 'skipped')
36
+
37
+ def addUnexpectedSuccess(self, test):
38
+ super().addUnexpectedSuccess(test)
39
+ self.record(test, 'failed')
40
+
41
+ def addSubTest(self, test, subtest, err):
42
+ super().addSubTest(test, subtest, err)
43
+ if err is not None:
44
+ self.record(test, 'failed')
45
+
46
+ def main():
47
+ parser = argparse.ArgumentParser()
48
+ parser.add_argument('start_dir')
49
+ parser.add_argument('--pattern', default='test*.py')
50
+ args = parser.parse_args()
51
+ sys.path.insert(0, str(Path.cwd()))
52
+ suite = unittest.defaultTestLoader.discover(args.start_dir, pattern=args.pattern)
53
+ result = unittest.TextTestRunner(resultclass=EvidenceResult, verbosity=2).run(suite)
54
+ tests = [{'id': key, 'status': value} for key, value in result.records.items()]
55
+ print(json.dumps({'teimmoEvidence': 1, 'tests': tests}))
56
+ return 0 if result.wasSuccessful() and tests else 1
57
+
58
+ if __name__ == '__main__':
59
+ sys.exit(main())
package/runtime.mjs ADDED
@@ -0,0 +1,181 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { spawn, spawnSync } from 'node:child_process';
4
+ import { assert, write } from './artifacts.mjs';
5
+ import {prepareWorkspace,collectWorkspace} from './native-workspace.mjs';
6
+ import {callGroup} from './workspace-layout.mjs';
7
+
8
+ export function agentCommand(agent, model, prompt, custom = {}) {
9
+ if (Object.hasOwn(custom, agent)) {
10
+ const adapter = custom[agent];
11
+ assert(typeof adapter.command === 'string' && Array.isArray(adapter.args), 'Invalid custom adapter');
12
+ return [adapter.command, ...adapter.args.map(arg => arg.replaceAll('{model}', model || '').replaceAll('{prompt}', prompt))];
13
+ }
14
+ const modelArgs = model ? ['--model', model] : [];
15
+ const commands = {
16
+ codex: ['codex', 'exec', '--ephemeral', '--sandbox', 'read-only', ...modelArgs, prompt],
17
+ claude: ['claude', '-p', prompt, '--output-format', 'json', ...modelArgs],
18
+ gemini: ['gemini', '-p', prompt, '--output-format', 'json', ...modelArgs],
19
+ antigravity: ['agy', '-p', prompt, '--output-format', 'json', ...modelArgs],
20
+ opencode: ['opencode', 'run', '--format', 'json', ...modelArgs, prompt]
21
+ };
22
+ assert(Object.hasOwn(commands, agent), 'Unknown agent. Configure an argv adapter.');
23
+ return commands[agent];
24
+ }
25
+ export class ResponseProtocolError extends Error {}
26
+ export function parseResponse(text) {
27
+ const trimmed = text.trim().replace(/^\x60\x60\x60(?:json)?\s*/, '').replace(/\s*\x60\x60\x60$/, '');
28
+ let object;
29
+ try { object = JSON.parse(trimmed); } catch (syntax) {
30
+ // OpenCode and similar CLIs emit one JSON event per line.
31
+ let events;
32
+ try { events = trimmed.split(/\r?\n/).filter(Boolean).map(line => JSON.parse(line)); }
33
+ catch { throw new ResponseProtocolError('Invalid response JSON: ' + syntax.message); }
34
+ if (events.some(event => event.event)) {
35
+ const results = events.filter(event => event.event === 'result');
36
+ assert(results.length === 1, 'Expected exactly one completed Antigravity result');
37
+ return parseResponse(JSON.stringify(results[0]));
38
+ }
39
+ const parts = events.filter(event => event.type === 'text').map(event => event.part?.text || event.text || '');
40
+ if (parts.length) return parseResponse(parts.join(''));
41
+ throw new Error('Expected one JSON response or supported JSONL text events');
42
+ }
43
+ assert(object && typeof object === 'object' && !Array.isArray(object), 'Expected response object');
44
+ if (object.event === 'result') return parseResponse(JSON.stringify(object.result));
45
+ if (object.status !== undefined) assert(object.status === 'SUCCESS', 'Provider did not complete successfully: ' + object.status + ' ' + (object.error || ''));
46
+ assert(!object.is_error && !object.error, 'Provider reported an error: ' + (object.error || object.result || 'unknown'));
47
+ if (object?.type === 'text') return parseResponse(object.part?.text || object.text || '');
48
+ if (object?.structured_output) object = object.structured_output;
49
+ if (typeof object.result === 'string') return parseResponse(object.result);
50
+ if (typeof object.response === 'string') return parseResponse(object.response);
51
+ assert(object && typeof object.summary === 'string' && Array.isArray(object.files), 'Response requires summary and files');
52
+ return object;
53
+ }
54
+ export function invocation(route, prompt, config, promptFile, answerFile) {
55
+ const adapters = config.adapters || {};
56
+ let argv, input = null;
57
+ if (Object.hasOwn(adapters, route.agent)) {
58
+ const adapter = adapters[route.agent];
59
+ assert(typeof adapter.command === 'string' && adapter.command.length && Array.isArray(adapter.args) && adapter.args.every(arg => typeof arg === 'string'), 'Invalid custom adapter');
60
+ argv = [adapter.command, ...adapter.args.map(arg => arg.replace(/\{(model|promptFile|prompt)\}/g, (_, key) => ({model: route.model || '', promptFile, prompt})[key]))];
61
+ } else if (route.agent === 'codex') {
62
+ argv = agentCommand('codex', route.model, '-');
63
+ argv.splice(argv.length - 1, 0, '--ignore-user-config', '-o', answerFile);
64
+ input = prompt;
65
+ } else if (route.agent === 'antigravity') {
66
+ argv = ['agy', '--input-format', 'stream-json', '--output-format', 'stream-json', '--disable-slash-commands',
67
+ '--settings', JSON.stringify({permissions:{deny:['write_file(*)','command(*)','mcp(*)','read_url(*)','execute_url(*)']}}),
68
+ ...(route.model ? ['--model', route.model] : [])];
69
+ input = JSON.stringify({event:'user',message:{content:prompt}}) + '\n';
70
+ } else {
71
+ argv = agentCommand(route.agent, route.model, 'Read the full task in ' + promptFile + '. Return only the requested JSON object as your final response. Do not directly write files or run mutating tools.');
72
+ }
73
+ if (!Object.hasOwn(adapters, route.agent) && config.executables?.[route.agent]) {
74
+ assert(typeof config.executables[route.agent] === 'string', 'Executable must be a path or command');
75
+ argv[0] = config.executables[route.agent];
76
+ }
77
+ assert(argv.join(' ').length < 28000, 'Adapter command exceeds command-line limit. Use {promptFile} in adapter args.');
78
+ return {argv,input};
79
+ }
80
+ export async function execute(argv, timeoutMs, log, cwd = process.cwd(), input = null) {
81
+ assert(Array.isArray(argv) && argv.length && argv.every(arg => typeof arg === 'string'), 'Invalid command argv');
82
+ fs.mkdirSync(path.dirname(log), { recursive: true });
83
+ const stdoutFile = log + '.stdout';
84
+ const output = fs.createWriteStream(log), stdout = fs.createWriteStream(stdoutFile);
85
+ return new Promise(resolve => {
86
+ let error = null, timedOut = false, bytes = 0, terminating = false;
87
+ const started = Date.now();
88
+ const childEnv={...process.env};
89
+ // A harness invoked by node:test must still launch a real independent test runner.
90
+ delete childEnv.NODE_TEST_CONTEXT;
91
+ const child = spawn(argv[0], argv.slice(1), {
92
+ cwd, env:childEnv, shell: false, windowsHide: true, detached: process.platform !== 'win32',
93
+ stdio: ['pipe', 'pipe', 'pipe']
94
+ });
95
+ function terminate() {
96
+ if (terminating || !child.pid) return;
97
+ terminating = true;
98
+ if (process.platform === 'win32') {
99
+ const killed=spawnSync('taskkill', ['/pid', String(child.pid), '/t', '/f'], { windowsHide: true, stdio: 'ignore',timeout:5000 });
100
+ if(killed.status!==0){error ||= 'Process-tree termination unavailable; direct child termination attempted';child.kill('SIGKILL');}
101
+ } else {
102
+ try { process.kill(-child.pid, 'SIGKILL'); } catch { child.kill('SIGKILL'); }
103
+ }
104
+ }
105
+ const timer = setTimeout(() => { timedOut = true; terminate(); }, timeoutMs);
106
+ const onInterrupt = () => { error = 'Interrupted'; terminate(); };
107
+ process.once('SIGINT', onInterrupt);
108
+ process.once('SIGTERM', onInterrupt);
109
+ const emit = (chunk, isStdout) => {
110
+ bytes += chunk.length;
111
+ if (bytes > 16 * 1024 * 1024) { error = 'Output limit exceeded'; terminate(); return; }
112
+ output.write(chunk);
113
+ if (isStdout) stdout.write(chunk);
114
+ };
115
+ output.on('error', e => { error = e.message; terminate(); });
116
+ stdout.on('error', e => { error = e.message; terminate(); });
117
+ child.stdout.on('data', chunk => emit(chunk, true));
118
+ child.stderr.on('data', chunk => emit(chunk, false));
119
+ child.stdin.on('error', e => { if (e.code !== 'EPIPE') error = e.message; });
120
+ child.stdin.end(input);
121
+ child.on('error', e => { error = e.message; });
122
+ child.on('close', (code, signal) => {
123
+ clearTimeout(timer);
124
+ process.removeListener('SIGINT', onInterrupt);
125
+ process.removeListener('SIGTERM', onInterrupt);
126
+ output.end(() => stdout.end(() => resolve({
127
+ code, signal, error, timedOut, durationMs: Date.now() - started,
128
+ log: path.relative(cwd, log).replaceAll('\\', '/'),
129
+ stdout: path.relative(cwd, stdoutFile).replaceAll('\\', '/')
130
+ })));
131
+ });
132
+ });
133
+ }
134
+ export async function invoke(root, route, prompt, config, id, native = null) {
135
+ const directory = path.join(root, '.harness', 'calls',...(config.stageFolders?[callGroup(id)]:[]));
136
+ const promptFile = path.join(directory, id + '.prompt.txt');
137
+ const answerFile = path.join(directory, id + '.answer.json');
138
+ write(promptFile, prompt);
139
+ const {argv,input} = invocation(route, prompt, config, promptFile, answerFile);
140
+ let workspace;
141
+ if(native){
142
+ assert(route.agent==='codex'&&!Object.hasOwn(config.adapters||{},'codex'),'Native workspace requires built-in Codex adapter');
143
+ if(process.platform==='win32'){
144
+ assert(['elevated','unelevated','mxc'].includes(config.codexWindowsSandbox),'Native Codex requires an explicitly configured codexWindowsSandbox backend on Windows; qualify it with your installed CLI first. Proposal mode remains available.');
145
+ argv.splice(argv.length-1,0,'-c','windows.sandbox='+JSON.stringify(config.codexWindowsSandbox));
146
+ }
147
+ workspace=prepareWorkspace(root,path.join(root,'.harness','native',id,'workspace'),native.frozen);
148
+ argv[argv.indexOf('--sandbox')+1]='workspace-write';
149
+ argv.splice(argv.length-1,0,'--json');
150
+ write(path.join(directory,id+'.workspace.json'),JSON.stringify({...workspace,baseline:undefined,inputFiles:Object.keys(workspace.baseline)},null,2));
151
+ }
152
+ const result = await execute(argv, config.agentTimeoutMs, path.join(directory, id + '.log'), workspace?.directory||root, input);
153
+ // execute reports paths relative to its cwd; callers always resolve relative to the project.
154
+ if(workspace)for(const key of ['log','stdout'])result[key]=path.relative(root,path.resolve(workspace.directory,result[key])).replaceAll('\\','/');
155
+ if(result.code!==0||result.error||result.timedOut){
156
+ const diagnostic=fs.existsSync(path.join(root,result.log))?fs.readFileSync(path.join(root,result.log),'utf8').slice(-20000):'';
157
+ result.failureCategory=classifyFailure(result,diagnostic);
158
+ throw new Error('Agent execution failed ['+result.failureCategory+']: '+JSON.stringify(result));
159
+ }
160
+ const text = fs.existsSync(answerFile) ? fs.readFileSync(answerFile, 'utf8') : fs.readFileSync(path.join(root, result.stdout), 'utf8');
161
+ const response = parseResponse(text);
162
+ assert(!response.blocked,'Agent reported blocked execution: '+JSON.stringify(response.blocked));
163
+ if(workspace){
164
+ assert(!response.contextRequests?.length,'Native Codex must read missing context in its workspace');
165
+ const extra=(response.regressionTests||[]).map(test=>test.file);
166
+ response.files=collectWorkspace(workspace,{allowed:[...native.allowed,...extra],frozen:native.frozen});
167
+ result.native={workspace:path.relative(root,workspace.directory).replaceAll('\\','/'),changedFiles:response.files.map(f=>f.path),excluded:workspace.excluded};
168
+ write(path.join(directory,id+'.workspace.json'),JSON.stringify({...result.native,inputFiles:Object.keys(workspace.baseline),validated:true},null,2));
169
+ }
170
+ write(answerFile, JSON.stringify(response, null, 2));
171
+ return { response, result, answer: path.relative(root, answerFile).replaceAll('\\', '/') };
172
+ }
173
+
174
+ export function classifyFailure(result,diagnostic='') {
175
+ if(result.timedOut)return 'timeout';
176
+ if(/not logged|authentication|unauthorized|invalid.*token|401\b/i.test(diagnostic))return 'authentication';
177
+ if(/quota|rate.?limit|429\b/i.test(diagnostic))return 'quota';
178
+ if(/Could not find home|ENOENT|not found|permission denied|access denied|CreateProcessWithLogonW|native MXC is unavailable|read-only sandbox/i.test(diagnostic+' '+(result.error||'')))return 'environment';
179
+ if(/ECONN|ENOTFOUND|connection|network|TLS/i.test(diagnostic))return 'network';
180
+ return 'provider-or-protocol';
181
+ }