@aibyzero/cm-workflow 0.16.7 → 0.16.9
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/CHANGELOG.md +37 -0
- package/README.md +39 -3
- package/VERSION +1 -1
- package/assets/readme/workflow-recovery-detailed.png +0 -0
- package/assets/readme/workflow-stages-detailed.png +0 -0
- package/compat/claude-commands/cm-notify.md +3 -0
- package/docs/installation.md +1 -1
- package/docs/js-workflow-control.md +61 -4
- package/docs/next-steps.md +8 -2
- package/docs/user-guide.md +204 -0
- package/package.json +2 -1
- package/runtime/js/cm-ai/claude-review-stream.mjs +49 -13
- package/runtime/js/cm-ai/cm-ai-admission.mjs +3 -1
- package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +138 -26
- package/runtime/js/cm-ai/cm-ai-qa-log.mjs +142 -21
- package/runtime/js/cm-ai/code-projects.mjs +4 -1
- package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -1
- package/runtime/js/cm-ai/developer-adapter.mjs +7 -0
- package/runtime/js/cm-ai/drive-core.mjs +26 -4
- package/runtime/js/cm-ai/durable-runner-state.mjs +951 -43
- package/runtime/js/cm-ai/effect-abandon-log.mjs +5 -2
- package/runtime/js/cm-ai/effect-contract.mjs +6 -1
- package/runtime/js/cm-ai/execution-store.mjs +4 -2
- package/runtime/js/cm-ai/external-run-guard.mjs +18 -7
- package/runtime/js/cm-ai/host-check.mjs +4 -1
- package/runtime/js/cm-ai/host-conversation-execution.mjs +11 -4
- package/runtime/js/cm-ai/host-documentation.mjs +53 -12
- package/runtime/js/cm-ai/host-project-execution.mjs +2 -2
- package/runtime/js/cm-ai/host-qa-executor.mjs +86 -17
- package/runtime/js/cm-ai/host-qa-fix-owner.mjs +44 -9
- package/runtime/js/cm-ai/host-session.mjs +47 -7
- package/runtime/js/cm-ai/host-tool-bridge.mjs +55 -6
- package/runtime/js/cm-ai/host-workflow-capabilities.mjs +4 -2
- package/runtime/js/cm-ai/operator-guidance.mjs +112 -3
- package/runtime/js/cm-ai/provider-review-observation.mjs +50 -0
- package/runtime/js/cm-ai/qa-resource-release.mjs +46 -0
- package/runtime/js/cm-ai/qa-round-budget.mjs +13 -0
- package/runtime/js/cm-ai/review-dispatch-limits.mjs +18 -0
- package/runtime/js/cm-ai/review-package.mjs +10 -1
- package/runtime/js/cm-ai/reviewed-deliveries.mjs +29 -6
- package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +1 -1
- package/runtime/js/cm-ai/task-commit.mjs +39 -0
- package/runtime/js/cm-ai/task-runner.mjs +636 -65
- package/runtime/js/cm-ai/worker-claude-developer.mjs +9 -0
- package/runtime/js/cm-ai/worker-claude.mjs +10 -3
- package/runtime/js/cm-ai/worker-process-identity.mjs +43 -0
- package/runtime/js/cm-fix/cause-package.mjs +37 -8
- package/runtime/js/cm-fix/diagnosis.mjs +43 -0
- package/runtime/js/cm-fix/execution.mjs +356 -187
- package/runtime/js/cm-fix/host.mjs +2 -1
- package/runtime/js/cm-fix/investigation.mjs +25 -9
- package/runtime/js/cm-fix/pinned-baseline.mjs +24 -0
- package/runtime/js/cm-fix/progress.mjs +15 -3
- package/runtime/js/cm-fix/protected-edits.mjs +10 -3
- package/runtime/js/cm-fix/repair.mjs +11 -3
- package/runtime/js/cm-fix/test-author.mjs +10 -3
- package/runtime/js/cm-idea/session.mjs +67 -4
- package/runtime/js/cm-prd/review-correction.mjs +10 -4
- package/runtime/js/cm-prd/session.mjs +43 -0
- package/runtime/js/cm-refactor/records.mjs +98 -8
- package/runtime/js/cm-refactor/workflow.mjs +79 -9
- package/runtime/js/cm-test/host.mjs +10 -3
- package/runtime/js/cm-test/session.mjs +45 -6
- package/runtime/js/notify-run.mjs +26 -0
- package/runtime/js/notify-safe-read.mjs +49 -0
- package/runtime/js/notify-send.mjs +312 -0
- package/runtime/js/notify.mjs +492 -0
- package/runtime/js/policy-binding-compat.mjs +54 -0
- package/runtime/model-efficiency.md +17 -0
- package/scripts/ci-test-shards.mjs +67 -0
- package/scripts/ci-test-shards.test.mjs +64 -0
- package/scripts/ci-test-weights.json +222 -0
- package/scripts/cm-ai-abandon-effect-position.test.mjs +70 -2
- package/scripts/cm-ai-answer-gap-dispatch.test.mjs +86 -0
- package/scripts/cm-ai-answer-gap-driver.test.mjs +51 -0
- package/scripts/cm-ai-answer-gap-fixture.mjs +96 -0
- package/scripts/cm-ai-answer-gap-recheck.test.mjs +70 -0
- package/scripts/cm-ai-answer-gap-redo.test.mjs +103 -0
- package/scripts/cm-ai-batch-drive.mjs +55 -10
- package/scripts/cm-ai-batch-drive.test.mjs +65 -0
- package/scripts/cm-ai-batch-host.mjs +132 -13
- package/scripts/cm-ai-batch-host.test.mjs +255 -7
- package/scripts/cm-ai-batch-run-fixture.mjs +499 -0
- package/scripts/cm-ai-batch-run-member-stops.test.mjs +38 -0
- package/scripts/cm-ai-batch-run-parallel.test.mjs +7 -0
- package/scripts/cm-ai-batch-run-reschedule.test.mjs +17 -0
- package/scripts/cm-ai-batch-run.mjs +189 -22
- package/scripts/cm-ai-batch-run.test.mjs +22 -334
- package/scripts/cm-ai-develop-answer-invalid.test.mjs +104 -0
- package/scripts/cm-ai-develop-call-timeout.test.mjs +153 -0
- package/scripts/cm-ai-develop-driver-gaps.test.mjs +4 -3
- package/scripts/cm-ai-documentation-sync-gap.test.mjs +424 -0
- package/scripts/cm-ai-drive.mjs +68 -23
- package/scripts/cm-ai-drive.test.mjs +37 -2
- package/scripts/cm-ai-fix-run-delivery.test.mjs +138 -0
- package/scripts/cm-ai-host-cli-workflow.test.mjs +271 -0
- package/scripts/cm-ai-host-fixture.mjs +268 -0
- package/scripts/cm-ai-host-protected.test.mjs +251 -0
- package/scripts/cm-ai-host.mjs +28 -16
- package/scripts/cm-ai-host.test.mjs +17 -759
- package/scripts/cm-ai-light-modules.test.mjs +57 -0
- package/scripts/cm-ai-operator-guidance.test.mjs +30 -5
- package/scripts/cm-ai-project-qa-gate.test.mjs +71 -4
- package/scripts/cm-ai-protected-scope.test.mjs +7 -3
- package/scripts/cm-ai-qa-answer-gaps.test.mjs +99 -0
- package/scripts/cm-ai-qa-fix-cross-session.test.mjs +78 -11
- package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +127 -8
- package/scripts/cm-ai-review-dispatch-exit.test.mjs +475 -0
- package/scripts/cm-ai-review-failure.test.mjs +124 -13
- package/scripts/cm-ai-review-timeout.test.mjs +188 -10
- package/scripts/cm-ai-run.mjs +15 -6
- package/scripts/cm-ai-supersede.test.mjs +486 -41
- package/scripts/cm-check-drive-files.mjs +8 -0
- package/scripts/cm-check-drive.test.mjs +2 -5
- package/scripts/cm-check-runtime.sh +4 -2
- package/scripts/cm-claude-developer-worker.test.mjs +15 -0
- package/scripts/cm-claude-review-stream.test.mjs +21 -16
- package/scripts/cm-claude-review-synthetic.test.mjs +155 -0
- package/scripts/cm-claude-worker.test.mjs +18 -2
- package/scripts/cm-external-model-recovery.test.mjs +29 -3
- package/scripts/cm-fix-abandon.test.mjs +249 -10
- package/scripts/cm-fix-cause-package.test.mjs +33 -0
- package/scripts/cm-fix-drive-unprotected.test.mjs +37 -0
- package/scripts/cm-fix-drive.mjs +34 -8
- package/scripts/cm-fix-host.mjs +8 -7
- package/scripts/cm-fix-rediagnosis.test.mjs +71 -4
- package/scripts/cm-fix-review-budget.test.mjs +13 -0
- package/scripts/cm-fix-review-recovery.test.mjs +35 -0
- package/scripts/cm-host-answer-timeout.test.mjs +65 -0
- package/scripts/cm-host-call-kinds.test.mjs +28 -0
- package/scripts/cm-host-documentation.test.mjs +49 -0
- package/scripts/cm-host-qa-executor.test.mjs +143 -10
- package/scripts/cm-idea-answer-gaps.test.mjs +164 -0
- package/scripts/cm-idea-drive.mjs +49 -11
- package/scripts/cm-idea-drive.test.mjs +66 -0
- package/scripts/cm-idea-host.mjs +106 -16
- package/scripts/cm-init-answer-gaps.test.mjs +258 -0
- package/scripts/cm-init-drive.mjs +41 -7
- package/scripts/cm-init-host.mjs +61 -12
- package/scripts/cm-log-event.mjs +49 -12
- package/scripts/cm-notify-command.test.mjs +900 -0
- package/scripts/cm-notify-read-drift.test.mjs +205 -0
- package/scripts/cm-notify.mjs +469 -0
- package/scripts/cm-notify.test.mjs +685 -0
- package/scripts/cm-patrol.mjs +83 -0
- package/scripts/cm-patrol.test.mjs +161 -0
- package/scripts/cm-prd-answer-gaps.test.mjs +216 -0
- package/scripts/cm-prd-drive.mjs +18 -5
- package/scripts/cm-prd-drive.test.mjs +15 -0
- package/scripts/cm-prd-host.mjs +37 -4
- package/scripts/cm-prd-review-disposition.test.mjs +6 -1
- package/scripts/cm-prd-review-gate.mjs +56 -0
- package/scripts/cm-refactor-answer-gaps.test.mjs +206 -0
- package/scripts/cm-refactor-drive.mjs +52 -8
- package/scripts/cm-refactor-drive.test.mjs +44 -0
- package/scripts/cm-refactor-host.test.mjs +10 -6
- package/scripts/cm-release-smoke.sh +2 -0
- package/scripts/cm-test-answer-gaps.test.mjs +151 -0
- package/scripts/cm-test-drive.mjs +21 -5
- package/scripts/cm-token-report.mjs +497 -0
- package/scripts/cm-token-report.test.mjs +346 -0
- package/scripts/fixtures/claude-review-process.mjs +1 -1
- package/scripts/policy-binding-compat.test.mjs +99 -0
- package/scripts/scan-public-safety.py +4 -0
- package/scripts/validate-public-repo.py +4 -0
- package/skills/cm-ai/SKILL.md +7 -3
- package/skills/cm-ai/references/N6-qa-eval.md +2 -2
- package/skills/cm-ai/references/js-host-modes.md +90 -0
- package/skills/cm-ai/references/js-host-qa-recovery.md +136 -0
- package/skills/cm-ai/references/js-host-recovery.md +311 -0
- package/skills/cm-ai/references/js-host.md +76 -331
- package/skills/cm-check/SKILL.md +3 -3
- package/skills/cm-fix/SKILL.md +2 -0
- package/skills/cm-fix/references/js-host.md +56 -10
- package/skills/cm-idea/references/js-host.md +27 -2
- package/skills/cm-init/references/js-host.md +16 -3
- package/skills/cm-notify/SKILL.md +34 -0
- package/skills/cm-prd/SKILL.md +2 -0
- package/skills/cm-prd/references/js-change-recovery.md +35 -1
- package/skills/cm-refactor/references/js-host.md +17 -0
- package/skills/cm-test/references/js-host.md +14 -1
|
@@ -9,7 +9,7 @@ export function createFixHost({owner,config,runtime='codex',permissions=[],autho
|
|
|
9
9
|
const extra=new Set(permissions);
|
|
10
10
|
const host={async handle(request){
|
|
11
11
|
shape(request,['requestId','operation',...(request.operation==='resume'?['evidenceFiles']:[]),
|
|
12
|
-
...(['abandon_step','abandon_review','rediagnose'].includes(request.operation)&&Object.hasOwn(request,'reason')?['reason']:[]),
|
|
12
|
+
...(['abandon_step','abandon_review','rediagnose','rerun_blocked_step'].includes(request.operation)&&Object.hasOwn(request,'reason')?['reason']:[]),
|
|
13
13
|
...(request.operation==='prepare_revision'&&Object.hasOwn(request,'tests')?['tests']:[]),
|
|
14
14
|
...(request.operation==='reconcile_review'?['invocationId']:[]),
|
|
15
15
|
...(request.operation==='recover_final_review'?['invocationId','packageDigest','previousInvocationStopped','reason']:[])]);
|
|
@@ -29,6 +29,7 @@ export function createFixHost({owner,config,runtime='codex',permissions=[],autho
|
|
|
29
29
|
authorized:extra.has('--allow-final-review-recovery'),recoveryInvocationId,invocationId:request.invocationId,
|
|
30
30
|
packageDigest:request.packageDigest,previousInvocationStopped:request.previousInvocationStopped,reason:request.reason});
|
|
31
31
|
if(request.operation==='abandon_step')return owner.abandonStep({authorized:extra.has('--allow-abandon'),reason:request.reason});
|
|
32
|
+
if(request.operation==='rerun_blocked_step')return owner.rerunBlockedStep({authorized:extra.has('--allow-rerun-blocked-step'),reason:request.reason});
|
|
32
33
|
// Reviewer-invocation authority stays separate from local step abandonment.
|
|
33
34
|
if(request.operation==='abandon_review')return owner.abandonReview({authorized:extra.has('--allow-abandon-review'),reason:request.reason});
|
|
34
35
|
if(request.operation==='rediagnose')return owner.rediagnose({authorized:extra.has('--allow-rediagnosis'),reason:request.reason});
|
|
@@ -2,19 +2,35 @@
|
|
|
2
2
|
// Structural completeness is not proof: independent Review checks the claims.
|
|
3
3
|
import {need,shape,text} from '../cm-ai/effect-contract.mjs';
|
|
4
4
|
|
|
5
|
+
// Names the first failing field (and its item limit) on the thrown error without
|
|
6
|
+
// changing its code, so a rejected answer can say what to fix.
|
|
7
|
+
export function atField(field,check,limit=null,actual=null){
|
|
8
|
+
try{return check();}
|
|
9
|
+
catch(error){
|
|
10
|
+
if(error&&typeof error==='object'&&error.field===undefined)Object.assign(error,{field},limit===null?{}:{limit,actual});
|
|
11
|
+
throw error;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
const count=value=>Array.isArray(value)?value.length:null;
|
|
15
|
+
|
|
5
16
|
export function inspectFixInvestigation(value,crossLayer){
|
|
6
|
-
shape(value,['discardedAlternatives','boundaryAnalysis']);
|
|
7
|
-
need(Array.isArray(value.discardedAlternatives)
|
|
8
|
-
|
|
17
|
+
atField('investigation',()=>shape(value,['discardedAlternatives','boundaryAnalysis']));
|
|
18
|
+
atField('investigation.discardedAlternatives',()=>need(Array.isArray(value.discardedAlternatives)
|
|
19
|
+
&&value.discardedAlternatives.length<=3,'invalid_fix_investigation'),3,count(value.discardedAlternatives));
|
|
20
|
+
value.discardedAlternatives.forEach((item,index)=>atField(`investigation.discardedAlternatives[${index}]`,
|
|
21
|
+
()=>{shape(item,['option','reason']);text(item.option);text(item.reason);}));
|
|
9
22
|
const boundary=value.boundaryAnalysis;
|
|
10
23
|
if(boundary===null)return value; // Missing evidence stays missing, even on cross-layer work.
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
24
|
+
atField('investigation.boundaryAnalysis',()=>{
|
|
25
|
+
need(crossLayer===true,'invalid_fix_investigation');
|
|
26
|
+
shape(boundary,['callChain','edgeEvidence','lastNormalEdge','firstFailingEdge','hypotheses']);
|
|
27
|
+
for(const key of ['callChain','edgeEvidence','lastNormalEdge','firstFailingEdge'])atField(`investigation.boundaryAnalysis.${key}`,()=>text(boundary[key]));
|
|
28
|
+
});
|
|
29
|
+
atField('investigation.boundaryAnalysis.hypotheses',()=>need(Array.isArray(boundary.hypotheses)&&boundary.hypotheses.length>0
|
|
30
|
+
&&boundary.hypotheses.length<=3,'invalid_fix_investigation'),3,count(boundary.hypotheses));
|
|
31
|
+
boundary.hypotheses.forEach((item,index)=>atField(`investigation.boundaryAnalysis.hypotheses[${index}]`,()=>{
|
|
16
32
|
shape(item,['hypothesis','support','counterTest','result']);for(const key of ['hypothesis','support','counterTest','result'])text(item[key]);
|
|
17
|
-
}
|
|
33
|
+
}));
|
|
18
34
|
return value;
|
|
19
35
|
}
|
|
20
36
|
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// V2/V6 for cm-fix write steps redone after an abandonment or a blocked rerun:
|
|
2
|
+
// the redo registers the baseline its first intent captured (journaled), so the
|
|
3
|
+
// earlier attempt's residue is reviewed instead of becoming the "before" image.
|
|
4
|
+
import {readReviewBaseline} from '../cm-ai/review-package.mjs';
|
|
5
|
+
import {digest,need} from '../cm-ai/effect-contract.mjs';
|
|
6
|
+
|
|
7
|
+
const metadata=file=>{if(!file)return null;const {contentBase64,...rest}=file;return rest;};
|
|
8
|
+
// The pinned baseline must bind exactly what a fresh capture would bind now
|
|
9
|
+
// (identity, root, scope, requirements); only file images may differ.
|
|
10
|
+
export function readPinned(raw,fresh){
|
|
11
|
+
const pinned=readReviewBaseline(raw);
|
|
12
|
+
for(const key of ['identity','rootDigest','specsPath','scope','requirements','version'])
|
|
13
|
+
need(digest(pinned[key]??null)===digest(fresh[key]??null),'fix_pinned_baseline_mismatch');
|
|
14
|
+
return pinned;
|
|
15
|
+
}
|
|
16
|
+
// Paths whose current image differs from the pinned one where it may not:
|
|
17
|
+
// outside the step scope always; inside it too in protected mode.
|
|
18
|
+
export function pinnedResidue(baseline,now,scope,protectedMode){
|
|
19
|
+
const before=new Map(baseline.files.map(file=>[file.path,metadata(file)])),after=new Map(now.files.map(file=>[file.path,metadata(file)]));
|
|
20
|
+
const changed=[...new Set([...before.keys(),...after.keys()])].filter(file=>digest(before.get(file)??null)!==digest(after.get(file)??null));
|
|
21
|
+
const refused=changed.filter(file=>protectedMode||!scope.includes(file)).sort();
|
|
22
|
+
if(refused.length)throw Object.assign(new Error(`fix_pinned_residue: ${refused.slice(0,20).join(', ')}`),{code:protectedMode?'fix_protected_residue':'fix_pinned_residue',paths:refused});
|
|
23
|
+
return changed;
|
|
24
|
+
}
|
|
@@ -51,13 +51,20 @@ export function fixProgress(status,config={},authorization={}){
|
|
|
51
51
|
}
|
|
52
52
|
}
|
|
53
53
|
const invocation=status.finalReviewInvocation;
|
|
54
|
+
if(stage==='unknown'&&status.pending==='rediagnosis')return {...result,current:'重新诊断已登记但还没有有效结论',blocker:'rediagnosis_answer_required',
|
|
55
|
+
nextAction:'原 run 再次使用 rediagnose(--allow-rediagnosis、reason)提交合法诊断答案;沿用已登记的这一次重新诊断,不另占次数,之后进入第二轮根因审查。',requiresUser:true};
|
|
54
56
|
if(stage==='unknown'){
|
|
55
57
|
const finalPending=!revision&&invocation&&(!review||review.observationStatus==='unknown');
|
|
58
|
+
const recoveryLimit=finalPending&&!invocation.providerThreadId&&(status.finalReviewRecoveryCount??0)>=2;
|
|
59
|
+
if(recoveryLimit)return {...result,current:'首轮最终审查无线程恢复已用满',blocker:'fix_review_recovery_limit',
|
|
60
|
+
nextAction:'首轮最终审查的 worker 连续没有打开审查线程,无线程恢复已用满 2 次,不再续审。先查清审查 CLI 为何起不来(登录、额度、网络或本机环境);原运行记录保留,修好后发 cancel 结束本运行,用新的 runId 重新发起修复。',
|
|
61
|
+
requiresUser:true};
|
|
56
62
|
return {...result,current:finalPending?'独立审查结果未确认':'操作结果未确认',blocker:'result_unconfirmed',
|
|
57
63
|
remaining:finalPending?['取得有效独立审查结果','保存审查证据','核对完成条件','审后回归',...(config.walkthrough?['走查']:[]),'完成收尾']:null,
|
|
58
|
-
nextAction:finalPending&&invocation.providerThreadId
|
|
59
|
-
?'
|
|
60
|
-
:status.reviewAbandonable?'审查没有结论:先确认原审查进程已停止,再用 abandon_review(--allow-abandon-review
|
|
64
|
+
nextAction:finalPending&&(invocation.providerThreadId||(status.finalReviewRecoveryCount??0)<2)
|
|
65
|
+
?'先确认原调用已停止;核对当前审查包并取得本次一次续审授权(recover_final_review),再恢复原任务。'
|
|
66
|
+
:status.reviewAbandonable?'审查没有结论:先确认原审查进程已停止,再用 abandon_review(--allow-abandon-review,原因审查每轮、第二轮最终审查各最多两次)放弃这次调用,然后重新审查。'
|
|
67
|
+
:status.reviewAbandonBudgetExhausted?'fix_review_abandon_budget_exhausted: 本轮审查已无结论放弃重派 2 次,不再重派;查清审查进程为何一直没有结论后,用新的 cm-fix 运行重做。'
|
|
61
68
|
:'核对原操作与实际结果;不要重跑已完成步骤或推定成功。',requiresUser:true,
|
|
62
69
|
...(finalPending?{recovery:{invocationId:invocation.invocationId,packageDigest:invocation.packageDigest,
|
|
63
70
|
completedRecoveryPreparations:status.finalReviewRecoveryCount??0,
|
|
@@ -78,6 +85,11 @@ export function fixProgress(status,config={},authorization={}){
|
|
|
78
85
|
requiresUser:currentStage==='final_review_required'&&authorization.finalReviewAllowed!==true,
|
|
79
86
|
...(currentStage==='final_review_required'?{notice:'按现有启动权限执行;恢复派发仍需本次绑定授权。'}:{})};
|
|
80
87
|
}
|
|
88
|
+
// V10: a legitimate blocked verdict of a local step can be rerun with a reason.
|
|
89
|
+
if(status.blockedRerun)return {...result,current:'步骤给出合法的阻断结论',blocker:stage,
|
|
90
|
+
nextAction:status.blockedRerun.used<status.blockedRerun.limit
|
|
91
|
+
?`先处理阻断原因(环境、证据或答复),再在原 run 用 rerun_blocked_step(--allow-rerun-blocked-step、单行 reason)重跑 ${status.blockedRerun.pending};已用 ${status.blockedRerun.used}/${status.blockedRerun.limit} 次,阻断结果保留为历史。`
|
|
92
|
+
:`本步骤带理由重跑已用满 ${status.blockedRerun.limit} 次;保留历史,交用户判断。`,requiresUser:true};
|
|
81
93
|
return {...result,current:'当前流程受阻或需人工判断',blocker:stage,
|
|
82
94
|
nextAction:'按现有阶段要求处理阻断;历史记录不代表当前条件已通过。',requiresUser:true};
|
|
83
95
|
}
|
|
@@ -61,7 +61,10 @@ export function captureProtectedEdits(cwd,scope){
|
|
|
61
61
|
return Object.fromEntries(scope.map(file=>[file,snapshot(cwd,file)]));
|
|
62
62
|
}
|
|
63
63
|
|
|
64
|
-
|
|
64
|
+
// onApply (cm-ai protected development) journals the applying subprocess:
|
|
65
|
+
// apply_spawning before the spawn, apply_started with its pid right after. A
|
|
66
|
+
// journal failure kills the new group and fails the apply.
|
|
67
|
+
export async function commitProtectedEdits({cwd,specsRoot,scope,edits,expected,identity,timeoutMs,signal,onApply=null}){
|
|
65
68
|
need(Array.isArray(edits),'protected_edit_invalid');
|
|
66
69
|
for(const edit of edits)need(Object.hasOwn(expected,edit.path)&&edit.beforeSha256===expected[edit.path],'protected_edit_stale');
|
|
67
70
|
need(!signal.aborted,'cancelled');
|
|
@@ -69,10 +72,14 @@ export async function commitProtectedEdits({cwd,specsRoot,scope,edits,expected,i
|
|
|
69
72
|
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'cm-fix-edits-')),file=path.join(dir,'edits.json');
|
|
70
73
|
try{
|
|
71
74
|
fs.writeFileSync(file,JSON.stringify({cwd,scope,edits}),{mode:0o600,flag:'wx'});
|
|
75
|
+
let journalFailed=false;
|
|
76
|
+
onApply?.({phase:'apply_spawning'});
|
|
72
77
|
const check=createHostCheck({cwd,specsRoot,timeoutMs,commands:[{id:'protected-edits',
|
|
73
|
-
command:[process.execPath,fileURLToPath(import.meta.url),file]}]
|
|
78
|
+
command:[process.execPath,fileURLToPath(import.meta.url),file]}],
|
|
79
|
+
...(onApply?{onSpawn:({pid})=>{try{onApply({phase:'apply_started',pid});}
|
|
80
|
+
catch{journalFailed=true;try{process.kill(-pid,'SIGKILL');}catch{}}}}:{})});
|
|
74
81
|
const [observed]=await check({identity},{signal});
|
|
75
|
-
need(observed.outcome==='passed','protected_edit_failed');
|
|
82
|
+
need(!journalFailed&&observed.outcome==='passed','protected_edit_failed');
|
|
76
83
|
}finally{if(fs.existsSync(file))fs.unlinkSync(file);fs.rmdirSync(dir);}
|
|
77
84
|
}
|
|
78
85
|
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import {currentTestFiles,verifyExtensionFiles} from './test-extension.mjs';
|
|
4
4
|
import {types} from 'node:util';
|
|
5
5
|
import {captureReviewBaseline,readReviewBaseline} from '../cm-ai/review-package.mjs';
|
|
6
|
+
import {readPinned,pinnedResidue} from './pinned-baseline.mjs';
|
|
6
7
|
import {validateDeveloperScope} from '../cm-ai/developer-adapter.mjs';
|
|
7
8
|
import {inspectFixRedTest,verifyFixRedEvidence,redEvidenceRetry} from './red-test.mjs';
|
|
8
9
|
import {inspectFixBaseline,fixBaselineFiles} from './baseline.mjs';
|
|
@@ -45,7 +46,7 @@ export function verifyFixRepair({codeProject,specsRoot,baseline,result,allowUnch
|
|
|
45
46
|
need(digest(files)===digest(checked.files),'repair_evidence_changed');
|
|
46
47
|
}
|
|
47
48
|
|
|
48
|
-
export function prepareFixRepair(options,{bridge,assertReviewReady}){
|
|
49
|
+
export function prepareFixRepair(options,{bridge,assertReviewReady,pinnedBaseline=null,protectedMode=false}){
|
|
49
50
|
const config=json(options);shape(config,['codeProject','specsRoot','identity','scope','requirements','defect','diagnosis',
|
|
50
51
|
'redTest','baseline','redEvidence','beforeBaseline',...(Object.hasOwn(config,'reviewFeedback')?['reviewFeedback']:[]),...(Object.hasOwn(config,'testExtension')?['testExtension']:[])]);
|
|
51
52
|
const priorReview=Object.hasOwn(config,'reviewFeedback')?inspectFixRepairReview(config.reviewFeedback,config.identity):null;
|
|
@@ -71,7 +72,13 @@ export function prepareFixRepair(options,{bridge,assertReviewReady}){
|
|
|
71
72
|
verifyTests();
|
|
72
73
|
const capture=()=>captureReviewBaseline({root:config.codeProject,specsRoot:config.specsRoot,identity:config.identity,
|
|
73
74
|
scope:config.scope,requirements:config.requirements});
|
|
74
|
-
|
|
75
|
+
// A redo after abandonment keeps the first intent's baseline (pinnedBaseline):
|
|
76
|
+
// the abandoned attempt's residue in scope is reviewed as part of this step.
|
|
77
|
+
const fresh=capture(),baseline=pinnedBaseline===null?fresh:readPinned(pinnedBaseline,fresh);let used=false;
|
|
78
|
+
// Out of scope nothing may differ from the pinned image; in protected mode
|
|
79
|
+
// (host-applied proposals) not even the scope: a partial write is restored
|
|
80
|
+
// first, never sent to review as a new delivery (V6).
|
|
81
|
+
const residue=now=>pinnedResidue(baseline,now,config.scope,protectedMode);
|
|
75
82
|
return Object.freeze({baseline,async execute({authorized,signal,register}){
|
|
76
83
|
need(authorized===true,'repair_authorization_required');need(!used,'repair_already_attempted');
|
|
77
84
|
need(typeof register==='function','repair_registration_required');need(!signal.aborted,'cancelled');
|
|
@@ -79,7 +86,8 @@ export function prepareFixRepair(options,{bridge,assertReviewReady}){
|
|
|
79
86
|
const result=callback();if(types.isPromise(result))Promise.prototype.then.call(result,()=>{},()=>{});
|
|
80
87
|
need(result===undefined,'repair_sync_boundary_required');
|
|
81
88
|
};
|
|
82
|
-
synchronous(assertReviewReady);verifyTests();
|
|
89
|
+
synchronous(assertReviewReady);verifyTests();
|
|
90
|
+
if(pinnedBaseline===null)need(digest(capture())===digest(baseline),'repair_baseline_changed');else residue(capture());
|
|
83
91
|
used=true;synchronous(()=>register(baseline));need(!signal.aborted,'cancelled');
|
|
84
92
|
const response=json(await bridge.call('fix_repair',{
|
|
85
93
|
identity:config.identity,codeProject:config.codeProject,scope:config.scope,defect:config.defect,diagnosis:config.diagnosis,
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// review-channel readiness; filesystem diff checks detect, not sandbox, writes.
|
|
3
3
|
import {types} from 'node:util';
|
|
4
4
|
import {captureReviewBaseline,readReviewBaseline} from '../cm-ai/review-package.mjs';
|
|
5
|
+
import {readPinned,pinnedResidue} from './pinned-baseline.mjs';
|
|
5
6
|
import {validateDeveloperScope} from '../cm-ai/developer-adapter.mjs';
|
|
6
7
|
import {digest,json,need,shape,validIdentity} from '../cm-ai/effect-contract.mjs';
|
|
7
8
|
|
|
@@ -26,13 +27,19 @@ export function inspectFixTestAuthor(raw,baselineRaw){
|
|
|
26
27
|
return value;
|
|
27
28
|
}
|
|
28
29
|
|
|
29
|
-
export function prepareFixTestAuthor(options,{bridge,assertReviewReady}){
|
|
30
|
+
export function prepareFixTestAuthor(options,{bridge,assertReviewReady,pinnedBaseline=null,protectedMode=false}){
|
|
30
31
|
const config=json(options);shape(config,['codeProject','specsRoot','identity','testFiles','requirements','defect','diagnosis','reproduction',...(Object.hasOwn(config,'reviewFeedback')?['reviewFeedback','testPlan']:[])]);
|
|
31
32
|
validIdentity(config.identity);validateDeveloperScope(config.testFiles);
|
|
32
33
|
need(bridge&&typeof bridge.call==='function'&&typeof assertReviewReady==='function','test_author_unavailable');
|
|
33
34
|
const capture=()=>captureReviewBaseline({root:config.codeProject,specsRoot:config.specsRoot,identity:config.identity,
|
|
34
35
|
scope:config.testFiles,requirements:config.requirements});
|
|
35
|
-
|
|
36
|
+
// A redo after abandonment keeps the first intent's baseline (pinnedBaseline):
|
|
37
|
+
// the abandoned attempt's residue in scope is reviewed as part of this step.
|
|
38
|
+
const fresh=capture(),baseline=pinnedBaseline===null?fresh:readPinned(pinnedBaseline,fresh);let used=false;
|
|
39
|
+
// Out of scope nothing may differ from the pinned image; in protected mode
|
|
40
|
+
// (host-applied proposals) not even the scope: a partial write is restored
|
|
41
|
+
// first, never sent to review as a new delivery (V6).
|
|
42
|
+
const residue=now=>pinnedResidue(baseline,now,config.testFiles,protectedMode);
|
|
36
43
|
return Object.freeze({baseline,async execute({authorized,signal,register}){
|
|
37
44
|
need(authorized===true,'test_author_authorization_required');need(!used,'test_author_already_attempted');
|
|
38
45
|
need(typeof register==='function','test_author_registration_required');need(!signal.aborted,'cancelled');
|
|
@@ -42,7 +49,7 @@ export function prepareFixTestAuthor(options,{bridge,assertReviewReady}){
|
|
|
42
49
|
need(result===undefined,'test_author_sync_boundary_required');
|
|
43
50
|
};
|
|
44
51
|
synchronous(assertReviewReady);
|
|
45
|
-
need(digest(capture())===digest(baseline),'test_author_baseline_changed');
|
|
52
|
+
if(pinnedBaseline===null)need(digest(capture())===digest(baseline),'test_author_baseline_changed');else residue(capture());
|
|
46
53
|
used=true;synchronous(()=>register(baseline));need(!signal.aborted,'cancelled');
|
|
47
54
|
const response=json(await bridge.call('fix_test_author',{
|
|
48
55
|
identity:config.identity,codeProject:config.codeProject,scope:config.testFiles,
|
|
@@ -6,12 +6,40 @@ import {need,json,shape,digest} from '../cm-ai/effect-contract.mjs';
|
|
|
6
6
|
import {readCmInitSource} from '../cm-init/draft-inspection.mjs';
|
|
7
7
|
import {replaceSessionFile} from '../cm-prd/session.mjs';
|
|
8
8
|
|
|
9
|
+
// V1 (O09/O10/O13/O14) and V7: a call whose answer was recorded and then refused
|
|
10
|
+
// on every replay (discard), or whose outcome is unknown (abandon), may be asked
|
|
11
|
+
// again under the same pending request with a fresh callId. The record is
|
|
12
|
+
// append-only (abandonedCalls), at most MAX_CALL_ABANDONS per kind in a session;
|
|
13
|
+
// writes (init_write) are never re-asked here. A confirmation is asked of the
|
|
14
|
+
// person again; an answer bound to an abandoned callId is never accepted.
|
|
15
|
+
export const MAX_CALL_ABANDONS=2;
|
|
16
|
+
export const DRAFT_REASKABLE=Object.freeze({'cm-init':['init_analyze','init_generate','init_verify','init_confirm','init_review'],
|
|
17
|
+
'cm-idea':['idea_interview','idea_confirm_save']});
|
|
18
|
+
const ABANDON_KEYS=['kind','callId','requestDigest','operation','reason','resultDigest','evidence','at'];
|
|
19
|
+
function checkAbandoned(list,workflow){
|
|
20
|
+
need(Array.isArray(list)&&list.length<=MAX_CALL_ABANDONS*DRAFT_REASKABLE[workflow].length,'idea_session_abandon_record_invalid');
|
|
21
|
+
const ids=new Set();
|
|
22
|
+
for(const item of list){
|
|
23
|
+
need(item&&typeof item==='object'&&!Array.isArray(item)&&Object.keys(item).length===ABANDON_KEYS.length
|
|
24
|
+
&&ABANDON_KEYS.every(key=>Object.hasOwn(item,key))&&DRAFT_REASKABLE[workflow].includes(item.kind)
|
|
25
|
+
&&typeof item.callId==='string'&&!ids.has(item.callId)&&/^[a-f0-9]{64}$/.test(item.requestDigest)
|
|
26
|
+
&&typeof item.operation==='string'&&['answer_rejected','answer_missing'].includes(item.reason)
|
|
27
|
+
&&(item.reason==='answer_rejected'?/^[a-f0-9]{64}$/.test(item.resultDigest??''):item.resultDigest===null)
|
|
28
|
+
&&item.evidence&&/^[a-f0-9]{64}$/.test(item.evidence.sha256??'')&&Number.isSafeInteger(item.evidence.length)
|
|
29
|
+
&&item.evidence.length>0&&item.evidence.length<=2000&&typeof item.at==='string'&&Number.isFinite(Date.parse(item.at))
|
|
30
|
+
&&list.filter(other=>other.kind===item.kind).length<=MAX_CALL_ABANDONS,'idea_session_abandon_record_invalid');
|
|
31
|
+
ids.add(item.callId);
|
|
32
|
+
}
|
|
33
|
+
return ids;
|
|
34
|
+
}
|
|
9
35
|
export function openIdeaSession(file,binding){
|
|
10
36
|
return openDraftSession(file,binding,'cm-idea');
|
|
11
37
|
}
|
|
12
38
|
|
|
13
39
|
// Same private single-call journal for init; workflow identity stays disjoint.
|
|
14
|
-
|
|
40
|
+
// legacyBindings: older bindings accepted as a controlled migration (see
|
|
41
|
+
// runtime/js/policy-binding-compat.mjs); a session opened under one keeps it.
|
|
42
|
+
export function openDraftSession(file,binding,workflow,{legacyBindings=[]}={}){
|
|
15
43
|
need(['cm-idea','cm-init'].includes(workflow),'draft_session_workflow_invalid');
|
|
16
44
|
need(typeof file==='string'&&path.isAbsolute(file)&&path.resolve(file)===file
|
|
17
45
|
&&/^[A-Za-z0-9][A-Za-z0-9._-]*\.json$/.test(path.basename(file)),'idea_session_path_invalid');
|
|
@@ -35,11 +63,18 @@ export function openDraftSession(file,binding,workflow){
|
|
|
35
63
|
let bytes,state;
|
|
36
64
|
try{
|
|
37
65
|
bytes=read(name);state=bytes===null?{version:1,workflow,binding,checkpoint:null,pending:null,cancelled:false}:JSON.parse(bytes);
|
|
38
|
-
shape(state,['version','workflow','binding','checkpoint','pending','cancelled']);
|
|
39
|
-
need(state.version===1&&state.workflow===workflow&&digest(state.binding)===digest(binding)
|
|
66
|
+
shape(state,['version','workflow','binding','checkpoint','pending','cancelled',...(Object.hasOwn(state,'abandonedCalls')?['abandonedCalls']:[])]);
|
|
67
|
+
need(state.version===1&&state.workflow===workflow&&(digest(state.binding)===digest(binding)
|
|
68
|
+
||bytes!==null&&legacyBindings.some(item=>digest(item)===digest(state.binding))),'idea_session_binding_changed');
|
|
69
|
+
// Older files have no abandonedCalls and replay unchanged; a present list is checked.
|
|
70
|
+
if(Object.hasOwn(state,'abandonedCalls')){const ids=checkAbandoned(state.abandonedCalls,workflow);
|
|
71
|
+
need(!ids.has(state.pending?.call?.callId),'idea_session_abandon_record_invalid');}
|
|
40
72
|
}catch(e){fs.unlinkSync(path.join(root,lockName));throw e;}
|
|
41
73
|
const write=next=>{
|
|
42
74
|
next=json(next,1024*1024);const after=JSON.stringify(next);
|
|
75
|
+
// abandonedCalls only grows: every earlier record stays, in order.
|
|
76
|
+
const before=state.abandonedCalls??[],now=next.abandonedCalls??[];
|
|
77
|
+
need(now.length>=before.length&&before.every((item,index)=>digest(item)===digest(now[index])),'idea_session_abandon_record_invalid');
|
|
43
78
|
need(read(name)===bytes,'idea_session_changed');replaceSessionFile(root,name,bytes,after);
|
|
44
79
|
bytes=after;state=next;
|
|
45
80
|
};
|
|
@@ -49,13 +84,41 @@ export function openDraftSession(file,binding,workflow){
|
|
|
49
84
|
write({...state,checkpoint,pending:{request,call:null,writing:false}});},
|
|
50
85
|
commit(checkpoint){write({...state,checkpoint,pending:null});},
|
|
51
86
|
cancel(checkpoint){write({...state,checkpoint,cancelled:true});},
|
|
52
|
-
|
|
87
|
+
// expected (idea saves only): path and content digest of the one host-owned
|
|
88
|
+
// file, recorded before writing so recovery can compare the disk (V6).
|
|
89
|
+
writing(expected){need(state.pending!==null&&!state.cancelled,'idea_session_not_active');
|
|
90
|
+
write({...state,pending:{...state.pending,writing:true,...(expected?{expected}:{})}});},
|
|
91
|
+
// V6: the disk shows no write happened, so the same approved request may write.
|
|
92
|
+
writeAbsent(){need(state.pending?.writing===true&&state.pending.expected&&!state.cancelled,'idea_session_not_active');
|
|
93
|
+
const {expected,...pending}=state.pending;write({...state,pending:{...pending,writing:false}});},
|
|
94
|
+
get abandonedCalls(){return json(state.abandonedCalls??[]);},
|
|
95
|
+
abandonCall(resolution){
|
|
96
|
+
need(!state.cancelled,'cancelled');
|
|
97
|
+
need(resolution!==null&&typeof resolution==='object'&&!Array.isArray(resolution)
|
|
98
|
+
&&(resolution.discard===true)!==(resolution.abandon===true)&&!Object.hasOwn(resolution,'result')
|
|
99
|
+
&&Object.keys(resolution).every(key=>['callId','requestDigest','discard','abandon','evidence'].includes(key)),'idea_session_receipt_mismatch');
|
|
100
|
+
need(typeof resolution.evidence==='string'&&resolution.evidence.trim()&&resolution.evidence.length<=2000,'idea_session_abandon_evidence_required');
|
|
101
|
+
need(state.pending!==null,'idea_session_no_pending_call');need(!state.pending.writing,'idea_save_outcome_unknown');
|
|
102
|
+
const call=state.pending.call;
|
|
103
|
+
need(call&&call.callId===resolution.callId&&call.requestDigest===resolution.requestDigest,'idea_session_receipt_mismatch');
|
|
104
|
+
need(resolution.discard===true?Object.hasOwn(call,'result'):!Object.hasOwn(call,'result'),'idea_session_abandon_state');
|
|
105
|
+
need(DRAFT_REASKABLE[workflow].includes(call.kind),workflow==='cm-init'&&call.kind==='init_write'?'init_write_recovery_required':'idea_session_abandon_kind');
|
|
106
|
+
const list=state.abandonedCalls??[];
|
|
107
|
+
need(list.filter(item=>item.kind===call.kind).length<MAX_CALL_ABANDONS,'idea_session_abandon_limit');
|
|
108
|
+
const record={kind:call.kind,callId:call.callId,requestDigest:call.requestDigest,operation:state.pending.request.operation,
|
|
109
|
+
reason:resolution.discard===true?'answer_rejected':'answer_missing',
|
|
110
|
+
resultDigest:resolution.discard===true?digest(call.result):null,
|
|
111
|
+
evidence:{sha256:digest(resolution.evidence),length:resolution.evidence.length},at:new Date().toISOString()};
|
|
112
|
+
write({...state,abandonedCalls:[...list,record],pending:{...state.pending,call:null}});
|
|
113
|
+
return {...record,remaining:MAX_CALL_ABANDONS-list.filter(item=>item.kind===call.kind).length-1};
|
|
114
|
+
},
|
|
53
115
|
resume(resolution){
|
|
54
116
|
need(!state.cancelled,'cancelled');
|
|
55
117
|
if(state.pending===null){need(resolution===null,'idea_session_no_pending_call');return null;}
|
|
56
118
|
need(!state.pending.writing,'idea_save_outcome_unknown');
|
|
57
119
|
if(resolution!==null){
|
|
58
120
|
shape(resolution,['callId','requestDigest','result','evidence']);
|
|
121
|
+
need(!(state.abandonedCalls??[]).some(item=>item.callId===resolution.callId),'idea_session_call_abandoned');
|
|
59
122
|
const call=state.pending.call;
|
|
60
123
|
need(call&&!Object.hasOwn(call,'result')&&call.callId===resolution.callId&&call.requestDigest===resolution.requestDigest
|
|
61
124
|
&&typeof resolution.evidence==='string'&&resolution.evidence.trim(),'idea_session_receipt_mismatch');
|
|
@@ -128,10 +128,13 @@ function loadCorrection({specs,stage,feature}){
|
|
|
128
128
|
'prd_correction_archive_original_mismatch');seen.add(item.path);
|
|
129
129
|
}
|
|
130
130
|
const {after,plan}=inspectProposal(review,value.proposal),states=[];
|
|
131
|
+
// V6 (O04): reconcile each reviewed file against the archive: the corrected
|
|
132
|
+
// bytes continue, the original bytes are still to be written, anything else
|
|
133
|
+
// is a conflict for a person (listed with all three digests, never overwritten).
|
|
131
134
|
const before=value.before.map(item=>{
|
|
132
135
|
const currentHash=sha(readCorrectionFile(specs,item.path)),next=after.find(row=>row.path===item.path).sha256;
|
|
133
|
-
|
|
134
|
-
|
|
136
|
+
states.push({path:item.path,status:currentHash===next?'matches_correction':currentHash===item.sha256?'needs_correction':'conflict',
|
|
137
|
+
...(currentHash!==next&¤tHash!==item.sha256?{currentSha256:currentHash,originalSha256:item.sha256,correctedSha256:next}:{})});
|
|
135
138
|
return {...item,sha256:currentHash};
|
|
136
139
|
});
|
|
137
140
|
return {specs,stage,feature,review,archiveName,archiveHash:sha(bytes),evidenceHash:sha(readCmInitSource(specs,review.evidence)),
|
|
@@ -139,8 +142,10 @@ function loadCorrection({specs,stage,feature}){
|
|
|
139
142
|
}
|
|
140
143
|
|
|
141
144
|
export function inspectPrdCorrectionRecovery(input){
|
|
142
|
-
const value=loadCorrection(input);
|
|
143
|
-
return json({status:'correction_recovery_inspected',archive:`.reviews/${value.archiveName}`,states:value.states,
|
|
145
|
+
const value=loadCorrection(input),conflict=value.states.some(item=>item.status==='conflict');
|
|
146
|
+
return json({status:conflict?'correction_recovery_conflict':'correction_recovery_inspected',archive:`.reviews/${value.archiveName}`,states:value.states,
|
|
147
|
+
...(conflict?{guidance:{summary:'修正存档里的文件既不是原文也不是修正稿(conflict),宿主不会覆盖。',
|
|
148
|
+
nextStep:'逐个核对 conflict 文件的改动来源,保留用户改动;处理成原文或修正稿后再 inspect_correction,确认无冲突再 resume_correction。',authorizationGranted:false}}:{}),
|
|
144
149
|
packageDigest:value.review.packageDigest,decisions:value.plan.decisions,artifacts:value.after,
|
|
145
150
|
writeAuthorized:false,completionAuthorized:false});
|
|
146
151
|
}
|
|
@@ -149,6 +154,7 @@ export function resumePrdCorrection(input,signal){
|
|
|
149
154
|
assertPrdBatchActive(input.specs,[input.feature]);
|
|
150
155
|
need(input.writeEnabled===true&&!signal.aborted,'prd_correction_not_enabled');
|
|
151
156
|
const value=loadCorrection(input),{specs,stage,feature}=input;
|
|
157
|
+
need(!value.states.some(item=>item.status==='conflict'),'prd_correction_recovery_conflict');
|
|
152
158
|
const current=()=>{
|
|
153
159
|
need(!signal.aborted,'cancelled');const latest=inspectPrdFindings({specs,stage,feature});
|
|
154
160
|
need(latest.packageDigest===value.review.packageDigest&&latest.gate.outcome===value.review.gate.outcome
|
|
@@ -27,6 +27,7 @@ export function replaceSessionFile(root,relative,before,after){
|
|
|
27
27
|
const d=fs.openSync(dir,'r');try{fs.fsyncSync(d);}finally{fs.closeSync(d);}
|
|
28
28
|
}finally{if(fd!==undefined)fs.closeSync(fd);try{fs.unlinkSync(tmp);}catch(e){if(e.code!=='ENOENT')throw e;}}
|
|
29
29
|
}
|
|
30
|
+
export const MAX_ANSWER_DISCARDS=2;
|
|
30
31
|
export function openPrdSession({specs,sessionId,identity,executionPolicy=null}){
|
|
31
32
|
need(/^prd-[a-zA-Z0-9-]{1,80}$/.test(sessionId),'prd_session_id_invalid');
|
|
32
33
|
for(const relative of ['.reviews','.reviews/prd-sessions',`.reviews/prd-sessions/${sessionId}`]){
|
|
@@ -111,6 +112,48 @@ export function openPrdSession({specs,sessionId,identity,executionPolicy=null}){
|
|
|
111
112
|
evidence:{sha256:digest(resolution.evidence),length:resolution.evidence.length}};
|
|
112
113
|
state.checkpoint=active.before;state.active=null;cursor=0;save();return decision;
|
|
113
114
|
},
|
|
115
|
+
// V1 (O02): a recorded answer that the host then refused (validation runs
|
|
116
|
+
// after recording, so a plain resume replays the same refusal forever) is
|
|
117
|
+
// discarded by an explicit, append-only record and asked again under the same
|
|
118
|
+
// pending operation. Only the last recorded answer, never prd_review (its own
|
|
119
|
+
// abandon path, below) or prd_correct (its archive drives recovery); at most
|
|
120
|
+
// MAX_ANSWER_DISCARDS per call kind in a session.
|
|
121
|
+
discardAnswer(resolution){
|
|
122
|
+
need(resolution!==null&&typeof resolution==='object'&&!Array.isArray(resolution)&&resolution.discard===true
|
|
123
|
+
&&!Object.hasOwn(resolution,'result')
|
|
124
|
+
&&Object.keys(resolution).every(key=>['callId','requestDigest','discard','evidence'].includes(key)),'prd_recovery_binding');
|
|
125
|
+
need(typeof resolution.evidence==='string'&&resolution.evidence.trim()&&resolution.evidence.length<=2000,'prd_recovery_evidence_required');
|
|
126
|
+
const active=state.active,index=active?active.calls.findIndex(item=>item.callId===resolution.callId):-1,call=active?.calls[index];
|
|
127
|
+
need(call&&index===active.calls.length-1&&call.requestDigest===resolution.requestDigest&&Object.hasOwn(call,'result'),'prd_recovery_binding');
|
|
128
|
+
need(call.kind!=='prd_review','prd_review_recovery_required');
|
|
129
|
+
need(call.kind!=='prd_correct','prd_correction_recovery_required');
|
|
130
|
+
const discarded=state.discardedAnswers??[];
|
|
131
|
+
need(discarded.filter(item=>item.kind===call.kind).length<MAX_ANSWER_DISCARDS,'prd_answer_discard_limit');
|
|
132
|
+
const decision={operation:active.request.operation,kind:call.kind,callId:call.callId,requestDigest:call.requestDigest,
|
|
133
|
+
resultDigest:digest(call.result),evidence:{sha256:digest(resolution.evidence),length:resolution.evidence.length},
|
|
134
|
+
at:new Date().toISOString()};
|
|
135
|
+
state.discardedAnswers=[...discarded,decision];active.calls.splice(index,1);cursor=0;save();return json(decision);
|
|
136
|
+
},
|
|
137
|
+
// V5 (O05/O06): the one prd_review attempt of this operation is abandoned with
|
|
138
|
+
// an operator reason: its result was lost, or the recorded one fails the
|
|
139
|
+
// publication contract. The host releases the gate claim first; this record
|
|
140
|
+
// then restores the operation's before checkpoint, so a fresh, independent
|
|
141
|
+
// review can be claimed. A recorded result that would publish is never
|
|
142
|
+
// abandoned (the caller checks), and nothing unreviewed is adopted.
|
|
143
|
+
abandonReview(resolution){
|
|
144
|
+
need(resolution!==null&&typeof resolution==='object'&&!Array.isArray(resolution)&&resolution.abandonReview===true
|
|
145
|
+
&&!Object.hasOwn(resolution,'result')
|
|
146
|
+
&&Object.keys(resolution).every(key=>['callId','requestDigest','abandonReview','evidence'].includes(key)),'prd_recovery_binding');
|
|
147
|
+
need(typeof resolution.evidence==='string'&&resolution.evidence.trim()&&resolution.evidence.length<=2000,'prd_recovery_evidence_required');
|
|
148
|
+
const active=state.active,call=active?.calls.find(item=>item.callId===resolution.callId);
|
|
149
|
+
need(active?.request.operation==='final_review'&&call?.kind==='prd_review'&&call.requestDigest===resolution.requestDigest,'prd_recovery_binding');
|
|
150
|
+
const decision={operation:'final_review',stage:active.request.stage,feature:active.request.feature,kind:'prd_review',
|
|
151
|
+
callId:call.callId,requestDigest:call.requestDigest,resultDigest:Object.hasOwn(call,'result')?digest(call.result):null,
|
|
152
|
+
packageDigest:call.payload.package.packageDigest,evidence:{sha256:digest(resolution.evidence),length:resolution.evidence.length},
|
|
153
|
+
at:new Date().toISOString()};
|
|
154
|
+
state.abandonedReviews=[...(state.abandonedReviews??[]),decision];
|
|
155
|
+
state.checkpoint=active.before;state.active=null;cursor=0;save();return json(decision);
|
|
156
|
+
},
|
|
114
157
|
async call(kind,payload,signal,perform){
|
|
115
158
|
need(state.active!==null,'prd_operation_required');const index=cursor++,input=json({kind,payload},12*1024*1024);
|
|
116
159
|
const active=state.active;
|
|
@@ -25,17 +25,62 @@ export function replaceText(target,before,after,mode=0o644){
|
|
|
25
25
|
const d=fs.openSync(dir,'r');try{fs.fsyncSync(d);}finally{fs.closeSync(d);}
|
|
26
26
|
}finally{if(fd!==undefined)fs.closeSync(fd);try{fs.unlinkSync(tmp);}catch(error){if(error.code!=='ENOENT')throw error;}}
|
|
27
27
|
}
|
|
28
|
-
|
|
28
|
+
// V1 (O18/O19/O21): a host answer that was recorded and then refused on every
|
|
29
|
+
// replay, or whose outcome nobody can tell, may be discarded by an explicit,
|
|
30
|
+
// append-only `discard` row and asked again under the same key. Only the most
|
|
31
|
+
// recent intent, only a `host` effect whose call kind the workflow lists as
|
|
32
|
+
// re-askable, at most MAX_DISCARDS_PER_KIND per call kind in a run. A kind with
|
|
33
|
+
// external side effects also needs an operator release record. Replay enforces
|
|
34
|
+
// the same rules, so a forged, duplicated or over-limit row is refused.
|
|
35
|
+
export const MAX_DISCARDS_PER_KIND=2;
|
|
36
|
+
const DISCARD_REASONS=['answer_rejected','answer_missing'];
|
|
37
|
+
// A re-asked call has its own identity: the intent after N discards of a key
|
|
38
|
+
// carries attempt N+1, and its request digest binds that attempt. A receipt for
|
|
39
|
+
// a discarded attempt therefore never matches the new one. A first attempt keeps
|
|
40
|
+
// the original digest of its input, so older journals replay unchanged.
|
|
41
|
+
export const effectDigest=entry=>(entry.attempt??1)>1?digest({input:entry.input,attempt:entry.attempt}):digest(entry.input);
|
|
42
|
+
export function discardSummary(effects,discards,lastIntent){
|
|
43
|
+
const last=lastIntent!==null&&effects.has(lastIntent)?[lastIntent,effects.get(lastIntent)]:null;
|
|
44
|
+
return {discards:discards.map(({key,kind,reason,attempt,at})=>({key,kind,reason,attempt,at})),
|
|
45
|
+
lastAnswer:last&&last[1].kind==='host'&&Object.hasOwn(last[1],'result')?{key:last[0],kind:last[1].input?.kind??null,
|
|
46
|
+
attempt:last[1].attempt??1,requestDigest:effectDigest(last[1]),resultDigest:digest(last[1].result)}:null,
|
|
47
|
+
unknown:[...effects].filter(([,entry])=>!Object.hasOwn(entry,'result'))
|
|
48
|
+
.map(([key,entry])=>({key,kind:entry.kind,callKind:entry.kind==='host'?entry.input?.kind??null:null,
|
|
49
|
+
attempt:entry.attempt??1,requestDigest:effectDigest(entry)}))};
|
|
50
|
+
}
|
|
51
|
+
const DISCARD_KEYS=['type','key','kind','reason','attempt','requestDigest','resultDigest','evidence','released','at','previous'];
|
|
52
|
+
function checkDiscard(row,entry,lastIntent,discards,policy){
|
|
53
|
+
const allowed=policy?.(row.kind)??null;
|
|
54
|
+
need(allowed&&entry&&entry.kind==='host'&&entry.input?.kind===row.kind&&lastIntent===row.key
|
|
55
|
+
&&Object.keys(row).every(name=>DISCARD_KEYS.includes(name)||name==='hash')
|
|
56
|
+
&&DISCARD_REASONS.includes(row.reason)&&discards.filter(item=>item.kind===row.kind).length<MAX_DISCARDS_PER_KIND
|
|
57
|
+
&&row.attempt===(entry.attempt??1)&&row.requestDigest===effectDigest(entry)
|
|
58
|
+
&&row.evidence&&typeof row.evidence==='object'&&/^[a-f0-9]{64}$/.test(row.evidence.sha256??'')
|
|
59
|
+
&&Number.isSafeInteger(row.evidence.length)&&row.evidence.length>0&&row.evidence.length<=2000
|
|
60
|
+
&&typeof row.at==='string'&&Number.isFinite(Date.parse(row.at))
|
|
61
|
+
&&(row.reason==='answer_rejected'?Object.hasOwn(entry,'result')&&row.resultDigest===digest(entry.result)
|
|
62
|
+
:!Object.hasOwn(entry,'result')&&row.resultDigest===null)
|
|
63
|
+
&&(allowed.release?row.released?.source==='operator_confirmed'&&/^[a-f0-9]{64}$/.test(row.released.evidence??''):row.released===null),
|
|
64
|
+
'refactor_journal_invalid');
|
|
65
|
+
}
|
|
66
|
+
export function openRefactorRecords(directory,{discardable=null}={}){
|
|
29
67
|
need(canonicalFuture(directory)===directory,'refactor_archive_changed');
|
|
30
68
|
const target=path.join(directory,'execution.jsonl'),lock=path.join(directory,'.writer.json');
|
|
31
|
-
let events=[],last=null,locked=false;const effects=new Map();
|
|
69
|
+
let events=[],last=null,locked=false,lastIntent=null;const effects=new Map(),discards=[];
|
|
70
|
+
const nextAttempt=key=>discards.filter(item=>item.key===key).length+1;
|
|
32
71
|
if(fs.existsSync(target)){
|
|
33
72
|
const stat=fs.lstatSync(target);need(stat.isFile()&&!stat.isSymbolicLink()&&stat.nlink===1&&stat.size<=32*1024*1024,'refactor_journal_invalid');
|
|
34
73
|
const source=fs.readFileSync(target,'utf8');need(source.endsWith('\n'),'refactor_journal_incomplete');
|
|
35
74
|
events=source.trimEnd().split('\n').map(line=>JSON.parse(line));
|
|
36
75
|
for(const row of events){const {hash,...body}=row;need(hash===digest(body)&&body.previous===last,'refactor_journal_invalid');last=hash;
|
|
37
|
-
if(row.type==='intent'){need(!effects.has(row.key),'refactor_journal_invalid');
|
|
76
|
+
if(row.type==='intent'){need(!effects.has(row.key),'refactor_journal_invalid');
|
|
77
|
+
// A key asked again after a discard must carry exactly the next attempt.
|
|
78
|
+
const attempt=nextAttempt(row.key);
|
|
79
|
+
need(attempt===1?!Object.hasOwn(row,'attempt'):row.attempt===attempt,'refactor_journal_invalid');
|
|
80
|
+
effects.set(row.key,{input:row.input,kind:row.kind,...(attempt>1?{attempt}:{})});lastIntent=row.key;}
|
|
38
81
|
if(row.type==='result'){const entry=effects.get(row.key);need(entry&&!Object.hasOwn(entry,'result'),'refactor_journal_invalid');entry.result=row.result;}
|
|
82
|
+
if(row.type==='discard'){checkDiscard(row,effects.get(row.key),lastIntent,discards,discardable);
|
|
83
|
+
discards.push(row);effects.delete(row.key);lastIntent=null;}
|
|
39
84
|
}
|
|
40
85
|
}
|
|
41
86
|
function append(body){
|
|
@@ -46,6 +91,43 @@ export function openRefactorRecords(directory){
|
|
|
46
91
|
}
|
|
47
92
|
return {
|
|
48
93
|
get context(){return events.find(row=>row.type==='context')?.value??null;},
|
|
94
|
+
get discards(){return discards.map(row=>({...row}));},
|
|
95
|
+
get recovery(){return discardSummary(effects,discards,lastIntent);},
|
|
96
|
+
// True when key/requestDigest name an attempt that was discarded: its late
|
|
97
|
+
// receipt must never be adopted for the attempt asked afterwards.
|
|
98
|
+
discarded(key,requestDigest){return discards.some(item=>item.key===key&&item.requestDigest===requestDigest);},
|
|
99
|
+
// V7: the current user's fresh decision for a registered re-asked confirmation
|
|
100
|
+
// (attempt > 1) that the driver deliberately left unanswered. Bound to the exact
|
|
101
|
+
// key, attempt and request digest of the last, still unanswered intent.
|
|
102
|
+
confirm({key,attempt,requestDigest,decision,evidence}){
|
|
103
|
+
need(typeof evidence==='string'&&evidence.trim()&&evidence.length<=2000,'refactor_confirmation_evidence_required');
|
|
104
|
+
const entry=effects.get(key);
|
|
105
|
+
need(entry&&entry.kind==='host'&&entry.input?.kind==='refactor_confirm'&&!Object.hasOwn(entry,'result')
|
|
106
|
+
&&lastIntent===key&&Number.isSafeInteger(attempt)&&attempt>1&&(entry.attempt??1)===attempt
|
|
107
|
+
&&effectDigest(entry)===requestDigest,'refactor_confirmation_binding');
|
|
108
|
+
need(['approved','rejected'].includes(decision),'refactor_decision_invalid');
|
|
109
|
+
const result={value:{decision},durationMs:0,confirmation:{source:'operator_confirmed',evidence:digest(evidence),at:new Date().toISOString()}};
|
|
110
|
+
append({type:'result',key,result});entry.result=result;return {key,attempt,decision};
|
|
111
|
+
},
|
|
112
|
+
// The caller binds key/requestDigest from status and supplies the reason;
|
|
113
|
+
// the row is checked with the replay rules before it is appended.
|
|
114
|
+
discard({key,requestDigest,evidence,released=null}){
|
|
115
|
+
need(typeof evidence==='string'&&evidence.trim()&&evidence.length<=2000,'refactor_discard_evidence_required');
|
|
116
|
+
const entry=effects.get(key);
|
|
117
|
+
need(entry&&entry.kind==='host'&&effectDigest(entry)===requestDigest,'refactor_discard_binding');
|
|
118
|
+
need(lastIntent===key,'refactor_discard_not_last');
|
|
119
|
+
const kind=entry.input.kind,allowed=discardable?.(kind)??null;need(allowed,'refactor_discard_kind');
|
|
120
|
+
need(discards.filter(item=>item.kind===kind).length<MAX_DISCARDS_PER_KIND,'refactor_discard_limit');
|
|
121
|
+
need(!allowed.release||typeof released==='string'&&released.trim()&&released.length<=2000,'refactor_discard_release_required');
|
|
122
|
+
const row={type:'discard',key,kind,reason:Object.hasOwn(entry,'result')?'answer_rejected':'answer_missing',
|
|
123
|
+
attempt:entry.attempt??1,requestDigest:effectDigest(entry),
|
|
124
|
+
resultDigest:Object.hasOwn(entry,'result')?digest(entry.result):null,
|
|
125
|
+
evidence:{sha256:digest(evidence),length:evidence.length},
|
|
126
|
+
released:allowed.release?{source:'operator_confirmed',evidence:digest(released)}:null,at:new Date().toISOString()};
|
|
127
|
+
checkDiscard(row,entry,lastIntent,discards,discardable);
|
|
128
|
+
append(row);discards.push({...row});effects.delete(key);lastIntent=null;
|
|
129
|
+
return {key,kind,reason:row.reason,attempt:row.attempt,remaining:MAX_DISCARDS_PER_KIND-discards.filter(item=>item.kind===kind).length};
|
|
130
|
+
},
|
|
49
131
|
get progress(){return events.findLast(row=>row.type==='progress')?.value??null;},
|
|
50
132
|
effects,
|
|
51
133
|
acquire(){
|
|
@@ -63,18 +145,26 @@ export function openRefactorRecords(directory){
|
|
|
63
145
|
release(){if(locked){fs.unlinkSync(lock);locked=false;}},
|
|
64
146
|
initialize(value){need(!this.context,'refactor_already_started');append({type:'context',value});},
|
|
65
147
|
progressWrite(value){append({type:'progress',value});},
|
|
66
|
-
|
|
148
|
+
// perform/recover receive {key,attempt}. reask(old) lets a caller ask a lost
|
|
149
|
+
// answer again under a new attempt (V7): the lost attempt is discarded by an
|
|
150
|
+
// ordinary, counted discard row with the given evidence, then asked anew.
|
|
151
|
+
async effect(key,kind,input,perform,recover,{reask=null}={}){
|
|
67
152
|
input=json(input,4*1024*1024);
|
|
68
153
|
const old=effects.get(key);
|
|
69
154
|
if(old){need(old.kind===kind&&digest(old.input)===digest(input),'refactor_replay_mismatch');
|
|
70
155
|
if(Object.hasOwn(old,'result'))return json(old.result,4*1024*1024);
|
|
71
|
-
|
|
72
|
-
|
|
156
|
+
const evidence=reask?.(old)??null;
|
|
157
|
+
if(evidence)this.discard({key,requestDigest:effectDigest(old),evidence});
|
|
158
|
+
else{
|
|
159
|
+
need(typeof recover==='function','refactor_unknown_effect');
|
|
160
|
+
const result=json(await recover(old,perform),4*1024*1024);append({type:'result',key,result});old.result=result;return json(result,4*1024*1024);
|
|
161
|
+
}
|
|
73
162
|
}
|
|
74
163
|
if(['host','command'].includes(kind))need(![...effects.values()].some(entry=>['host','command'].includes(entry.kind)
|
|
75
164
|
&&!Object.hasOwn(entry,'result')),'refactor_unknown_effect');
|
|
76
|
-
|
|
77
|
-
|
|
165
|
+
const attempt=nextAttempt(key);
|
|
166
|
+
append({type:'intent',key,kind,input,...(attempt>1?{attempt}:{})});const entry={kind,input,...(attempt>1?{attempt}:{})};effects.set(key,entry);lastIntent=key;
|
|
167
|
+
const result=json(await perform({key,attempt}),4*1024*1024);append({type:'result',key,result});entry.result=result;return json(result,4*1024*1024);
|
|
78
168
|
},
|
|
79
169
|
async write(key,target,before,after,mode){
|
|
80
170
|
const input={target,before,after,mode};
|