@aibyzero/cm-workflow 0.12.0 → 0.13.2

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 (119) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +1 -0
  3. package/CHANGELOG.md +55 -1
  4. package/README.md +31 -3
  5. package/VERSION +1 -1
  6. package/compat/claude-commands/cm-runtime.md +3 -0
  7. package/docs/installation.md +43 -1
  8. package/docs/js-workflow-control.md +63 -6
  9. package/docs/runtime-failover.md +97 -0
  10. package/docs/user-guide.md +37 -1
  11. package/install-codex.sh +5 -0
  12. package/install.ps1 +10 -2
  13. package/install.sh +5 -0
  14. package/package.json +2 -1
  15. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +151 -0
  16. package/runtime/js/cm-ai/claude-review-stream.mjs +69 -8
  17. package/runtime/js/cm-ai/claude-tool-preview.mjs +6 -4
  18. package/runtime/js/cm-ai/cm-ai-admission.mjs +38 -16
  19. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +44 -17
  20. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +105 -12
  21. package/runtime/js/cm-ai/codex-config.mjs +6 -0
  22. package/runtime/js/cm-ai/codex-review-adapter.mjs +6 -2
  23. package/runtime/js/cm-ai/developer-adapter.mjs +41 -16
  24. package/runtime/js/cm-ai/durable-runner-state.mjs +72 -15
  25. package/runtime/js/cm-ai/effect-contract.mjs +10 -1
  26. package/runtime/js/cm-ai/fix-code-association.mjs +4 -1
  27. package/runtime/js/cm-ai/host-conversation-execution.mjs +112 -27
  28. package/runtime/js/cm-ai/host-documentation.mjs +4 -2
  29. package/runtime/js/cm-ai/host-qa-executor.mjs +17 -4
  30. package/runtime/js/cm-ai/host-qa-policy.mjs +6 -3
  31. package/runtime/js/cm-ai/host-role-routing.mjs +9 -5
  32. package/runtime/js/cm-ai/host-tool-bridge.mjs +10 -7
  33. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +9 -4
  34. package/runtime/js/cm-ai/host.mjs +1 -1
  35. package/runtime/js/cm-ai/provider-review-observation.mjs +8 -4
  36. package/runtime/js/cm-ai/qa-attachment.mjs +30 -0
  37. package/runtime/js/cm-ai/review-package.mjs +76 -18
  38. package/runtime/js/cm-ai/review-runner.mjs +15 -3
  39. package/runtime/js/cm-ai/runtime-failover.mjs +75 -0
  40. package/runtime/js/cm-ai/specification-material.mjs +98 -0
  41. package/runtime/js/cm-ai/task-runner.mjs +57 -20
  42. package/runtime/js/cm-ai/worker-claude-developer.mjs +174 -0
  43. package/runtime/js/cm-ai/worker-claude.mjs +18 -5
  44. package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -4
  45. package/runtime/js/cm-ai/worker-codex.mjs +8 -12
  46. package/runtime/js/cm-init/draft-generation.mjs +24 -4
  47. package/runtime/js/cm-init/draft-inspection.mjs +29 -1
  48. package/runtime/js/cm-prd/session.mjs +19 -2
  49. package/runtime/js/cm-prd/summary.mjs +46 -20
  50. package/runtime/review.md +11 -1
  51. package/runtime/workflow-config.md +39 -2
  52. package/runtime/workflow-routing.md +6 -1
  53. package/scripts/cm-ai-admission.test.mjs +99 -0
  54. package/scripts/cm-ai-batch-host.test.mjs +4 -1
  55. package/scripts/cm-ai-batch-run.test.mjs +7 -1
  56. package/scripts/cm-ai-bootstrap.test.mjs +2 -1
  57. package/scripts/cm-ai-fix-integration.test.mjs +2 -1
  58. package/scripts/cm-ai-host.mjs +81 -12
  59. package/scripts/cm-ai-host.test.mjs +520 -5
  60. package/scripts/cm-ai-multi-root.test.mjs +9 -3
  61. package/scripts/cm-ai-nested-execution.test.mjs +11 -4
  62. package/scripts/cm-ai-review-timeout.test.mjs +226 -0
  63. package/scripts/cm-ai-run.mjs +40 -13
  64. package/scripts/cm-ai-run.test.mjs +45 -9
  65. package/scripts/cm-check-host.test.mjs +1 -1
  66. package/scripts/cm-check-runtime.sh +51 -1
  67. package/scripts/cm-claude-developer-worker.test.mjs +236 -0
  68. package/scripts/cm-claude-probe.test.mjs +64 -1
  69. package/scripts/cm-claude-review-stream.test.mjs +236 -1
  70. package/scripts/cm-claude-worker.test.mjs +110 -1
  71. package/scripts/cm-codex-developer-adapter.test.mjs +50 -2
  72. package/scripts/cm-codex-developer-worker.test.mjs +84 -1
  73. package/scripts/cm-codex-review-progress.test.mjs +34 -6
  74. package/scripts/cm-failover.mjs +288 -0
  75. package/scripts/cm-failover.test.mjs +184 -0
  76. package/scripts/cm-host-qa-executor.test.mjs +277 -0
  77. package/scripts/cm-host-tool-bridge.test.mjs +31 -0
  78. package/scripts/cm-init-draft-generation.test.mjs +62 -0
  79. package/scripts/cm-init-draft-inspection.test.mjs +76 -0
  80. package/scripts/cm-init-host.mjs +4 -4
  81. package/scripts/cm-init-host.test.mjs +12 -7
  82. package/scripts/cm-init-session.test.mjs +50 -0
  83. package/scripts/cm-log-event.mjs +34 -5
  84. package/scripts/cm-prd-completion.test.mjs +2 -2
  85. package/scripts/cm-prd-host.mjs +39 -3
  86. package/scripts/cm-prd-host.test.mjs +52 -0
  87. package/scripts/cm-prd-review-gate.mjs +11 -2
  88. package/scripts/cm-prd-review-gate.test.mjs +62 -0
  89. package/scripts/cm-prd-session-recovery.test.mjs +167 -0
  90. package/scripts/cm-prd-summary.test.mjs +147 -0
  91. package/scripts/cm-review-dependency-snapshot.test.mjs +10 -0
  92. package/scripts/cm-review-inventory.test.mjs +189 -0
  93. package/scripts/cm-review-schema.test.mjs +35 -1
  94. package/scripts/cm-review-scope-recovery.test.mjs +63 -0
  95. package/scripts/cm-runtime-edit.mjs +104 -0
  96. package/scripts/cm-runtime-failover.test.mjs +130 -0
  97. package/scripts/cm-runtime-install.mjs +42 -0
  98. package/scripts/cm-runtime.mjs +113 -0
  99. package/scripts/cm-runtime.test.mjs +117 -0
  100. package/scripts/cm-spec-manifest.mjs +24 -21
  101. package/scripts/cm-spec-manifest.test.mjs +19 -0
  102. package/scripts/cm-workflow-config.mjs +113 -5
  103. package/scripts/cm-workflow-config.test.mjs +124 -1
  104. package/scripts/fixtures/prd-review-gate-python-oracle.py +18 -2
  105. package/scripts/test-cm-prd-review-gate.py +30 -0
  106. package/scripts/test-shell-compat.sh +34 -0
  107. package/scripts/validate-public-repo.py +5 -0
  108. package/skills/cm-ai/references/N4-review.md +5 -4
  109. package/skills/cm-ai/references/js-host.md +36 -2
  110. package/skills/cm-check/SKILL.md +7 -3
  111. package/skills/cm-init/SKILL.md +4 -0
  112. package/skills/cm-init/references/js-host.md +2 -0
  113. package/skills/cm-init/references/runtime-declaration.md +26 -0
  114. package/skills/cm-prd/SKILL.md +3 -3
  115. package/skills/cm-prd/references/js-change-recovery.md +24 -3
  116. package/skills/cm-prd/references/summary-card.md +7 -0
  117. package/skills/cm-runtime/SKILL.md +32 -0
  118. package/templates/auto-update/cm-update.sh +1 -1
  119. package/templates/cm-workflow.yml +16 -0
@@ -0,0 +1,151 @@
1
+ {
2
+ "type": "object",
3
+ "additionalProperties": false,
4
+ "required": [
5
+ "status"
6
+ ],
7
+ "properties": {
8
+ "status": {
9
+ "type": "string",
10
+ "enum": [
11
+ "succeeded",
12
+ "failed"
13
+ ]
14
+ },
15
+ "code": {
16
+ "type": "string",
17
+ "minLength": 1
18
+ },
19
+ "value": {
20
+ "type": "object",
21
+ "additionalProperties": false,
22
+ "required": [
23
+ "outcome"
24
+ ],
25
+ "properties": {
26
+ "outcome": {
27
+ "type": "string",
28
+ "enum": [
29
+ "implemented",
30
+ "blocked"
31
+ ]
32
+ },
33
+ "application": {
34
+ "type": "object",
35
+ "additionalProperties": false,
36
+ "required": [
37
+ "status",
38
+ "note"
39
+ ],
40
+ "properties": {
41
+ "status": {
42
+ "type": "string",
43
+ "enum": [
44
+ "applied",
45
+ "no_relevant_lesson"
46
+ ]
47
+ },
48
+ "note": {
49
+ "type": [
50
+ "string",
51
+ "null"
52
+ ]
53
+ }
54
+ }
55
+ },
56
+ "retrospective": {
57
+ "type": "object",
58
+ "additionalProperties": false,
59
+ "required": [
60
+ "status",
61
+ "candidates",
62
+ "reason"
63
+ ],
64
+ "properties": {
65
+ "status": {
66
+ "type": "string",
67
+ "enum": [
68
+ "no_new_lesson",
69
+ "lesson_candidate",
70
+ "writeback_pending"
71
+ ]
72
+ },
73
+ "candidates": {
74
+ "type": "array",
75
+ "maxItems": 3,
76
+ "items": {
77
+ "type": "object",
78
+ "additionalProperties": false,
79
+ "required": [
80
+ "classification",
81
+ "trigger",
82
+ "action",
83
+ "evidence"
84
+ ],
85
+ "properties": {
86
+ "classification": {
87
+ "type": "string",
88
+ "enum": [
89
+ "structured",
90
+ "memory_only"
91
+ ]
92
+ },
93
+ "trigger": {
94
+ "type": "string"
95
+ },
96
+ "action": {
97
+ "type": "string"
98
+ },
99
+ "evidence": {
100
+ "type": "array",
101
+ "items": {
102
+ "type": "string"
103
+ }
104
+ }
105
+ }
106
+ }
107
+ },
108
+ "reason": {
109
+ "type": [
110
+ "string",
111
+ "null"
112
+ ]
113
+ }
114
+ }
115
+ }
116
+ }
117
+ },
118
+ "edits": {
119
+ "type": "array",
120
+ "maxItems": 64,
121
+ "items": {
122
+ "type": "object",
123
+ "additionalProperties": false,
124
+ "required": [
125
+ "path",
126
+ "beforeSha256",
127
+ "content"
128
+ ],
129
+ "properties": {
130
+ "path": {
131
+ "type": "string",
132
+ "minLength": 1
133
+ },
134
+ "beforeSha256": {
135
+ "type": [
136
+ "string",
137
+ "null"
138
+ ],
139
+ "pattern": "^[a-f0-9]{64}$"
140
+ },
141
+ "content": {
142
+ "type": [
143
+ "string",
144
+ "null"
145
+ ]
146
+ }
147
+ }
148
+ }
149
+ }
150
+ }
151
+ }
@@ -1,7 +1,18 @@
1
1
  // Conservative print/stream-json decoder. No dispatch, grant or completion authority.
2
2
  // Process ownership must append process_closed and reject unsuccessful exits.
3
- export function createClaudeReviewStream(onEvent) {
4
- let session = null, stage = 'init', value;
3
+ export function reportClaudeRateLimitNotice(raw, onNotice) {
4
+ if (typeof onNotice !== 'function') return;
5
+ const info = Object.fromEntries(Object.entries(
6
+ raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {},
7
+ ).filter(([, value]) => value === null || typeof value === 'string'
8
+ || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value))));
9
+ // Diagnostics must not change the provider result or leak nested provider payloads.
10
+ try { onNotice({kind:'rate_limit', info}); } catch {}
11
+ }
12
+
13
+ export function createClaudeReviewStream(onEvent, onNotice = null) {
14
+ let session = null, stage = 'init', value, noticeCount = 0, thinkingCount = 0, rejectedAttempts = 0;
15
+ const pendingTools = new Map(), toolIds = new Set();
5
16
  const reject = code => { stage = 'failed'; throw Object.assign(new Error(code), {code}); };
6
17
  return Object.freeze({
7
18
  accept(message) {
@@ -18,21 +29,71 @@ export function createClaudeReviewStream(onEvent) {
18
29
  onEvent({event:'turn.started', item_type:null});
19
30
  return;
20
31
  }
21
- if (message.type === 'assistant' && stage === 'assistant') {
32
+ if (message.type === 'rate_limit_event') {
33
+ if (noticeCount >= 32) reject('unexpected_event');
34
+ noticeCount++;
35
+ reportClaudeRateLimitNotice(message.rate_limit_info, onNotice);
36
+ return;
37
+ }
38
+ if (message.type === 'system') {
39
+ if (message.subtype === 'thinking_tokens') {
40
+ // Long reviews emit usage heartbeats; worker-claude also caps total output at 1 MB.
41
+ if (thinkingCount >= 4096) reject('unexpected_event');
42
+ thinkingCount++;
43
+ return;
44
+ }
45
+ if (!['api_retry','hook_started','hook_response','commands_changed'].includes(message.subtype)
46
+ || noticeCount >= 32) reject('unexpected_event');
47
+ noticeCount++;
48
+ // CLI notifications carry no verdict; never forward hook output or command bodies.
49
+ const notice = {kind:'claude_system_notice', subtype:message.subtype};
50
+ for (const key of ['attempt','max_retries','error_status']) {
51
+ if (typeof message[key] === 'number' && Number.isFinite(message[key])) notice[key] = message[key];
52
+ }
53
+ if (typeof message.hook_name === 'string') notice.hook_name = message.hook_name;
54
+ try { if (typeof onNotice === 'function') onNotice(notice); } catch {}
55
+ return;
56
+ }
57
+ if (message.type === 'assistant') {
22
58
  if (message.parent_tool_use_id !== null || message.error != null
23
59
  || message.message?.role !== 'assistant') reject('unexpected_assistant');
24
60
  const content = message.message.content;
25
- if (!Array.isArray(content) || content.length === 0
26
- || content.some(block => block?.type !== 'text' || typeof block.text !== 'string')) {
27
- reject('unexpected_tool_or_content');
61
+ if (!Array.isArray(content) || content.length === 0) reject('unexpected_tool_or_content');
62
+ let substantive = false;
63
+ for (const block of content) {
64
+ if (['thinking','redacted_thinking'].includes(block?.type)) continue;
65
+ substantive = true;
66
+ if (block?.type === 'text' && typeof block.text === 'string') continue;
67
+ if (block?.type !== 'tool_use' || typeof block.id !== 'string' || !block.id.trim()
68
+ || toolIds.has(block.id) || typeof block.name !== 'string' || !block.name.trim()) {
69
+ reject('unexpected_tool_or_content');
70
+ }
71
+ if (block.name !== 'StructuredOutput' && ++rejectedAttempts > 16) reject('unexpected_tool_or_content');
72
+ toolIds.add(block.id);
73
+ pendingTools.set(block.id, block.name);
28
74
  }
29
75
  // Result is authoritative for structured output; assistant prose is never a verdict.
30
- stage = 'result';
76
+ if (substantive) stage = 'result';
77
+ return;
78
+ }
79
+ if (message.type === 'user') {
80
+ const content = message.message?.content;
81
+ if (message.message?.role !== 'user' || !Array.isArray(content) || content.length === 0) {
82
+ reject('unexpected_tool_or_content');
83
+ }
84
+ for (const block of content) {
85
+ if (block?.type !== 'tool_result' || !pendingTools.has(block.tool_use_id)
86
+ || (pendingTools.get(block.tool_use_id) !== 'StructuredOutput' && block.is_error !== true)) {
87
+ reject('unexpected_tool_or_content');
88
+ }
89
+ pendingTools.delete(block.tool_use_id);
90
+ }
31
91
  return;
32
92
  }
33
93
  if (message.type === 'result') {
34
94
  if (message.subtype !== 'success' || message.is_error !== false) reject('provider_failed');
35
- if (stage !== 'result' || message.num_turns !== 1) reject('unexpected_result');
95
+ if (stage !== 'result' || pendingTools.size !== 0 || !Number.isInteger(message.num_turns)
96
+ || message.num_turns < 1 || message.num_turns > 20) reject('unexpected_result');
36
97
  if (message.structured_output !== undefined) value = message.structured_output;
37
98
  else {
38
99
  try { value = JSON.parse(message.result); } catch { reject('invalid_output_json'); }
@@ -62,7 +62,8 @@ export async function previewClaudeTools({cwd,model,cli='claude',spawnProcess=sp
62
62
  const checks={json:true,post:request.method==='POST',
63
63
  messages_endpoint:new URL(request.url,'http://127.0.0.1').pathname==='/v1/messages',
64
64
  model_matches:data.model===model,messages_array:Array.isArray(data.messages),
65
- tools_empty:Array.isArray(tools)&&tools.length===0,
65
+ tools_allowed:Array.isArray(tools)&&(tools.length===0
66
+ ||(tools.length===1&&tools[0]?.name==='StructuredOutput')),
66
67
  synthetic_auth:request.headers['x-api-key']==='cm-synthetic-local-probe'};
67
68
  safe={valid:Object.values(checks).every(Boolean),checks};
68
69
  }catch{}
@@ -70,7 +71,7 @@ export async function previewClaudeTools({cwd,model,cli='claude',spawnProcess=sp
70
71
  if(index<8)observations[index]=safe;
71
72
  response.writeHead(400,{'Content-Type':'application/json'});
72
73
  response.end(JSON.stringify({type:'error',error:{type:'invalid_request_error',message:'CM_LOCAL_PROBE_STOP'}}));
73
- // Inspection is finished; do not let CLI-internal repair/retry issue another model request.
74
+ // Stop after the first valid request; a CLI retry may already be in flight.
74
75
  if(safe.valid){stoppedByProbe=true;controller.abort();}
75
76
  });
76
77
  });
@@ -99,9 +100,10 @@ export async function previewClaudeTools({cwd,model,cli='claude',spawnProcess=sp
99
100
  }
100
101
  const messages=observations.filter(item=>item.startup!==true);
101
102
  return {model,disabledSkills:[],preflight:{provider:'claude',prompt_transport:'stdin',
102
- config_fingerprint:fingerprint,passed:messages.length===1&&messages[0].valid
103
+ config_fingerprint:fingerprint,passed:messages.length>=1&&messages.length<=2&&messages.every(message=>message.valid)
103
104
  &&stoppedByProbe&&result?.status==='cancelled'&&closeEvidence!==null&&!closeEvidence.timed_out,
104
- local_requests:observations.length,message_requests:messages.length,listener_closed:closed,isolation:'macos-loopback-sandbox',
105
+ local_requests:observations.length,message_requests:messages.length,message_requests_expected:'1-2',
106
+ listener_closed:closed,isolation:'macos-loopback-sandbox',
105
107
  process_code:result?.code??'unknown',stopped_by_probe:stoppedByProbe,exit_code:closeEvidence?.exit_code??null,
106
108
  request_checks:observations.map(item=>item.startup?{startup:true}:item.checks??{complete:false})}};
107
109
  }
@@ -4,6 +4,7 @@ import path from 'node:path';
4
4
  import { createHash } from 'node:crypto';
5
5
  import { spawnSync } from 'node:child_process';
6
6
  import { fileURLToPath } from 'node:url';
7
+ import {buildManifest,verifyManifest} from '../../../scripts/cm-spec-manifest.mjs';
7
8
 
8
9
  const TASK=/^\s*-\s*\[([ xX])\]\s+(?:~~)?(T-[A-Za-z0-9][A-Za-z0-9._-]*)(?=[:\s])[:\s]*(.*)$/;
9
10
  const DEPENDENCY=/^\s*-\s*(T-[A-Za-z0-9][A-Za-z0-9._-]*)\s+依赖\s+(.+)$/;
@@ -200,22 +201,27 @@ function validateTestCases(specsDir,status,names){
200
201
  }
201
202
 
202
203
  function readFeature(specsDir,name){
203
- return parseFeatureTaskText(fs.readFileSync(path.join(specsDir,name,'tasks.md'),'utf8'));
204
+ const parsed=parseFeatureTaskText(fs.readFileSync(path.join(specsDir,name,'tasks.md'),'utf8'),{allowDependencyPunctuation:true});
205
+ if(parsed.error)parsed.detail={feature:name,...parsed.detail};
206
+ return parsed;
204
207
  }
205
208
 
206
209
  export function declaredAcceptanceIds(source){
207
210
  return new Set(source.split(/\r?\n/).map(line=>line.match(ACCEPTANCE)).filter(Boolean).map(match=>match[1]||match[2]));
208
211
  }
209
212
 
210
- export function parseFeatureTaskText(source){
213
+ export function parseFeatureTaskText(source,{allowDependencyPunctuation=false}={}){
211
214
  const lines=source.split(/\r?\n/);
212
215
  const tasks=[];
213
216
  const taskIds=new Set();
214
217
  const dependencies=new Map();
215
- for(const line of lines){
218
+ const dependencyLocations=new Map();
219
+ const location=index=>({line:index+1,text:lines[index].slice(0,120)});
220
+ const invalid=(error,index)=>({error,detail:location(index)});
221
+ for(const [index,line] of lines.entries()){
216
222
  const task=line.match(TASK);
217
223
  if(task){
218
- if(taskIds.has(task[2]))return {error:'tasks_invalid'};
224
+ if(taskIds.has(task[2]))return invalid('tasks_invalid',index);
219
225
  taskIds.add(task[2]);
220
226
  const dropped=/\[DROPPED(?:\s[^\]]*)?\]/.test(task[3]);
221
227
  tasks.push({
@@ -228,30 +234,39 @@ export function parseFeatureTaskText(source){
228
234
  }
229
235
  const dependency=line.match(DEPENDENCY);
230
236
  if(dependency){
231
- if(dependencies.has(dependency[1]))return {error:'dependencies_invalid'};
232
- const required=dependency[2].split(/[,,]/).map(value=>value.trim()).filter(Boolean);
233
- if(!required.length||required.some(id=>!TASK_ID.test(id)))return {error:'dependencies_invalid'};
237
+ if(dependencies.has(dependency[1]))return invalid('dependencies_invalid',index);
238
+ // Only cm-ai admission opts in; cm-prd self-check retains strict parsing.
239
+ const required=dependency[2].split(/[,,]/).map(value=>value.trim()).filter(Boolean)
240
+ .map(value=>allowDependencyPunctuation?value.replace(/[。..;;、\s]+$/u,''):value);
241
+ if(!required.length||required.some(id=>!TASK_ID.test(id)))return invalid('dependencies_invalid',index);
234
242
  dependencies.set(dependency[1],required);
243
+ dependencyLocations.set(dependency[1],location(index));
235
244
  }
236
245
  }
237
- if(!tasks.length)return {error:'tasks_invalid'};
238
- return {tasks,dependencies};
246
+ if(!tasks.length)return invalid('tasks_invalid',Math.max(0,lines.findIndex(line=>line.trim())));
247
+ return {tasks,dependencies,dependencyLocations};
239
248
  }
240
249
 
241
250
  export function validDependencies(tasks,dependencies){
251
+ return invalidDependency(tasks,dependencies)===null;
252
+ }
253
+
254
+ function invalidDependency(tasks,dependencies){
242
255
  const ids=new Set(tasks.map(task=>task.id));
243
256
  for(const [taskId,required] of dependencies){
244
- if(!ids.has(taskId)||required.some(id=>id===taskId||!ids.has(id)))return false;
257
+ if(!ids.has(taskId)||required.some(id=>id===taskId||!ids.has(id)))return taskId;
245
258
  }
246
259
  const visiting=new Set(),visited=new Set();
260
+ let cycleTask=null;
247
261
  const visit=id=>{
248
- if(visiting.has(id))return false;
262
+ if(visiting.has(id)){cycleTask=id;return false;}
249
263
  if(visited.has(id))return true;
250
264
  visiting.add(id);
251
265
  for(const dependency of dependencies.get(id)||[])if(!visit(dependency))return false;
252
266
  visiting.delete(id);visited.add(id);return true;
253
267
  };
254
- return tasks.every(task=>visit(task.id));
268
+ tasks.every(task=>visit(task.id));
269
+ return cycleTask;
255
270
  }
256
271
 
257
272
  function validateBootstrap(codeProject,specsDir,names){
@@ -260,7 +275,7 @@ function validateBootstrap(codeProject,specsDir,names){
260
275
  if(empty&&!hasBootstrap)return 'bootstrap_required';
261
276
  if(!empty&&hasBootstrap){
262
277
  const parsed=readFeature(specsDir,'0.bootstrap');
263
- if(parsed.error)return parsed.error;
278
+ if(parsed.error)return null; // Let selection retain the parser's location and feature summaries.
264
279
  const bootstrapTask=parsed.tasks.find(task=>task.id==='T-001');
265
280
  if(bootstrapTask&&!bootstrapTask.completed&&!bootstrapTask.dropped)return 'bootstrap_conflict';
266
281
  }
@@ -295,8 +310,10 @@ function selectTask(specsDir,names){
295
310
  const evidenceNames=evidence.names;
296
311
  for(const name of names){
297
312
  const parsed=readFeature(specsDir,name);
298
- if(parsed.error)return {error:parsed.error,features,warnings};
299
- if(!validDependencies(parsed.tasks,parsed.dependencies))return {error:'dependencies_invalid',features,warnings};
313
+ if(parsed.error)return {error:parsed.error,detail:parsed.detail,features,warnings};
314
+ const invalidId=invalidDependency(parsed.tasks,parsed.dependencies);
315
+ if(invalidId!==null)return {error:'dependencies_invalid',
316
+ detail:{feature:name,...parsed.dependencyLocations.get(invalidId)},features,warnings};
300
317
  const byId=new Map(parsed.tasks.map(task=>[task.id,task]));
301
318
  const pending=parsed.tasks.filter(task=>!task.completed&&!task.dropped);
302
319
  const missing=missingReviewIds(name,parsed.tasks,evidenceNames);
@@ -340,6 +357,10 @@ function admissionFor(options,inProgressBootstrap=null){
340
357
  const featuresProblem=approvedFeaturesProblem(status.value,discovered.names);
341
358
  if(featuresProblem==='spec_features_changed')return result(base,'awaiting_spec_approval',featuresProblem);
342
359
  if(featuresProblem)return result(base,'blocked',featuresProblem);
360
+ if(Object.hasOwn(status.value,'specFiles')){
361
+ try{verifyManifest(buildManifest(specsDir),path.join(specsDir,'.cm-specs-status'));}
362
+ catch{return result(base,'blocked','spec_drift');}
363
+ }
343
364
  const testCasesProblem=validateTestCases(specsDir,status.value,discovered.names);
344
365
  if(testCasesProblem==='test_cases_changed')return result(base,'awaiting_spec_approval',testCasesProblem);
345
366
  if(testCasesProblem)return result(base,'blocked',testCasesProblem);
@@ -347,7 +368,8 @@ function admissionFor(options,inProgressBootstrap=null){
347
368
  if(bootstrapProblem&&!(bootstrapProblem==='bootstrap_conflict'&&inProgressBootstrap==='T-001'))
348
369
  return result(base,'blocked',bootstrapProblem);
349
370
  const selection=selectTask(specsDir,discovered.names);
350
- if(selection.error)return result(base,'blocked',selection.error,{features:selection.features,warnings:selection.warnings});
371
+ if(selection.error)return result(base,'blocked',selection.error,{features:selection.features,warnings:selection.warnings,
372
+ ...(selection.detail?{detail:selection.detail}:{})});
351
373
  if(!selection.nextTask)return result(base,'complete','all_tasks_terminal',{features:selection.features,warnings:selection.warnings});
352
374
  return result(base,'ready','task_selected',{features:selection.features,nextTask:selection.nextTask,warnings:selection.warnings});
353
375
  }
@@ -2,7 +2,7 @@
2
2
  import {inspectCmAiAdmission} from './cm-ai-admission.mjs';
3
3
  import {inspectCmAiContextRefresh,inspectCmAiTaskLearningInput} from './cm-ai-context-refresh.mjs';
4
4
  import {findCmAiQaDecision,inspectCmAiQaDecision,inspectCmAiQaResult,recordCmAiQaDecision,
5
- latestCmAiQaRun,recordCmAiQaRun} from './cm-ai-qa-log.mjs';
5
+ latestCmAiQaRun,recordCmAiQaRun,inspectCmAiQaRecovery} from './cm-ai-qa-log.mjs';
6
6
  import {recordCmAiRunDone} from './cm-ai-run-finalizer.mjs';
7
7
  import {readHostQaFixHandoff} from './host-qa-fix.mjs';
8
8
  import {digest,freeze,hex,id,json,need,shape,text,validIdentity} from './effect-contract.mjs';
@@ -11,8 +11,10 @@ const sameIdentity=(left,right)=>['repositoryId','runId','taskId','attempt'].eve
11
11
  const sameTask=(left,right)=>['repositoryId','runId','taskId'].every(key=>left[key]===right[key]);
12
12
  const boundStatus=(status,identity)=>{validIdentity(status?.identity);
13
13
  need(sameIdentity(status.identity,identity),'identity_mismatch');return status;};
14
+ const retryReview=status=>status.state==='pending_review'&&status.code==='review_transport_timeout';
15
+ const retryDeveloper=status=>status.state==='blocked'&&status.code==='developer_result_invalid';
14
16
  const pendingAction=status=>status.state==='awaiting_spec_approval'?'spec_approval':
15
- status.state==='changes_requested'?'resume':
17
+ status.state==='changes_requested'||retryDeveloper(status)||retryReview(status)?'resume':
16
18
  status.state==='awaiting_review'?'decision':status.state==='unknown'?'reconcile':
17
19
  status.state==='pending_review'&&status.code==='provider_review_observed'?'review_evidence':
18
20
  status.state==='pending_review'?'decision':status.state==='approved'?'complete':
@@ -123,6 +125,7 @@ export function createCmAiConversationEntry(options) {
123
125
  if(options&&Object.hasOwn(options,'qaDecision'))optionKeys.push('qaDecision');
124
126
  if(options&&Object.hasOwn(options,'qaDecisionProvider'))optionKeys.push('qaDecisionProvider');
125
127
  if(options&&Object.hasOwn(options,'qaExecutor'))optionKeys.push('qaExecutor');
128
+ if(options&&Object.hasOwn(options,'rerunUnknownQa'))optionKeys.push('rerunUnknownQa');
126
129
  if(options&&Object.hasOwn(options,'qaLogHome'))optionKeys.push('qaLogHome');
127
130
  if(options&&Object.hasOwn(options,'applicableAgentFiles'))optionKeys.push('applicableAgentFiles');
128
131
  if(options&&Object.hasOwn(options,'documentationResult'))optionKeys.push('documentationResult');
@@ -136,12 +139,14 @@ export function createCmAiConversationEntry(options) {
136
139
  if(runner&&Object.hasOwn(runner,'attachLearningEvidence'))runnerKeys.push('attachLearningEvidence');
137
140
  if(runner&&Object.hasOwn(runner,'inspectFixAssociation'))runnerKeys.push('inspectFixAssociation');
138
141
  if(runner&&Object.hasOwn(runner,'acceptCompletedFix'))runnerKeys.push('acceptCompletedFix');
142
+ if(runner&&Object.hasOwn(runner,'attachQa'))runnerKeys.push('attachQa');
139
143
  if(runner&&Object.hasOwn(runner,'inspectBootstrapAdmission'))runnerKeys.push('inspectBootstrapAdmission');
140
144
  shape(runner,runnerKeys);
141
145
  for(const name of ['executeEffect','status','cancel','run'])need(typeof runner[name]==='function');
142
146
  if(Object.hasOwn(runner,'attachLearningEvidence'))need(typeof runner.attachLearningEvidence==='function');
143
147
  if(Object.hasOwn(runner,'inspectFixAssociation'))need(typeof runner.inspectFixAssociation==='function');
144
148
  if(Object.hasOwn(runner,'acceptCompletedFix'))need(typeof runner.acceptCompletedFix==='function');
149
+ if(Object.hasOwn(runner,'attachQa'))need(typeof runner.attachQa==='function');
145
150
  if(Object.hasOwn(runner,'inspectBootstrapAdmission'))need(typeof runner.inspectBootstrapAdmission==='function');
146
151
 
147
152
  const hostDecision=Object.hasOwn(options,'hostDecision')?json(options.hostDecision):null;
@@ -163,6 +168,7 @@ export function createCmAiConversationEntry(options) {
163
168
  const decideQa=qaProvider?.decide,qaTimeout=qaProvider?.timeoutMs;
164
169
  let pendingQa=null;
165
170
  let qaExecutor=null,pendingExecution=null,cancellationEpoch=0;
171
+ let rerunUnknownQa=options.rerunUnknownQa??false;need(typeof rerunUnknownQa==='boolean');
166
172
  if(Object.hasOwn(options,'qaExecutor')){
167
173
  shape(options.qaExecutor,['mode','caseCount','timeoutMs','run',
168
174
  ...(Object.hasOwn(options.qaExecutor,'configuration')?['configuration']:[])]);
@@ -241,13 +247,13 @@ export function createCmAiConversationEntry(options) {
241
247
  const notCancelled=()=>{const current=runner.status();
242
248
  need(startedEpoch===cancellationEpoch&&!current.cancellationRequested&&!current.cancelAfterCommit,'cancelled');};
243
249
  // Reuse the runner's two-attempt lifecycle, including its fresh review
244
- // identity and review_limit. Never retry unknown/provider failures.
250
+ // identity and review_limit. Only no-result transport timeouts may redispatch.
245
251
  const call=(name,packageDigest,extra={})=>route({version:1,operation:name,
246
252
  requestId:operation.requestId,identity:runner.status().identity,...(packageDigest===undefined?{}:{packageDigest}),...extra});
247
253
  let result=await call('status');
248
254
  for(let round=identity.attempt;round<=2;round++){
249
- if(result.code===null&&['ready','changes_requested'].includes(result.state))result=await call('start');
250
- if(['reported','advanced'].includes(result.outcome)&&result.code===null&&result.state==='awaiting_review')
255
+ if(result.code===null&&['ready','changes_requested'].includes(result.state)||retryDeveloper(result))result=await call('start');
256
+ if(['reported','advanced'].includes(result.outcome)&&(result.code===null&&result.state==='awaiting_review'||retryReview(result)))
251
257
  result=await call('decision',result.packageDigest);
252
258
  if(result.outcome==='advanced'&&result.code===null&&result.state==='changes_requested'
253
259
  &&result.identity.attempt===round+1)continue;
@@ -263,11 +269,16 @@ export function createCmAiConversationEntry(options) {
263
269
  notCancelled();
264
270
  need(pendingExecution===null,'qa_execution_pending');
265
271
  const binding={specsDir:options.specsDir,feature:options.feature,identity:result.identity,packageDigest:result.packageDigest};
266
- let previous;
272
+ let previous,recovery=null;
267
273
  try{previous=latestCmAiQaRun(binding);}
268
274
  catch(error){
269
- if(error.code==='qa_result_incomplete')return summary(operation,{...runner.status(),code:'qa_execution_unknown'},'blocked');
270
- throw error;
275
+ if(error.code!=='qa_result_incomplete')throw error;
276
+ if(rerunUnknownQa){
277
+ try{recovery=inspectCmAiQaRecovery(binding);}
278
+ catch(error){if(error.code!=='qa_execution_unknown')throw error;}
279
+ }
280
+ if(recovery===null)return summary(operation,{...runner.status(),code:'qa_execution_unknown'},'blocked');
281
+ previous=null;
271
282
  }
272
283
  let testRunId=previous?.testRunId;
273
284
  const accepted=runner.status().acceptedQaFix;
@@ -275,14 +286,20 @@ export function createCmAiConversationEntry(options) {
275
286
  if(previous===null||repaired){
276
287
  // Later rounds require an original completed child accepted by the
277
288
  // parent journal. Unknown executions and unrepaired failures stop.
278
- const qaRound=repaired?accepted.qaRound+1:1;
289
+ const qaRound=recovery?.qaRound??(repaired?accepted.qaRound+1:1);
279
290
  need(qaRound>=1&&qaRound<=3,'qa_round_invalid');
280
- testRunId=`qa-${digest(repaired?{...binding,qaRound,repair:accepted.evidenceDigest}:binding).slice(0,48)}`;
291
+ testRunId=`qa-${digest(recovery?{...binding,previousTestRunId:recovery.testRunId}:
292
+ repaired?{...binding,qaRound,repair:accepted.evidenceDigest}:binding).slice(0,48)}`;
281
293
  const invocation={...binding,codeProject:options.codeProject,testRunId,mode:qaExecutor.mode,caseCount:qaExecutor.caseCount,
282
- ...(repaired?{qaRound}: {})};
294
+ ...(repaired||recovery?{qaRound}: {})};
283
295
  const logInput={...invocation,...(Object.hasOwn(options,'qaLogHome')?{logHome:options.qaLogHome}:{})};
284
296
  notCancelled();
285
- recordCmAiQaRun({...logInput,phase:'start'});
297
+ if(recovery){
298
+ need(qaExecutor.mode===recovery.mode&&qaExecutor.caseCount===recovery.caseCount,'qa_execution_mismatch');
299
+ recordCmAiQaRun({...logInput,testRunId:recovery.testRunId,phase:'abandoned'});
300
+ rerunUnknownQa=false;
301
+ }
302
+ recordCmAiQaRun({...logInput,phase:'start',...(recovery?{previousTestRunId:recovery.testRunId}:{})});
286
303
  const controller=new AbortController();pendingExecution=controller;
287
304
  let timer,timedOut=false;
288
305
  try{
@@ -344,7 +361,7 @@ export function createCmAiConversationEntry(options) {
344
361
  if(hostDecisionProvider!==null){
345
362
  // A historical terminal or outstanding invocation is owned by the runner;
346
363
  // never ask for fresh authorization to replay or reopen it.
347
- if(status.state!=='awaiting_review'||status.code!==null)return summary(operation,status,'reported');
364
+ if(!(status.state==='awaiting_review'&&status.code===null)&&!retryReview(status))return summary(operation,status,'reported');
348
365
  need(pendingReviewDecision===null,'review_decision_pending');
349
366
  need(!status.cancellationRequested&&!status.cancelAfterCommit,'cancelled');
350
367
  const controller=new AbortController();pendingReviewDecision=controller;
@@ -370,7 +387,10 @@ export function createCmAiConversationEntry(options) {
370
387
  if(decision===null)return summary(operation,{...status,code:'decision_required'},'awaiting');
371
388
  if(validateHostDecision(decision,status)==='denied')
372
389
  return summary(operation,{...status,code:'permission_denied'},'denied');
373
- const result=await runner.executeEffect({version:1,id:`review-${identity.attempt}`,identity,kind:'review'});
390
+ const retries=retryReview(status)?status.calls.filter(call=>call.channel==='host-authorized'
391
+ &&call.terminal==='failed'&&call.contextId===status.reviewInvocation.registration.grant.logicalContextId).length:0;
392
+ const effectId=`review-${identity.attempt}${retries?`-retry-${retries}`:''}`;
393
+ const result=await runner.executeEffect({version:1,id:effectId,identity,kind:'review'});
374
394
  return effectSummary(operation,result,runner,identity);
375
395
  }
376
396
  if(operation.operation==='complete'){
@@ -401,7 +421,9 @@ export function createCmAiConversationEntry(options) {
401
421
  const interrupted=new Promise((_,reject)=>{
402
422
  controller.signal.addEventListener('abort',()=>reject(Object.assign(new Error('QA decision interrupted'),
403
423
  {code:timedOut?'qa_decision_timeout':'cancelled'})),{once:true});
404
- timer=setTimeout(()=>{timedOut=true;controller.abort();},qaTimeout);
424
+ // Allow the request watchdog to publish its BLOCKED decision at
425
+ // the same configured deadline before the outer cancellation.
426
+ timer=setTimeout(()=>{timedOut=true;controller.abort();},qaTimeout+1000);
405
427
  });
406
428
  decision=json(await Promise.race([
407
429
  Promise.resolve().then(()=>{need(!controller.signal.aborted,'cancelled');
@@ -519,7 +541,7 @@ export function createCmAiConversationEntry(options) {
519
541
  need(admission.state==='ready'&&admission.nextTask?.feature===options.feature
520
542
  &&admission.nextTask.id===identity.taskId,'task_mismatch');
521
543
  const status=boundStatus(runner.status(),identity);
522
- const developable=['ready','changes_requested'].includes(status.state);
544
+ const developable=['ready','changes_requested'].includes(status.state)||retryDeveloper(status);
523
545
  const repeatable=operation.operation==='start'&&status.state==='awaiting_review';
524
546
  if(!developable&&!repeatable)
525
547
  return summary(operation,status,'reported');
@@ -530,7 +552,12 @@ export function createCmAiConversationEntry(options) {
530
552
  const learningInput=inspectCmAiTaskLearningInput({specsDir:options.specsDir,codeProject:options.codeProject,
531
553
  feature:options.feature,identity,applicableAgentFiles:applicableAgentFiles??[]},
532
554
  {admission:runner.inspectBootstrapAdmission?.()??null});
533
- const result=await runner.executeEffect({version:1,id:`develop-${identity.attempt}`,identity,kind:'develop',learningInput});
555
+ // Keep rejected effects immutable. A run-wide rejection count gives each
556
+ // corrected result a new effect id without changing the provider attempt.
557
+ const rejectedValues=status.calls.filter(call=>call.terminal==='failed'
558
+ &&call.failureResult?.code==='invalid_result'&&call.failureResult.retryable===true).length;
559
+ const effectId=`develop-${identity.attempt}${rejectedValues?`-retry-${rejectedValues}`:''}`;
560
+ const result=await runner.executeEffect({version:1,id:effectId,identity,kind:'develop',learningInput});
534
561
  return effectSummary(operation,result,runner,identity);
535
562
  }
536
563
  const handle=async raw=>{try{return await route(raw);}catch(error){return rejected(ownerIdentity,error);}};