@aibyzero/cm-workflow 0.16.8 → 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 +19 -0
- package/README.md +14 -3
- package/VERSION +1 -1
- package/compat/claude-commands/cm-notify.md +3 -0
- package/docs/installation.md +1 -1
- package/docs/js-workflow-control.md +25 -1
- package/docs/next-steps.md +8 -2
- package/docs/user-guide.md +105 -5
- package/package.json +2 -1
- package/runtime/js/cm-ai/claude-review-stream.mjs +49 -13
- package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +111 -20
- package/runtime/js/cm-ai/cm-ai-qa-log.mjs +69 -22
- package/runtime/js/cm-ai/code-projects.mjs +4 -1
- package/runtime/js/cm-ai/developer-adapter.mjs +7 -0
- package/runtime/js/cm-ai/drive-core.mjs +9 -0
- 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/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 +49 -4
- package/runtime/js/cm-ai/host-qa-fix-owner.mjs +44 -9
- package/runtime/js/cm-ai/host-session.mjs +1 -1
- package/runtime/js/cm-ai/host-tool-bridge.mjs +40 -3
- 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-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/execution.mjs +176 -48
- package/runtime/js/cm-fix/host.mjs +2 -1
- package/runtime/js/cm-fix/pinned-baseline.mjs +24 -0
- package/runtime/js/cm-fix/progress.mjs +13 -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-safe-read.mjs +49 -0
- package/runtime/js/notify-send.mjs +312 -0
- package/runtime/js/notify.mjs +137 -33
- package/runtime/js/policy-binding-compat.mjs +54 -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 +184 -22
- package/scripts/cm-ai-batch-run.test.mjs +21 -341
- 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 +64 -22
- package/scripts/cm-ai-drive.test.mjs +29 -2
- 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 +27 -15
- 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-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 +56 -10
- 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 +163 -10
- package/scripts/cm-fix-drive-unprotected.test.mjs +37 -0
- package/scripts/cm-fix-drive.mjs +25 -7
- package/scripts/cm-fix-host.mjs +8 -7
- 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 +22 -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 +21 -10
- 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 +221 -4
- 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/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/references/js-host-qa-recovery.md +27 -1
- package/skills/cm-ai/references/js-host-recovery.md +120 -8
- package/skills/cm-ai/references/js-host.md +14 -7
- package/skills/cm-check/SKILL.md +3 -3
- package/skills/cm-fix/references/js-host.md +44 -5
- 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/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
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// Fixed cm-refactor flow; the host proposes text, the owner applies and judges it.
|
|
2
2
|
import fs from 'node:fs';
|
|
3
|
+
import os from 'node:os';
|
|
3
4
|
import path from 'node:path';
|
|
4
5
|
import {randomUUID} from 'node:crypto';
|
|
5
6
|
import {spawnSync} from 'node:child_process';
|
|
@@ -20,6 +21,28 @@ const markdown=value=>'```json\n'+JSON.stringify(value,null,2)+'\n```\n';
|
|
|
20
21
|
const relative=name=>typeof name==='string'&&!path.isAbsolute(name)&&!name.includes('\\')
|
|
21
22
|
&&name.split('/').every(part=>part&&part!=='.'&&part!=='..');
|
|
22
23
|
const protectedName=name=>/(^|\/)(AGENTS\.md|CLAUDE\.md|\.env(?:\..*)?|\.claude|\.codex|\.git|.*\.(pem|key|p12))(\/|$)/i.test(name);
|
|
24
|
+
// Text-only current-host answers: the host, never the session, writes files, so
|
|
25
|
+
// a refused or lost answer can be discarded and asked again (V1); a confirmation
|
|
26
|
+
// is asked of the person again (V7). Commands and writes are never discardable.
|
|
27
|
+
export const REFACTOR_REASKABLE_KINDS=Object.freeze(['refactor_analyze','refactor_confirm','refactor_apply','refactor_review',
|
|
28
|
+
'refactor_batch','refactor_prepare_tests','refactor_revise_tests','refactor_retrospective']);
|
|
29
|
+
export const refactorDiscardable=kind=>REFACTOR_REASKABLE_KINDS.includes(kind)?{release:false}:null;
|
|
30
|
+
function refactorGuidance(reason,recovery){
|
|
31
|
+
const unknown=recovery.unknown,last=recovery.lastAnswer;
|
|
32
|
+
const blocking=unknown.find(item=>item.kind!=='host'||!REFACTOR_REASKABLE_KINDS.includes(item.callKind));
|
|
33
|
+
if(reason==='refactor_confirm_reask_limit')return {summary:'当前用户的确认已经丢失并重新问过 2 次,本运行不再重问。',
|
|
34
|
+
nextStep:'先查清确认为什么一直拿不到(会话断开、超时或宿主反复退出);交人处理,确认仍需要时另起新运行。',recoveryOperation:null,authorizationGranted:false};
|
|
35
|
+
if(unknown.length&&blocking)return {summary:`原${blocking.kind==='command'?'命令':blocking.kind==='write'?'写盘':'宿主'}结果未知(${blocking.key}),宿主不能证明它没执行或已清理。`,
|
|
36
|
+
nextStep:'找回原宿主回执后 resume,由会话在 refactor_recover 中给出 completed(命令须 cleanupConfirmed:true)或 not_started;这类结果不能作废重做,也不要手删归档。',
|
|
37
|
+
recoveryOperation:'resume',authorizationGranted:false};
|
|
38
|
+
if(unknown.length){const item=unknown[0];return {summary:`宿主反问 ${item.callKind} 的结果未知,会话也答不出原结果。`,
|
|
39
|
+
nextStep:`它只是文字应答、不写盘:resume 带 discard {key:"${item.key}",requestDigest:"${item.requestDigest}",evidence:"原因"} 作废后重问;每种最多 ${2} 次,超过报 refactor_discard_limit。`,
|
|
40
|
+
recoveryOperation:'resume',authorizationGranted:false};}
|
|
41
|
+
if(last&&REFACTOR_REASKABLE_KINDS.includes(last.kind)&&reason)return {summary:`已记录的 ${last.kind} 应答在回放时被拒(${reason}),每次 resume 都会原样失败。`,
|
|
42
|
+
nextStep:`确认是应答本身不合格后,resume 带 discard {key:"${last.key}",requestDigest:"${last.requestDigest}",evidence:"原因"} 作废并重问${last.kind==='refactor_confirm'?'当前用户':''};每种最多 2 次,已发布的审查和已执行的命令不能作废。`,
|
|
43
|
+
recoveryOperation:'resume',authorizationGranted:false};
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
23
46
|
function orderedUnits(units,scope,assembly){
|
|
24
47
|
need(Array.isArray(units)&&units.length>0,'refactor_units_invalid');const seen=new Set(),done=new Set(),result=[];
|
|
25
48
|
for(const unit of units){shape(unit,['id','files','dependsOn']);need(/^[a-z][a-z0-9-]*$/.test(unit.id)&&!seen.has(unit.id)
|
|
@@ -54,7 +77,7 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
54
77
|
for(const name of writebacks)need(relative(name)&&(name==='AGENTS.md'||name==='CLAUDE.md'||name==='README.md'
|
|
55
78
|
||/^\.claude\/rules\/[a-zA-Z0-9._-]+\.md$/.test(name)),'refactor_writeback_scope');
|
|
56
79
|
need(new Set([...config.scope,...setup.paths,...writebacks]).size===config.scope.length+setup.paths.length+writebacks.length,'refactor_scope_overlap');
|
|
57
|
-
const records=openRefactorRecords(directory),routes={};
|
|
80
|
+
const records=openRefactorRecords(directory,{discardable:refactorDiscardable}),routes={};
|
|
58
81
|
for(const role of ['coder','tester','reviewer'])routes[role]=resolveRole(loadConfig({projectRoot:project}),role,config.runtime);
|
|
59
82
|
let controller=new AbortController(),active=false,view=records.progress??{stage:records.context?'interrupted':'ready',reason:null};
|
|
60
83
|
let context=records.context,files={},reports=view.reports??[],judgeBefore=null,analysis=null,proposal=null,rulebook=null,reviewResult=null;
|
|
@@ -90,7 +113,10 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
90
113
|
need(digest(context.baseline.files[name]??null)===digest(now.files[name]??null),'refactor_out_of_scope_change');
|
|
91
114
|
}
|
|
92
115
|
}
|
|
93
|
-
function status(){
|
|
116
|
+
function status(){
|
|
117
|
+
const recovery=['blocked','correction_required'].includes(view.stage)&&context?records.recovery:null;
|
|
118
|
+
const guidance=recovery?refactorGuidance(view.reason,recovery):null;
|
|
119
|
+
return json({...view,...(recovery?{recovery}:{}),...(guidance?{guidance}:{}),runId:context?.runId??null,attempt:active?attempt:view.attempt??attempt,scope:config.scope,reports,
|
|
94
120
|
commandCount:active?commandCount:view.commandCount??0,hostCalls:active?hostCalls:view.hostCalls??0,
|
|
95
121
|
baselineCount:config.baselineCommands.length,differentialCount:judgeBefore?.cases.length??view.differentialCount??0,completionAuthorized:false},1024*1024);}
|
|
96
122
|
function projectStatus(){if(specs){const target=path.join(specs,'.cm-status.json');replaceText(target,readText(target),JSON.stringify({node:'REFACTOR',feature,task,
|
|
@@ -108,9 +134,13 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
108
134
|
},(_entry,perform)=>perform()); // Original writer deduplicates the exact deterministic event identity.
|
|
109
135
|
}
|
|
110
136
|
async function recover(entry,perform){
|
|
111
|
-
|
|
112
|
-
|
|
137
|
+
// A re-asked call (attempt > 1) is reconciled as that attempt only: the
|
|
138
|
+
// answer must name it, so a receipt of a discarded attempt is never adopted.
|
|
139
|
+
const attempt=entry.attempt??1;
|
|
140
|
+
guard();const response=json(await call('refactor_recover',{kind:entry.kind,input:entry.input,...(attempt>1?{attempt}:{}),
|
|
141
|
+
instructions:'Trusted host reconciliation only. Inspect original invocation/process receipt. Return {decision:completed,result,evidence} only for the actual recorded outcome, or {decision:not_started,evidence} with proof no dispatch/execution occurred. Unknown => {decision:unknown,evidence}. Never infer from time or repeat an unknown review/command. No new execution. When attempt is given, reconcile only that attempt and echo it.'},controller.signal),4*1024*1024);
|
|
113
142
|
need(nonempty(response.evidence),'refactor_unknown_effect');
|
|
143
|
+
if(attempt>1)need(response.attempt===attempt,'refactor_recover_attempt_mismatch');
|
|
114
144
|
if(response.decision==='not_started')return perform();
|
|
115
145
|
need(response.decision==='completed','refactor_unknown_effect');
|
|
116
146
|
if(entry.kind==='command'){
|
|
@@ -122,11 +152,20 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
122
152
|
}
|
|
123
153
|
async function invoke(key,kind,payload){
|
|
124
154
|
const input={kind,payload};hostCalls++;
|
|
125
|
-
return records.effect(`host/${key}`,'host',input,async()=>{
|
|
155
|
+
return records.effect(`host/${key}`,'host',input,async({attempt}={})=>{
|
|
126
156
|
guard();need(!controller.signal.aborted,'cancelled');const at=Date.now();
|
|
127
|
-
|
|
157
|
+
// A re-asked call names its attempt, so the session can tell it from the discarded one.
|
|
158
|
+
const result=json(await call(kind,attempt>1?{...payload,recovery:{key:`host/${key}`,attempt}}:payload,controller.signal),1024*1024);
|
|
128
159
|
guard();need(!controller.signal.aborted,'cancelled');return {value:result,durationMs:Date.now()-at};
|
|
129
|
-
},recover
|
|
160
|
+
},recover,{
|
|
161
|
+
// V7: a lost confirmation is asked of the person again as a new attempt,
|
|
162
|
+
// recorded by an ordinary discard row (counted, at most 2 per run); an
|
|
163
|
+
// answer bound to the lost call is never adopted.
|
|
164
|
+
reask:old=>old.input.kind==='refactor_confirm'?(guard(),'V7:原确认结果丢失,自动重新问当前用户'):null,
|
|
165
|
+
}).then(result=>result.value,error=>{
|
|
166
|
+
if(kind==='refactor_confirm'&&error?.code==='refactor_discard_limit')
|
|
167
|
+
throw Object.assign(new Error('refactor_confirm_reask_limit'),{code:'refactor_confirm_reask_limit'});
|
|
168
|
+
throw error;});
|
|
130
169
|
}
|
|
131
170
|
async function confirm(key,gate,payload){
|
|
132
171
|
humanCalls++;await event(`${key}-pause`,'pause',gate);progress(`awaiting_${gate}`);
|
|
@@ -473,7 +512,19 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
473
512
|
lessons:{path:lessons,before:context.lessons,after:files.__lessons??context.lessons},project,baselineCommands:config.baselineCommands,judgeCommand:config.judgeCommand,
|
|
474
513
|
preTaskDirty:context.baseline.gitState,route:routes.reviewer,
|
|
475
514
|
instructions:'Fresh independent reviewer per runtime/review.md, no author history. Review ALL diff including tests/Learning/rules/docs/LESSONS and judge coverage. Return {markdown} with original N4 header binding exact handoff SHA, attempt=round, scope, findings. No writes or unapproved provider. Missing channel is blocked, never invent approval.'});
|
|
476
|
-
|
|
515
|
+
// The review is validated in full before it becomes immutable evidence, so a
|
|
516
|
+
// reply that fails (missing header, wrong handoff digest, short scope) stays
|
|
517
|
+
// discardable. An already published review is checked as before (old journals).
|
|
518
|
+
const reviewPath=path.join(reviews,`${feature}-${task}-r${attempt}.md`);
|
|
519
|
+
if(!records.effects.has(`publish/${prefix}-review`)){
|
|
520
|
+
need(nonempty(reviewed.markdown),'refactor_review_invalid');
|
|
521
|
+
const scratch=fs.mkdtempSync(path.join(os.tmpdir(),'cm-refactor-review-'));
|
|
522
|
+
try{const draft=path.join(scratch,path.basename(reviewPath));fs.writeFileSync(draft,reviewed.markdown,{mode:0o600});
|
|
523
|
+
try{validateReview(draft,{task,attempt,handoff,changedFiles:changed});}
|
|
524
|
+
catch(error){throw Object.assign(new Error('refactor_review_invalid'),{code:'refactor_review_invalid',detail:error.message});}}
|
|
525
|
+
finally{fs.rmSync(scratch,{recursive:true,force:true});}
|
|
526
|
+
}
|
|
527
|
+
const review=await publish(`${prefix}-review`,reviewPath,reviewed.markdown);
|
|
477
528
|
reviewResult=validateReview(review,{task,attempt,handoff,changedFiles:changed});interceptions+=Number(reviewResult.blocking_findings);
|
|
478
529
|
if(Object.hasOwn(reviewed,'judgeRevision')){
|
|
479
530
|
need(attempt===1&&reviewResult.verdict==='changes_requested','refactor_judge_revision_unavailable');
|
|
@@ -540,6 +591,24 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
540
591
|
baseline:baselineSnapshot,batch:batchTrack,lessons:readText(lessons),lessonsMode:fs.existsSync(lessons)?fs.statSync(lessons).mode&0o777:0o644,
|
|
541
592
|
metrics:specs?readText(path.join(specs,'METRICS.md')):null,metricsMode:specs&&fs.existsSync(path.join(specs,'METRICS.md'))?fs.statSync(path.join(specs,'METRICS.md')).mode&0o777:0o600};records.initialize(context);
|
|
542
593
|
}else{guard();if(request.operation==='prepare_judge_revision')return await prepareJudgeRevision(request.judgeRevision);
|
|
594
|
+
if(request.operation==='resume'&&Object.hasOwn(request,'discard')){
|
|
595
|
+
need(view.stage==='blocked','refactor_discard_unavailable');
|
|
596
|
+
const value=request.discard;
|
|
597
|
+
need(value&&typeof value==='object'&&!Array.isArray(value)
|
|
598
|
+
&&Object.keys(value).every(key=>['key','requestDigest','evidence'].includes(key)),'refactor_discard_binding');
|
|
599
|
+
const decision=records.discard({key:value.key,requestDigest:value.requestDigest,evidence:value.evidence});
|
|
600
|
+
await event(`discard-${records.discards.length}`,'decision','answer_discarded',{key:decision.key,kind:decision.kind,reason:decision.reason});
|
|
601
|
+
}
|
|
602
|
+
// V7: the current user's decision for the registered re-asked confirmation.
|
|
603
|
+
if(request.operation==='resume'&&Object.hasOwn(request,'confirmation')){
|
|
604
|
+
need(view.stage==='blocked'&&!Object.hasOwn(request,'discard'),'refactor_confirmation_unavailable');
|
|
605
|
+
const value=request.confirmation;
|
|
606
|
+
need(value&&typeof value==='object'&&!Array.isArray(value)&&Object.keys(value).sort().join(',')==='attempt,decision,evidence,key,requestDigest',
|
|
607
|
+
'refactor_confirmation_binding');
|
|
608
|
+
const decision=records.confirm(value);
|
|
609
|
+
await event(`confirmation-${decision.key.replace(/[^a-z0-9-]/gi,'-')}-${decision.attempt}`,'decision','reask_confirmed',
|
|
610
|
+
{key:decision.key,attempt:decision.attempt,decision:decision.decision});
|
|
611
|
+
}
|
|
543
612
|
if(view.stage==='done')return status();need(request.operation!=='start','refactor_resume_required');}
|
|
544
613
|
if(await flow()){
|
|
545
614
|
if(request.operation==='resume'){
|
|
@@ -553,7 +622,8 @@ export function createCmRefactorHost(raw,{call}){
|
|
|
553
622
|
}
|
|
554
623
|
projectStatus();
|
|
555
624
|
return status();
|
|
556
|
-
}catch(error){view={...
|
|
625
|
+
}catch(error){const {reasonDetail:_,...rest}=view;view={...rest,stage:controller.signal.aborted?'cancelled':'blocked',reason:error.code??error.message,
|
|
626
|
+
...(typeof error.detail==='string'?{reasonDetail:error.detail.slice(0,500)}:{})};
|
|
557
627
|
try{records.progressWrite(view);projectStatus();}catch{}return status();
|
|
558
628
|
}finally{records.release();active=false;}
|
|
559
629
|
}});
|
|
@@ -16,6 +16,8 @@ import {inspectCmTestRecovery} from './recovery.mjs';
|
|
|
16
16
|
import {collectBranchImpact,assertBranchComparison,inspectImpactAnalysis} from './branch-impact.mjs';
|
|
17
17
|
import {inside,canonicalFuture,selectReportDirectory,snapshotSource,sourceChanges,readSourceFiles,checkSourceEvidence} from './source-snapshot.mjs';
|
|
18
18
|
import {isQaEnvironmentCarrier} from '../cm-ai/qa-environment.mjs';
|
|
19
|
+
import {cmTestRecoveryGuidance} from './session.mjs';
|
|
20
|
+
import {legacyTestBindings} from '../policy-binding-compat.mjs';
|
|
19
21
|
|
|
20
22
|
const nonempty=value=>typeof value==='string'&&value.trim().length>0;
|
|
21
23
|
const read=file=>{
|
|
@@ -48,7 +50,7 @@ export function createCmTestHost(raw,{call,session=null}){
|
|
|
48
50
|
const controller=new AbortController();let stage='ready',result=null,reason=null,logFile=null;
|
|
49
51
|
const binding={routes,workflowRoot:admission.workflowRoot,policy:digest(fs.readFileSync(path.join(config.skillDir,'references/js-host.md'),'utf8')),
|
|
50
52
|
...(admission.operation==='impact'?{comparison:{...admission.comparison,dirty:false}}:{})};
|
|
51
|
-
if(session?.context)session.validate(binding);
|
|
53
|
+
if(session?.context)session.validate(binding,legacyTestBindings(binding,config.skillDir));
|
|
52
54
|
if(session?.context){stage='interrupted';logFile=session.logFile;}
|
|
53
55
|
if(session?.progress?.result){result=session.progress.result;stage=result.stage;logFile=result.logFile;}
|
|
54
56
|
if(session?.progress?.cancelled){stage='cancelled';controller.abort();}
|
|
@@ -258,7 +260,8 @@ export function createCmTestHost(raw,{call,session=null}){
|
|
|
258
260
|
if(impact)assertBranchComparison(project,impact.comparison);
|
|
259
261
|
}catch(error){
|
|
260
262
|
reason=error?.code??'cm_test_failed';problems.push(reason);
|
|
261
|
-
if(session){stage=controller.signal.aborted?'cancelled':'interrupted';
|
|
263
|
+
if(session){stage=controller.signal.aborted?'cancelled':'interrupted';const recovery=session.recovery;
|
|
264
|
+
return json({stage,runId,logFile,reason,pending:session.pending,recovery,guidance:cmTestRecoveryGuidance(recovery),completionAuthorized:false});}
|
|
262
265
|
}
|
|
263
266
|
stage='reporting';
|
|
264
267
|
result={...await effect('evaluation',{rows,artifacts,reason,problems},()=>{
|
|
@@ -326,7 +329,11 @@ export function createCmTestHost(raw,{call,session=null}){
|
|
|
326
329
|
}
|
|
327
330
|
return Object.freeze({async handle(request){
|
|
328
331
|
shape(request,request.operation==='resume'?['requestId','operation','resolution']:['requestId','operation']);
|
|
329
|
-
if(request.operation==='status')
|
|
332
|
+
if(request.operation==='status'){
|
|
333
|
+
const recovery=session&&stage==='interrupted'?session.recovery:null;
|
|
334
|
+
return json({stage,runId,logFile,result,reason,pending:session?.pending??null,
|
|
335
|
+
...(recovery?{recovery,guidance:cmTestRecoveryGuidance(recovery)}:{}),completionAuthorized:false});
|
|
336
|
+
}
|
|
330
337
|
if(request.operation==='cancel'){session?.save({cancelled:true,result});controller.abort();return {stage:'cancelled',completionAuthorized:false};}
|
|
331
338
|
if(request.operation==='resume'){
|
|
332
339
|
need(session&&session.context&&!controller.signal.aborted,'cm_test_resume_unavailable');
|
|
@@ -2,10 +2,35 @@
|
|
|
2
2
|
// in the original cm-test flow. Unknown actions are never dispatched twice.
|
|
3
3
|
import fs from 'node:fs';
|
|
4
4
|
import path from 'node:path';
|
|
5
|
-
import {openRefactorRecords} from '../cm-refactor/records.mjs';
|
|
5
|
+
import {openRefactorRecords,effectDigest} from '../cm-refactor/records.mjs';
|
|
6
6
|
import {need,digest,json,shape} from '../cm-ai/effect-contract.mjs';
|
|
7
7
|
import {inside,canonicalFuture,sourceChanges} from './source-snapshot.mjs';
|
|
8
8
|
|
|
9
|
+
// V1 (O21): change_impact/test_cases are read-only answers and may be discarded
|
|
10
|
+
// and asked again. V4: qa_logic/qa_browser act on devices or browsers, so a
|
|
11
|
+
// discard also needs cleanup:'completed' (session receipt or operator check that
|
|
12
|
+
// resources are released), recorded as a release in the same row.
|
|
13
|
+
export const CM_TEST_REASKABLE=Object.freeze({change_impact:{release:false},test_cases:{release:false},
|
|
14
|
+
qa_logic:{release:true},qa_browser:{release:true}});
|
|
15
|
+
export const cmTestDiscardable=kind=>CM_TEST_REASKABLE[kind]??null;
|
|
16
|
+
const discardCode=code=>({refactor_discard_binding:'cm_test_discard_binding',refactor_discard_not_last:'cm_test_discard_not_last',
|
|
17
|
+
refactor_discard_kind:'cm_test_discard_kind',refactor_discard_limit:'cm_test_discard_limit',
|
|
18
|
+
refactor_discard_evidence_required:'cm_test_discard_evidence_required',
|
|
19
|
+
refactor_discard_release_required:'cm_test_resource_release_required'})[code]??code;
|
|
20
|
+
export function cmTestRecoveryGuidance(recovery){
|
|
21
|
+
if(!recovery)return null;
|
|
22
|
+
const unknown=recovery.unknown[0],last=recovery.lastAnswer;
|
|
23
|
+
if(unknown&&(unknown.kind!=='host'||!CM_TEST_REASKABLE[unknown.callKind]))return {summary:`原${unknown.kind==='command'?'命令':'记录'}结果未知(${unknown.key}),不能重做。`,
|
|
24
|
+
nextStep:'只用原执行回执 {key,requestDigest,result,evidence,cleanup:"completed"} 恢复;没有回执就人工核对后另起新运行。',authorizationGranted:false};
|
|
25
|
+
const target=unknown??last;
|
|
26
|
+
if(!target)return null;
|
|
27
|
+
const kind=unknown?unknown.callKind:last.kind,release=CM_TEST_REASKABLE[kind]?.release;
|
|
28
|
+
if(!CM_TEST_REASKABLE[kind])return null;
|
|
29
|
+
return {summary:unknown?`${kind} 的应答没有拿到(超时、断开或宿主退出),会话也没有原回执。`:`已记录的 ${kind} 应答被宿主拒收,每次 resume 都会原样失败。`,
|
|
30
|
+
nextStep:`resume 带 resolution {key:"${target.key}",requestDigest:"${target.requestDigest}",discard:true,evidence:"原因"${release?',cleanup:"completed"':''}} 作废后重问;`
|
|
31
|
+
+(release?'它会操作浏览器或设备,只有会话确认清理完成或你核实资源已释放(设备可能仍在使用)后才能带 cleanup:"completed";':'')+'每种最多 2 次。',
|
|
32
|
+
authorizationGranted:false};
|
|
33
|
+
}
|
|
9
34
|
export function openTestSession(directory,config){
|
|
10
35
|
need(path.isAbsolute(directory)&&canonicalFuture(directory)===directory,'cm_test_session_path_invalid');
|
|
11
36
|
for(const root of [config.project,config.arguments.specs,config.arguments.reportDir].filter(Boolean)){
|
|
@@ -16,17 +41,19 @@ export function openTestSession(directory,config){
|
|
|
16
41
|
const file=path.join(directory,name);
|
|
17
42
|
if(fs.existsSync(file))need((fs.lstatSync(file).mode&0o777)===0o600,'cm_test_session_permissions');
|
|
18
43
|
}
|
|
19
|
-
const records=openRefactorRecords(directory);records.acquire();
|
|
44
|
+
const records=openRefactorRecords(directory,{discardable:cmTestDiscardable});records.acquire();
|
|
20
45
|
let sequence=0,resolution=null;
|
|
21
46
|
const unknown=()=>[...records.effects].find(([,entry])=>!Object.hasOwn(entry,'result'));
|
|
22
47
|
return {
|
|
23
48
|
get context(){return records.context;},
|
|
24
49
|
get progress(){return records.progress;},
|
|
25
50
|
get logFile(){return [...records.effects.values()].filter(entry=>entry.result?.value?.logFile).at(-1)?.result.value.logFile??null;},
|
|
26
|
-
get pending(){const entry=unknown();return entry?{key:entry[0],kind:entry[1].kind,requestDigest:
|
|
51
|
+
get pending(){const entry=unknown();return entry?{key:entry[0],kind:entry[1].kind,requestDigest:effectDigest(entry[1])}:null;},
|
|
52
|
+
get recovery(){return records.recovery;},
|
|
27
53
|
initialize(context){records.initialize({...context,workflow:'cm-test',configDigest:digest(config)});},
|
|
28
|
-
|
|
29
|
-
|
|
54
|
+
// legacy: older bindings accepted as a controlled migration (policy-binding-compat.mjs).
|
|
55
|
+
validate(binding,legacy=[]){need(records.context?.workflow==='cm-test'&&records.context.configDigest===digest(config)
|
|
56
|
+
&&[binding,...legacy].some(item=>digest(records.context.binding)===digest(item)),'cm_test_session_binding_changed');},
|
|
30
57
|
begin(current,receipt){
|
|
31
58
|
need(!records.progress?.cancelled,'cancelled');
|
|
32
59
|
const last=[...records.effects.values()].filter(entry=>Object.hasOwn(entry,'result')).at(-1)?.result.source??records.context.source;
|
|
@@ -34,8 +61,20 @@ export function openTestSession(directory,config){
|
|
|
34
61
|
const logged=[...records.effects.values()].filter(entry=>entry.result?.value?.logDigest).at(-1)?.result.value;
|
|
35
62
|
if(logged)need(fs.realpathSync(logged.logFile)===logged.logFile&&fs.lstatSync(logged.logFile).isFile()
|
|
36
63
|
&&digest(fs.readFileSync(logged.logFile,'utf8'))===logged.logDigest,'cm_test_resume_log_changed');
|
|
64
|
+
if(receipt?.discard===true){
|
|
65
|
+
shape(receipt,['key','requestDigest','discard','evidence',...(Object.hasOwn(receipt,'cleanup')?['cleanup']:[])]);
|
|
66
|
+
need(!Object.hasOwn(receipt,'cleanup')||['completed'].includes(receipt.cleanup),'cm_test_resolution_invalid');
|
|
67
|
+
const entry=records.effects.get(receipt.key),kind=entry?.kind==='host'?entry.input.kind:null;
|
|
68
|
+
need(!CM_TEST_REASKABLE[kind]?.release||receipt.cleanup==='completed','cm_test_resource_release_required');
|
|
69
|
+
try{records.discard({key:receipt.key,requestDigest:receipt.requestDigest,evidence:receipt.evidence,
|
|
70
|
+
released:CM_TEST_REASKABLE[kind]?.release?`cleanup completed: ${receipt.evidence}`:null});}
|
|
71
|
+
catch(error){throw Object.assign(new Error(discardCode(error.code)),{code:discardCode(error.code)});}
|
|
72
|
+
receipt=null;
|
|
73
|
+
}
|
|
37
74
|
if(receipt!==null){
|
|
38
75
|
shape(receipt,['key','requestDigest','result','evidence','cleanup']);const pending=this.pending;
|
|
76
|
+
// A late receipt of a discarded attempt never becomes the result of the attempt asked afterwards.
|
|
77
|
+
need(!records.discarded(receipt.key,receipt.requestDigest),'cm_test_resolution_abandoned');
|
|
39
78
|
need(pending&&['host','command'].includes(pending.kind)&&receipt.key===pending.key&&receipt.requestDigest===pending.requestDigest
|
|
40
79
|
&&typeof receipt.evidence==='string'&&receipt.evidence.trim()&&receipt.cleanup==='completed','cm_test_resolution_invalid');
|
|
41
80
|
}
|
|
@@ -45,7 +84,7 @@ export function openTestSession(directory,config){
|
|
|
45
84
|
const key=String(++sequence);
|
|
46
85
|
return (await records.effect(key,kind,input,async()=>({value:await perform(),source:snapshot()}),async old=>{
|
|
47
86
|
if(['snapshot','evaluation'].includes(old.kind))return {value:await perform(),source:snapshot()};
|
|
48
|
-
need(resolution&&resolution.key===key&&resolution.requestDigest===
|
|
87
|
+
need(resolution&&resolution.key===key&&resolution.requestDigest===effectDigest(old),'cm_test_outcome_unknown');
|
|
49
88
|
const {result,...provenance}=resolution,value=json(result,4*1024*1024);
|
|
50
89
|
resolution=null;return {value,source:snapshot(),reconciliation:{source:'trusted_host_original_result',...provenance}};
|
|
51
90
|
})).value;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// Synchronous safe reader for the runtime's own read of notify.json.
|
|
2
|
+
// Side-effect free on purpose: notify.mjs is imported by every host, so this
|
|
3
|
+
// module only imports node:fs and never touches process, timers or the disk
|
|
4
|
+
// at import time. The boundary is the same as the sender's async
|
|
5
|
+
// readRegularFile (runtime/js/notify-send.mjs, which stays a self-contained
|
|
6
|
+
// single file because it is copied alone to <CM_WORKFLOW_HOME>/notify/): lstat
|
|
7
|
+
// must show a regular file (never a symlink), at most 64 KiB, opened without
|
|
8
|
+
// following links and without blocking (a FIFO is refused, never waited on),
|
|
9
|
+
// and the opened handle must be the same file object (dev+ino) and still pass
|
|
10
|
+
// the type and size checks. A test runs one fixture matrix through both
|
|
11
|
+
// readers and fails if their accept/reject decisions or reasons drift apart.
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
|
|
14
|
+
export const MAX_NOTIFY_FILE_BYTES=64*1024;
|
|
15
|
+
|
|
16
|
+
// state: 'missing' (no such path) | 'invalid'. reason: 'permission' (not a
|
|
17
|
+
// regular file, a link, or swapped while checking) | 'too_large' | undefined.
|
|
18
|
+
export class SafeReadError extends Error{
|
|
19
|
+
constructor(message,state,reason){super(message);this.state=state;this.reason=reason;}
|
|
20
|
+
}
|
|
21
|
+
const refuse=(message,reason)=>new SafeReadError(message,'invalid',reason);
|
|
22
|
+
|
|
23
|
+
// Returns a Buffer (bytes:true) or the text decoded strictly as UTF-8 with a
|
|
24
|
+
// leading BOM removed, like the sender's reader. Throws SafeReadError only.
|
|
25
|
+
export function readRegularFileSync(file,label,{fileOps=fs,bytes:raw=false}={}){
|
|
26
|
+
let link;
|
|
27
|
+
try{link=fileOps.lstatSync(file,{bigint:true});}
|
|
28
|
+
catch(error){throw error?.code==='ENOENT'?new SafeReadError(`读不到 ${label}`,'missing'):refuse(`读不到 ${label}`);}
|
|
29
|
+
const notRegular=()=>refuse(`${label} 必须是普通文件(不能是符号链接)`,'permission');
|
|
30
|
+
const tooLarge=()=>refuse(`${label} 太大`,'too_large');
|
|
31
|
+
if(link.isSymbolicLink()||!link.isFile())throw notRegular();
|
|
32
|
+
if(link.size>BigInt(MAX_NOTIFY_FILE_BYTES))throw tooLarge();
|
|
33
|
+
let fd=null;
|
|
34
|
+
try{
|
|
35
|
+
// O_NONBLOCK: a file swapped for a FIFO after lstat opens at once and is
|
|
36
|
+
// then refused by the type check on the handle.
|
|
37
|
+
fd=fileOps.openSync(file,fs.constants.O_RDONLY|(fs.constants.O_NOFOLLOW??0)|(fs.constants.O_NONBLOCK??0));
|
|
38
|
+
const st=fileOps.fstatSync(fd,{bigint:true});
|
|
39
|
+
if(!st.isFile())throw notRegular();
|
|
40
|
+
if(st.dev!==link.dev||st.ino!==link.ino)throw refuse(`${label} 在核对期间被替换,为安全起见不使用它`,'permission');
|
|
41
|
+
if(st.size>BigInt(MAX_NOTIFY_FILE_BYTES))throw tooLarge();
|
|
42
|
+
const size=Number(st.size),buffer=Buffer.alloc(size);let read=0;
|
|
43
|
+
while(read<size){const n=fileOps.readSync(fd,buffer,read,size-read,read);if(n===0)break;read+=n;}
|
|
44
|
+
const data=buffer.subarray(0,read);
|
|
45
|
+
return raw?data:new TextDecoder('utf-8',{fatal:true}).decode(data).replace(/^\uFEFF/,'');
|
|
46
|
+
}catch(error){
|
|
47
|
+
throw error instanceof SafeReadError?error:refuse(`读取 ${label} 失败`);
|
|
48
|
+
}finally{if(fd!==null){try{fileOps.closeSync(fd);}catch{}}}
|
|
49
|
+
}
|