@aibyzero/cm-workflow 0.19.0 → 0.20.0
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/.codex-plugin/plugin.json +1 -1
- package/AGENTS.md +8 -0
- package/CHANGELOG.md +8 -0
- package/README.md +8 -1
- package/VERSION +1 -1
- package/docs/architecture.md +3 -0
- package/docs/cm-acceptance-completion.md +185 -0
- package/docs/installation.md +1 -1
- package/package.json +1 -1
- package/runtime/js/autonomy.mjs +159 -3
- package/runtime/js/check-coverage.mjs +130 -0
- package/runtime/js/cm-ai/acceptance-contract.mjs +252 -0
- package/runtime/js/cm-ai/claude-developer-proposal.schema.json +18 -0
- package/runtime/js/cm-ai/cm-ai-admission.mjs +14 -6
- package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +10 -6
- package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +8 -3
- package/runtime/js/cm-ai/codex-developer-basic-output.schema.json +1 -1
- package/runtime/js/cm-ai/codex-developer-output.schema.json +1 -1
- package/runtime/js/cm-ai/completion-summary.mjs +187 -0
- package/runtime/js/cm-ai/control-policy.mjs +3 -1
- package/runtime/js/cm-ai/delivery-evidence.mjs +173 -0
- package/runtime/js/cm-ai/developer-adapter.mjs +4 -0
- package/runtime/js/cm-ai/drive-core.mjs +6 -2
- package/runtime/js/cm-ai/durable-runner-state.mjs +2 -2
- package/runtime/js/cm-ai/gate-bridge.mjs +13 -1
- package/runtime/js/cm-ai/host-conversation-execution.mjs +26 -14
- package/runtime/js/cm-ai/host-progress.mjs +2 -1
- package/runtime/js/cm-ai/log-rows.mjs +3 -2
- package/runtime/js/cm-ai/operator-guidance.mjs +110 -4
- package/runtime/js/cm-ai/requirement-evidence.mjs +4 -2
- package/runtime/js/cm-ai/review-package.mjs +2 -2
- package/runtime/js/cm-ai/specification-material.mjs +57 -12
- package/runtime/js/cm-ai/task-runner.mjs +38 -13
- package/runtime/js/cm-ai/verification-auto.mjs +6 -4
- package/runtime/js/cm-prd/acceptance-preview.mjs +203 -0
- package/runtime/js/cm-prd/change.mjs +17 -1
- package/runtime/js/cm-prd/summary.mjs +5 -0
- package/runtime/js/node-test-selection.mjs +38 -0
- package/runtime/js/run-analysis.mjs +153 -0
- package/runtime/js/session-boundary.mjs +17 -5
- package/runtime/js/session-handoff.mjs +5 -2
- package/scripts/cm-acceptance-preview.mjs +26 -0
- package/scripts/cm-acceptance-preview.test.mjs +156 -0
- package/scripts/cm-ai-acceptance-contract.test.mjs +185 -0
- package/scripts/cm-ai-admission.test.mjs +5 -2
- package/scripts/cm-ai-blockage.test.mjs +120 -0
- package/scripts/cm-ai-checklist-coverage.test.mjs +5 -2
- package/scripts/cm-ai-completion-summary.test.mjs +154 -0
- package/scripts/cm-ai-conversation-entry-ops.test.mjs +8 -2
- package/scripts/cm-ai-progress.test.mjs +7 -0
- package/scripts/cm-ai-project-qa-gate.test.mjs +55 -4
- package/scripts/cm-ai-run.test.mjs +23 -1
- package/scripts/cm-ai-spec-rebind.test.mjs +51 -15
- package/scripts/cm-ai-verification-auto.test.mjs +33 -8
- package/scripts/cm-ai-verification-gate.test.mjs +1 -1
- package/scripts/cm-autonomy-acceptance.test.mjs +212 -0
- package/scripts/cm-autonomy-review-r1.test.mjs +93 -0
- package/scripts/cm-autonomy.mjs +3 -1
- package/scripts/cm-autonomy.test.mjs +10 -9
- package/scripts/cm-check-runtime.sh +1 -1
- package/scripts/cm-delivery-evidence.mjs +59 -0
- package/scripts/cm-delivery-evidence.test.mjs +177 -0
- package/scripts/cm-drive-liveness.test.mjs +6 -0
- package/scripts/cm-driver-light-import.test.mjs +32 -0
- package/scripts/cm-mandatory-check-coverage.test.mjs +82 -0
- package/scripts/cm-node-test-selection.test.mjs +108 -0
- package/scripts/cm-notify-read-drift.test.mjs +6 -3
- package/scripts/cm-prd-completion.test.mjs +12 -0
- package/scripts/cm-prd-host.mjs +3 -1
- package/scripts/cm-prd-host.test.mjs +18 -1
- package/scripts/cm-prd-summary.test.mjs +19 -4
- package/scripts/cm-review-inventory.test.mjs +21 -6
- package/scripts/cm-run-analysis.mjs +21 -0
- package/scripts/cm-run-analysis.test.mjs +120 -0
- package/scripts/cm-start-check.mjs +60 -53
- package/scripts/cm-start-check.test.mjs +76 -1
- package/scripts/cm-usage-report.py +8 -3
- package/scripts/cm019-r1-contract.test.mjs +137 -0
- package/scripts/cm019-review-gates.test.mjs +97 -0
- package/skills/cm-ai/references/js-host.md +5 -1
- package/skills/cm-prd/references/js-change-recovery.md +1 -1
- package/skills/cm-prd/references/js-host.md +1 -0
|
@@ -9,7 +9,9 @@ export const CONTROL_RECOVERY_OPERATIONS=Object.freeze(['abandon_review','abando
|
|
|
9
9
|
export const CONTROL_FIX_RECOVERY_OPERATIONS=Object.freeze(['abandon_step','abandon_review','rediagnose',
|
|
10
10
|
'rerun_blocked_step','recover_final_review','reconcile_review']);
|
|
11
11
|
// verification is optional so policies saved before it existed keep their exact
|
|
12
|
-
// digest; absent means the same as disabled
|
|
12
|
+
// digest; absent means the same as disabled for legacy baselines. New baselines
|
|
13
|
+
// carry a mandatory acceptanceContract; disabled never disables that contract.
|
|
14
|
+
// precheck enables the delivery
|
|
13
15
|
// verification gate for every launch of the run it is saved into; auto enables
|
|
14
16
|
// the same gate answered by the host (verification-auto.mjs), for unattended runs.
|
|
15
17
|
export function readControlPolicy(raw){
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
// Local declarations, not an authentication service or a deployment executor.
|
|
2
|
+
// Original execution/review evidence remains authoritative for task completion.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import {createHash,randomUUID} from 'node:crypto';
|
|
6
|
+
import {digest,need,shape,hex,id,validIdentity,json,freeze} from './effect-contract.mjs';
|
|
7
|
+
import {readExecutionSnapshot} from './execution-snapshot.mjs';
|
|
8
|
+
import {readRunnerHistory,attemptBaseline} from './durable-runner-state.mjs';
|
|
9
|
+
import {readReviewSourceFiles,verifyReviewPackage} from './review-package.mjs';
|
|
10
|
+
import {verifyApprovedManifest} from '../../../scripts/cm-spec-manifest.mjs';
|
|
11
|
+
|
|
12
|
+
const directory='.reviews/.delivery',MAX_RECORDS=1000;
|
|
13
|
+
const environmentKey=value=>value.trim().toLowerCase();
|
|
14
|
+
const key=s=>[s.dev,s.ino,s.mode,s.nlink,s.size,s.mtimeNs,s.ctimeNs].join(':');
|
|
15
|
+
const line=value=>need(typeof value==='string'&&value.trim().length>0&&value.length<=240
|
|
16
|
+
&&!/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/.test(value),'delivery_invalid_text');
|
|
17
|
+
function rootDirectory(specsDir,create=false){
|
|
18
|
+
need(typeof specsDir==='string'&&path.isAbsolute(specsDir)&&fs.realpathSync(specsDir)===specsDir,'delivery_invalid_root');
|
|
19
|
+
let current=specsDir;
|
|
20
|
+
for(const part of directory.split('/')){
|
|
21
|
+
current=path.join(current,part);
|
|
22
|
+
if(create)try{fs.mkdirSync(current,{mode:0o700});}catch(error){if(error.code!=='EEXIST')throw error;}
|
|
23
|
+
try{const stat=fs.lstatSync(current);need(stat.isDirectory()&&!stat.isSymbolicLink(),'delivery_invalid_directory');}
|
|
24
|
+
catch(error){if(!create&&error.code==='ENOENT')return null;throw error;}
|
|
25
|
+
}
|
|
26
|
+
return current;
|
|
27
|
+
}
|
|
28
|
+
// Bounded streaming hash also supports build files larger than review text.
|
|
29
|
+
export function deliveryFile(file,{maxBytes=1024*1024*1024}={}){
|
|
30
|
+
need(typeof file==='string'&&path.isAbsolute(file)&&fs.realpathSync(file)===file,'delivery_invalid_file');
|
|
31
|
+
const before=fs.lstatSync(file,{bigint:true});
|
|
32
|
+
need(before.isFile()&&!before.isSymbolicLink()&&before.nlink===1n&&before.size>0n&&before.size<=1024n*1024n*1024n,'delivery_invalid_file');
|
|
33
|
+
need(before.size<=BigInt(maxBytes),'delivery_evidence_budget_exceeded');
|
|
34
|
+
const fd=fs.openSync(file,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW),hash=createHash('sha256');
|
|
35
|
+
let size=0;
|
|
36
|
+
try{
|
|
37
|
+
need(key(fs.fstatSync(fd,{bigint:true}))===key(before),'delivery_file_changed');
|
|
38
|
+
const buffer=Buffer.alloc(64*1024);
|
|
39
|
+
while(true){const n=fs.readSync(fd,buffer,0,buffer.length,null);if(!n)break;
|
|
40
|
+
size+=n;need(BigInt(size)<=before.size,'delivery_file_changed');hash.update(buffer.subarray(0,n));}
|
|
41
|
+
need(BigInt(size)===before.size&&key(fs.fstatSync(fd,{bigint:true}))===key(before)
|
|
42
|
+
&&key(fs.lstatSync(file,{bigint:true}))===key(before),'delivery_file_changed');
|
|
43
|
+
}finally{fs.closeSync(fd);}
|
|
44
|
+
return {path:file,sha256:hash.digest('hex'),size};
|
|
45
|
+
}
|
|
46
|
+
function validFile(file){shape(file,['path','sha256','size']);need(typeof file.path==='string'&&path.isAbsolute(file.path),'delivery_invalid_file');
|
|
47
|
+
hex(file.sha256);need(Number.isSafeInteger(file.size)&&file.size>0&&file.size<=1024*1024*1024,'delivery_invalid_file');}
|
|
48
|
+
function validCandidate(c){
|
|
49
|
+
shape(c,['version','feature','identity','packageDigest','specificationDigest','artifact','runnerRevision']);
|
|
50
|
+
need(c.version===1,'delivery_invalid_candidate');line(c.feature);need(!/[\\/]/.test(c.feature)&&!['.','..'].includes(c.feature),'delivery_invalid_candidate');
|
|
51
|
+
validIdentity(c.identity);[c.packageDigest,c.specificationDigest,c.runnerRevision].forEach(hex);validFile(c.artifact);
|
|
52
|
+
}
|
|
53
|
+
function validStatement(kind,s){
|
|
54
|
+
shape(s,kind==='acceptance'?['actor','environment','outcome','note']:['actor','environment','execution','verification','note']);
|
|
55
|
+
[s.actor,s.environment,s.note].forEach(line);
|
|
56
|
+
if(kind==='acceptance')need(['accepted','rejected','revoked'].includes(s.outcome),'delivery_invalid_statement');
|
|
57
|
+
else {need(['succeeded','failed'].includes(s.execution)&&['passed','failed','unknown'].includes(s.verification),'delivery_invalid_statement');
|
|
58
|
+
need(s.execution==='succeeded'||s.verification!=='passed','delivery_invalid_statement');}
|
|
59
|
+
}
|
|
60
|
+
function validRecord(record,sequence,previousDigest){
|
|
61
|
+
const r=json(record,32*1024);shape(r,['version','sequence','previousDigest','at','kind','candidate','statement','evidence','provenance','recordDigest']);
|
|
62
|
+
need(r.version===1&&r.sequence===sequence&&r.previousDigest===previousDigest&&['acceptance','deployment'].includes(r.kind),'delivery_record_invalid');
|
|
63
|
+
need(typeof r.at==='string'&&new Date(r.at).toISOString()===r.at&&r.provenance==='interactive-terminal-declaration','delivery_record_invalid');
|
|
64
|
+
validCandidate(r.candidate);validStatement(r.kind,r.statement);
|
|
65
|
+
shape(r.evidence,['report','verificationReport']);validFile(r.evidence.report);
|
|
66
|
+
if(r.evidence.verificationReport!==null)validFile(r.evidence.verificationReport);
|
|
67
|
+
need(r.kind==='deployment'&&r.statement.verification!=='unknown'?r.evidence.verificationReport!==null:r.evidence.verificationReport===null,'delivery_verification_report_required');
|
|
68
|
+
const {recordDigest,...body}=r;need(digest(body)===recordDigest,'delivery_record_invalid');return r;
|
|
69
|
+
}
|
|
70
|
+
export function readDeliveryRecords(specsDir){
|
|
71
|
+
const dir=rootDirectory(specsDir);if(dir===null)return freeze([]);
|
|
72
|
+
const before=fs.lstatSync(dir,{bigint:true}),entries=fs.readdirSync(dir);
|
|
73
|
+
need(entries.length<=MAX_RECORDS*2,'delivery_record_limit');
|
|
74
|
+
const names=entries.filter(name=>!name.startsWith('.pending-')&&name!=='.DS_Store').sort();
|
|
75
|
+
need(names.length<=MAX_RECORDS,'delivery_record_limit');const records=[],watched=[];
|
|
76
|
+
for(const [index,name] of names.entries()){
|
|
77
|
+
need(name===String(index+1).padStart(6,'0'),'delivery_record_invalid');
|
|
78
|
+
const entry=path.join(dir,name),entryStat=fs.lstatSync(entry,{bigint:true});
|
|
79
|
+
need(entryStat.isDirectory()&&!entryStat.isSymbolicLink()&&JSON.stringify(fs.readdirSync(entry))===JSON.stringify(['record.json']),'delivery_record_invalid');
|
|
80
|
+
const location=path.join(entry,'record.json'),stat=key(fs.lstatSync(location,{bigint:true}));
|
|
81
|
+
const file=readReviewSourceFiles(specsDir,[`${directory}/${name}/record.json`])[0];watched.push([entry,key(entryStat)],[location,stat]);
|
|
82
|
+
records.push(validRecord(JSON.parse(Buffer.from(file.contentBase64,'base64').toString('utf8')),index+1,records.at(-1)?.recordDigest??null));
|
|
83
|
+
}
|
|
84
|
+
need(key(before)===key(fs.lstatSync(dir,{bigint:true}))&&watched.every(([file,stat])=>key(fs.lstatSync(file,{bigint:true}))===stat),'delivery_snapshot_changed');return freeze(records);
|
|
85
|
+
}
|
|
86
|
+
function currentDeliveryOwner({specsDir,repositoryId,runId,feature}){
|
|
87
|
+
[repositoryId,runId].forEach(id);line(feature);
|
|
88
|
+
const snapshot=readExecutionSnapshot({specsRoot:specsDir,identity:{repositoryId,runId}}),init=snapshot.records[0]?.payload;
|
|
89
|
+
const history=readRunnerHistory(snapshot.records,init.config,init.version),state=history.state;
|
|
90
|
+
need(history.pending===null&&state.state==='fixture_completed'&&state.receipt?.result?.verdict==='approved','delivery_candidate_incomplete');
|
|
91
|
+
const pkg=state.reviewPackage,baseline=attemptBaseline(history.original,state.attempt);
|
|
92
|
+
need(baseline.specification?.feature===feature&&init.config.completion?.owner?.specsRoot===specsDir,'delivery_candidate_mismatch');
|
|
93
|
+
verifyReviewPackage({root:init.config.root,baseline,checks:pkg.checks,reviewPackage:pkg,expectedDigest:pkg.packageDigest,
|
|
94
|
+
...(pkg.handoff?{handoffPath:init.config.completion.handoffs[state.attempt-1]}:{})});
|
|
95
|
+
const manifest=verifyApprovedManifest(specsDir,path.join(specsDir,'.cm-specs-status'));
|
|
96
|
+
return {version:1,feature,identity:pkg.identity,packageDigest:pkg.packageDigest,specificationDigest:digest(manifest),runnerRevision:snapshot.revision};
|
|
97
|
+
}
|
|
98
|
+
export function deliveryCandidate(options){
|
|
99
|
+
const candidate={...currentDeliveryOwner(options),artifact:deliveryFile(options.artifact)};
|
|
100
|
+
validCandidate(candidate);return freeze(candidate);
|
|
101
|
+
}
|
|
102
|
+
export function previewDelivery({specsDir,repositoryId,runId,feature,artifact,kind,statement,report,verificationReport=null}){
|
|
103
|
+
need(['acceptance','deployment'].includes(kind),'delivery_invalid_kind');validStatement(kind,statement);
|
|
104
|
+
const candidate=deliveryCandidate({specsDir,repositoryId,runId,feature,artifact}),records=readDeliveryRecords(specsDir);
|
|
105
|
+
need(records.length<MAX_RECORDS,'delivery_record_limit');
|
|
106
|
+
const body={version:1,sequence:records.length+1,previousDigest:records.at(-1)?.recordDigest??null,
|
|
107
|
+
kind,candidate,statement:json({...statement,environment:environmentKey(statement.environment)}),evidence:{report:deliveryFile(report),verificationReport:verificationReport===null?null:deliveryFile(verificationReport)}};
|
|
108
|
+
// Same shape check as persisted records, before asking a human anything.
|
|
109
|
+
const probe={...body,at:new Date().toISOString(),provenance:'interactive-terminal-declaration'};
|
|
110
|
+
validRecord({...probe,recordDigest:digest(probe)},body.sequence,body.previousDigest);
|
|
111
|
+
return freeze({...body,previewDigest:digest(body)});
|
|
112
|
+
}
|
|
113
|
+
export function deliveryConfirmation(preview){return `RECORD ${preview.kind} ${preview.previewDigest}`;}
|
|
114
|
+
// Confirmation is provided by a trusted host callback, never by parsed model JSON.
|
|
115
|
+
// The bundled CLI supplies a real interactive terminal callback; no --yes exists.
|
|
116
|
+
export async function recordDelivery(options,{confirm}={}){
|
|
117
|
+
need(typeof confirm==='function','delivery_confirmation_required');
|
|
118
|
+
const preview=previewDelivery(options),answer=await confirm(preview,deliveryConfirmation(preview));
|
|
119
|
+
need(answer===deliveryConfirmation(preview),'delivery_confirmation_refused');
|
|
120
|
+
need(digest(previewDelivery(options))===digest(preview),'delivery_preview_changed');
|
|
121
|
+
const {previewDigest,...body}=preview,recordBody={...body,at:new Date().toISOString(),provenance:'interactive-terminal-declaration'};
|
|
122
|
+
const record=freeze({...recordBody,recordDigest:digest(recordBody)}),dir=rootDirectory(options.specsDir,true);
|
|
123
|
+
const temp=path.join(dir,`.pending-${randomUUID()}`),target=path.join(dir,String(record.sequence).padStart(6,'0'));
|
|
124
|
+
// Publish a nonempty directory by atomic rename. Unlike hard-link publication,
|
|
125
|
+
// a crash cannot leave the committed record with a second link. Existing valid
|
|
126
|
+
// nonempty directories cannot be replaced. Unpublished stages remain evidence.
|
|
127
|
+
fs.mkdirSync(temp,{mode:0o700});
|
|
128
|
+
const fd=fs.openSync(path.join(temp,'record.json'),'wx',0o600);
|
|
129
|
+
try{fs.writeFileSync(fd,JSON.stringify(record)+'\n');fs.fsyncSync(fd);}finally{fs.closeSync(fd);}
|
|
130
|
+
try{
|
|
131
|
+
try{fs.lstatSync(target);need(false,'delivery_concurrent_write');}catch(error){if(error.code!=='ENOENT')throw error;}
|
|
132
|
+
fs.renameSync(temp,target);
|
|
133
|
+
}catch(error){if(['EEXIST','ENOTEMPTY'].includes(error.code))need(false,'delivery_concurrent_write');throw error;}
|
|
134
|
+
return record;
|
|
135
|
+
}
|
|
136
|
+
const unknown=reason=>({status:'unknown',reason,evidence:[],environments:[]});
|
|
137
|
+
export function deliveryProjection({specsDir,feature,identity,packageDigest,specificationDigest,current=true,artifactSha256=null,maxEvidenceBytes=1024*1024*1024*3}){
|
|
138
|
+
const result={productAcceptance:unknown('external_owner_acceptance_not_recorded'),deployment:unknown('deployment_evidence_not_recorded')};
|
|
139
|
+
try{
|
|
140
|
+
const records=readDeliveryRecords(specsDir);let owner,remaining=maxEvidenceBytes;
|
|
141
|
+
need(Number.isSafeInteger(remaining)&&remaining>=0,'delivery_evidence_budget_exceeded');
|
|
142
|
+
const checkedFiles=new Map();
|
|
143
|
+
const checkFile=file=>{
|
|
144
|
+
const prior=checkedFiles.get(file.path);if(prior!==undefined){need(digest(prior)===digest(file),'delivery_evidence_changed');return;}
|
|
145
|
+
const checked=deliveryFile(file.path,{maxBytes:remaining});remaining-=checked.size;
|
|
146
|
+
need(digest(checked)===digest(file),'delivery_evidence_changed');checkedFiles.set(file.path,checked);
|
|
147
|
+
};
|
|
148
|
+
const ownerMatches=()=>{
|
|
149
|
+
if(owner===undefined)try{const inspected=currentDeliveryOwner({specsDir,repositoryId:identity.repositoryId,runId:identity.runId,feature});
|
|
150
|
+
owner=digest(inspected.identity)===digest(identity)&&inspected.packageDigest===packageDigest&&inspected.specificationDigest===specificationDigest;
|
|
151
|
+
}catch{owner=false;}
|
|
152
|
+
return owner;
|
|
153
|
+
};
|
|
154
|
+
for(const [kind,field] of [['acceptance','productAcceptance'],['deployment','deployment']]){
|
|
155
|
+
const selected=new Map();for(const record of records)if(record.kind===kind&&record.candidate.feature===feature)selected.set(environmentKey(record.statement.environment),record);
|
|
156
|
+
if(!selected.size)continue;
|
|
157
|
+
const environments=[...selected].map(([environment,r])=>{
|
|
158
|
+
let reason=null;
|
|
159
|
+
if(!current||(artifactSha256!==null&&artifactSha256!==r.candidate.artifact.sha256)||digest(r.candidate.identity)!==digest(identity)||r.candidate.packageDigest!==packageDigest||r.candidate.specificationDigest!==specificationDigest)reason='delivery_candidate_changed';
|
|
160
|
+
else if(!ownerMatches())reason='delivery_candidate_changed';
|
|
161
|
+
else try{for(const file of [r.candidate.artifact,r.evidence.report,r.evidence.verificationReport].filter(Boolean))
|
|
162
|
+
checkFile(file);}
|
|
163
|
+
catch(error){reason=error.code==='delivery_evidence_budget_exceeded'?error.code:'delivery_evidence_changed';}
|
|
164
|
+
return {environment,status:reason==='delivery_evidence_budget_exceeded'?'unknown':reason?'stale':'recorded',reason,statement:r.statement,artifactSha256:r.candidate.artifact.sha256,
|
|
165
|
+
at:r.at,provenance:r.provenance,evidence:[`${directory}/${String(r.sequence).padStart(6,'0')}/record.json#sha256=${r.recordDigest}`]};
|
|
166
|
+
});
|
|
167
|
+
result[field]={status:environments.some(e=>e.status==='unknown')?'unknown':environments.every(e=>e.status==='recorded')?'recorded':'stale',reason:null,environments,
|
|
168
|
+
evidence:environments.flatMap(e=>e.evidence)};
|
|
169
|
+
}
|
|
170
|
+
}catch{result.productAcceptance=unknown('delivery_records_unavailable');result.deployment=unknown('delivery_records_unavailable');}
|
|
171
|
+
return freeze(result);
|
|
172
|
+
}
|
|
173
|
+
export {deliveryLines} from './operator-guidance.mjs';
|
|
@@ -29,6 +29,10 @@ The top-level reason explains blocked outcomes; otherwise it must be null. Use n
|
|
|
29
29
|
Use outcome blocked when implementation is not possible. Do not claim implementation if no implementation was made.
|
|
30
30
|
Always also return requirements: one item {requirement, satisfied, evidence, run, result} for each requirement written in the
|
|
31
31
|
task's description and verification (specification), evidence naming where it is met (file, test name, expected command result).
|
|
32
|
+
When specification.acceptanceContract exists, its obligations are the mandatory set: return exactly one item per obligation,
|
|
33
|
+
copying id, requirement, evidenceType, environment and run verbatim, and adding satisfied, evidence and optional result.
|
|
34
|
+
Do not omit or combine obligations, reinterpret the required environment, or declare unresolved mappings satisfied.
|
|
35
|
+
Without an acceptanceContract, id, evidenceType and environment may be omitted or null for legacy reports.
|
|
32
36
|
Use null when the task states none. The host runs the task's checks itself before development (baseline) and with only the
|
|
33
37
|
task's test files delivered (red), and checks tagged items against those runs: set run "red" on an item stating that a new
|
|
34
38
|
test fails before the implementation; set run "baseline" on an item stating the result before development, with result
|
|
@@ -3,7 +3,7 @@ import fs from 'node:fs';
|
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import {spawn} from 'node:child_process';
|
|
5
5
|
import readline from 'node:readline';
|
|
6
|
-
import {guidanceText} from './operator-guidance.mjs';
|
|
6
|
+
import {guidanceText,completionLines} from './operator-guidance.mjs';
|
|
7
7
|
import {applyRateLimitResume,nextRateLimitRetry,rateLimitedReview,rateLimitRetriesDone,RATE_LIMIT_RETRY_ENV,RATE_LIMIT_EXPECTED_ENV,
|
|
8
8
|
RATE_LIMIT_PLAN_DIGEST_ENV,planFileFromArgv,planDigest,digestBytes,expectedReviewStop,readExpectedReviewStop} from './drive-rate-limit.mjs';
|
|
9
9
|
|
|
@@ -137,7 +137,11 @@ export function driveHost({host,args,cwd,operation,request={},answers,paths,answ
|
|
|
137
137
|
if(typeof sessionBoundary==='function'&&!row.error){let block=null;try{block=sessionBoundary(row.result,operation);}catch{stderr('会话边界结论生成失败;请按技能输出模板手写三行结论(业务结果不受影响)');}
|
|
138
138
|
// stderr, not stdout: callers parse stdout as one JSON result.
|
|
139
139
|
if(typeof block==='string'&&block)process.stderr.write(block+'\n');}
|
|
140
|
-
const guidance=guidanceText(row.result);if(guidance)stderr(guidance);
|
|
140
|
+
try{const guidance=guidanceText(row.result);if(guidance)stderr(guidance);}
|
|
141
|
+
catch{stderr('恢复指引显示失败;业务结果不受影响');}
|
|
142
|
+
try{if(row.result?.state!=='run_done'||typeof sessionBoundary!=='function')
|
|
143
|
+
for(const line of completionLines(row.result?.completion))stderr(line);}
|
|
144
|
+
catch{stderr('完成摘要显示失败;业务结果不受影响');}
|
|
141
145
|
if(row.result?.stage)stderr(`stage = ${row.result.stage}`);
|
|
142
146
|
if(row.error)stderr(`宿主拒绝:${row.error.code}(真实原因和位置在上面 [host] 那行 diagnostic 里)`);
|
|
143
147
|
};
|
|
@@ -1150,7 +1150,7 @@ function checkpoint(before,raw,effect,config,original,session,controls,version=1
|
|
|
1150
1150
|
same(s.receipts,before.receipts);same(s.receipt,before.receipt);same(s.priorReview,before.priorReview);
|
|
1151
1151
|
if(s.state==='fixture_completed') {
|
|
1152
1152
|
checkCompletion({receipt:s.receipt,registered:before.receipt,execution:s.calls.find(c=>c.invocationId===s.receipt?.id),
|
|
1153
|
-
reviewPackage:s.reviewPackage,identity});expectedState='fixture_completed';
|
|
1153
|
+
reviewPackage:s.reviewPackage,identity,historical:true});expectedState='fixture_completed';
|
|
1154
1154
|
} else if(s.state==='blocked'){
|
|
1155
1155
|
expectedState='blocked';
|
|
1156
1156
|
if(['completion_checks_changed','completion_package_changed'].includes(s.code)){
|
|
@@ -1854,7 +1854,7 @@ export function readRunnerHistory(raw,config,version=1) {
|
|
|
1854
1854
|
const c=readCommitIntent(p.commit,{owner:completion.owner,identity:pending.identity,fingerprints:completion.fingerprints});
|
|
1855
1855
|
const base=attemptBaseline(original,pending.identity.attempt),s=beforeIntent;
|
|
1856
1856
|
checkCompletion({receipt:s.receipt,registered:s.receipts.find(x=>x.id===s.receipt?.id),
|
|
1857
|
-
execution:s.calls.find(x=>x.invocationId===s.receipt?.id),reviewPackage:s.reviewPackage,identity:pending.identity});
|
|
1857
|
+
execution:s.calls.find(x=>x.invocationId===s.receipt?.id),reviewPackage:s.reviewPackage,identity:pending.identity,historical:true});
|
|
1858
1858
|
same(c.proof,{root:config.root,baselineDigest:base.baselineDigest,packageDigest:s.reviewPackage.packageDigest,
|
|
1859
1859
|
receiptDigest:s.receipt.receiptDigest,checksDigest:s.reviewPackage.checksDigest});
|
|
1860
1860
|
need(c.plan.evidence.every(e=>path.dirname(e.path)===completion.reviewsDir)
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
// Pure S2b comparison only. This is not the Python gate and cannot write tasks.
|
|
2
2
|
import { digest,need,shape,id,json,validIdentity } from './effect-contract.mjs';
|
|
3
3
|
import { reviewResult } from './review-runner.mjs';
|
|
4
|
-
|
|
4
|
+
import {verifyAcceptanceEvidence,acceptanceCoverage} from './acceptance-contract.mjs';
|
|
5
|
+
export function checkCompletion({receipt,registered,execution,reviewPackage,identity,historical=false}) {
|
|
5
6
|
const r=json(receipt);validIdentity(identity);
|
|
6
7
|
shape(r,['version','kind','id','identity','packageDigest','baseIdentity','artifactDigest',
|
|
7
8
|
'requirementsDigest','checksDigest','execution','route','result','receiptDigest']);
|
|
@@ -21,5 +22,16 @@ export function checkCompletion({receipt,registered,execution,reviewPackage,iden
|
|
|
21
22
|
const result=reviewResult(r.result,reviewPackage);
|
|
22
23
|
need(r.execution.resultDigest===digest(result) && result.verdict==='approved','review_not_approved');
|
|
23
24
|
need(reviewPackage.checks.length>0 && reviewPackage.checks.every(c=>c.outcome==='passed' && c.exitCode===0),'checks_not_passed');
|
|
25
|
+
if(reviewPackage.specification?.acceptanceContract){
|
|
26
|
+
const contract=reviewPackage.specification.acceptanceContract;
|
|
27
|
+
// Replay verifies the registered host evidence below. Reinterpreting its
|
|
28
|
+
// already accepted selection with today's Node path/parser would change
|
|
29
|
+
// historical completion after a runtime upgrade. Live completion stays strict.
|
|
30
|
+
if(!historical)need(acceptanceCoverage(contract,reviewPackage.checks).satisfied,'verification_precheck_failed');
|
|
31
|
+
let handoff;
|
|
32
|
+
try{handoff=JSON.parse(Buffer.from(reviewPackage.handoff.contentBase64,'base64').toString('utf8'));}
|
|
33
|
+
catch{need(false,'verification_precheck_failed');}
|
|
34
|
+
verifyAcceptanceEvidence({contract,identity,evidence:handoff.evidence});
|
|
35
|
+
}
|
|
24
36
|
return json({outcome:'eligible',receiptDigest});
|
|
25
37
|
}
|
|
@@ -24,6 +24,7 @@ import {checklistGaps} from './checklist-coverage.mjs';
|
|
|
24
24
|
import {readRequirementItems,splitRequirementReport} from './requirement-evidence.mjs';
|
|
25
25
|
import {replayDelivery,notReplayed} from './host-replay.mjs';
|
|
26
26
|
import {autoVerificationVerdict} from './verification-auto.mjs';
|
|
27
|
+
import {acceptanceProblems,acceptanceCoverage,describeAcceptanceProblems} from './acceptance-contract.mjs';
|
|
27
28
|
import {declaredTaskScope} from '../task-scope.mjs';
|
|
28
29
|
import {specsPermissionArgs} from './codex-config.mjs';
|
|
29
30
|
import {createProjectExecution} from './host-project-execution.mjs';
|
|
@@ -34,7 +35,7 @@ import {verifySpecificationMaterial} from './specification-material.mjs';
|
|
|
34
35
|
import {isFinalCmAiTask} from './cm-ai-admission.mjs';
|
|
35
36
|
import {createHostBootstrap} from './host-bootstrap.mjs';
|
|
36
37
|
import {withHostProgress} from './host-progress.mjs';
|
|
37
|
-
import {digest,id,hex,json,need,shape,freeze,arrayItems} from './effect-contract.mjs';
|
|
38
|
+
import {digest,id,hex,json,need,shape,freeze,arrayItems,boundedReason} from './effect-contract.mjs';
|
|
38
39
|
export const protectedTextInstructions='\nProtected current-host mode: do not write files or run commands. Return {status,value,edits} on success; '
|
|
39
40
|
+'value retains the original implementation/Learning contract. edits is [{path,beforeSha256,content[,mode]}], complete UTF-8 text or null for deletion; '
|
|
40
41
|
+'optional mode "0755" or "0644" sets the permission bits of a written file. '
|
|
@@ -52,11 +53,9 @@ export const externalConversationDefinition=execution=>externalConversations.get
|
|
|
52
53
|
// passing it is not an approval, produces no receipt and consumes no review
|
|
53
54
|
// round. A satisfied gate still leaves the full independent review ahead.
|
|
54
55
|
//
|
|
55
|
-
//
|
|
56
|
-
//
|
|
57
|
-
//
|
|
58
|
-
// nonempty evidence location, and that the gate passes only when every returned
|
|
59
|
-
// requirement is satisfied. Mechanical shape is not semantic coverage.
|
|
56
|
+
// This parser validates reports, not coverage. The caller and runner separately
|
|
57
|
+
// compare new reports with their approved acceptanceContract. Legacy reports
|
|
58
|
+
// keep their original shape. Nonempty evidence is still not semantic proof.
|
|
60
59
|
export function readVerificationPrecheck(raw){
|
|
61
60
|
const value=json(raw,256*1024);shape(value,['items']);
|
|
62
61
|
const items=readRequirementItems(arrayItems(value.items));
|
|
@@ -226,23 +225,35 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
|
|
|
226
225
|
snapshot:control.baselineSnapshot??null,scope:request.scope??definition.scope,
|
|
227
226
|
tests:declaredTests(request.identity.taskId),checkCommands:protection.checkCommands,timeoutMs:protection.timeoutMs,
|
|
228
227
|
identity:request.identity,greenChecks:request.checks,signal:control.signal}):null;
|
|
229
|
-
// The
|
|
230
|
-
//
|
|
231
|
-
//
|
|
232
|
-
//
|
|
228
|
+
// The optional legacy gate retains its original policy. A new frozen contract
|
|
229
|
+
// always runs, including when the optional precheck/auto setting is disabled.
|
|
230
|
+
// A failed gate carries a bounded diagnostic through the existing checkpoint
|
|
231
|
+
// reason. It survives restart without becoming approval or recovery authority.
|
|
233
232
|
// A v2 policy may enable the gate durably (it is part of the run fingerprint);
|
|
234
233
|
// the legacy launch flag keeps working for runs created without it.
|
|
235
234
|
// auto: the host answers from the developer's report and its own runs
|
|
236
235
|
// (verification-auto.mjs); precheck: the session answers, seeing the host runs.
|
|
237
236
|
const gateMode=controlPolicy?.verification==='auto'?'auto'
|
|
238
237
|
:options.verificationPrecheck===true||controlPolicy?.verification==='precheck'?'precheck':null;
|
|
239
|
-
const verificationGate=
|
|
238
|
+
const verificationGate=async(request,control)=>{
|
|
239
|
+
const contract=request.acceptanceContract??null;
|
|
240
|
+
if(!gateMode&&!contract)return {satisfied:true}; // original, unprotected run
|
|
240
241
|
const facts=await hostRuns(request,control);
|
|
241
|
-
const
|
|
242
|
+
const report=requirementReports.get(reportKey(request.identity))??null;
|
|
243
|
+
const verdict=gateMode!=='precheck'?autoVerificationVerdict({report,contract,
|
|
242
244
|
facts:facts??notReplayed(definition.codeProjects?'multi_root':'no_host_checks',request.checks)})
|
|
243
245
|
:readVerificationPrecheck(await bridge.call('verification_precheck',
|
|
244
246
|
{...request,codeProject:definition.codeProject,feature:definition.feature,
|
|
245
247
|
scope:request.scope??definition.scope,...(facts?{hostRuns:facts}:{})},control.signal));
|
|
248
|
+
const coverage=contract?acceptanceCoverage(contract,request.checks):null;
|
|
249
|
+
const problems=contract?acceptanceProblems(contract,gateMode==='precheck'?verdict.items:report,facts):[];
|
|
250
|
+
if(coverage&&!coverage.satisfied)problems.push('mandatory checks missing or unverifiable: '+JSON.stringify(coverage));
|
|
251
|
+
if(problems.length){
|
|
252
|
+
try{process.stderr.write(JSON.stringify({diagnostic:'acceptance_contract_failed',task:request.identity.taskId,problems})+'\n');}
|
|
253
|
+
catch{/* presentation never changes the blocking verdict */}
|
|
254
|
+
return {satisfied:false,reason:boundedReason('verification_precheck_failed: ',
|
|
255
|
+
describeAcceptanceProblems(contract,[...new Set([...problems,...(verdict.unsatisfied??[])])]))};
|
|
256
|
+
}
|
|
246
257
|
if(!verdict.satisfied)try{
|
|
247
258
|
process.stderr.write(JSON.stringify({diagnostic:'verification_precheck_failed',
|
|
248
259
|
task:request.identity.taskId,attempt:request.identity.attempt,mode:gateMode,
|
|
@@ -264,8 +275,9 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
|
|
|
264
275
|
// The answered items travel to the runner, which binds them into the host
|
|
265
276
|
// handoff the reviewer reads; a failed gate halts before any handoff exists.
|
|
266
277
|
// The host record travels as its own handoff entry (host-replay.mjs), never inside the items.
|
|
267
|
-
return verdict.satisfied?{satisfied:true,items:verdict.items,...(facts?{hostRecord:facts}:{})}:{
|
|
268
|
-
|
|
278
|
+
return verdict.satisfied?{satisfied:true,items:verdict.items,...(facts?{hostRecord:facts}:{}),...(coverage?{coverage}:{})}
|
|
279
|
+
:{satisfied:false,reason:boundedReason('verification_precheck_failed: ',verdict.unsatisfied??['门禁未记录具体缺项'])};
|
|
280
|
+
};
|
|
269
281
|
const outerTimeoutMs=provider?protection.timeoutMs:1800000;
|
|
270
282
|
const progress=(request,control,stage,run,selectedRuntime=runtime)=>withHostProgress({definition,
|
|
271
283
|
identity:request.identity,runtime:selectedRuntime,stage,signal:control.signal},run);
|
|
@@ -5,6 +5,7 @@ import {randomUUID} from 'node:crypto';
|
|
|
5
5
|
import {fileURLToPath} from 'node:url';
|
|
6
6
|
import {need} from './effect-contract.mjs';
|
|
7
7
|
import {readStatusProjection,writeStatusProjection} from './status-projection.mjs';
|
|
8
|
+
import {completionLines} from './completion-summary.mjs';
|
|
8
9
|
|
|
9
10
|
const writer=fileURLToPath(new URL('../../../scripts/cm-log-event.py',import.meta.url));
|
|
10
11
|
const phases={developing:['N3','正在开发'],checking:['N3','正在执行检查'],
|
|
@@ -73,7 +74,7 @@ export function projectHostResult({specsDir,feature,result,readCurrent}){
|
|
|
73
74
|
if(['N6','N7','N8'].includes(previous.node))return;
|
|
74
75
|
const node=['blocked','unknown','cancelled'].includes(result.state)?previous.node:selected[0];
|
|
75
76
|
writeStatusProjection({specsDir,feature,identity:result.identity,node,state:result.state,
|
|
76
|
-
detail:(result.guidance?.summary??selected[1])+(result.code?`(${result.code})`:''),code:result.code,
|
|
77
|
+
detail:(result.guidance?.summary??(result.state==='fixture_completed'?completionLines(result.completion)[0]:null)??selected[1])+(result.code?`(${result.code})`:''),code:result.code,
|
|
77
78
|
...(result.state==='changes_requested'&&result.identity.attempt>1?{previousAttempt:result.identity.attempt-1}:{}),
|
|
78
79
|
expectedToken:previous.progress_id??null});
|
|
79
80
|
}catch{diagnostic();}
|
|
@@ -26,11 +26,12 @@ export function scanRows(log,visit) {
|
|
|
26
26
|
// read to its recorded size. Lines are parsed with plain JSON.parse, as the
|
|
27
27
|
// historical log readers did; only selected rows are kept, in log order.
|
|
28
28
|
const stableKey=s=>[s.dev,s.ino,s.mode,s.nlink,s.size,s.mtimeNs,s.ctimeNs].join(':');
|
|
29
|
-
export function readStableLogRows(file,select,code){
|
|
29
|
+
export function readStableLogRows(file,select,code,{maxBytes=Infinity}={}){
|
|
30
30
|
let descriptor;
|
|
31
31
|
try{
|
|
32
32
|
const before=fs.lstatSync(file,{bigint:true});
|
|
33
|
-
need(before.isFile()&&!before.isSymbolicLink()&&before.nlink===1n
|
|
33
|
+
need(before.isFile()&&!before.isSymbolicLink()&&before.nlink===1n
|
|
34
|
+
&&(maxBytes===Infinity||before.size<=BigInt(maxBytes)),code);
|
|
34
35
|
descriptor=fs.openSync(file,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW);
|
|
35
36
|
need(stableKey(fs.fstatSync(descriptor,{bigint:true}))===stableKey(before),code);
|
|
36
37
|
const rows=[],chunk=Buffer.alloc(64*1024),decoder=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true});
|
|
@@ -26,10 +26,73 @@ const documentationMessages={
|
|
|
26
26
|
const explain=(summary,nextStep,operation=null,prerequisites=[])=>Object.freeze({
|
|
27
27
|
summary,nextStep,recoveryOperation:operation,prerequisites:Object.freeze(prerequisites),authorizationGranted:false,
|
|
28
28
|
});
|
|
29
|
+
const phases={verification_precheck_failed:['verification','验收要求核对'],
|
|
30
|
+
develop_checks_not_passed:['checks','开发检查'],checks_not_passed:['checks','旧完成检查'],
|
|
31
|
+
completion_checks_changed:['completion','完成前复查'],completion_package_changed:['completion','完成前复查'],
|
|
32
|
+
complete_recheck_failed:['completion','完成前复查'],complete_commit_interrupted:['completion','完成写入恢复'],
|
|
33
|
+
spec_drift:['specification','规格绑定核对']};
|
|
34
|
+
const reviewStops=new Set(['review_transport_timeout','review_provider_failed','review_verdict_invalid',
|
|
35
|
+
'review_abandoned','review_redispatch_limit','review_blocked','review_limit']);
|
|
36
|
+
const safeLine=value=>typeof value==='string'&&!/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/.test(value);
|
|
37
|
+
const clipDiagnostic=value=>{
|
|
38
|
+
let text='';for(const char of value){if(Buffer.byteLength(text+char)>1600)break;text+=char;}
|
|
39
|
+
const truncated=text.length!==value.length;
|
|
40
|
+
return {status:'recorded',source:'current_result.reason',text:text+(truncated?'…(完整原因见 result.reason)':''),truncated};
|
|
41
|
+
};
|
|
42
|
+
// Reasons are explanatory evidence, never a recovery permission. Display only
|
|
43
|
+
// host-formatted diagnostics for this code; arbitrary provider reasons stay out
|
|
44
|
+
// of the driver's human channel. Older checkpoints legitimately have no detail.
|
|
45
|
+
function diagnosticFor(result){
|
|
46
|
+
const {reason,code}=result;
|
|
47
|
+
if(safeLine(reason)&&reason.length<=8192){
|
|
48
|
+
if(['verification_precheck_failed','develop_checks_not_passed','checks_not_passed','completion_checks_changed'].includes(code)
|
|
49
|
+
&&reason.startsWith(code+':')&&reason.slice(code.length+1).trim())return clipDiagnostic(reason);
|
|
50
|
+
if(code==='spec_drift'&&/^(规格当前未处于|规格已重新批准,变更文件:|规格已变更:)/.test(reason))
|
|
51
|
+
return clipDiagnostic(reason.split(';')[0]); // Do not copy legacy launch flags into v2/batch guidance.
|
|
52
|
+
}
|
|
53
|
+
return {status:'unknown',source:null,text:'当前结果未记录可展示的具体缺项;请核对原运行证据,不推断其他检查已通过。',truncated:false};
|
|
54
|
+
}
|
|
55
|
+
const identityMatches=(a,b)=>a&&b&&['repositoryId','runId','taskId','attempt'].every(key=>a[key]===b[key]);
|
|
56
|
+
function validEvidenceFor(result){
|
|
57
|
+
const c=result.completion,items=[];
|
|
58
|
+
// A receipt's presence or a successful historical run is insufficient. Only
|
|
59
|
+
// the already validated, current snapshot projection can supply these claims.
|
|
60
|
+
if(/^[a-f0-9]{64}$/.test(c?.snapshotDigest??'')&&c?.binding?.runnerRevision
|
|
61
|
+
&&identityMatches(c.binding.identity,result.identity)&&c.binding.packageDigest===result.packageDigest
|
|
62
|
+
&&c.task?.status==='completed'&&!['spec_drift','correction_review_required'].includes(result.code)){
|
|
63
|
+
if(c.task.review?.status==='passed')for(const reference of c.task.review.evidence??[])
|
|
64
|
+
if(/^receipt:[a-f0-9]{64}$/.test(reference))items.push({kind:'task_review',reference});
|
|
65
|
+
if(c.feature?.status==='passed'&&c.feature.qa?.status==='passed')items.push({kind:'feature_qa',reference:'completion.feature.qa'});
|
|
66
|
+
}
|
|
67
|
+
return {status:items.length?'confirmed':'unknown',items:Object.freeze(items.map(Object.freeze)),
|
|
68
|
+
message:items.length?'仅列当前完成摘要已核对的证据;恢复动作仍须再次核对原条件。'
|
|
69
|
+
:'当前结果不足以确认哪些旧证据仍可复用;保留原记录,不将历史通过当作当前通过。'};
|
|
70
|
+
}
|
|
71
|
+
function blockageFor(result,guidance,{executionActive=false}={}){
|
|
72
|
+
const action=guidance.recoveryOperation;
|
|
73
|
+
const phase=executionActive?['in_flight','原操作执行中']:Object.hasOwn(phases,result.code)?phases[result.code]
|
|
74
|
+
:result.state==='pending_review'||reviewStops.has(result.code)||['abandon_review','reconcile_review'].includes(result.pendingAction)
|
|
75
|
+
?['review','独立审查']:['unknown','阶段未确认'];
|
|
76
|
+
let checks='unknown',reviewCalls='unknown';
|
|
77
|
+
if(['abandon_effect','abandon_review','develop_redo'].includes(action)){checks='not_dispatched';reviewCalls='not_dispatched';}
|
|
78
|
+
else if(action==='complete'){checks=result.code==='complete_commit_interrupted'?'not_dispatched':'rerun';reviewCalls='not_dispatched';}
|
|
79
|
+
// advance may cross review -> completion/QA, or review -> next development
|
|
80
|
+
// attempt. Describe the whole operation, not only the phase where it starts.
|
|
81
|
+
else if(action==='advance'){checks='may_run';reviewCalls='may_dispatch';}
|
|
82
|
+
const decision=executionActive?'wait':action&&['abandon_effect','abandon_review','develop_redo','bootstrap_review_recover'].includes(action)
|
|
83
|
+
||result.code==='spec_drift'&&result.pendingAction==='spec_rebind'?'required':action?'existing_conditions'
|
|
84
|
+
:['blocked','unknown'].includes(result.state)?'not_available':'unknown';
|
|
85
|
+
return Object.freeze({version:1,phase:Object.freeze({code:phase[0],label:phase[1]}),
|
|
86
|
+
detail:Object.freeze(diagnosticFor(result)),validEvidence:Object.freeze(validEvidenceFor(result)),
|
|
87
|
+
recovery:Object.freeze({operation:action,decision,checks,reviewCalls,
|
|
88
|
+
budget:'original_limits_apply',authorizationGranted:false}),
|
|
89
|
+
inspection:Object.freeze({readOnly:true,dispatchedCalls:0})});
|
|
90
|
+
}
|
|
91
|
+
const withBlockage=(result,guidance,options={})=>guidance?Object.freeze({...guidance,blockage:blockageFor(result,guidance,options)}):null;
|
|
29
92
|
// Rendering context is private and ephemeral; it never enters results or journals.
|
|
30
93
|
const guidanceContext=new WeakMap();
|
|
31
94
|
export function operatorGuidance(result,options={}){
|
|
32
|
-
const guidance=renderOperatorGuidance(result,options);
|
|
95
|
+
const guidance=withBlockage(result,renderOperatorGuidance(result,options),options);
|
|
33
96
|
if(guidance)guidanceContext.set(guidance,{executionActive:options.executionActive===true,protocol:options.protocol??'legacy'});
|
|
34
97
|
return guidance;
|
|
35
98
|
}
|
|
@@ -161,14 +224,33 @@ function renderOperatorGuidance(result,{executionActive=false,protocol='legacy',
|
|
|
161
224
|
'核对 code、reason 和原运行证据;保留已有文件与历史,不把通用阻塞当作重试许可。');
|
|
162
225
|
return null;
|
|
163
226
|
}
|
|
164
|
-
//
|
|
227
|
+
// Static instructions plus bounded host-formatted diagnostics; never raw
|
|
228
|
+
// provider output. The structured explanation does not authorize an operation.
|
|
165
229
|
export function guidanceText(result){
|
|
166
230
|
if(result?.workflow!=='cm-ai')return null;
|
|
167
231
|
const guidance=result?.guidance;
|
|
168
|
-
const bounded=value=>
|
|
232
|
+
const bounded=value=>safeLine(value)&&Buffer.byteLength(value,'utf8')<=2000;
|
|
169
233
|
if(!guidance||guidance.authorizationGranted!==false||!bounded(guidance.summary)||!bounded(guidance.nextStep)
|
|
170
234
|
||!Array.isArray(guidance.prerequisites)||guidance.prerequisites.length>8||!guidance.prerequisites.every(bounded))return null;
|
|
171
|
-
|
|
235
|
+
const text=`${guidance.summary} ${guidance.nextStep} ${guidance.prerequisites.join(';')}`.trim();
|
|
236
|
+
const b=guidance.blockage;
|
|
237
|
+
if(!b||b.version!==1||!bounded(b.phase?.label)||!bounded(b.detail?.text)
|
|
238
|
+
||!bounded(b.validEvidence?.message)||!Array.isArray(b.validEvidence?.items)||b.validEvidence.items.length>8
|
|
239
|
+
||!b.validEvidence.items.every(item=>item&&['task_review','feature_qa'].includes(item.kind))
|
|
240
|
+
||b.recovery?.authorizationGranted!==false)return text;
|
|
241
|
+
const checks={unknown:'检查是否重跑待核对',not_dispatched:'该恢复动作不直接运行检查',rerun:'将重新运行检查',
|
|
242
|
+
may_run:'推进可能跨阶段并运行检查或 QA'};
|
|
243
|
+
const review={unknown:'审查调用待核对',not_dispatched:'该恢复动作不直接派发审查',may_dispatch:'后续可能派发审查,仍受原授权与预算约束'};
|
|
244
|
+
const decisions={wait:'等待原操作,不重复派发',required:'需要用户按原入口确认具体恢复动作',
|
|
245
|
+
existing_conditions:'按原运行已有授权与前置条件核对',not_available:'当前没有已确认可直接发送的恢复操作',
|
|
246
|
+
unknown:'是否需要新决定,须核对上述原入口条件'};
|
|
247
|
+
if(!Object.hasOwn(checks,b.recovery.checks)||!Object.hasOwn(review,b.recovery.reviewCalls)
|
|
248
|
+
||!Object.hasOwn(decisions,b.recovery.decision))return text;
|
|
249
|
+
const evidence=b.validEvidence.status==='confirmed'
|
|
250
|
+
?`当前已核对证据:${b.validEvidence.items.map(item=>item.kind==='task_review'?'任务独立审查':item.kind==='feature_qa'?'功能 QA':'未知').join('、')}`
|
|
251
|
+
:'当前可复用证据:UNKNOWN';
|
|
252
|
+
return `${text}\n阶段:${b.phase.label}。门禁记录的缺项/原因:${b.detail.text}\n${evidence}。${b.validEvidence.message}`
|
|
253
|
+
+`\n恢复条件:${decisions[b.recovery.decision]};${checks[b.recovery.checks]};${review[b.recovery.reviewCalls]}。查询本身不派发调用,也不重置原预算。`;
|
|
172
254
|
}
|
|
173
255
|
|
|
174
256
|
// Q24: in-run recovery operations the batch entry forwards to the stopped member
|
|
@@ -182,6 +264,9 @@ const BATCH_RECOVERY={
|
|
|
182
264
|
// A member result is not a batch control surface. Keep unsupported single-run
|
|
183
265
|
// recovery operations out of batch instructions without changing pendingAction.
|
|
184
266
|
export function batchOperatorGuidance(result,{taskKey=null,protocol='legacy'}={}){
|
|
267
|
+
return withBlockage(result,renderBatchOperatorGuidance(result,{taskKey,protocol}),guidanceContext.get(result?.guidance));
|
|
268
|
+
}
|
|
269
|
+
function renderBatchOperatorGuidance(result,{taskKey=null,protocol='legacy'}={}){
|
|
185
270
|
const context=guidanceContext.get(result?.guidance);
|
|
186
271
|
const g=context?operatorGuidance(result,{...context,protocol,surface:'batch'}):result?.guidance;
|
|
187
272
|
if(!g)return null;
|
|
@@ -206,3 +291,24 @@ export function batchOperatorGuidance(result,{taskKey=null,protocol='legacy'}={}
|
|
|
206
291
|
'批次入口不支持此成员恢复操作;先核对原成员运行与 reason,不通过 advance 重派或新建运行绕过。');
|
|
207
292
|
return g;
|
|
208
293
|
}
|
|
294
|
+
|
|
295
|
+
// Pure formatting shared by all drivers, including partial check-only runtimes.
|
|
296
|
+
export function deliveryLines(value){
|
|
297
|
+
return [['productAcceptance','产品人工验收'],['deployment','发布/部署']].map(([field,label])=>{
|
|
298
|
+
const section=value[field];if(!section?.environments?.length)return `${label}:UNKNOWN`;
|
|
299
|
+
return `${label}:`+section.environments.map(e=>`${e.environment} [${e.artifactSha256.slice(0,12)}] ${e.status==='recorded'?'声明已记录':e.status==='unknown'?'UNKNOWN':'STALE'}(${
|
|
300
|
+
field==='productAcceptance'?e.statement.outcome:`执行 ${e.statement.execution};部署后验证 ${e.statement.verification}`})`).join(';');
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
const label={completed:'已完成',passed:'PASS',failed:'FAIL',blocked:'BLOCKED',unknown:'UNKNOWN',pending:'未完成',
|
|
305
|
+
skipped:'SKIPPED',finalized:'已收尾',ready_to_finalize:'具备收尾条件,尚未收尾'};
|
|
306
|
+
export function completionLines(summary){
|
|
307
|
+
if(!summary||summary.version!==1)return [];
|
|
308
|
+
const feature=summary.feature,project=summary.project;
|
|
309
|
+
const protection={contract_v1:'冻结合同 v1',legacy_unprotected:'旧运行,未受新合同保护',unknown:'验收保护 UNKNOWN'}[summary.task.acceptanceProtection];
|
|
310
|
+
return [`完成范围:task ${summary.binding.identity?.taskId??'未知'} ${label[summary.task.status]??'UNKNOWN'}(独立审查 ${label[summary.task.review?.status]??'UNKNOWN'})${protection?`;${protection}`:''}`,
|
|
311
|
+
`功能 ${summary.binding.feature??'未知'}:任务 ${feature.tasks?`${feature.tasks.completed}/${feature.tasks.total}`:'UNKNOWN'};QA ${label[feature.qa?.status]??'UNKNOWN'};当前资格 ${label[feature.status]??'UNKNOWN'}`,
|
|
312
|
+
`项目批准范围:${project.totalFeatures===undefined?'UNKNOWN':`${project.completedFeatures}/${project.totalFeatures} 个功能通过,${project.pendingTasks} 个待办`};${label[project.status]??'UNKNOWN'}`,
|
|
313
|
+
`本运行收尾:${label[summary.run.status]??'UNKNOWN'};${deliveryLines(summary).join(';')}`];
|
|
314
|
+
}
|
|
@@ -27,12 +27,14 @@ export function readRequirementItems(raw,code='verification_precheck_invalid'){
|
|
|
27
27
|
need(Array.isArray(raw)&&raw.length>0&&raw.length<=REQUIREMENT_ITEM_LIMIT,code);
|
|
28
28
|
const items=raw.map(item=>{
|
|
29
29
|
need(item!==null&&typeof item==='object'&&!Array.isArray(item),code);
|
|
30
|
-
try{shape(item,['requirement','satisfied','evidence',...['run','result'].filter(key=>Object.hasOwn(item,key))]);}catch{need(false,code);}
|
|
30
|
+
try{shape(item,['requirement','satisfied','evidence',...['run','result','id','evidenceType','environment'].filter(key=>Object.hasOwn(item,key))]);}catch{need(false,code);}
|
|
31
31
|
need(typeof item.satisfied==='boolean',code);
|
|
32
32
|
boundedText(item.requirement,code);boundedText(item.evidence,code);
|
|
33
33
|
const run=item.run??null,result=item.result??null;
|
|
34
34
|
need(run===null||RUNS.has(run),code);need(result===null||RESULTS.has(result),code);
|
|
35
|
+
for(const key of ['id','evidenceType','environment'])if(item[key]!==undefined&&item[key]!==null)boundedText(item[key],code);
|
|
35
36
|
return freeze({requirement:item.requirement,satisfied:item.satisfied,evidence:item.evidence,
|
|
37
|
+
...Object.fromEntries(['id','evidenceType','environment'].filter(key=>item[key]!=null).map(key=>[key,item[key]])),
|
|
36
38
|
...(run===null?{}:{run}),...(result===null||run!=='baseline'?{}:{result})});
|
|
37
39
|
});
|
|
38
40
|
need(Buffer.byteLength(JSON.stringify(items),'utf8')<=REQUIREMENT_EVIDENCE_LIMIT,code);
|
|
@@ -68,7 +70,7 @@ export function readRequirementEvidence(entry){
|
|
|
68
70
|
export function requirementReportProblem(raw){
|
|
69
71
|
if(!Array.isArray(raw))return 'not a list';
|
|
70
72
|
if(raw.length>REQUIREMENT_ITEM_LIMIT)return `more than ${REQUIREMENT_ITEM_LIMIT} items`;
|
|
71
|
-
const known=['requirement','satisfied','evidence','run','result'];
|
|
73
|
+
const known=['requirement','satisfied','evidence','run','result','id','evidenceType','environment'];
|
|
72
74
|
for(const [index,item] of raw.entries()){
|
|
73
75
|
const at=`item ${index+1}`;
|
|
74
76
|
if(item===null||typeof item!=='object'||Array.isArray(item))return `${at}: not an object`;
|
|
@@ -466,7 +466,7 @@ const sealed = (data,key) => {
|
|
|
466
466
|
need(Buffer.byteLength(JSON.stringify(result))<=8*1024*1024,'limit_exceeded');
|
|
467
467
|
return freeze(result);
|
|
468
468
|
};
|
|
469
|
-
export function captureReviewBaseline(options,legacy=false,policyVersion=2,baselinePolicy=null) {
|
|
469
|
+
export function captureReviewBaseline(options,legacy=false,policyVersion=2,baselinePolicy=null,acceptance=true) {
|
|
470
470
|
const v=plain(options); keys(v,['root','identity','scope','requirements',
|
|
471
471
|
...['specsRoot','codeProjectPaths','bootstrapRequirements','specification','version','scopeRevisionPaths'].filter(key=>Object.hasOwn(v,key))]); identityCheck(v.identity);
|
|
472
472
|
const version=v.version??2;need([1,2].includes(version));
|
|
@@ -480,7 +480,7 @@ export function captureReviewBaseline(options,legacy=false,policyVersion=2,basel
|
|
|
480
480
|
if(Object.hasOwn(v,'specification')){
|
|
481
481
|
keys(v.specification,['specsRoot','feature']);
|
|
482
482
|
need(v.specification.specsRoot===v.specsRoot,'spec_drift');
|
|
483
|
-
specification=captureSpecificationMaterial({...v.specification,taskId:v.identity.taskId});
|
|
483
|
+
specification=captureSpecificationMaterial({...v.specification,taskId:v.identity.taskId,acceptance});
|
|
484
484
|
}
|
|
485
485
|
const scope=paths(v.scope), requirements=requirementPaths(v.requirements,bootstrap!==null||specification!==null),root=rootPath(v.root);
|
|
486
486
|
need(![...scope,...requirements].some(p=>inDependencyDirectory(p)||inCocoaPodsTree(root,p)),'excluded_snapshot_path');
|