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/cli.mjs ADDED
@@ -0,0 +1,757 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { spawnSync } from 'node:child_process';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { analyze, applyFiles, assert, contractDigest, digest, inventory, readJson, recoverWrites, relativeFile, snapshot, testDigest, write } from './artifacts.mjs';
8
+ import { agentCommand, invoke, ResponseProtocolError } from './runtime.mjs';
9
+ export { agentCommand, execute } from './runtime.mjs';
10
+ import { execute } from './runtime.mjs';
11
+ import {domainTemplate,validateDomain,inspectDomain,domainProposals} from './domain.mjs';
12
+ import {installSkills,skillNames} from './skillpack.mjs';
13
+ import {evidenceFor,environmentFingerprint,validateEvidence} from './evidence.mjs';
14
+ import {buildContext,readSource} from './context.mjs';
15
+ import {obligations,inheritedChecks,checkObligations,carryObligations,retireObligation} from './obligations.mjs';
16
+ import {activeRegressionChecks,carryableChecks,validateRegressionSupersessions,supersedeRegression,deriveRegressionCommand} from './regression-supersession.mjs';
17
+ import {reopenPlan,recoverReplan,planReviewContext} from './replan.mjs';
18
+ import {workspaceGuide} from './workspace-layout.mjs';
19
+
20
+ const root = process.cwd();
21
+ const home = path.join(root, '.harness');
22
+ const spec = path.join(root, 'harness-spec');
23
+ const stateFile = path.join(home, 'state.json');
24
+ const stages = ['discussion', 'requirements', 'design', 'tasks', 'analysis', 'approval', 'implementation', 'verification', 'review-spec', 'review-quality', 'complete'];
25
+ const instructions = {
26
+ discussion: 'Discuss the idea. Identify users, problem, alternatives, smallest useful MVP and assumptions. Ask up to 3 consequential unanswered questions. If user decisions suffice, set ready=true and questions=[]. Write ONLY harness-spec/brief.md. Do not implement.',
27
+ requirements: 'Write ONLY harness-spec/requirements.md. Define measurable criteria named AC-01, AC-02 etc, including edge cases. Use the conversation as context, not as permission to skip ahead to implementation.',
28
+ design: 'Write ONLY harness-spec/design.md. Specify components, interfaces, chosen toolchain, compatibility and failure behavior. Consider existing source. Follow project instructions and supplied standards.',
29
+ tasks: 'Write harness-spec/tasks.md with task IDs T-01 etc and criterion references. Create executable acceptance tests in NEW files under tests/ or acceptance/. Write harness-spec/checks.json as [{"id":"check-1","argv":["python","-B","tests/acceptance.py"],"files":["tests/acceptance.py"],"timeoutMs":60000}]. Cover every AC with real assertions. Test imports must work when launched with cwd=repo root; configure import path inside the test when needed. Use -B for Python. Do not implement product source. Avoid generated outputs outside ignored folders.',
30
+ analysis: 'Review requirements, design, tasks and checks for contradictions or missing coverage. Write ONLY harness-spec/analysis.md and harness-spec/traceability.json. JSON shape {"criteria":["AC-01"],"tasks":[{"id":"T-01","criteria":["AC-01"],"dependsOn":[]}],"coverage":[{"criterion":"AC-01","checks":["check-1"]}]}. Include every AC and every task. Set approved=false and provide findings if the plan has substantive gaps, otherwise approved=true and findings=[].',
31
+ implementation: 'Implement the approved tasks in dependency order. Propose only product files. Preserve harness-spec and acceptance tests. Include suitable implementation tests if useful. Never claim runtime success; the harness executes the checks. Return full contents of changed files.',
32
+ repair: 'Diagnose the failure evidence and reviewer findings, then fix product code. Preserve frozen requirements, tasks and acceptance files. For missing regression coverage, create NEW test files and include regressionTests:[{baseCheck:"existing-check-id",file:"tests/new_regression.py",criteria:["AC-01"]}] in your JSON. The runner derives the invocation from the approved base check by replacing its test-file argument. Include the new test contents in files. Use this for adding coverage without changing existing acceptance tests. If the original contract itself is incorrect, request replan in summary. Return full contents of changed product files.',
33
+ 'review-spec': 'Review specification compliance using the source and actual test results. Check every AC, missing behavior, scope expansion and vacuous tests. Return no files, approved boolean and findings array. Include concrete file references and affected AC in findings. This is a fresh review invocation.',
34
+ 'review-quality': 'Review maintainability, error handling, regressions, portability and test quality. Evaluate source directly. Return no files, approved boolean and findings array. Raise actionable defects with file references. This is a fresh review invocation.'
35
+ };
36
+ for(const stage of Object.keys(instructions))instructions[stage]+=' Follow the workspace map: '+workspaceGuide;
37
+ instructions.design+=' Include a concrete product file tree and explain module responsibilities. Follow existing repo/toolchain conventions; do not create generic stage folders inside product code. Tasks and checks must use the same paths.';
38
+ instructions.tasks += ' Every behavioral check MUST declare evidence:{format:"node-tap",tests:[{id:"test-1",name:"exact top-level node:test name",criteria:["AC-01"],cases:["C-01"]}]}; use node --test --test-reporter=tap tests/file.mjs with flat named tests and real assertions. For other languages use evidence format "json" and emit one JSON line {teimmoEvidence:1,tests:[{id:"test-1",status:"passed"|"failed"|"skipped"}]}. Generic lint/build checks use kind:"command",purpose:"..." and cannot cover AC. Each task must have independently executable checks; keep test names stable. Use NEW filenames, including after a change. Inherited tests remain mandatory.';
39
+ instructions.analysis += ' Each task additionally needs files:["exact/product/path"] and checks:["check-1"] for bounded task execution. Each AC and domain case must bind to named tests through evidence.tests criteria/cases. Do not call generic command results business verification. Re-evaluate prior findings against CURRENT artifacts; resolved findings are history, not a new blocker. All authored documents must agree on scope.';
40
+ instructions.requirements += ' Specify observable product behavior. Evidence metadata belongs in checks.json; do not require a duplicate product test file or metadata strings embedded in product code.';
41
+ instructions.design += ' For a new project, define concrete product filenames, exported interfaces, HTTP routes/request/response shapes and startup/storage lifecycle needed by acceptance tests. These technical interfaces are design decisions you must make and document before implementation; they do not require nonexistent product code. Do not leave every source path as optional recommendations. Preserve existing interfaces when supplied.';
42
+ instructions.tasks += ' On a new project no product implementation exists yet. Author real executable behavioral tests against the concrete interface chosen in design, and declare future product files for later implementation. Missing future source/package files are expected, not a blocker. Do not request implementation before writing tests. If design has an interface gap, choose a small concrete technical interface consistent with confirmed requirements and record it in tasks.md. Never invent business policy or weaken assertions.';
43
+ instructions.tasks += ' Execute the acceptance suite directly. Do not use source substring checks for AC IDs as evidence of product behavior, or create a redundant test suite that the approved command never executes.';
44
+ instructions.tasks += ' Choose a command native to the product language; the Python example is not mandatory. Every check.files must include its runner AND all local assertion/helper/fixture files it invokes. Partition checks by task using separate files or exact test-name filters, so an early task does not need future task behavior. Keep a final full-suite check if useful. A missing frozen test dependency is rejected.';
45
+ instructions.analysis += ' If only technical alignment needs correction, return replanStage:"design" or "tasks" with concrete findings; the bounded planner reruns that stage onward. Do not use this to invent business decisions or resolve unanswered user questions. Include all local test files in check.files and verify independently executable task scopes. If the issue needs user intent, omit replanStage and stop for a decision.';
46
+ instructions.tasks += ' Register server/process/temp-resource cleanup immediately after acquisition and before the first assertion or request that may throw. A failing assertion must still close every listener/child process; use try/finally or early t.after hooks. Tests must exit nonzero on product defects rather than hang. Restart tests must clean up the current instance even if the first request fails.';
47
+ instructions.analysis += ' Deterministic business-gate findings are authoritative structural gaps. Correct case/dimension/AC/check mappings in top-level domain using existing assertions and confirmed facts. Do not invent facts, erase cases, or mark a relevant dimension N/A merely to silence a gap; stop for unresolved user decisions.';
48
+ instructions.repair += ' Each regressionTests item also needs evidence with its NEW named tests, format, criteria and case IDs. Do not copy names from base tests if the new test has different names.';
49
+ instructions.repair += ' Added tests must assert confirmed observable requirements, not introduce new platform exclusions or require a particular implementation API. If requirements conflict, request replan with the conflicting criteria instead of freezing a new policy in a regression test.';
50
+ for(const key of Object.keys(instructions))instructions[key]+=' If essential source is missing/partial, return files:[] and contextRequests:[{path:"relative/file",startLine:1,count:120}] instead of guessing. At most 3 ranges per request.';
51
+ for(const stage of ['discussion','requirements','design','tasks','analysis'])instructions[stage]+=' When harness-spec/domain.json is supplied, return its COMPLETE updated object in top-level domain (not files). Preserve version1 and stable IDs. Fields: purpose; actors[{id,description}]; scope{in:[],out:[]}; terms[{term,meaning}]; facts/decisions/rules use statement and source pointing to actual conversation; decisions status proposed|confirmed, rules actors:[actor IDs]; questions[{id,question,blocking,resolution,source}]; cases[{id,rules:[rule IDs],kinds:[dimension IDs],given,when,then,criteria:[AC IDs],checks:[check IDs]}]; dimensions[{id,status:unreviewed|covered|na,rationale}]. Dimensions happy,error,boundary,permission,state,concurrency,retry,integration,data,performance,compatibility must all be examined proportionally. Do not invent a user answer: unresolved questions retain empty resolution/source; proposed decisions remain proposed. Record confirmed facts from conversation. Unknowns should stop discovery for questions, not be marked na. Case mappings may be empty during discussion; tasks must bind each case in checks.json evidence.tests cases/criteria, analysis maps domain cases to the actual generated AC/check IDs. This domain field is the only exception to the stage file list; implementation/review may never return it.';
52
+ class PauseRequested extends Error {}
53
+ class BudgetReached extends Error {}
54
+ let runStarted=Date.now(),runCalls=0;
55
+ function enforceBudget(state){
56
+ const cfg=config();
57
+ if(runCalls >= (cfg.maxCallsPerRun??30)||Date.now()-runStarted >= (cfg.maxRunMs??1800000)){event(state,'loop','BUDGET_EXHAUSTED','Per-run call/time budget reached; resume explicitly.');throw new BudgetReached('Run budget exhausted');}
58
+ }
59
+ function allChecks(state){const checks=[...analyze(root).checks,...(state.regressionChecks||[]),...inheritedChecks(root)];assert(new Set(checks.map(c=>c.id)).size===checks.length,'Check IDs collide with inherited/regression checks');return checks;}
60
+ function currentTask(state){return state.taskRuns?.find(t=>t.status!=='accepted')||null;}
61
+ function freshness(state){return state.sourceHash!==snapshot(root)||state.environmentHash!==environmentFingerprint(root,config());}
62
+ function verdictOf(state){return state.phase==='complete'&&(!state.evidenceVersion||freshness(state))?'STALE':state.status;}
63
+ function checkpoint(state) {
64
+ const file = path.join(home, 'pause.request');
65
+ if (!fs.existsSync(file)) return;
66
+ fs.unlinkSync(file);
67
+ event(state, state.phase, 'PAUSED', 'Paused at a durable checkpoint. Switch routing or resume run.');
68
+ throw new PauseRequested('Paused');
69
+ }
70
+ function config() {
71
+ const value = readJson(path.join(home, 'config.json'));
72
+ value.adapters ||= {};
73
+ value.routes ||= {};
74
+ assert(Number.isInteger(value.maxAttempts) && value.maxAttempts > 0 && value.maxAttempts <= 20, 'maxAttempts must be 1..20');
75
+ assert(Number.isInteger(value.agentTimeoutMs) && value.agentTimeoutMs > 0 && value.agentTimeoutMs <= 3600000, 'agentTimeoutMs must be 1..3600000');
76
+ assert(value.repairTestTimeouts===undefined||typeof value.repairTestTimeouts==='boolean','repairTestTimeouts must be boolean');
77
+ assert(value.stageFolders===undefined||typeof value.stageFolders==='boolean','stageFolders must be boolean');
78
+ for(const key of ['maxCallsPerRun','maxRunMs'])if(value[key]!==undefined)assert(Number.isInteger(value[key])&&value[key]>0,key+' must be positive');
79
+ assert(value.executionMode===undefined||['tasks','change'].includes(value.executionMode),'Unknown executionMode');
80
+ assert(value.codexMode===undefined||['proposal','workspace'].includes(value.codexMode),'Unknown codexMode');
81
+ assert(value.codexWindowsSandbox===undefined||['elevated','unelevated','mxc'].includes(value.codexWindowsSandbox),'Unknown codexWindowsSandbox');
82
+ assert(value.evidenceInputs===undefined||Array.isArray(value.evidenceInputs)&&value.evidenceInputs.every(x=>typeof x==='string'),'evidenceInputs must be a path array');
83
+ return value;
84
+ }
85
+ function save(state) { write(stateFile, JSON.stringify(state, null, 2)); }
86
+ function escape(text) {
87
+ return String(text ?? '').replace(/[&<>"']/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[char]));
88
+ }
89
+ function routing(state) {
90
+ return {default:{agent:state.agent,model:state.model},overrides:readJson(path.join(home,'config.json')).routes || {}};
91
+ }
92
+ function report(state) {
93
+ const verdict = verdictOf(state);
94
+ const rows = state.history.map(event => '<tr><td>' + escape(event.stage) + '</td><td>' + escape(event.status) +
95
+ '</td><td>' + escape(event.agent) + '</td><td>' + escape(event.model || 'default') +
96
+ '</td><td>' + escape(event.detail) + '</td></tr>').join('');
97
+ const coverage = (state.coverage || []).map(row => '<tr><td>' + escape(row.criterion) + '</td><td>' +
98
+ escape(row.tasks.join(', ')) + '</td><td>' + escape(row.checks.join(', ')) + '</td></tr>').join('');
99
+ const links = ['brief.md','domain.json','requirements.md','design.md','tasks.md','analysis.md','traceability.json','checks.json']
100
+ .filter(name => fs.existsSync(path.join(spec,name)))
101
+ .map(name => '<li><a href="../harness-spec/' + name + '">' + name + '</a></li>').join('');
102
+ const evidence = (state.checks || []).map(check => '<li>' + escape(check.id) + ' · exit ' + escape(check.code) +
103
+ ' · ' + escape(check.evidence?.level || 'unverified') + ' · <a href="' + escape(check.log.replace('.harness/', '')) + '">log</a></li>').join('');
104
+ const activeRoutes = routing(state);
105
+ let business;
106
+ try { business=inspectDomain(root,fs.existsSync(path.join(spec,'traceability.json'))?analyze(root):null,state.domainRequired); }
107
+ catch(error){business={enabled:true,ready:false,gaps:[error.message]};}
108
+ const html = '<!doctype html><html lang="vi"><meta charset="utf-8"><meta name="viewport" content="width=device-width">' +
109
+ '<title>Harness results</title><style>body{font:16px system-ui;max-width:1200px;margin:32px auto;padding:16px;color:#18202b;background:#fafbfc}table{border-collapse:collapse;width:100%;background:white}td,th{padding:10px;border:1px solid #ddd;text-align:left;overflow-wrap:anywhere}a{color:#245bbc}small{color:#526070}</style>' +
110
+ '<h1>' + escape(state.title) + '</h1><p><strong>' + escape(verdict) + '</strong> · ' + escape(state.phase) +
111
+ '</p><p>Agent calls ' + (state.metrics?.calls || 0) + ' · elapsed agent seconds ' + Math.round((state.metrics?.agentMs || 0) / 1000) +
112
+ '</p><h2>Task checkpoints</h2><pre>' + escape(JSON.stringify(state.taskRuns||[],null,2)) + '</pre><h2>Agent routing</h2><pre>' + escape(JSON.stringify(activeRoutes,null,2)) + '</pre><h2>Business coverage</h2><pre>' + escape(JSON.stringify(business,null,2)) + '</pre><h2>Artifacts</h2><ul>' + links + '</ul><h2>Acceptance evidence</h2><ul>' + evidence +
113
+ '</ul><h2>Requirement coverage</h2><table><tr><th>Criterion</th><th>Tasks</th><th>Checks</th></tr>' + coverage +
114
+ '</table><h2>Stage history</h2><table><tr><th>Stage</th><th>Result</th><th>Agent</th><th>Model</th><th>Evidence</th></tr>' + rows + '</table></html>';
115
+ write(path.join(home, 'report.html'), html);
116
+ write(path.join(home, 'report.json'), JSON.stringify({ ...state, business, routing:activeRoutes, status: verdict }, null, 2));
117
+ return verdict;
118
+ }
119
+ function event(state, stage, status, detail = '', route = state) {
120
+ state.history.push({ at: new Date().toISOString(), stage, status, detail, agent: route.agent, model: route.model });
121
+ state.status = status;
122
+ save(state);
123
+ report(state);
124
+ console.log(stage + ' ' + status + ' ' + detail);
125
+ }
126
+ function context(state, stage) {
127
+ const pieces = [];
128
+ for (const name of fs.readdirSync(spec).sort()) {
129
+ if (name === 'questions.json') continue;
130
+ const full = path.join(spec, name);
131
+ if (fs.statSync(full).isFile()) pieces.push('FILE harness-spec/' + name + '\n' + fs.readFileSync(full, 'utf8'));
132
+ }
133
+ for (const name of ['AGENTS.md', 'CLAUDE.md', 'GEMINI.md']) {
134
+ const full = path.join(root, name);
135
+ if (fs.existsSync(full)) pieces.push('PROJECT INSTRUCTIONS ' + name + '\n' + fs.readFileSync(full, 'utf8'));
136
+ }
137
+ if (state.findings?.length) pieces.push('PRIOR REVIEW FINDINGS — re-evaluate against current artifacts; resolved findings do not block\n' + JSON.stringify(state.findings));
138
+ if (state.regressionChecks?.length) {
139
+ const supersessions=validateRegressionSupersessions(state);
140
+ pieces.push('EFFECTIVE ACCEPTANCE CONTRACT\nThe runner executes the immutable original checks.json and ALL registered additive regression checks on every verification, including superseded checks. Superseded checks remain frozen and visible for audit, but their named results do NOT count as behavioral evidence. A supersession needs a concrete reason, an independently passing replacement covering the same AC IDs, and a recorded source hash. Review the replacement assertions for quality. Do not demand editing a frozen check solely to repair its vacuity when a valid formal supersession exists.\n' + JSON.stringify({activeRegressionChecks:activeRegressionChecks(state),supersessions,allRegressionChecks:state.regressionChecks,coverage:state.coverage}));
141
+ }
142
+ const {lessons,superseded}=planReviewContext(root,state);
143
+ if(superseded.length)pieces.push('ARCHIVED SUPERSEDED REGRESSIONS\nThese original tests remain as historical artifacts and do not supply active acceptance evidence. Review their active replacements; do not require rewriting an archived test just to remove its historical vacuity. New behavioral defects remain actionable.\n'+JSON.stringify(superseded));
144
+ if (lessons.length) pieces.push('LESSONS FROM PRIOR REVIEWS — preserve previous fixes\n' + lessons.map(item => item.detail).join('\n'));
145
+ if (['repair','review-spec','review-quality'].includes(stage)) {
146
+ for (const check of state.checks || []) pieces.push('TEST ' + check.id + '\nEXECUTION '+JSON.stringify({code:check.code,timedOut:check.timedOut,error:check.error,signal:check.signal,durationMs:check.durationMs})+'\n' + fs.readFileSync(path.join(root, check.log), 'utf8').slice(-12000));
147
+ }
148
+ const cfg=config(),task=currentTask(state);
149
+ const taskChecks=task?allChecks(state).filter(check=>task.checks.includes(check.id)||check.inherited):(state.taskRuns?.length?allChecks(state):[]);
150
+ const productFocus=task?.files||(state.taskRuns?.flatMap(item=>item.files))||[];
151
+ const dependencies=task?(state.taskRuns||[]).filter(other=>task.dependsOn.includes(other.id)).flatMap(other=>other.files):[];
152
+ const source=buildContext(root,{focus:[...productFocus,...taskChecks.flatMap(check=>check.files),...dependencies,...(cfg.context?.focus||[])],budget:cfg.context?.budget||90000,focusChunk:60000});
153
+ write(path.join(home,'context-manifest.json'),JSON.stringify(source.manifest,null,2));
154
+ pieces.push(source.text);
155
+ if(task)pieces.push('CURRENT TASK ONLY\n'+JSON.stringify(task)+'\nImplement/review only this task. Its dependencies have accepted checkpoints.');
156
+ if(task)pieces.push('APPROVED NEW FILES NOT YET CREATED\n'+JSON.stringify(task.files.filter(name=>!fs.existsSync(relativeFile(root,name))))+'\nCreate these files from the approved specification; absence is expected, not missing source context.');
157
+ const inherited=inheritedChecks(root);if(inherited.length)pieces.push('INHERITED ACCEPTANCE OBLIGATIONS\n'+JSON.stringify(inherited));
158
+ const result = pieces.join('\n\n');
159
+ assert(result.length < 220000, 'Context exceeds budget. Split this change into smaller independently verifiable changes.');
160
+ return result;
161
+ }
162
+ async function ask(state, stage) {
163
+ checkpoint(state);
164
+ const cfg = config();
165
+ const route = cfg.routes[stage] || (stage.startsWith('review-') ? cfg.routes.review : null) || { agent: state.agent, model: state.model };
166
+ const contract = ['implementation','repair'].includes(stage) ? analyze(root) : null;
167
+ const frozen = [...(contract?.checks || []), ...(state.regressionChecks || []), ...inheritedChecks(root)].flatMap(check => check.files);
168
+ const input = context(state, stage);
169
+ const native=contract&&route.agent==='codex'&&cfg.codexMode==='workspace'?{frozen,allowed:currentTask(state)?.files||state.taskRuns?.flatMap(t=>t.files)}:null;
170
+ if(native)assert(Array.isArray(native.allowed)&&native.allowed.length,'Native workspace requires approved task files; use executionMode tasks');
171
+ const carry=state.contextCarry;
172
+ const reusable=carry&&carry.stage===stage&&carry.taskId===(currentTask(state)?.id||null)&&carry.sourceHash===snapshot(root);
173
+ let correction = reusable?carry.text:'';
174
+ if(!reusable)delete state.contextCarry;
175
+ for (let attempt = 0; attempt < 4; attempt++) {
176
+ enforceBudget(state);runCalls++;
177
+ const id = stage + '-' + randomUUID();
178
+ let prompt = 'You are a software delivery agent. CURRENT STAGE: ' + stage + '.\n' +
179
+ instructions[stage] + '\nWork only on the CURRENT STAGE, even if older conversation requests a broader outcome.\n' +
180
+ 'When domain.json is supplied, preserve confirmed business decisions, scope, actors and rules. Map its cases into requirements and checks; surface contradictions and unknowns instead of inventing business policy. Only planning may update it through the validated top-level domain field; product stages cannot change the business record.\n' +
181
+ 'Return ONLY JSON with shape {"summary":"...","questions":[],"ready":true,"approved":true,"findings":[],"files":[{"path":"relative/path","content":"full text"}]}. ' +
182
+ 'All file proposals must use forward slashes. File content must decode to normal source text with real newlines, not double-escaped newline characters. Do not write files directly, use subagents, run commands, commit, deploy or read active logs. ' +
183
+ 'The supplied context contains source and test results; report missing context explicitly. The harness validates and applies files.\n' +
184
+ correction + '\nCONTEXT\n' + input;
185
+ if(native)prompt='You are a software delivery agent. CURRENT STAGE: '+stage+'.\n'+instructions[stage]+'\n'+
186
+ 'NATIVE WORKSPACE MODE: You are in an isolated source snapshot. Read source and run local commands/tests here. Edit product files directly; the harness collects the actual diff. Do not commit, deploy, use subagents, change harness-spec, edit frozen acceptance tests, or access files outside this workspace. Do not change dependency installations or fetch network resources. No user configuration or credentials are needed. Generated ignored test outputs are discarded.\n'+
187
+ 'Allowed product files: '+JSON.stringify(native.allowed)+'\nFrozen acceptance files: '+JSON.stringify(frozen)+'\n'+
188
+ 'Return ONLY JSON {"summary":"...","files":[]}. If the environment blocks required tools, also return blocked:{category:"environment",reason:"actual tool error"}; do not claim implementation succeeded. Do not include file contents in final JSON. For repair, additive regressionTests metadata may be included as instructed above, but existing tests remain frozen. Read missing context using tools; do not return contextRequests.\n'+correction+'\nCONTEXT\n'+input;
189
+ state.metrics ||= { calls: 0, agentMs: 0 };
190
+ state.metrics.calls++;
191
+ event(state, stage, 'RUNNING', id, route);
192
+ const started = Date.now();
193
+ const before = snapshot(root);
194
+ let call;
195
+ try {
196
+ call = await invoke(root, route, prompt, cfg, id,native);
197
+ assert(before === snapshot(root), 'Source changed while the agent was running. Proposal mode requires a stable workspace; inspect concurrent edits and tool activity before retrying.');
198
+ const response = call.response;
199
+ if(response.contextRequests?.length){
200
+ assert(Array.isArray(response.contextRequests)&&response.contextRequests.length<=3,'At most 3 context requests');
201
+ assert(response.files.length===0,'Context request cannot also propose writes');
202
+ correction+='\nREQUESTED SOURCE RANGES\n'+JSON.stringify(response.contextRequests.map(r=>{
203
+ if(currentTask(state)?.files.includes(r.path)&&!fs.existsSync(relativeFile(root,r.path)))return {path:r.path,status:'not-created',instruction:'Approved new file: create it from the specification; no existing source to read.'};
204
+ return readSource(root,r.path,r.startLine||1,r.count||120,{allowAbsent:['discussion','requirements','design','tasks','analysis'].includes(stage)});
205
+ }));
206
+ assert(correction.length<100000,'Requested context too large');
207
+ state.contextCarry={stage,taskId:currentTask(state)?.id||null,sourceHash:before,text:correction};
208
+ state.metrics.agentMs += Date.now()-started;
209
+ event(state,stage,'CONTEXT_LOADED',response.contextRequests.map(r=>r.path).join(', '),route);continue;
210
+ }
211
+ if (stage === 'discussion') assert(Array.isArray(response.questions) && typeof response.ready === 'boolean', 'Discussion requires questions and ready');
212
+ if (stage === 'analysis' || stage.startsWith('review-')) assert(typeof response.approved === 'boolean' && Array.isArray(response.findings), 'Review requires approved and findings');
213
+ const additions = [];
214
+ assert(response.regressionTests === undefined || Array.isArray(response.regressionTests), 'regressionTests must be an array');
215
+ for (const test of response.regressionTests || []) {
216
+ assert(stage === 'repair', 'Regression additions belong to repair');
217
+ const base = contract.checks.find(check => check.id === test.baseCheck);
218
+ const {argv,entry}=deriveRegressionCommand(base,test.file);
219
+ assert(Array.isArray(test.criteria) && test.criteria.length && test.criteria.every(id => contract.trace.criteria.includes(id)), 'Regression criteria must reference approved AC IDs');
220
+ const file = relativeFile(root, test.file);
221
+ assert((test.file.startsWith('tests/') || test.file.startsWith('acceptance/')) && !fs.existsSync(file), 'Regression file must be new');
222
+ assert(response.files.some(proposal => proposal.path === test.file), 'Regression file content missing');
223
+ additions.push({id:'regression-' + ((state.regressionChecks?.length || 0) + additions.length + 1), argv, files:[test.file,...base.files.filter(file=>file!==entry)], timeoutMs:base.timeoutMs, criteria:test.criteria,evidence:test.evidence});
224
+ validateEvidence(additions.at(-1));
225
+ }
226
+ const task=currentTask(state);
227
+ const boundary=task?.files||(state.taskRuns?.flatMap(t=>t.files));
228
+ if(boundary&&['implementation','repair'].includes(stage))for(const file of response.files)assert(boundary.includes(file.path)||additions.some(a=>a.files.includes(file.path)),'File outside approved task boundary: '+file.path);
229
+ const proposed=domainProposals(stage,response);
230
+ applyFiles(root, stage, proposed, frozen);
231
+ if(response.domain!==undefined)state.domainRequired=true;
232
+ if (additions.length) {
233
+ state.regressionChecks = [...(state.regressionChecks || []), ...additions];
234
+ state.regressionHash = testDigest(root, state.regressionChecks);
235
+ for (const check of additions) for (const criterion of check.criteria) state.coverage.find(row => row.criterion === criterion)?.checks.push(check.id);
236
+ }
237
+ state.metrics.agentMs += Date.now() - started;
238
+ state.lastResponse = call.answer;
239
+ delete state.contextCarry;
240
+ if(call.result.native)state.lastNative=call.result.native;
241
+ event(state, stage, 'RECORDED', response.summary + ' | ' + call.answer, route);
242
+ return response;
243
+ } catch (error) {
244
+ state.metrics.agentMs += Date.now() - started;
245
+ if ((!call && !(error instanceof ResponseProtocolError)) || before !== snapshot(root)) throw error;
246
+ event(state, stage, 'INVALID_RESPONSE', error.message, route);
247
+ correction += '\nPrevious response rejected: ' + error.message + '. Correct the response and obey the allowed files for CURRENT STAGE.';
248
+ if (attempt === 3) throw error;
249
+ }
250
+ }
251
+ throw new Error('Context/response retry limit reached');
252
+ }
253
+ async function verify(state, baseline = false, task = null) {
254
+ checkpoint(state);
255
+ checkObligations(root);
256
+ const checks = allChecks(state).filter(c=>!task||c.inherited||task.checks.includes(c.id)||(state.regressionChecks||[]).some(r=>r.id===c.id));
257
+ event(state, baseline ? 'baseline' : 'verification', 'RUNNING', 'Executing ' + checks.length + ' checks; previous results are historical until this verification finishes.');
258
+ const before = snapshot(root), environmentBefore=environmentFingerprint(root,config()), results = [];
259
+ for (const check of checks) {
260
+ const result = await execute(check.argv, check.timeoutMs || 120000,
261
+ path.join(home, 'logs', check.id + '-' + randomUUID() + '.log'), root);
262
+ let evidence;try{evidence=evidenceFor(root,check,result);}catch(error){evidence={valid:false,level:'unverified',gaps:[error.message],tests:[]};}
263
+ results.push({ id: check.id, inherited:Boolean(check.inherited), ...result,evidence });
264
+ }
265
+ state.checks = results;
266
+ const repairTimeouts=Boolean(config().repairTestTimeouts);
267
+ const blocked = results.some(result => result.error || (result.timedOut&&!repairTimeouts) || (result.code === null&&!result.timedOut));
268
+ const status = blocked || before !== snapshot(root) || environmentBefore!==environmentFingerprint(root,config()) ? 'BLOCKED' : results.some(result => result.timedOut || result.code !== 0) ? 'FAIL' : results.some(result=>!result.evidence.valid)?'BLOCKED':'PASS';
269
+ state.verifiedHash = status === 'PASS' && !baseline ? before : null;
270
+ state.verifiedEnvironmentHash=status==='PASS'&&!baseline?environmentFingerprint(root,config()):null;
271
+ event(state, baseline ? 'baseline' : 'verification', status, JSON.stringify(results));
272
+ return status;
273
+ }
274
+ function approved(state) {
275
+ checkObligations(root);
276
+ const plan = analyze(root);
277
+ const business=inspectDomain(root,plan,state.domainRequired);
278
+ assert(business.ready,'Business coverage blocked: '+business.gaps.join('; '));
279
+ assert(state.contractHash === contractDigest(root) && state.testsHash === testDigest(root, [...plan.checks,...inheritedChecks(root)]),
280
+ 'Approved specification or tests changed. Replan and approve the revised contract.');
281
+ if (state.regressionChecks?.length) assert(state.regressionHash === testDigest(root, state.regressionChecks), 'Frozen regression tests changed');
282
+ validateRegressionSupersessions(state);
283
+ return plan;
284
+ }
285
+ async function run(state) {
286
+ const cfg = config();
287
+ if (state.phase === 'discussion') {
288
+ const response = await ask(state, 'discussion');
289
+ if (response.questions.length || !response.ready) {
290
+ write(path.join(spec, 'questions.json'), JSON.stringify(response.questions, null, 2));
291
+ event(state, 'discussion', 'WAITING_INPUT', response.questions.join(' | '));
292
+ return;
293
+ }
294
+ state.phase = 'requirements';
295
+ save(state);
296
+ }
297
+ let planningRepairs=0;
298
+ while (['requirements','design','tasks','analysis'].includes(state.phase)) {
299
+ const stage=state.phase;
300
+ const response = await ask(state, stage);
301
+ if (stage === 'analysis') {
302
+ if (!response.approved || response.findings.length) {
303
+ state.findings = response.findings;
304
+ const domain=fs.existsSync(path.join(spec,'domain.json'))?readJson(path.join(spec,'domain.json')):null;
305
+ const unknown=domain?.questions.some(q=>q.blocking&&!q.resolution)||domain?.decisions.some(d=>d.status==='proposed');
306
+ if(['design','tasks'].includes(response.replanStage)&&!unknown){
307
+ state.phase=response.replanStage;event(state,stage,'PLANNING_REPAIR',JSON.stringify({stage:state.phase,findings:response.findings}));
308
+ if(++planningRepairs>=cfg.maxAttempts){event(state,'plan','BUDGET_EXHAUSTED','Planning correction budget reached; review findings before resuming');return;}
309
+ continue;
310
+ }
311
+ event(state, stage, 'NEEDS_REPLAN', JSON.stringify(response.findings));
312
+ return;
313
+ }
314
+ let plan;
315
+ try{plan=analyze(root);}catch(error){
316
+ if(!error.message.startsWith('Unfrozen test dependency:'))throw error;
317
+ state.findings=[error.message];state.phase='tasks';event(state,stage,'PLANNING_REPAIR',error.message);
318
+ if(++planningRepairs>=cfg.maxAttempts){event(state,'plan','BUDGET_EXHAUSTED','Planning correction budget reached');return;}
319
+ continue;
320
+ }
321
+ state.coverage = plan.coverage;
322
+ state.taskOrder = plan.order;
323
+ const business=inspectDomain(root,plan,state.domainRequired);
324
+ if(!business.ready){
325
+ state.findings=business.gaps.map(gap=>'Deterministic business gate: '+gap);
326
+ const domain=fs.existsSync(path.join(spec,'domain.json'))?readJson(path.join(spec,'domain.json')):null;
327
+ const unknown=domain?.questions.some(q=>q.blocking&&!q.resolution)||domain?.decisions.some(d=>d.status==='proposed');
328
+ if(unknown){event(state,stage,'NEEDS_REPLAN',JSON.stringify(state.findings));return;}
329
+ state.phase='analysis';event(state,stage,'PLANNING_REPAIR',JSON.stringify(state.findings));
330
+ if(++planningRepairs>=cfg.maxAttempts){event(state,'plan','BUDGET_EXHAUSTED','Business mapping correction budget reached');return;}
331
+ continue;
332
+ }
333
+ state.findings=[];
334
+ } else assert(fs.existsSync(path.join(spec, stage + '.md')), 'Missing artifact: ' + stage);
335
+ state.phase = stages[stages.indexOf(stage) + 1];
336
+ save(state);
337
+ }
338
+ if (state.phase === 'approval') {
339
+ event(state, 'plan', 'WAITING_APPROVAL', 'Review requirements, tasks, coverage and executable checks before approve.');
340
+ return;
341
+ }
342
+ approved(state);
343
+ if (state.phase === 'complete' && state.evidenceVersion===1 && !freshness(state)) {
344
+ event(state, 'acceptance', 'PASS', 'Evidence matches source');
345
+ return;
346
+ }
347
+ if (state.phase === 'complete') state.phase = currentTask(state)?'implementation':'verification';
348
+ if (state.phase === 'review') state.phase = 'review-spec'; // v0.2 persisted checkpoint.
349
+ if (state.phase.startsWith('review-') && (state.verifiedHash !== snapshot(root)||state.verifiedEnvironmentHash!==environmentFingerprint(root,config()))) {
350
+ state.phase = 'verification';
351
+ event(state, 'verification', 'STALE', 'Source changed since test evidence, or evidence predates verified snapshots. Re-running checks.');
352
+ }
353
+ let attempts = 0;
354
+ while (attempts < cfg.maxAttempts) {
355
+ attempts++;
356
+ enforceBudget(state);
357
+ const task=currentTask(state);
358
+ const attemptSource = snapshot(root);
359
+ if(task){assert(task.dependsOn.every(id=>state.taskRuns.find(t=>t.id===id)?.status==='accepted'),'Task dependency not accepted');task.status='running';save(state);}
360
+ if (state.phase === 'implementation' || state.phase === 'repair') {
361
+ await ask(state, state.phase);
362
+ approved(state);
363
+ state.phase = 'verification';
364
+ save(state);
365
+ }
366
+ if (state.phase === 'verification') {
367
+ const verdict = await verify(state,false,task);
368
+ if (verdict === 'BLOCKED') { state.phase = 'verification'; save(state); return; }
369
+ if (verdict === 'FAIL') {
370
+ state.phase = 'repair';
371
+ state.noProgress = attemptSource === snapshot(root) ? (state.noProgress || 0) + 1 : 0;
372
+ if (state.noProgress >= 2) { event(state, 'loop', 'NO_PROGRESS', 'Repeated failure without source changes'); return; }
373
+ save(state);
374
+ continue;
375
+ }
376
+ state.phase = 'review-spec';
377
+ save(state);
378
+ }
379
+ let rejected = false;
380
+ for (const stage of ['review-spec','review-quality']) {
381
+ if (state.phase !== stage) continue;
382
+ const before = snapshot(root), response = await ask(state, stage);
383
+ assert(before === snapshot(root), 'Review changed source');
384
+ if (!response.approved || response.findings.length) {
385
+ state.findings = response.findings;
386
+ state.phase = 'repair';
387
+ event(state, stage, 'FAIL', JSON.stringify(response.findings));
388
+ rejected = true;
389
+ break;
390
+ }
391
+ state.phase = stage === 'review-spec' ? 'review-quality' : 'complete';
392
+ save(state);
393
+ }
394
+ if (rejected) {
395
+ state.noProgress = attemptSource === snapshot(root) ? (state.noProgress || 0) + 1 : 0;
396
+ if (state.noProgress >= 2) { event(state, 'loop', 'NO_PROGRESS', 'Repeated review rejection without source changes'); return; }
397
+ continue;
398
+ }
399
+ assert(state.phase === 'complete', 'Invalid execution checkpoint');
400
+ approved(state);
401
+ if(task){
402
+ task.status='accepted';task.acceptedAt=new Date().toISOString();task.evidence=state.checks;task.sourceHash=snapshot(root);
403
+ // Persist task acceptance with the NEXT executable phase, never an interim complete phase.
404
+ state.phase=currentTask(state)?'implementation':'verification';
405
+ event(state,'task','ACCEPTED',task.id);
406
+ if(currentTask(state)){state.phase='implementation';state.noProgress=0;save(state);continue;}
407
+ const finalVerification=await verify(state);
408
+ if(finalVerification==='FAIL'){state.phase='repair';event(state,'integration','FAIL','Integrated checks failed; repairing with all accepted task evidence.');continue;}
409
+ if(finalVerification!=='PASS'){state.phase='verification';event(state,'integration','BLOCKED','Integrated check execution/evidence unavailable.');return;}
410
+ let integrationRejected=false;
411
+ for(const review of ['review-spec','review-quality']){
412
+ state.phase=review;save(state);
413
+ const response=await ask(state,review);
414
+ if(!response.approved||response.findings.length){state.findings=response.findings;state.phase='repair';event(state,'integration','FAIL',JSON.stringify(response.findings));integrationRejected=true;break;}
415
+ }
416
+ if(integrationRejected)continue;
417
+ state.phase='complete';
418
+ }
419
+ if(state.verifiedHash!==snapshot(root)||state.verifiedEnvironmentHash!==environmentFingerprint(root,config())){
420
+ state.phase='verification';event(state,'verification','STALE','Evidence changed during review; verify again.');continue;
421
+ }
422
+ state.sourceHash = snapshot(root);
423
+ state.environmentHash=environmentFingerprint(root,config());state.evidenceVersion=1;
424
+ state.findings = [];
425
+ state.noProgress = 0;
426
+ event(state, 'acceptance', 'PASS', 'All checks passed with specification and quality reviews');
427
+ return;
428
+ }
429
+ event(state, 'loop', 'BUDGET_EXHAUSTED', 'Resume run explicitly or switch agent/model');
430
+ }
431
+ function archive(state, request) {
432
+ assert(state.phase === 'complete' && report(state) === 'PASS', 'Finish and verify the current change first');
433
+ const id = new Date().toISOString().replace(/[:.]/g, '-') + '-' + randomUUID().slice(0,6);
434
+ const retained=carryObligations(root,carryableChecks(state,allChecks(state)),id);
435
+ const target = path.join(home, 'archive', id);
436
+ for (const name of fs.readdirSync(spec)) assert(fs.lstatSync(path.join(spec, name)).isFile(), 'Specification must contain ordinary files');
437
+ fs.mkdirSync(target, { recursive: true });
438
+ fs.cpSync(spec, path.join(target, 'spec'), { recursive: true });
439
+ write(path.join(target, 'state.json'), JSON.stringify(state, null, 2));
440
+ const older = path.join(spec, 'baseline.md');
441
+ const baseline = (fs.existsSync(older) ? fs.readFileSync(older, 'utf8') + '\n\n' : '') + fs.readFileSync(path.join(spec, 'requirements.md'), 'utf8');
442
+ write(path.join(home, 'pending-change.json'), JSON.stringify({ id }));
443
+ for (const name of fs.readdirSync(spec)) {
444
+ const file = path.join(spec, name);
445
+ assert(fs.lstatSync(file).isFile(), 'Unexpected directory in current specification');
446
+ fs.unlinkSync(file);
447
+ }
448
+ write(path.join(spec,'obligations.json'),JSON.stringify(retained,null,2));
449
+ write(path.join(spec, 'baseline.md'), '# Previously accepted behavior\n\n' + baseline);
450
+ write(path.join(spec, 'conversation.md'), '# Requested change\n\n' + request + '\n');
451
+ const previousDomain=path.join(target,'spec/domain.json');
452
+ if(fs.existsSync(previousDomain)) {
453
+ const domain=readJson(previousDomain);
454
+ domain.questions.push({id:'change-review-'+id,question:'Reconcile the requested change with previous scope, rules and regression cases: '+request,blocking:true,resolution:'',source:''});
455
+ write(path.join(spec,'domain.json'),JSON.stringify(domain,null,2));
456
+ }
457
+ const next = { version: 3, title: request, phase: 'discussion', status: 'NEW', agent: state.agent, model: state.model, previous: id, history: [], metrics: { calls: 0, agentMs: 0 } };
458
+ next.domainRequired=Boolean(state.domainRequired || fs.existsSync(previousDomain));
459
+ save(next);
460
+ fs.unlinkSync(path.join(home, 'pending-change.json'));
461
+ return next;
462
+ }
463
+ function recoverChange() {
464
+ const journal = path.join(home, 'pending-change.json');
465
+ if (!fs.existsSync(journal)) return;
466
+ const { id } = readJson(journal);
467
+ assert(typeof id === 'string' && /^[\w-]+$/.test(id), 'Invalid pending change ID');
468
+ const archive = path.join(home, 'archive', id);
469
+ for (const name of fs.readdirSync(spec)) {
470
+ const file = relativeFile(root, 'harness-spec/' + name);
471
+ assert(fs.lstatSync(file).isFile(), 'Unexpected path in interrupted change');
472
+ fs.unlinkSync(file);
473
+ }
474
+ for (const name of fs.readdirSync(path.join(archive, 'spec'))) {
475
+ const file = relativeFile(root, '.harness/archive/' + id + '/spec/' + name);
476
+ write(relativeFile(root, 'harness-spec/' + name), fs.readFileSync(file));
477
+ }
478
+ write(stateFile, fs.readFileSync(path.join(archive, 'state.json')));
479
+ fs.unlinkSync(journal);
480
+ }
481
+ function importSpec(source) {
482
+ const folder = path.resolve(source);
483
+ assert(fs.statSync(folder).isDirectory(), 'Import expects a specification folder');
484
+ const content = [];
485
+ function scan(directory, depth) {
486
+ assert(depth < 8, 'Specification nesting too deep');
487
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
488
+ if (entry.isSymbolicLink() || entry.name.startsWith('.')) continue;
489
+ const full = path.join(directory, entry.name);
490
+ if (entry.isDirectory()) scan(full, depth + 1);
491
+ else if (entry.name.endsWith('.md')) content.push('## ' + path.relative(folder, full) + '\n\n' + fs.readFileSync(full, 'utf8'));
492
+ }
493
+ }
494
+ scan(folder, 0);
495
+ assert(content.length && content.join('').length < 150000, 'Import must contain Markdown within 150k characters');
496
+ write(path.join(spec, 'imported-spec.md'), content.join('\n\n'));
497
+ }
498
+ const help = [
499
+ 'TeImMo — The Immortal Moon (sddh remains a CLI alias)',
500
+ 'teimmo setup [idea] (initialize discovery, business record and project skills; safe to rerun)',
501
+ 'sddh new <idea> | discuss <answer> | run | approve | replan | status',
502
+ 'sddh switch <agent> [model] | route <stage|review> <agent> [model]',
503
+ 'sddh analyze | change <request> | import <spec-folder> | pause | recover | recheck',
504
+ 'sddh doctor [agent] (check executable availability; does not prove authentication)',
505
+ 'teimmo skills install | context | domain template|init|save <json-file>|check',
506
+ 'teimmo source <path> [start-line] [count] | context-manifest [focus-path...]',
507
+ 'teimmo obligations [retire <id> <impact reason>]',
508
+ 'teimmo regressions supersede <old-id> <replacement-id> <reason> (frozen audit record)',
509
+ 'teimmo adopt-plan (validate an authored plan, then require agent analysis and approval)',
510
+ 'teimmo serve [port] (read-only local dashboard; default chooses a free port)',
511
+ 'Start at the project Git root or in a new empty folder. Results: .harness/report.html'
512
+ ].join('\n');
513
+ async function main() {
514
+ const [command, ...args] = process.argv.slice(2);
515
+ if (!command || command === '--help') { console.log(help); return; }
516
+ if(command==='serve') {
517
+ assert(args.length<=1,'Use serve [port]');
518
+ const port=args.length?Number(args[0]):0;
519
+ const {startDashboard}=await import('./dashboard.mjs');
520
+ const dashboard=await startDashboard(root,{port});
521
+ console.log(JSON.stringify({url:dashboard.url}));
522
+ await new Promise((resolve,reject)=>{
523
+ let stopping=false;
524
+ const stop=()=>{
525
+ if(stopping)return;
526
+ stopping=true;
527
+ process.off('SIGINT',stop);
528
+ process.off('SIGTERM',stop);
529
+ dashboard.close().then(resolve,reject);
530
+ };
531
+ process.once('SIGINT',stop);
532
+ process.once('SIGTERM',stop);
533
+ });
534
+ return;
535
+ }
536
+ if(command==='domain'&&args[0]==='template'){console.log(JSON.stringify(domainTemplate(),null,2));return;}
537
+ if(command==='skills'&&args[0]!=='install'){console.log(skillNames.join('\n'));return;}
538
+ if(command==='source'){console.log(JSON.stringify(readSource(root,args[0],Number(args[1]||1),Number(args[2]||120)),null,2));return;}
539
+ if(command==='context-manifest'){console.log(JSON.stringify(buildContext(root,{focus:args}).manifest,null,2));return;}
540
+ if(command==='context') {
541
+ const current=readJson(stateFile),domainFile=path.join(spec,'domain.json');
542
+ let plan=null,planError=null;try{plan=analyze(root);}catch(error){planError=error.message;}
543
+ const documents={};
544
+ for(const name of ['conversation.md','brief.md','requirements.md','design.md','tasks.md','baseline.md']) {
545
+ const file=path.join(spec,name);if(fs.existsSync(file))documents[name]=fs.readFileSync(file,'utf8');
546
+ }
547
+ console.log(JSON.stringify({title:current.title,phase:current.phase,status:verdictOf(current),routing:routing(current),planError,domain:fs.existsSync(domainFile)?readJson(domainFile):null,business:inspectDomain(root,plan,current.domainRequired),documents,taskRuns:current.taskRuns||[],obligations:obligations(root),approvalReceipt:current.approvalReceipt||null,findings:current.findings||[],checks:current.checks||[],recentEvents:current.history.slice(-8),instruction:'Load before continuing a chat or switching agents. A missing/unresolved decision is not consent. Structural case coverage does not prove all business cases.'},null,2));
548
+ return;
549
+ }
550
+ if (command === 'doctor') {
551
+ const cfg = fs.existsSync(path.join(home, 'config.json')) ? readJson(path.join(home, 'config.json')) : {};
552
+ const results = [];
553
+ for (const agent of args.length ? args : ['codex','antigravity']) {
554
+ const command = cfg.executables?.[agent] || agentCommand(agent, null, '', cfg.adapters || {})[0];
555
+ const probe = spawnSync(command, ['--version'], {encoding:'utf8',timeout:15000,windowsHide:true,shell:false});
556
+ results.push({agent,command,available:probe.status===0,version:probe.stdout?.trim() || '',error:probe.error?.message || probe.stderr?.trim() || null,authentication:'NOT_CHECKED'});
557
+ }
558
+ console.log(JSON.stringify(results,null,2));
559
+ if (results.some(result=>!result.available)) process.exitCode=1;
560
+ return;
561
+ }
562
+ if (['init','verify','handoff'].includes(command)) {
563
+ assert(fs.existsSync(fileURLToPath(new URL('./legacy.mjs',import.meta.url))),'Legacy cc-sdd workflow is source-only. Use teimmo new for the core harness workflow.');
564
+ const result = spawnSync(process.execPath, [fileURLToPath(new URL('./legacy.mjs', import.meta.url)), command, ...args], { stdio: 'inherit' });
565
+ process.exitCode = result.status || 0;
566
+ return;
567
+ }
568
+ // Inspection must also work in a host's read-only skill session. Do not
569
+ // acquire locks, recover journals or regenerate reports just to read status.
570
+ if (command === 'status') {
571
+ const current = readJson(stateFile), lock = path.join(home, 'lock');
572
+ let lockOwner;
573
+ try { lockOwner=fs.readFileSync(lock,'utf8').trim(); }
574
+ catch(error) { if(error.code!=='ENOENT')throw error; }
575
+ console.log(JSON.stringify({...current,routing:routing(current),status:verdictOf(current),...(lockOwner===undefined?{}:{lockOwner})},null,2));
576
+ return;
577
+ }
578
+ relativeFile(root, '.harness');
579
+ fs.mkdirSync(home, { recursive: true });
580
+ if (command === 'pause') {
581
+ assert(fs.existsSync(stateFile), 'Initialize a project first');
582
+ write(path.join(home, 'pause.request'), new Date().toISOString());
583
+ console.log('Pause requested for the next stage boundary');
584
+ return;
585
+ }
586
+ const lock = path.join(home, 'lock');
587
+ if (command === 'recover' && fs.existsSync(lock)) {
588
+ const pid = Number(fs.readFileSync(lock, 'utf8'));
589
+ assert(Number.isInteger(pid) && pid > 0, 'Invalid lock PID; inspect manually');
590
+ let alive = true;
591
+ try { process.kill(pid, 0); } catch (error) { if (error.code === 'ESRCH') alive = false; }
592
+ assert(!alive, 'Lock owner still exists or cannot be checked');
593
+ fs.unlinkSync(lock);
594
+ }
595
+ const fd = fs.openSync(lock, 'wx');
596
+ fs.writeFileSync(fd, String(process.pid));
597
+ let state;
598
+ try {
599
+ relativeFile(root, 'harness-spec');
600
+ if(command==='setup')assert(!fs.readdirSync(home).some(name=>name.startsWith('pending-')),'Pending transaction found; inspect and recover before setup');
601
+ else { recoverChange(); recoverWrites(root); recoverReplan(root); }
602
+ if(command==='skills'){console.log(JSON.stringify(installSkills(root),null,2));return;}
603
+ if (command === 'new' || command === 'setup') {
604
+ const setup=command==='setup',created=!fs.existsSync(stateFile);
605
+ assert(setup||created, 'Already initialized');
606
+ assert(setup||args.join(' ').trim(), 'Provide an idea');
607
+ const git = spawnSync('git', ['rev-parse','--show-toplevel'], { encoding: 'utf8' });
608
+ if (git.status === 0) {
609
+ // Windows short names and macOS /var aliases can name the same directory
610
+ // differently. Compare filesystem identity, not a spelling of the path.
611
+ const gitRoot=fs.statSync(git.stdout.trim(),{bigint:true}),cwd=fs.statSync(root,{bigint:true});
612
+ assert(gitRoot.ino!==0n&&cwd.ino!==0n,'Cannot identify Git root on this filesystem');
613
+ assert(gitRoot.dev===cwd.dev&&gitRoot.ino===cwd.ino,'Run at Git root');
614
+ }
615
+ else assert(spawnSync('git', ['init','-q']).status === 0, 'Git init failed');
616
+ if(created){
617
+ assert(!fs.existsSync(spec), 'Existing harness-spec folder found; preserve it and use an empty workspace for new initialization');
618
+ assert(!fs.existsSync(path.join(home,'config.json')),'Existing local config without state; preserve it and restore the project before setup');
619
+ const idea=args.join(' ').trim();
620
+ write(path.join(home, '.gitignore'), '*\n');
621
+ write(path.join(spec, 'conversation.md'), idea?'# Idea\n\n'+idea+'\n':'# Discovery\n\nNo product idea has been supplied. Ask the user through brainstorm before defining product scope or business decisions.\n');
622
+ write(path.join(spec,'WORKSPACE.md'),workspaceGuide);
623
+ write(path.join(home, 'config.json'), JSON.stringify({ maxAttempts: 5, agentTimeoutMs: 900000, repairTestTimeouts:true, stageFolders:true, maxCallsPerRun:30, maxRunMs:1800000, executionMode:'tasks', adapters: {}, routes: {} }, null, 2));
624
+ state = { version: 3, title: idea||'Project discovery: '+path.basename(root), phase: 'discussion', status: 'NEW', agent: 'codex', model: null, history: [], metrics: { calls: 0, agentMs: 0 } };
625
+ save(state); report(state);
626
+ }else state=readJson(stateFile);
627
+ if(!setup)return;
628
+ let domain='preserved';const domainFile=path.join(spec,'domain.json');
629
+ if(!fs.existsSync(domainFile)&&state.phase==='discussion'&&!state.contractHash){
630
+ write(domainFile,JSON.stringify(domainTemplate(),null,2));state.domainRequired=true;save(state);report(state);domain='initialized';
631
+ }else if(!fs.existsSync(domainFile))domain='not enabled: preserve current contract';
632
+ const skills=installSkills(root);
633
+ console.log(JSON.stringify({ready:true,created,domain,skills,ideaApplied:created&&Boolean(args.join(' ').trim()),next:{codex:'$teimmo-brainstorm',antigravity:'/teimmo-brainstorm'},note:'Open this project in your agent; reload skills or start a new chat. No model was called and no plan was approved.'},null,2));return;
634
+ }
635
+ state = readJson(stateFile);
636
+ if(command==='regressions'){
637
+ if(!args.length){console.log(JSON.stringify({checks:state.regressionChecks||[],supersessions:validateRegressionSupersessions(state)},null,2));return;}
638
+ assert(args[0]==='supersede'&&args[1]&&args[2],'Use regressions supersede <old-id> <replacement-id> <reason>');
639
+ assert(['repair','verification','review-spec','review-quality'].includes(state.phase),'Supersede only during active implementation review');
640
+ approved(state);
641
+ const entry=supersedeRegression(state,args[1],args[2],args.slice(3).join(' '),snapshot(root));
642
+ for(const row of state.coverage||[])row.checks=row.checks.filter(id=>id!==entry.from);
643
+ state.phase='review-spec';state.noProgress=0;
644
+ event(state,'regressions','SUPERSEDED',entry.from+' -> '+entry.to+' | '+entry.reason);
645
+ console.log(JSON.stringify(entry,null,2));return;
646
+ }
647
+ if(command==='obligations'){
648
+ if(args[0]==='retire'){assert(['discussion','requirements','design','tasks','analysis','approval'].includes(state.phase),'Retire only during planning');console.log(JSON.stringify(retireObligation(root,args[1],args.slice(2).join(' ')),null,2));event(state,'obligations','RETIRED',args[1]);}
649
+ else console.log(JSON.stringify(obligations(root),null,2));return;
650
+ }
651
+ if(command==='domain') {
652
+ const filename=path.join(spec,'domain.json');
653
+ if(args[0]==='check') {
654
+ let plan=null;if(fs.existsSync(path.join(spec,'traceability.json')))plan=analyze(root);
655
+ const result=inspectDomain(root,plan,state.domainRequired);console.log(JSON.stringify(result,null,2));
656
+ if(!result.ready)process.exitCode=1;return;
657
+ }
658
+ assert(['discussion','requirements','design','tasks','analysis','approval'].includes(state.phase),'Business contract frozen; reopen planning before changing it');
659
+ if(args[0]==='init') {
660
+ assert(!fs.existsSync(filename),'Domain record already exists; read context before editing');
661
+ write(filename,JSON.stringify(domainTemplate(),null,2));
662
+ } else {
663
+ assert(args[0]==='save'&&args[1],'Use domain save <json-file>');
664
+ const text=fs.readFileSync(path.resolve(args[1]),'utf8');assert(text.length<100000,'Business record exceeds 100k characters');
665
+ write(filename,JSON.stringify(validateDomain(JSON.parse(text.replace(/^\uFEFF/,''))),null,2));
666
+ }
667
+ state.domainRequired=true;event(state,'domain','RECORDED','Business record saved; run domain check for gaps');return;
668
+ }
669
+ if (command === 'recover') { event(state, 'recovery', 'READY', 'Interrupted file transaction rolled back; resume run'); return; }
670
+ if (command === 'switch' || command === 'route') {
671
+ const offset = command === 'route' ? 1 : 0;
672
+ if (offset) assert(Object.hasOwn(instructions, args[0]) || args[0] === 'review', 'Unknown routing stage');
673
+ const route = { agent: args[offset], model: args[offset+1] || null };
674
+ const inheritDefault = offset && route.agent === 'default';
675
+ if (!inheritDefault) agentCommand(route.agent, route.model, 'probe', config().adapters);
676
+ if (offset) {
677
+ const cfg = config();
678
+ if (inheritDefault) delete cfg.routes[args[0]];
679
+ else cfg.routes[args[0]] = route;
680
+ write(path.join(home, 'config.json'), JSON.stringify(cfg, null, 2));
681
+ } else Object.assign(state, route);
682
+ // Routing updates retain the current execution verdict.
683
+ state.noProgress=0; // An explicit strategy change grants a new bounded repair attempt.
684
+ state.history.push({ at: new Date().toISOString(), stage: 'routing', status: 'CHANGED', detail: command + ' ' + args.join(' '), ...route });
685
+ save(state); report(state); return;
686
+ }
687
+ if (command === 'import') {
688
+ assert(state.phase === 'discussion', 'Import before planning; reopen discussion with replan');
689
+ assert(args[0], 'Specify an OpenSpec change, Spec Kit feature or Markdown specification directory');
690
+ importSpec(args[0]); event(state,'import','RECORDED',path.resolve(args[0])); return;
691
+ }
692
+ if (command === 'change') {
693
+ assert(args.join(' ').trim(), 'Describe the next change');
694
+ state = archive(state, args.join(' ')); save(state); report(state); return;
695
+ }
696
+ if (command === 'replan') {
697
+ if(state.contractHash){
698
+ approved(state);
699
+ state=reopenPlan(root,state,carryableChecks(state,allChecks(state)));
700
+ save(state);report(state);return;
701
+ }
702
+ state.phase = 'discussion'; state.contractHash = null; state.testsHash = null;
703
+ state.taskRuns=null;state.approvalReceipt=null;state.verifiedHash=null;
704
+ event(state, 'plan', 'REOPENED'); return;
705
+ }
706
+ if (command === 'analyze') {
707
+ const plan = analyze(root); state.coverage = plan.coverage; state.taskOrder = plan.order;
708
+ save(state); report(state); console.log(JSON.stringify(plan, null, 2)); return;
709
+ }
710
+ if(command==='adopt-plan'){
711
+ assert(['discussion','requirements','design','tasks','analysis'].includes(state.phase),'Adopt a plan only before approval');
712
+ const plan=analyze(root);state.coverage=plan.coverage;state.taskOrder=plan.order;
713
+ state.phase='analysis';event(state,'plan','IMPORTED','Existing plan validated; agent analysis and explicit approval still required');return;
714
+ }
715
+ if (command === 'approve') {
716
+ assert(state.phase === 'approval', 'Plan must reach approval first');
717
+ const plan = analyze(root);
718
+ const business=inspectDomain(root,plan,state.domainRequired);
719
+ assert(business.ready,'Business coverage blocked: '+business.gaps.join('; '));
720
+ state.contractHash = contractDigest(root);
721
+ checkObligations(root);
722
+ state.testsHash = testDigest(root, [...plan.checks,...inheritedChecks(root)]);
723
+ state.approvalReceipt={version:1,at:new Date().toISOString(),contractHash:state.contractHash,testsHash:state.testsHash,mechanism:'explicit-cli-action',identityVerified:false};
724
+ if(config().executionMode==='tasks'){
725
+ assert(plan.trace.tasks.every(t=>t.files?.length&&t.checks?.length),'Task execution needs files and checks for every task');
726
+ state.taskRuns=plan.order.map(id=>({...plan.trace.tasks.find(t=>t.id===id),status:'pending'}));
727
+ } else state.taskRuns=null;
728
+ state.regressionChecks ||= []; state.regressionHash = state.regressionChecks.length?testDigest(root,state.regressionChecks):null;
729
+ state.coverage = plan.coverage; state.taskOrder = plan.order;
730
+ save(state);
731
+ const baseline = await verify(state, true);
732
+ if (baseline === 'BLOCKED') { process.exitCode = 1; return; }
733
+ state.phase = 'implementation';
734
+ event(state, 'plan', 'APPROVED', 'Contract frozen, baseline recorded'); return;
735
+ }
736
+ if (command === 'recheck') {
737
+ approved(state);
738
+ state.phase = 'verification';
739
+ save(state);
740
+ } else if (command === 'discuss') {
741
+ assert(state.phase === 'discussion' && args.length, 'Answer during discussion, or replan to reopen');
742
+ fs.appendFileSync(path.join(spec, 'conversation.md'), '\n## User\n\n' + args.join(' ') + '\n');
743
+ } else assert(command === 'run', help);
744
+ await run(state);
745
+ if (['BLOCKED','BUDGET_EXHAUSTED','NO_PROGRESS','NEEDS_REPLAN'].includes(state.status)) process.exitCode = 1;
746
+ } catch (error) {
747
+ if (error instanceof PauseRequested) return;
748
+ if (error instanceof BudgetReached) {process.exitCode=1;return;}
749
+ if (state && command!=='setup') event(state, state.phase, 'BLOCKED', error.message);
750
+ throw error;
751
+ } finally {
752
+ fs.closeSync(fd); fs.unlinkSync(lock);
753
+ }
754
+ }
755
+ if (process.argv[1] && fs.existsSync(process.argv[1]) && fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url))) {
756
+ main().catch(error => { console.error(error.message); process.exitCode = 1; });
757
+ }