@aibyzero/cm-workflow 0.16.4 → 0.16.5

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.
Files changed (167) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +8 -0
  3. package/CHANGELOG.md +50 -0
  4. package/README.md +12 -1
  5. package/VERSION +1 -1
  6. package/docs/installation.md +21 -1
  7. package/docs/js-workflow-control.md +245 -33
  8. package/docs/runtime-failover.md +1 -1
  9. package/package.json +1 -1
  10. package/runtime/js/cm-ai/accepted-fix.mjs +23 -5
  11. package/runtime/js/cm-ai/bootstrap-feature.mjs +15 -0
  12. package/runtime/js/cm-ai/claude-review-stream.mjs +12 -0
  13. package/runtime/js/cm-ai/cm-ai-admission.mjs +115 -41
  14. package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +3 -2
  15. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +137 -22
  16. package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +11 -9
  17. package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +22 -5
  18. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +180 -53
  19. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +2 -1
  20. package/runtime/js/cm-ai/codex-review-adapter.mjs +24 -4
  21. package/runtime/js/cm-ai/developer-adapter.mjs +6 -2
  22. package/runtime/js/cm-ai/diagnostic-reason.mjs +10 -0
  23. package/runtime/js/cm-ai/drive-bootstrap.mjs +305 -0
  24. package/runtime/js/cm-ai/drive-core.mjs +39 -7
  25. package/runtime/js/cm-ai/durable-runner-state.mjs +307 -53
  26. package/runtime/js/cm-ai/effect-abandon-log.mjs +19 -0
  27. package/runtime/js/cm-ai/effect-contract.mjs +44 -2
  28. package/runtime/js/cm-ai/execution-store-limits.mjs +18 -0
  29. package/runtime/js/cm-ai/execution-store.mjs +6 -4
  30. package/runtime/js/cm-ai/fix-code-association.mjs +171 -18
  31. package/runtime/js/cm-ai/host-bootstrap.mjs +68 -21
  32. package/runtime/js/cm-ai/host-conversation-execution.mjs +16 -4
  33. package/runtime/js/cm-ai/host-handoff.mjs +13 -6
  34. package/runtime/js/cm-ai/host-qa-executor.mjs +21 -7
  35. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +4 -4
  36. package/runtime/js/cm-ai/host-qa-policy.mjs +16 -7
  37. package/runtime/js/cm-ai/host-session.mjs +12 -4
  38. package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
  39. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +13 -4
  40. package/runtime/js/cm-ai/host.mjs +1 -1
  41. package/runtime/js/cm-ai/launch-mismatch.mjs +42 -0
  42. package/runtime/js/cm-ai/log-rows.mjs +21 -0
  43. package/runtime/js/cm-ai/project-qa-gate.mjs +84 -0
  44. package/runtime/js/cm-ai/provider-review-observation.mjs +53 -9
  45. package/runtime/js/cm-ai/qa-config-revision.mjs +44 -10
  46. package/runtime/js/cm-ai/review-abandon-log.mjs +21 -0
  47. package/runtime/js/cm-ai/review-package.mjs +427 -31
  48. package/runtime/js/cm-ai/review-runner.mjs +47 -1
  49. package/runtime/js/cm-ai/reviewed-deliveries.mjs +97 -0
  50. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +104 -10
  51. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +42 -3
  52. package/runtime/js/cm-ai/specification-material.mjs +154 -12
  53. package/runtime/js/cm-ai/task-commit.mjs +2 -2
  54. package/runtime/js/cm-ai/task-runner.mjs +502 -65
  55. package/runtime/js/cm-fix/execution.mjs +109 -25
  56. package/runtime/js/cm-fix/host-review.mjs +7 -3
  57. package/runtime/js/cm-fix/host.mjs +3 -1
  58. package/runtime/js/cm-fix/progress.mjs +1 -0
  59. package/runtime/js/cm-fix/protected-edits.mjs +15 -4
  60. package/runtime/js/cm-fix/qa-source.mjs +6 -4
  61. package/runtime/js/cm-prd/analysis.mjs +2 -1
  62. package/runtime/js/cm-prd/change.mjs +28 -10
  63. package/runtime/js/cm-prd/draft.mjs +5 -2
  64. package/runtime/js/cm-prd/review-preparation.mjs +10 -3
  65. package/runtime/js/cm-prd/review-publication.mjs +4 -2
  66. package/runtime/js/cm-prd/self-check.mjs +6 -3
  67. package/runtime/js/cm-prd/summary.mjs +3 -1
  68. package/runtime/js/cm-prd/validation-reason.mjs +20 -0
  69. package/runtime/js/spec-task-line.mjs +117 -0
  70. package/runtime/js/specs-status.mjs +10 -3
  71. package/scripts/cm-ai-abandon-effect-position.test.mjs +201 -0
  72. package/scripts/cm-ai-admission.mjs +18 -11
  73. package/scripts/cm-ai-admission.test.mjs +65 -1
  74. package/scripts/cm-ai-batch-drive.mjs +92 -20
  75. package/scripts/cm-ai-batch-drive.test.mjs +164 -3
  76. package/scripts/cm-ai-batch-host.mjs +27 -11
  77. package/scripts/cm-ai-batch-host.test.mjs +2 -1
  78. package/scripts/cm-ai-batch-run.mjs +33 -10
  79. package/scripts/cm-ai-batch-run.test.mjs +56 -5
  80. package/scripts/cm-ai-bootstrap-driver-preflight.test.mjs +45 -0
  81. package/scripts/cm-ai-bootstrap-flow.test.mjs +158 -0
  82. package/scripts/cm-ai-bootstrap-merge.test.mjs +45 -0
  83. package/scripts/cm-ai-bootstrap.test.mjs +99 -7
  84. package/scripts/cm-ai-conversation-entry-ops.test.mjs +82 -2
  85. package/scripts/cm-ai-develop-driver-gaps.test.mjs +822 -0
  86. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +468 -0
  87. package/scripts/cm-ai-drive-timeout.test.mjs +17 -0
  88. package/scripts/cm-ai-drive.mjs +479 -47
  89. package/scripts/cm-ai-drive.test.mjs +240 -10
  90. package/scripts/cm-ai-fix-later-delivery.test.mjs +383 -0
  91. package/scripts/cm-ai-host.mjs +84 -25
  92. package/scripts/cm-ai-host.test.mjs +232 -12
  93. package/scripts/cm-ai-launch-diagnostics.test.mjs +142 -0
  94. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  95. package/scripts/cm-ai-project-qa-gate.test.mjs +308 -0
  96. package/scripts/cm-ai-qa-config-revision.test.mjs +166 -15
  97. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +157 -0
  98. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +27 -2
  99. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +400 -0
  100. package/scripts/cm-ai-review-drift-precedence.test.mjs +90 -0
  101. package/scripts/cm-ai-review-failure.test.mjs +917 -0
  102. package/scripts/cm-ai-review-timeout-config.test.mjs +29 -7
  103. package/scripts/cm-ai-review-timeout.test.mjs +199 -4
  104. package/scripts/cm-ai-run.mjs +160 -60
  105. package/scripts/cm-ai-run.test.mjs +4 -3
  106. package/scripts/cm-ai-runner-error-code-regression.test.mjs +219 -0
  107. package/scripts/cm-ai-selection-guard.test.mjs +100 -0
  108. package/scripts/cm-ai-session-chain.test.mjs +7 -3
  109. package/scripts/cm-ai-spec-rebind.test.mjs +481 -0
  110. package/scripts/cm-ai-supersede.test.mjs +571 -17
  111. package/scripts/cm-ai-verification-gate.test.mjs +2 -1
  112. package/scripts/cm-capability-gate.test.mjs +21 -2
  113. package/scripts/cm-check-drive.test.mjs +1 -1
  114. package/scripts/cm-check-host.test.mjs +1 -1
  115. package/scripts/cm-check-runtime.sh +1 -1
  116. package/scripts/cm-claude-developer-worker.test.mjs +3 -1
  117. package/scripts/cm-claude-probe.test.mjs +9 -1
  118. package/scripts/cm-claude-review-stream.test.mjs +25 -0
  119. package/scripts/cm-claude-worker.test.mjs +11 -4
  120. package/scripts/cm-codex-developer-worker.test.mjs +4 -2
  121. package/scripts/cm-failover.mjs +8 -8
  122. package/scripts/cm-fix-abandon.test.mjs +123 -5
  123. package/scripts/cm-fix-cause-package.test.mjs +2 -0
  124. package/scripts/cm-fix-drive.mjs +45 -13
  125. package/scripts/cm-fix-drive.test.mjs +36 -1
  126. package/scripts/cm-fix-host.mjs +9 -6
  127. package/scripts/cm-fix-review-budget.test.mjs +141 -0
  128. package/scripts/cm-fixture-process-cleanup.test.mjs +95 -0
  129. package/scripts/cm-host-check.test.mjs +6 -3
  130. package/scripts/cm-host-qa-executor.test.mjs +192 -17
  131. package/scripts/cm-host-session-diagnostic.test.mjs +10 -0
  132. package/scripts/cm-interactive-qa-diagnostic.test.mjs +53 -0
  133. package/scripts/cm-log-event.mjs +17 -0
  134. package/scripts/cm-log-event.test.mjs +31 -0
  135. package/scripts/cm-prd-completion.test.mjs +75 -0
  136. package/scripts/cm-prd-draft.test.mjs +14 -0
  137. package/scripts/cm-prd-gate-diagnostic.test.mjs +100 -0
  138. package/scripts/cm-prd-review-gate.mjs +126 -81
  139. package/scripts/cm-prd-review-gate.test.mjs +105 -1
  140. package/scripts/cm-prd-review-preparation.test.mjs +15 -0
  141. package/scripts/cm-prd-review-publication.test.mjs +6 -0
  142. package/scripts/cm-prd-self-check.test.mjs +6 -0
  143. package/scripts/cm-prd-summary.test.mjs +9 -0
  144. package/scripts/cm-review-dependency-snapshot.test.mjs +15 -0
  145. package/scripts/cm-review-inventory.test.mjs +253 -1
  146. package/scripts/cm-spec-manifest.mjs +28 -10
  147. package/scripts/cm-spec-manifest.test.mjs +8 -4
  148. package/scripts/cm-spec-task-line.test.mjs +138 -0
  149. package/scripts/cm-specs-status.test.mjs +12 -1
  150. package/scripts/cm-task-gate.mjs +18 -10
  151. package/scripts/cm-task-gate.py +1 -1
  152. package/scripts/cm-test-branch-impact.test.mjs +6 -3
  153. package/scripts/fixtures/claude-review-process.mjs +1 -0
  154. package/scripts/fixtures/process-cleanup.mjs +99 -0
  155. package/scripts/test-cm-log-event.py +2 -0
  156. package/scripts/test-cm-prd-review-gate.py +2 -1
  157. package/scripts/test-npm-install.py +1 -1
  158. package/scripts/test-scan-public-safety.py +1 -1
  159. package/scripts/test-spec-manifest.py +16 -8
  160. package/scripts/test-task-gate.py +2 -2
  161. package/scripts/test-workflow-config.py +1 -0
  162. package/scripts/validate-public-repo.py +1 -0
  163. package/skills/cm-ai/references/N1-init.md +1 -1
  164. package/skills/cm-ai/references/js-host.md +261 -42
  165. package/skills/cm-fix/references/js-host.md +22 -1
  166. package/skills/cm-prd/references/js-change-recovery.md +1 -1
  167. package/skills/cm-prd/references/js-host.md +6 -0
@@ -0,0 +1,19 @@
1
+ // Repeating this projection on resume repairs a crash after the journal append.
2
+ import {spawnSync} from 'node:child_process';
3
+ import {fileURLToPath} from 'node:url';
4
+ import {digest,need} from './effect-contract.mjs';
5
+
6
+ const writer=fileURLToPath(new URL('../../../scripts/cm-log-event.py',import.meta.url));
7
+ export function recordEffectAbandonment({specsDir,codeProject,feature,identity,record,logHome,runtime='codex'}){
8
+ const p=record.payload;
9
+ const data={node:p.effectKind==='complete'?'N5':p.effectKind==='review'?'N4':'N3',feature,task:identity.taskId,
10
+ effect_id:p.effectId,effect_kind:p.effectKind,intent_digest:p.intentDigest,
11
+ record_digest:record.digest,reason:p.reason};
12
+ const args=[writer,'--workflow','cm-ai','--event','effect_abandoned','--runtime',runtime,
13
+ '--project-root',codeProject,'--specs-dir',specsDir,'--run-id',identity.runId,
14
+ '--at',p.at,'--detail','显式放弃中断且无检查点的任务 effect','--data-json',JSON.stringify(data)];
15
+ const result=spawnSync('python3',args,{timeout:10000,maxBuffer:1024*1024,
16
+ ...(logHome?{env:{...process.env,CM_WORKFLOW_LOG_HOME:logHome}}:{})});
17
+ need(!result.error&&result.status===0,'effect_abandon_log_failed');
18
+ return digest(data);
19
+ }
@@ -4,6 +4,45 @@ export { digest };
4
4
  export const need=(ok,code='invalid_input')=>{
5
5
  if(!ok){const e=new Error(code);e.code=code;const at=raisedAt(e);if(at!==null)e.origin=at;throw e;}
6
6
  };
7
+ // One journal record payload (execution-store). Anything a record must carry,
8
+ // such as a review package inside a checkpoint, has to fit this, not only its own limits.
9
+ export const JOURNAL_PAYLOAD_LIMIT=1024*1024;
10
+ // A develop checkpoint must leave room for the later checkpoints of the same
11
+ // attempt, which carry the same package again. Their growth is bounded:
12
+ // - the reviewer result (verdict, digest, findings, summary; examinedPaths are
13
+ // fixed by the package) is truncated to REVIEW_TEXT_LIMIT bytes before any
14
+ // record is written, and the completion checkpoint journals it
15
+ // REVIEW_RESULT_COPIES times (frame receipt, receipts, priorReview, observation
16
+ // and inspection; the review and completion cache entries each repeat
17
+ // receipt, receipts, observation and inspection);
18
+ // - the review and completion cache entries each repeat the receipts, calls and
19
+ // Learning writeback that already exist when the package is made;
20
+ // - everything else (receipt and registration metadata, up to 64 observation
21
+ // events per copy, inspection metadata, the new calls, task commit fields) is
22
+ // bounded by REVIEW_FIXED_RESERVE.
23
+ export const REVIEW_TEXT_LIMIT=12*1024;
24
+ export const REVIEW_RESULT_COPIES=13;
25
+ export const REVIEW_FIXED_RESERVE=96*1024;
26
+ export const developCheckpointReserve=({examinedPathsBytes,receiptsBytes=2,callsBytes=2,writebackBytes=4})=>
27
+ REVIEW_RESULT_COPIES*(examinedPathsBytes+REVIEW_TEXT_LIMIT)+2*(receiptsBytes+callsBytes+writebackBytes)+REVIEW_FIXED_RESERVE;
28
+ // The runner reviews scope plus the project AGENTS.md a Learning writeback may change.
29
+ export const taskReviewScope=scope=>scope.includes('AGENTS.md')?scope:[...scope,'AGENTS.md'];
30
+ // Journaled reasons (checkpoint reason, host diagnostics) are one line of at most
31
+ // this many characters; replay refuses anything longer.
32
+ export const JOURNAL_REASON_LIMIT=8192;
33
+ // The one builder for reasons that name paths or other open-ended lists: every
34
+ // item is shown up to 300 characters (longer ones keep their start and end, so a
35
+ // file name stays visible), as many as fit, then "等 N 个" gives the total.
36
+ // Control characters become spaces. The result always fits the limit.
37
+ export function boundedReason(head,items,tail=''){
38
+ const line=value=>String(value).replace(/[\x00-\x1f\x7f]/g,' ');
39
+ const clip=value=>value.length>300?`${value.slice(0,150)}…${value.slice(-149)}`:value;
40
+ const list=items.map(item=>clip(line(item))),start=line(head),end=line(tail),more=` 等 ${list.length} 个`;
41
+ let shown=list.length;
42
+ const text=count=>`${start}${list.slice(0,count).join(', ')}${count<list.length?more:''}${end}`;
43
+ while(shown>0&&text(shown).length>JOURNAL_REASON_LIMIT)shown--;
44
+ return text(shown).slice(0,JOURNAL_REASON_LIMIT);
45
+ }
7
46
  // Explicit host call budget, shared by live initialization and journal replay.
8
47
  // This is not the short-lived authorization grant expiry.
9
48
  export const validCallTimeout=value=>need(Number.isInteger(value)&&value>=1&&value<=3600000);
@@ -12,7 +51,7 @@ const failureCodes=new Set(['invalid_input','limit_exceeded','call_timeout','can
12
51
  'unregistered_receipt','invalid_receipt','receipt_identity','receipt_package_mismatch','review_not_approved',
13
52
  'checks_not_passed','async_commit','commit_unknown','unsupported_path','unsupported_file','read_failed',
14
53
  'snapshot_changed','spec_drift','invalid_baseline','out_of_scope','empty_changes','invalid_package','package_mismatch',
15
- 'handoff_exists','verification_precheck_failed']);
54
+ 'handoff_exists','verification_precheck_failed','completion_checks_changed']);
16
55
  // An unlisted code becomes execution_error, which on its own is not actionable.
17
56
  // The EEXIST that blocked every retry of a task in #81 stayed invisible in the
18
57
  // log, the state and stderr until a temporary print was added by hand. Emit one
@@ -154,7 +193,10 @@ export function terminalFor(raw,request) {
154
193
  // Reviewer and unknown terminal contracts remain unchanged.
155
194
  need(request.role==='developer'&&v.accepted===true);
156
195
  shape(v.result,['code','reason',...(Object.hasOwn(v.result,'retryable')?['retryable']:[])]);
157
- need(['invalid_result','protected_edit_stale'].includes(v.result.code));id(v.result.reason);
196
+ // bootstrap_verification_failed is produced only by the host bootstrap
197
+ // capability (never a provider adapter); its reason is the code itself.
198
+ need(['invalid_result','protected_edit_stale','bootstrap_verification_failed'].includes(v.result.code));id(v.result.reason);
199
+ if(v.result.code==='bootstrap_verification_failed')need(v.result.reason===v.result.code);
158
200
  if(Object.hasOwn(v.result,'retryable'))need(v.result.retryable===true
159
201
  &&v.result.code==='invalid_result'&&request.requestedModel==='current-session');
160
202
  }
@@ -0,0 +1,18 @@
1
+ // Size and count limits of the local durable record store, without the store
2
+ // itself (no node:sqlite import), so owners can check an append before making it.
3
+ import { digest } from './effect-contract.mjs';
4
+
5
+ export const MiB=1024*1024,STATE_LIMIT=16*MiB,PHYSICAL_LIMIT=32*MiB,RECORD_LIMIT=1024;
6
+
7
+ // Whether append(input) on this snapshot stays within the store's limits (append
8
+ // input, payload, record count, whole state). Pure: an owner can refuse cleanly
9
+ // before an append that would fail inside its writer. The directory's physical
10
+ // limit (state plus retained temporary files) is not checked here.
11
+ export function appendFits(current,input){
12
+ const bytes=value=>Buffer.byteLength(JSON.stringify(value));
13
+ if(bytes(input)>MiB+1024||bytes(input.payload)>MiB||current.records.length>=RECORD_LIMIT)return false;
14
+ const record={version:1,seq:current.records.length+1,id:input.id,kind:input.kind,payload:input.payload,
15
+ previousDigest:current.records.at(-1)?.digest??null};
16
+ const {revision,...data}=current,next={...data,records:[...current.records,{...record,digest:digest(record)}]};
17
+ return bytes({...next,revision:digest(next)})<=STATE_LIMIT;
18
+ }
@@ -3,10 +3,11 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { randomUUID,createHash } from 'node:crypto';
5
5
  import { DatabaseSync } from 'node:sqlite';
6
- import { need,shape,id,hex,json,digest,freeze } from './effect-contract.mjs';
6
+ import { need,shape,id,hex,json,digest,freeze,JOURNAL_PAYLOAD_LIMIT } from './effect-contract.mjs';
7
7
  import { isSupportedExecutionPlatform } from './execution-platform.mjs';
8
+ import { MiB,STATE_LIMIT,PHYSICAL_LIMIT } from './execution-store-limits.mjs';
8
9
 
9
- const MiB=1024*1024,STATE_LIMIT=16*MiB,PHYSICAL_LIMIT=32*MiB,APP_ID=0x434d5831;
10
+ const APP_ID=0x434d5831;
10
11
  const PROTOCOL_SQL='CREATE TABLE protocol(version INTEGER NOT NULL CHECK(version=1))';
11
12
  const kinds=new Set(['intent','result','cancel','commit-intent','commit-result','finalized']);
12
13
  const seal=value=>freeze({...value,revision:digest(value)});
@@ -53,7 +54,7 @@ function validateState(raw,options) {
53
54
  for(const [index,r] of v.records.entries()) {
54
55
  shape(r,['version','seq','id','kind','payload','previousDigest','digest']);
55
56
  need(r.version===1,'store_version');need(r.seq===index+1 && r.previousDigest===previous,'store_corrupt');
56
- id(r.id);need(!ids.has(r.id) && kinds.has(r.kind),'store_corrupt');ids.add(r.id);json(r.payload,MiB);
57
+ id(r.id);need(!ids.has(r.id) && kinds.has(r.kind),'store_corrupt');ids.add(r.id);json(r.payload,JOURNAL_PAYLOAD_LIMIT);
57
58
  const {digest:checksum,...data}=r;hex(checksum);need(digest(data)===checksum,'store_corrupt');previous=checksum;
58
59
  }
59
60
  const {revision,...data}=v;hex(revision);need(digest(data)===revision,'store_corrupt');return v;
@@ -165,6 +166,7 @@ function acquireWriter(p,create) {
165
166
  return {db,inode:regular(p,64*1024),certificate:current,inspectionFd,release};
166
167
  }catch(error){release();if(error.errcode===5)need(false,'store_busy');throw error;}
167
168
  }
169
+ export { appendFits } from './execution-store-limits.mjs';
168
170
  export function openExecutionStore(input) {
169
171
  const options=json(input);shape(options,['specsRoot','identity','fingerprints','create']);
170
172
  shape(options.identity,['repositoryId','runId']);Object.values(options.identity).forEach(id);
@@ -214,7 +216,7 @@ export function openExecutionStore(input) {
214
216
  const append=input=>{
215
217
  need(!closed,'store_closed');need(!poisoned,'store_poisoned');
216
218
  const v=json(input,MiB+1024);shape(v,['id','kind','payload','expectedRevision']);
217
- id(v.id);hex(v.expectedRevision);need(kinds.has(v.kind));json(v.payload,MiB);
219
+ id(v.id);hex(v.expectedRevision);need(kinds.has(v.kind));json(v.payload,JOURNAL_PAYLOAD_LIMIT);
218
220
  const current=snapshot(),existing=current.records.find(r=>r.id===v.id);
219
221
  if(existing){need(existing.kind===v.kind && digest(existing.payload)===digest(v.payload),'record_conflict');return current;}
220
222
  need(v.expectedRevision===current.revision,'revision_mismatch');
@@ -1,12 +1,81 @@
1
1
  // Content composition only. This does not authenticate a review or clear a gate.
2
- import {captureReviewBaseline,readReviewBaseline,readReviewPackage} from './review-package.mjs';
2
+ import {captureReviewBaseline,compareReviewInventoryToBaseline,readReviewBaseline,readReviewPackage} from './review-package.mjs';
3
3
  import {verifySpecificationMaterial} from './specification-material.mjs';
4
- import {digest,json,need} from './effect-contract.mjs';
4
+ import {CONFIG_FILENAMES} from '../../../scripts/cm-workflow-config.mjs';
5
+ import {digest,hex,id,json,need,shape} from './effect-contract.mjs';
5
6
 
6
7
  const inventoryFile=({contentBase64,...metadata})=>metadata;
7
8
  const sameFile=(a,b)=>digest(a===null?null:inventoryFile(a))===digest(b===null?null:inventoryFile(b));
9
+ // Recorded steps are compact (run id and package digest). The list is not a
10
+ // search bound: it is every qualifying delivery, and the whole accepted-fix
11
+ // record is size-checked before it is persisted.
12
+ const MAX_STEPS=2048;
8
13
 
9
- export function composeFixCode({baseline,parentPackage,fixPackages}){
14
+ // Later reviewed deliveries of other runs that precede a QA fix, recorded as the
15
+ // ordered list of their packages and the index of the fix each precedes. The
16
+ // file transitions are re-derived from the runs' verified stores, never taken
17
+ // from the journal; an empty list is the historical strict composition.
18
+ export function readSteps(raw,fixCount){
19
+ need(Array.isArray(raw)&&raw.length<=MAX_STEPS,'fix_association_invalid');
20
+ let previous=0;const seen=new Set();
21
+ for(const step of raw){
22
+ shape(step,['beforeFix','runId','packageDigest']);
23
+ need(Number.isInteger(step.beforeFix)&&step.beforeFix>=previous&&step.beforeFix<fixCount,'fix_association_invalid');
24
+ previous=step.beforeFix;id(step.runId);hex(step.packageDigest);
25
+ need(!seen.has(step.packageDigest),'fix_association_invalid');seen.add(step.packageDigest);
26
+ }
27
+ return raw;
28
+ }
29
+ // The recorded form of a real reviewed package.
30
+ export const deliveryStep=(runId,pkg,beforeFix)=>({beforeFix,runId,packageDigest:pkg.packageDigest});
31
+ const compact=steps=>steps.map(({beforeFix,runId,packageDigest})=>({beforeFix,runId,packageDigest}));
32
+ // Durable order: only packages whose own review came after the parent's approving
33
+ // review count, so a transition reviewed before the parent is never replayed over
34
+ // it (for example to disguise an unreviewed revert of the parent's change).
35
+ // deliveries: [{runId,packages:[{pkg,reviewedAt}]}].
36
+ export const deliveredAfter=(item,after)=>Number.isSafeInteger(after)
37
+ &&Number.isSafeInteger(item.reviewedAt)&&item.reviewedAt>after;
38
+ const key=file=>file===null||file===undefined?null:`${file.sha256}:${file.mode}`;
39
+ const applyMeta=(state,pkg)=>{for(const change of pkg.changes){
40
+ if(change.after===null)state.delete(change.path);else state.set(change.path,inventoryFile(change.after));}};
41
+ // Every qualifying later package, in durable review order (ties: run id, then
42
+ // package position). Nothing is chosen or dropped by content.
43
+ function laterSequence(deliveries,after,rootDigest){
44
+ return deliveries.flatMap(delivery=>delivery.packages.map((item,index)=>({runId:delivery.runId,index,reviewedAt:item.reviewedAt,raw:item.pkg})))
45
+ .filter(entry=>deliveredAfter(entry,after)).map(entry=>({...entry,pkg:readReviewPackage(entry.raw)}))
46
+ .filter(entry=>entry.pkg.rootDigest===rootDigest)
47
+ .sort((a,b)=>a.reviewedAt-b.reviewedAt||(a.runId<b.runId?-1:a.runId>b.runId?1:0)||a.index-b.index);
48
+ }
49
+ function unexplainedError(paths){
50
+ const error=new Error(`fix_current_code_unexplained: ${paths.slice(0,20).join(', ')}${paths.length>20?` (+${paths.length-20} more)`:''}`);
51
+ error.code='fix_current_code_unexplained';error.paths=paths;return error;
52
+ }
53
+ // The root CM workflow config outside the run's scope is user-editable policy,
54
+ // not delivered code, and is the one tolerated unreviewed difference.
55
+ const toleratedConfig=ownScope=>{const scope=new Set(ownScope);return p=>CONFIG_FILENAMES.includes(p)&&!scope.has(p);};
56
+ // Apply one later delivery strictly: its reviewed before-state must be the
57
+ // running composition on every path it touches (tolerated config aside). None
58
+ // is ever skipped; a mismatch names the paths.
59
+ function applyDelivery(state,pkg,tolerated){
60
+ const stale=pkg.changes.filter(change=>!tolerated(change.path)&&!sameFile(state.get(change.path)??null,change.before))
61
+ .map(change=>change.path).sort();
62
+ if(stale.length)throw unexplainedError(stale);
63
+ applyMeta(state,pkg);
64
+ }
65
+ const strict=()=>false;
66
+ // The composition must be the current tree exactly, content and mode.
67
+ function compareCurrent({root,base,state,tolerated}){
68
+ const original=new Map(base.files.map(file=>[file.path,inventoryFile(file)]));
69
+ const actual=new Map(compareReviewInventoryToBaseline(root,base,{withMode:true})
70
+ .map(row=>[row.path,row.sha256===null?null:`${row.sha256}:${row.mode}`]));
71
+ const wanted=new Map([...new Set([...original.keys(),...state.keys()])]
72
+ .filter(p=>key(original.get(p))!==key(state.get(p))).map(p=>[p,key(state.get(p))]));
73
+ const unexplained=[...new Set([...wanted.keys(),...actual.keys()])]
74
+ .filter(p=>!tolerated(p)&&wanted.get(p)!==actual.get(p)).sort();
75
+ if(unexplained.length)throw unexplainedError(unexplained);
76
+ }
77
+
78
+ function bindChain({baseline,parentPackage,fixPackages}){
10
79
  const base=readReviewBaseline(baseline),parent=readReviewPackage(parentPackage);
11
80
  need(Array.isArray(fixPackages)&&fixPackages.length>0&&fixPackages.length<=2,'fix_chain_invalid');
12
81
  const fixes=fixPackages.map(readReviewPackage);
@@ -15,29 +84,113 @@ export function composeFixCode({baseline,parentPackage,fixPackages}){
15
84
  for(const fix of fixes)need(fix.rootDigest===parent.rootDigest&&fix.identity.repositoryId===parent.identity.repositoryId
16
85
  &&fix.identity.runId!==parent.identity.runId,'fix_parent_binding_mismatch');
17
86
  need(new Set(fixes.map(fix=>fix.identity.runId)).size===fixes.length,'fix_chain_invalid');
18
- const expected=new Map(base.files.map(file=>[file.path,file]));
19
- const apply=pkg=>{
20
- for(const change of pkg.changes){
21
- need(sameFile(expected.get(change.path)??null,change.before),'fix_before_mismatch');
22
- if(change.after===null)expected.delete(change.path);else expected.set(change.path,change.after);
23
- }
24
- };
25
- apply(parent);fixes.forEach(apply);
26
- const files=[...expected.values()].sort((a,b)=>a.path<b.path?-1:a.path>b.path?1:0);
87
+ return {base,parent,fixes};
88
+ }
89
+ const applyTo=expected=>pkg=>{
90
+ for(const change of pkg.changes){
91
+ need(sameFile(expected.get(change.path)??null,change.before),'fix_before_mismatch');
92
+ if(change.after===null)expected.delete(change.path);else expected.set(change.path,change.after);
93
+ }
94
+ };
95
+ // Strict order: parent, then for each fix its recorded preceding steps and the
96
+ // fix. Steps are resolved: each carries the real reviewed package (pkg).
97
+ function composeState({base,parent,fixes},steps){
98
+ const expected=new Map(base.files.map(file=>[file.path,file])),apply=applyTo(expected);
99
+ apply(parent);
100
+ for(const [index,fix] of fixes.entries()){
101
+ for(const step of steps.filter(step=>step.beforeFix===index))applyDelivery(expected,step.pkg,strict);
102
+ apply(fix);
103
+ }
104
+ return expected;
105
+ }
106
+
107
+ // steps: resolved steps [{beforeFix,runId,packageDigest,pkg}] whose packages were
108
+ // read from the named runs' verified stores.
109
+ export function composeFixCode({baseline,parentPackage,fixPackages,steps=[]}){
110
+ const chain=bindChain({baseline,parentPackage,fixPackages}),{base,parent,fixes}=chain;
111
+ readSteps(json(compact(steps)),fixes.length);
112
+ const resolved=steps.map(step=>{const pkg=readReviewPackage(step.pkg);
113
+ need(pkg.packageDigest===step.packageDigest&&pkg.rootDigest===base.rootDigest,'fix_association_unverified');return {...step,pkg};});
114
+ // Metadata-only transitions cannot rebuild legacy full-content inventories.
115
+ need(!resolved.length||base.version===2,'fix_before_mismatch');
116
+ const files=[...composeState(chain,resolved).values()].sort((a,b)=>a.path<b.path?-1:a.path>b.path?1:0);
27
117
  // Use the same canonical inventory for live association and journal replay.
28
118
  return {base,parent,fixes,files:base.version===1?files:files.map(inventoryFile)};
29
119
  }
30
120
 
31
- export function inspectFixCodeAssociation({root,specsRoot,baseline,parentPackage,fixPackage,fixPackages}){
32
- const {base,parent,fixes,files}=composeFixCode({baseline,parentPackage,fixPackages:fixPackages??[fixPackage]});
121
+ // A completed run's reviewed package is history: other task runs deliver later,
122
+ // separately reviewed changes on top of it (their AGENTS.md learning lines, their
123
+ // own files, even this run's files). Apply every one of them, in durable review
124
+ // order and strictly; the result must be the current tree exactly.
125
+ export function explainReviewedDrift({root,baseline,composed,ownScope,deliveries,after}){
126
+ const base=readReviewBaseline(baseline);
127
+ const state=new Map(composed.map(file=>[file.path,inventoryFile(file)])),tolerated=toleratedConfig(ownScope);
128
+ for(const entry of laterSequence(deliveries,after,base.rootDigest))applyDelivery(state,entry.pkg,tolerated);
129
+ compareCurrent({root,base,state,tolerated});
130
+ }
131
+
132
+ // Completed run without accepted fixes: its own reviewed composition, then drift.
133
+ export function explainCompletedDelivery({root,baseline,parentPackage,deliveries,after}){
134
+ const base=readReviewBaseline(baseline),parent=readReviewPackage(parentPackage);
135
+ need(parent.baseIdentity===base.baselineDigest&&parent.rootDigest===base.rootDigest
136
+ &&digest(parent.identity)===digest(base.identity),'fix_parent_binding_mismatch');
137
+ if(base.specification)verifySpecificationMaterial(base);
138
+ const expected=new Map(base.files.map(file=>[file.path,inventoryFile(file)]));
139
+ for(const change of parent.changes){
140
+ need(sameFile(expected.get(change.path)??null,change.before),'fix_before_mismatch');
141
+ if(change.after===null)expected.delete(change.path);else expected.set(change.path,inventoryFile(change.after));
142
+ }
143
+ explainReviewedDrift({root,baseline:base,composed:[...expected.values()],ownScope:parent.scope,deliveries,after});
144
+ }
145
+
146
+ // One deterministic order for a run with QA fixes, from facts fixed at
147
+ // acceptance. The accepted record's ordered list stays exactly as it is; every
148
+ // other qualifying delivery is applied after the last fix, in review order. A new
149
+ // fix (extend) takes, before itself, every qualifying delivery not yet recorded
150
+ // whose review preceded its own final review (fixTime), all in review order. So a
151
+ // delivery that was reviewed before a fix but committed only after its acceptance
152
+ // is simply applied after that fix. Every step and every later delivery applies
153
+ // strictly; the result must be the current tree exactly.
154
+ export function inspectFixCodeAssociation({root,specsRoot,baseline,parentPackage,fixPackage,fixPackages,steps=[],extend=false,
155
+ deliveries=null,after=null,fixTime=null}){
156
+ const chainPackages=fixPackages??[fixPackage];
157
+ const chain=bindChain({baseline,parentPackage,fixPackages:chainPackages}),{base,parent,fixes}=chain,last=fixes.length-1;
158
+ const prior=readSteps(json(steps),extend?last:fixes.length),ownScope=[...parent.scope,...fixes.flatMap(fix=>fix.scope)];
159
+ const tolerated=toleratedConfig(ownScope);
160
+ const later=typeof deliveries==='function'?laterSequence(deliveries(),after,base.rootDigest):[];
161
+ const slot=(runId,packageDigest)=>`${runId}\0${packageDigest}`;
162
+ const found=new Map(later.map(entry=>[slot(entry.runId,entry.pkg.packageDigest),entry]));
163
+ // Each recorded step must still be a completed, later reviewed delivery.
164
+ const recorded=prior.map(step=>{const entry=found.get(slot(step.runId,step.packageDigest));
165
+ need(entry,'fix_association_unverified');return {...step,pkg:entry.pkg};});
166
+ const used=new Set(recorded.map(step=>slot(step.runId,step.packageDigest)));
167
+ let rest=later.filter(entry=>!used.has(slot(entry.runId,entry.pkg.packageDigest)));
168
+ if(extend&&rest.length){
169
+ const time=typeof fixTime==='function'?fixTime(fixes[last]):null;
170
+ need(Number.isSafeInteger(time),'fix_association_unverified');
171
+ recorded.push(...rest.filter(entry=>entry.reviewedAt<time).map(entry=>({...deliveryStep(entry.runId,entry.pkg,last),pkg:entry.pkg})));
172
+ rest=rest.filter(entry=>entry.reviewedAt>=time);
173
+ }
174
+ const {files}=composeFixCode({baseline,parentPackage,fixPackages:chainPackages,steps:recorded});
33
175
  if(base.specification)verifySpecificationMaterial(base);
34
176
  const current=captureReviewBaseline({root,
35
177
  ...(base.specification?{specification:{specsRoot:base.specificationRoot,feature:base.specification.feature}}:{}),...(specsRoot===undefined?{}:{specsRoot}),identity:parent.identity,version:base.version,
36
178
  ...(base.codeProjectPaths?{codeProjectPaths:base.codeProjectPaths}:{}),
37
- scope:[...new Set([...parent.scope,...fixes.flatMap(fix=>fix.scope)])],requirements:base.requirements});
179
+ scope:[...new Set(ownScope)],requirements:base.requirements});
38
180
  need(current.rootDigest===base.rootDigest,'fix_parent_binding_mismatch');
39
181
  const compared=base.version===1?current.files:current.files.map(inventoryFile);
40
- need(digest(compared)===digest(files),'fix_current_code_unexplained');
41
- return json({version:1,kind:'cm-fix-code-association',parentPackageDigest:parent.packageDigest,
42
- fixPackageDigest:fixes.at(-1).packageDigest,currentFilesDigest:digest(compared)});
182
+ if(rest.length||digest(compared)!==digest(files)){
183
+ // Without a way to read other runs' deliveries the historical exact match holds.
184
+ need(typeof deliveries==='function','fix_current_code_unexplained');
185
+ // Metadata-only transitions cannot rebuild legacy full-content inventories.
186
+ need(!rest.length||base.version===2,'fix_before_mismatch');
187
+ const state=new Map(files.map(file=>[file.path,inventoryFile(file)]));
188
+ for(const entry of rest)applyDelivery(state,entry.pkg,tolerated);
189
+ compareCurrent({root,base,state,tolerated});
190
+ }
191
+ return associationRecord({parent,fixes,files,steps:compact(recorded)});
192
+ }
193
+ export function associationRecord({parent,fixes,files,steps}){
194
+ return json({version:steps.length?2:1,kind:'cm-fix-code-association',parentPackageDigest:parent.packageDigest,
195
+ fixPackageDigest:fixes.at(-1).packageDigest,currentFilesDigest:digest(files),...(steps.length?{laterDeliveries:steps}:{})});
43
196
  }
@@ -1,4 +1,4 @@
1
- // Approved 0.bootstrap instruction task, inside the original develop effect.
1
+ // Approved bootstrap instruction task, inside the original develop effect.
2
2
  // A factory capability owns only init's fixed paths; never a developer grant.
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
@@ -7,18 +7,35 @@ import {cmInitRuleTargets,generateCmInitDraft,validateCmInitSelection} from '../
7
7
  import {inspectCmInitDraft,readCmInitSource} from '../cm-init/draft-inspection.mjs';
8
8
  import {replaceSessionFile} from '../cm-prd/session.mjs';
9
9
  import {readReviewSourceFiles,readReviewBaseline} from './review-package.mjs';
10
- import {inspectCmAiBootstrapTask} from './cm-ai-admission.mjs';
10
+ import {inspectCmAiBootstrapTask,identifyApprovedBootstrapFeature} from './cm-ai-admission.mjs';
11
11
  import {readProjectInstructionContext,createCmAiTaskLearningApplication,createCmAiTaskLearningRetrospective} from './cm-ai-context-refresh.mjs';
12
12
  import {validateDeveloperScope,readDeveloperRequest} from './developer-adapter.mjs';
13
- import {digest,json,shape,need,freeze,validIdentity,hex,requestFor,terminalFor} from './effect-contract.mjs';
13
+ import {digest,json,shape,need,freeze,validIdentity,hex,requestFor,terminalFor,boundedReason} from './effect-contract.mjs';
14
14
 
15
15
  const capabilities=new WeakMap();
16
16
  const categories=['commands','globs','file_references','constraint_preservation','rule_applicability'];
17
17
  const sha=bytes=>bytes===null?null:createHash('sha256').update(bytes).digest('hex');
18
18
  const same=(a,b)=>need(digest(a)===digest(b),'bootstrap_binding_changed');
19
+ const learningSection=source=>/^## 项目教训[ \t]*\r?$/gmu.test(source);
19
20
  const canonical=root=>need(typeof root==='string'&&path.isAbsolute(root)&&fs.realpathSync(root)===root
20
21
  &&fs.lstatSync(root).isDirectory(),'bootstrap_root_invalid');
21
22
 
23
+ export function mergeBootstrapAgents(existing,generated){
24
+ need(typeof existing==='string'&&typeof generated==='string','bootstrap_instruction_conflict');
25
+ if(!existing)return generated;
26
+ const heading=/^## 项目教训[ \t]*\r?$/gmu.exec(existing);
27
+ if(!heading){need(generated.includes(existing),'bootstrap_instruction_conflict');return generated;}
28
+ const next=/^## [^\r\n]+\r?$/gmu;
29
+ next.lastIndex=heading.index+heading[0].length;
30
+ const end=next.exec(existing)?.index??existing.length;
31
+ const section=existing.slice(heading.index,end);
32
+ const before=existing.slice(0,heading.index),after=existing.slice(end);
33
+ need((!before||generated.includes(before))&&(!after||generated.includes(after)),'bootstrap_instruction_conflict');
34
+ if(generated.includes(section))return generated;
35
+ need(!/^## 项目教训[ \t]*\r?$/gmu.test(generated),'bootstrap_instruction_conflict');
36
+ return generated+(generated.endsWith('\n')?'':'\n')+'\n'+section;
37
+ }
38
+
22
39
  export function readBootstrapEvidence(raw,configuration,identity){
23
40
  const value=json(raw);
24
41
  shape(value,['version','workflow','phase','identity','invocationId','configurationDigest','files','contextFiles','evidenceDigest']);
@@ -50,11 +67,13 @@ export function validateBootstrapReviewPackage(pkg,evidence,configuration,identi
50
67
  export function bootstrapConfiguration(capability,{root,identity,scope,feature}){
51
68
  const configuration=capabilities.get(capability);need(configuration,'bootstrap_capability_required');
52
69
  same(configuration.codeProject,root);same(configuration.identity, {...identity,attempt:1});
53
- same(configuration.scope,scope);need(feature==='0.bootstrap','bootstrap_task_required');return configuration;
70
+ same(configuration.scope,scope);need(feature===configuration.feature
71
+ &&feature===identifyApprovedBootstrapFeature([configuration.feature]),'bootstrap_task_required');return configuration;
54
72
  }
55
73
 
56
74
  export function createHostBootstrap({definition,workflowRoot,selection,bridge,allowWrite}){
57
- const data=json(definition);validIdentity(data.identity);need(data.identity.attempt===1&&data.feature==='0.bootstrap','bootstrap_task_required');
75
+ const data=json(definition);validIdentity(data.identity);need(data.identity.attempt===1
76
+ &&data.feature===identifyApprovedBootstrapFeature(data.specsDir),'bootstrap_task_required');
58
77
  canonical(data.codeProject);canonical(data.specsDir);canonical(workflowRoot);
59
78
  need(typeof bridge?.call==='function'&&typeof allowWrite==='boolean','bootstrap_configuration_invalid');
60
79
  // Construction is non-writing and may occur during resume. Only the runner's
@@ -69,7 +88,7 @@ export function createHostBootstrap({definition,workflowRoot,selection,bridge,al
69
88
  for(const file of instructionPaths){const target=path.join(data.codeProject,file);
70
89
  need(target!==data.specsDir&&!target.startsWith(data.specsDir+path.sep),'bootstrap_specs_overlap');}
71
90
  const bootstrapRequirements={specsRoot:data.specsDir,feature:data.feature,
72
- files:readReviewSourceFiles(data.specsDir,['0.bootstrap/requirements.md','0.bootstrap/design.md'])};
91
+ files:readReviewSourceFiles(data.specsDir,[`${data.feature}/requirements.md`,`${data.feature}/design.md`])};
73
92
  const policyDigest=digest(instructionPaths.slice(2).map(file=>{
74
93
  const relative='templates/rules/'+path.basename(file);return [relative,sha(readCmInitSource(workflowRoot,relative))];}));
75
94
  const configuration=json({version:1,mode,codeProject:data.codeProject,specsDir:data.specsDir,feature:data.feature,
@@ -83,19 +102,26 @@ export function createHostBootstrap({definition,workflowRoot,selection,bridge,al
83
102
  };
84
103
  const capability={configuration,inspectAdmission:admission,
85
104
  assertWriteAuthorized(){need(allowWrite,'bootstrap_write_authorization_required');},
86
- async run(request,control,develop,{previous=null,previousWriteback=null,baseline}={}){
105
+ async run(request,control,develop,{previous=null,previousWriteback=null,baseline,verificationFailed=null}={}){
87
106
  need(allowWrite,'bootstrap_write_authorization_required');
88
107
  need(!control.signal.aborted,'cancelled');
89
108
  same({...request.identity,attempt:1},data.identity);same(request.payload.scope,data.scope);
90
109
  need(!used.has(request.invocationId),'bootstrap_dispatch_unknown');
91
110
  const currentAdmission=admission(baseline);
92
111
  need(currentAdmission.nextTask?.feature===data.feature&&currentAdmission.nextTask.id===request.identity.taskId,'bootstrap_task_required');
93
- const prior=previous===null?null:readBootstrapEvidence(previous,configuration,{...request.identity,attempt:request.identity.attempt-1});
94
- if(mode==='instructions')need(request.identity.attempt===1?prior===null:prior!==null,'bootstrap_prior_evidence_required');
112
+ // A revision binds to the previous attempt's evidence. A retryable develop
113
+ // block after this effect wrote the rules (develop_checks_not_passed) retries
114
+ // the same attempt, so it binds to that attempt's own recorded evidence.
115
+ const retry=previous!==null&&previous.identity?.attempt===request.identity.attempt;
116
+ const prior=previous===null?null:readBootstrapEvidence(previous,configuration,
117
+ {...request.identity,attempt:retry?request.identity.attempt:request.identity.attempt-1});
118
+ if(mode==='instructions')need(request.identity.attempt===1?prior===null||retry:prior!==null,'bootstrap_prior_evidence_required');
95
119
  const originals=instructionPaths.map(file=>({path:file,bytes:readCmInitSource(data.codeProject,file)}));
96
120
  for(const file of originals){
97
121
  const expected=file.path==='AGENTS.md'&&prior!==null&&previousWriteback?.outcome==='written'
98
- ?previousWriteback.agentsFile.sha256:prior?.files.find(item=>item.path===file.path).afterSha256??null;
122
+ ?previousWriteback.agentsFile.sha256:prior?.files.find(item=>item.path===file.path).afterSha256
123
+ ??(file.path==='AGENTS.md'&&file.bytes!==null
124
+ &&learningSection(new TextDecoder('utf8',{fatal:true}).decode(file.bytes))?sha(file.bytes):null);
99
125
  need(sha(file.bytes)===expected,'bootstrap_instruction_conflict');
100
126
  }
101
127
  used.add(request.invocationId);
@@ -120,29 +146,50 @@ export function createHostBootstrap({definition,workflowRoot,selection,bridge,al
120
146
  return terminalFor(response,request);
121
147
  }
122
148
  current();need(!control.signal.aborted,'cancelled');
123
- const draft=await generateCmInitDraft({project:data.codeProject,workflowRoot,selection:choice},{signal:control.signal,
149
+ const generated=await generateCmInitDraft({project:data.codeProject,workflowRoot,selection:choice},{signal:control.signal,
124
150
  generate:(payload,signal)=>bridge.call('init_generate',{...payload,bootstrap:{identity:request.identity,
125
151
  invocationId:request.invocationId,requirements:[...request.payload.requirements,...bootstrapRequirements.files],
126
152
  priorReview:request.payload.priorReview}},signal)});
127
- need(draft.status==='draft_generated'&&draft.inspection.status==='structurally_checked','bootstrap_generation_blocked');
128
- const verified=json(await bridge.call('init_verify',{project:data.codeProject,selection:choice,documents:draft.documents,
129
- inspection:draft.inspection,categories,learningInput:request.payload.learningInput,
153
+ need(generated.status==='draft_generated'&&generated.inspection.status==='structurally_checked','bootstrap_generation_blocked');
154
+ const agentsBefore=originals.find(file=>file.path==='AGENTS.md').bytes;
155
+ const documents=generated.documents.map(document=>document.path==='AGENTS.md'
156
+ ?{path:document.path,content:mergeBootstrapAgents(agentsBefore?.toString('utf8')??'',document.content)}:document);
157
+ const inspection=inspectCmInitDraft({project:data.codeProject,documents,selection:choice});
158
+ need(inspection.status==='structurally_checked','bootstrap_generation_blocked');
159
+ const verified=json(await bridge.call('init_verify',{project:data.codeProject,selection:choice,documents,
160
+ inspection,categories,learningInput:request.payload.learningInput,
130
161
  instructions:'Verify every generated instruction against the approved bootstrap selection and current project. Do not write files, install or dispatch providers. Return {checks,constraintChanges,application,retrospective}; checks use status/evidence. Application and retrospective use the original developer Learning response fields. Unverified assertions block. This is host verification, not independent Review.'},control.signal));
131
162
  shape(verified,['checks','constraintChanges','application','retrospective']);shape(verified.checks,categories);
132
- for(const check of Object.values(verified.checks)){shape(check,['status','evidence']);
133
- need(['verified','not_applicable'].includes(check.status)&&typeof check.evidence==='string'&&check.evidence.trim(),'bootstrap_verification_blocked');}
163
+ const unverified=[];
164
+ for(const name of categories){const check=verified.checks[name];shape(check,['status','evidence']);
165
+ need(typeof check.status==='string'&&typeof check.evidence==='string','bootstrap_verification_blocked');
166
+ if(!['verified','not_applicable'].includes(check.status)||!check.evidence.trim())
167
+ unverified.push(`${name}: ${check.status}; ${check.evidence.trim()||'(no evidence)'}`);}
168
+ // A well-formed verify that does not pass is a determinate answer, not an
169
+ // unknown effect: nothing has been written yet (writes follow below), so the
170
+ // same attempt redoes generation and verification against the evidence it
171
+ // started from. Only the runner's callback may carry the bounded reason.
172
+ if(unverified.length){
173
+ need(typeof verificationFailed==='function','bootstrap_verification_blocked');
174
+ current();verificationFailed(boundedReason('bootstrap_verification_failed: init_verify 未通过的核验组:',unverified,
175
+ '。规范尚未写入;按证据修正项目或生成内容后恢复运行,本轮重新生成并核验'));
176
+ return terminalFor({version:1,invocationId:request.invocationId,contextId:request.contextId,provider:request.provider,
177
+ effectiveModel:response?.effectiveModel??'host-bootstrap',status:'failed',accepted:true,
178
+ ...(response?.providerThreadId?{providerThreadId:response.providerThreadId}:{}),
179
+ result:{code:'bootstrap_verification_failed',reason:'bootstrap_verification_failed'}},request);
180
+ }
134
181
  need(Array.isArray(verified.constraintChanges)&&verified.constraintChanges.length===0,'bootstrap_constraint_confirmation_required');
135
182
  const learning=request.payload.learningInput;
136
- need(learning?.feature==='0.bootstrap','bootstrap_learning_required');
183
+ need(learning?.feature===data.feature,'bootstrap_learning_required');
137
184
  shape(verified.application,['status','note']);shape(verified.retrospective,['status','candidates','reason']);
138
185
  const binding={feature:learning.feature,identity:request.identity,learningDigest:learning.learningDigest};
139
186
  const application=createCmAiTaskLearningApplication({...binding,...verified.application});
140
187
  const retrospective=createCmAiTaskLearningRetrospective({...binding,...verified.retrospective});
141
188
  current();need(!control.signal.aborted,'cancelled');
142
- same(inspectCmInitDraft({project:data.codeProject,documents:draft.documents}).changes,draft.inspection.changes);
189
+ same(inspectCmInitDraft({project:data.codeProject,documents}).changes,inspection.changes);
143
190
  // All targets are prechecked before the first write. Interruption stays in
144
191
  // the runner's original unknown develop effect, never an automatic retry.
145
- for(const document of draft.documents){
192
+ for(const document of documents){
146
193
  need(!control.signal.aborted,'cancelled');canonical(data.codeProject);
147
194
  let parent=data.codeProject;
148
195
  for(const part of document.path.split('/').slice(0,-1)){
@@ -152,13 +199,13 @@ export function createHostBootstrap({definition,workflowRoot,selection,bridge,al
152
199
  const before=originals.find(file=>file.path===document.path).bytes;
153
200
  replaceSessionFile(data.codeProject,document.path,before===null?null:new TextDecoder('utf8',{fatal:true}).decode(before),document.content);
154
201
  }
155
- const after=inspectCmInitDraft({project:data.codeProject,documents:draft.documents});
202
+ const after=inspectCmInitDraft({project:data.codeProject,documents});
156
203
  need(after.status==='structurally_checked'&&after.changes.every(file=>file.action==='unchanged'),'bootstrap_write_unknown');
157
204
  const contextFiles=readProjectInstructionContext(data.codeProject).map(({content,...file})=>file);
158
205
  // Optional module rules must be reachable through the generated entry.
159
206
  const evidenceBody={version:1,workflow:'cm-ai',phase:'bootstrap_instructions',identity:request.identity,
160
207
  invocationId:request.invocationId,configurationDigest:digest(configuration),
161
- files:instructionPaths.map(file=>{const change=draft.inspection.changes.find(item=>item.path===file);
208
+ files:instructionPaths.map(file=>{const change=inspection.changes.find(item=>item.path===file);
162
209
  return {path:file,beforeSha256:change.beforeSha256,afterSha256:change.afterSha256};}),contextFiles};
163
210
  const bootstrap=readBootstrapEvidence({...evidenceBody,evidenceDigest:digest(evidenceBody)},configuration,request.identity);
164
211
  return terminalFor({version:1,invocationId:request.invocationId,contextId:request.contextId,provider:request.provider,
@@ -28,7 +28,8 @@ import {isFinalCmAiTask} from './cm-ai-admission.mjs';
28
28
  import {createHostBootstrap} from './host-bootstrap.mjs';
29
29
  import {digest,id,hex,json,need,shape,freeze,arrayItems} from './effect-contract.mjs';
30
30
  export const protectedTextInstructions='\nProtected current-host mode: do not write files or run commands. Return {status,value,edits} on success; '
31
- +'value retains the original implementation/Learning contract. edits is [{path,beforeSha256,content}], complete UTF-8 text or null for deletion. '
31
+ +'value retains the original implementation/Learning contract. edits is [{path,beforeSha256,content[,mode]}], complete UTF-8 text or null for deletion; '
32
+ +'optional mode "0755" or "0644" sets the permission bits of a written file. '
32
33
  +'Only the supplied scope and expected hashes are allowed. The fixed sandbox applies these edits. On failure return {status,code} without edits. '
33
34
  +'status must be exactly "succeeded" on success (with value and edits) or "failed" (with code). Return the object through the structured output schema; never wrap it in markdown fences.';
34
35
  const protectedConversations=new WeakMap();
@@ -89,8 +90,15 @@ export function deliveredText(codeProject,scope){
89
90
  export function resolveReviewTimeout(review,protection){
90
91
  if(review?.timeoutMs!=null)return {timeoutMs:review.timeoutMs};
91
92
  if(protection)return {timeoutMs:protection.timeoutMs};
92
- return {};
93
+ return {timeoutMs:900000};
93
94
  }
95
+ // The runner races each review against its own timer. That timer must outlast
96
+ // the reviewer's budget, or a budget raised above the runner's journaled call
97
+ // timeout (fixed at 30 minutes here) is still cut at 30 minutes and the attempt's
98
+ // only redispatch is spent. The worker stops its process group about a second
99
+ // after its own deadline; the margin leaves room for that and for close.
100
+ export const REVIEW_BOUND_MARGIN_MS=60000;
101
+ export const reviewRaceTimeout=(outerTimeoutMs,reviewTimeoutMs)=>Math.max(outerTimeoutMs,reviewTimeoutMs+REVIEW_BOUND_MARGIN_MS);
94
102
  export function createConversationExecution(definition,hostContextId,bridge,review=null,allowedAttempt=null,workflow=null,allowQa=false,runtime='codex',options={}){
95
103
  definition=json(definition);workflow=workflow===null?null:json(workflow);options=json(options);
96
104
  shape(options,[...['originalHostContextId','protection','batchWorkflowsDigest','qaLogHome','bootstrap','providerDevelopment','parallelMember','verificationPrecheck'].filter(key=>Object.hasOwn(options,key))]);
@@ -192,7 +200,8 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
192
200
  }catch{/* diagnostics never change the verdict */}
193
201
  return {satisfied:verdict.satisfied};
194
202
  }:null;
195
- const execution={configuration,timeoutMs:provider?protection.timeoutMs:1800000,excludedContexts:[durableHostContextId],hostDecision:null,applicableAgentFiles:[],
203
+ const outerTimeoutMs=provider?protection.timeoutMs:1800000;
204
+ const execution={configuration,timeoutMs:outerTimeoutMs,excludedContexts:[durableHostContextId],hostDecision:null,applicableAgentFiles:[],
196
205
  ...(verificationGate?{verificationGate}:{}),
197
206
  ...(bootstrap?{bootstrap}:{}),
198
207
  ...(provider?{developmentAttempt:provider.attempt}:{}),
@@ -237,7 +246,8 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
237
246
  if(response.value.outcome==='blocked')need(response.edits.length===0,'protected_edit_invalid');
238
247
  const seen=new Set();
239
248
  for(const edit of response.edits){
240
- shape(edit,['path','beforeSha256','content']);
249
+ shape(edit,['path','beforeSha256','content',...(Object.hasOwn(edit,'mode')?['mode']:[])]);
250
+ need(!Object.hasOwn(edit,'mode')||edit.content!==null&&['0644','0755'].includes(edit.mode),'protected_edit_invalid');
241
251
  need(bound.payload.scope.includes(edit.path)&&!seen.has(edit.path),'out_of_scope');seen.add(edit.path);
242
252
  if(edit.beforeSha256!==null)hex(edit.beforeSha256);
243
253
  need(edit.content===null||typeof edit.content==='string','protected_edit_invalid');
@@ -291,6 +301,8 @@ export function createConversationExecution(definition,hostContextId,bridge,revi
291
301
  :createClaudeReviewRun(claudeWorker(selectedOptions))(request,control);
292
302
  }}],
293
303
  reviewInvocation:{developerThreadId:author,excludedThreadIds:[durableHostContextId],hostContextId,
304
+ // Not journaled (unlike timeoutMs above), so a resumed run may raise it.
305
+ timeoutMs:reviewRaceTimeout(outerTimeoutMs,reviewOptions.timeoutMs),
294
306
  authorize:authority?.authorize??(()=>({status:'denied',code:'permission_denied'}))},
295
307
  };
296
308
  if(definition.codeProjects)execution.applicableAgentFiles=[...new Set([...execution.applicableAgentFiles,