@ai-content-space/loopx 0.1.2 → 0.1.3

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 (67) hide show
  1. package/README.md +343 -56
  2. package/README.zh-CN.md +392 -0
  3. package/package.json +4 -1
  4. package/plugins/loopx/.codex-plugin/plugin.json +1 -1
  5. package/plugins/loopx/scripts/plugin-install.test.mjs +1 -0
  6. package/plugins/loopx/skills/archive/SKILL.md +39 -0
  7. package/plugins/loopx/skills/build/SKILL.md +111 -9
  8. package/plugins/loopx/skills/clarify/SKILL.md +121 -1
  9. package/plugins/loopx/skills/debug/SKILL.md +296 -0
  10. package/plugins/loopx/skills/debug/condition-based-waiting.md +115 -0
  11. package/plugins/loopx/skills/debug/defense-in-depth.md +122 -0
  12. package/plugins/loopx/skills/debug/find-polluter.sh +63 -0
  13. package/plugins/loopx/skills/debug/root-cause-tracing.md +169 -0
  14. package/plugins/loopx/skills/go-style/SKILL.md +71 -0
  15. package/plugins/loopx/skills/kratos/SKILL.md +74 -0
  16. package/plugins/loopx/skills/kratos/references/advanced-features.md +314 -0
  17. package/plugins/loopx/skills/kratos/references/architecture.md +488 -0
  18. package/plugins/loopx/skills/kratos/references/configuration.md +399 -0
  19. package/plugins/loopx/skills/kratos/references/http-customization.md +512 -0
  20. package/plugins/loopx/skills/kratos/references/middleware-logging.md +400 -0
  21. package/plugins/loopx/skills/kratos/references/proto-api-design.md +432 -0
  22. package/plugins/loopx/skills/kratos/references/security-auth.md +411 -0
  23. package/plugins/loopx/skills/kratos/references/troubleshooting.md +385 -0
  24. package/plugins/loopx/skills/plan/SKILL.md +22 -2
  25. package/plugins/loopx/skills/review/SKILL.md +98 -1
  26. package/plugins/loopx/skills/tdd/SKILL.md +371 -0
  27. package/plugins/loopx/skills/tdd/testing-anti-patterns.md +299 -0
  28. package/plugins/loopx/skills/verify/SKILL.md +139 -0
  29. package/scripts/codex-stop-hook.mjs +71 -0
  30. package/scripts/codex-workflow-hook.mjs +153 -0
  31. package/skills/archive/SKILL.md +39 -0
  32. package/skills/build/SKILL.md +111 -9
  33. package/skills/clarify/SKILL.md +121 -1
  34. package/skills/debug/SKILL.md +296 -0
  35. package/skills/debug/condition-based-waiting.md +115 -0
  36. package/skills/debug/defense-in-depth.md +122 -0
  37. package/skills/debug/find-polluter.sh +63 -0
  38. package/skills/debug/root-cause-tracing.md +169 -0
  39. package/skills/go-style/SKILL.md +71 -0
  40. package/skills/kratos/SKILL.md +74 -0
  41. package/skills/kratos/references/advanced-features.md +314 -0
  42. package/skills/kratos/references/architecture.md +488 -0
  43. package/skills/kratos/references/configuration.md +399 -0
  44. package/skills/kratos/references/http-customization.md +512 -0
  45. package/skills/kratos/references/middleware-logging.md +400 -0
  46. package/skills/kratos/references/proto-api-design.md +432 -0
  47. package/skills/kratos/references/security-auth.md +411 -0
  48. package/skills/kratos/references/troubleshooting.md +385 -0
  49. package/skills/plan/SKILL.md +18 -2
  50. package/skills/review/SKILL.md +98 -1
  51. package/skills/tdd/SKILL.md +371 -0
  52. package/skills/tdd/testing-anti-patterns.md +299 -0
  53. package/skills/verify/SKILL.md +139 -0
  54. package/src/build-runtime.mjs +303 -26
  55. package/src/build-stop-gate.mjs +94 -0
  56. package/src/cli.mjs +47 -5
  57. package/src/codex-exec-runtime.mjs +105 -5
  58. package/src/context-manifest.mjs +172 -0
  59. package/src/install-discovery.mjs +352 -5
  60. package/src/next-skill.mjs +57 -5
  61. package/src/plan-runtime.mjs +79 -122
  62. package/src/review-runtime.mjs +378 -0
  63. package/src/runtime-maintenance.mjs +428 -14
  64. package/src/template-governance.mjs +223 -0
  65. package/src/workflow.mjs +1941 -117
  66. package/src/workspace-context.mjs +166 -0
  67. package/src/workspace-memory.mjs +69 -0
@@ -0,0 +1,139 @@
1
+ ---
2
+ name: verify
3
+ description: Use when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always
4
+ ---
5
+
6
+ # Verification Before Completion
7
+
8
+ ## Overview
9
+
10
+ Claiming work is complete without verification is dishonesty, not efficiency.
11
+
12
+ **Core principle:** Evidence before claims, always.
13
+
14
+ **Violating the letter of this rule is violating the spirit of this rule.**
15
+
16
+ ## The Iron Law
17
+
18
+ ```
19
+ NO COMPLETION CLAIMS WITHOUT FRESH VERIFICATION EVIDENCE
20
+ ```
21
+
22
+ If you haven't run the verification command in this message, you cannot claim it passes.
23
+
24
+ ## The Gate Function
25
+
26
+ ```
27
+ BEFORE claiming any status or expressing satisfaction:
28
+
29
+ 1. IDENTIFY: What command proves this claim?
30
+ 2. RUN: Execute the FULL command (fresh, complete)
31
+ 3. READ: Full output, check exit code, count failures
32
+ 4. VERIFY: Does output confirm the claim?
33
+ - If NO: State actual status with evidence
34
+ - If YES: State claim WITH evidence
35
+ 5. ONLY THEN: Make the claim
36
+
37
+ Skip any step = lying, not verifying
38
+ ```
39
+
40
+ ## Common Failures
41
+
42
+ | Claim | Requires | Not Sufficient |
43
+ |-------|----------|----------------|
44
+ | Tests pass | Test command output: 0 failures | Previous run, "should pass" |
45
+ | Linter clean | Linter output: 0 errors | Partial check, extrapolation |
46
+ | Build succeeds | Build command: exit 0 | Linter passing, logs look good |
47
+ | Bug fixed | Test original symptom: passes | Code changed, assumed fixed |
48
+ | Regression test works | Red-green cycle verified | Test passes once |
49
+ | Agent completed | VCS diff shows changes | Agent reports "success" |
50
+ | Requirements met | Line-by-line checklist | Tests passing |
51
+
52
+ ## Red Flags - STOP
53
+
54
+ - Using "should", "probably", "seems to"
55
+ - Expressing satisfaction before verification ("Great!", "Perfect!", "Done!", etc.)
56
+ - About to commit/push/PR without verification
57
+ - Trusting agent success reports
58
+ - Relying on partial verification
59
+ - Thinking "just this once"
60
+ - Tired and wanting work over
61
+ - **ANY wording implying success without having run verification**
62
+
63
+ ## Rationalization Prevention
64
+
65
+ | Excuse | Reality |
66
+ |--------|---------|
67
+ | "Should work now" | RUN the verification |
68
+ | "I'm confident" | Confidence ≠ evidence |
69
+ | "Just this once" | No exceptions |
70
+ | "Linter passed" | Linter ≠ compiler |
71
+ | "Agent said success" | Verify independently |
72
+ | "I'm tired" | Exhaustion ≠ excuse |
73
+ | "Partial check is enough" | Partial proves nothing |
74
+ | "Different words so rule doesn't apply" | Spirit over letter |
75
+
76
+ ## Key Patterns
77
+
78
+ **Tests:**
79
+ ```
80
+ ✅ [Run test command] [See: 34/34 pass] "All tests pass"
81
+ ❌ "Should pass now" / "Looks correct"
82
+ ```
83
+
84
+ **Regression tests (TDD Red-Green):**
85
+ ```
86
+ ✅ Write → Run (pass) → Revert fix → Run (MUST FAIL) → Restore → Run (pass)
87
+ ❌ "I've written a regression test" (without red-green verification)
88
+ ```
89
+
90
+ **Build:**
91
+ ```
92
+ ✅ [Run build] [See: exit 0] "Build passes"
93
+ ❌ "Linter passed" (linter doesn't check compilation)
94
+ ```
95
+
96
+ **Requirements:**
97
+ ```
98
+ ✅ Re-read plan → Create checklist → Verify each → Report gaps or completion
99
+ ❌ "Tests pass, phase complete"
100
+ ```
101
+
102
+ **Agent delegation:**
103
+ ```
104
+ ✅ Agent reports success → Check VCS diff → Verify changes → Report actual state
105
+ ❌ Trust agent report
106
+ ```
107
+
108
+ ## Why This Matters
109
+
110
+ From 24 failure memories:
111
+ - your human partner said "I don't believe you" - trust broken
112
+ - Undefined functions shipped - would crash
113
+ - Missing requirements shipped - incomplete features
114
+ - Time wasted on false completion → redirect → rework
115
+ - Violates: "Honesty is a core value. If you lie, you'll be replaced."
116
+
117
+ ## When To Apply
118
+
119
+ **ALWAYS before:**
120
+ - ANY variation of success/completion claims
121
+ - ANY expression of satisfaction
122
+ - ANY positive statement about work state
123
+ - Committing, PR creation, task completion
124
+ - Moving to next task
125
+ - Delegating to agents
126
+
127
+ **Rule applies to:**
128
+ - Exact phrases
129
+ - Paraphrases and synonyms
130
+ - Implications of success
131
+ - ANY communication suggesting completion/correctness
132
+
133
+ ## The Bottom Line
134
+
135
+ **No shortcuts for verification.**
136
+
137
+ Run the command. Read the output. THEN claim the result.
138
+
139
+ This is non-negotiable.
@@ -5,6 +5,7 @@ import { runCodexExecJson } from './codex-exec-runtime.mjs';
5
5
 
6
6
  const DEFAULT_BUILD_MAX_ITERATIONS = 10;
7
7
  const DEFAULT_BUILD_LANES = ['execution', 'evidence', 'verification'];
8
+ const DEFAULT_BUILD_CODEX_TIMEOUT_MS = 300000;
8
9
 
9
10
  function defaultLaneResult(name, iteration) {
10
11
  return {
@@ -45,6 +46,56 @@ function normalizeStatus(raw, fallback = 'complete') {
45
46
  return fallback;
46
47
  }
47
48
 
49
+ function normalizeDelegationStatus(raw, fallback = 'pending') {
50
+ const value = String(raw ?? fallback).trim().toLowerCase();
51
+ if (['active', 'complete', 'failed', 'blocked', 'pending', 'skipped'].includes(value)) {
52
+ return value;
53
+ }
54
+ return fallback;
55
+ }
56
+
57
+ function normalizeArray(raw, fallback = []) {
58
+ return Array.isArray(raw) ? raw.filter((item) => item !== null && item !== undefined).map(String) : fallback;
59
+ }
60
+
61
+ function normalizeEvidence(raw, fallback = []) {
62
+ return Array.isArray(raw)
63
+ ? raw.map((item, index) => ({
64
+ id: item?.id || `evidence-${index + 1}`,
65
+ kind: item?.kind || 'artifact',
66
+ summary: item?.summary || item?.message || 'Evidence item',
67
+ ref: item?.ref || item?.path || 'n/a',
68
+ }))
69
+ : fallback;
70
+ }
71
+
72
+ function normalizeDelegations(raw) {
73
+ return Array.isArray(raw)
74
+ ? raw.map((item, index) => ({
75
+ id: item?.id || `delegation-${index + 1}`,
76
+ role: item?.role || 'implementation',
77
+ status: normalizeDelegationStatus(item?.status, 'pending'),
78
+ blocking: item?.blocking !== false,
79
+ scope: Array.isArray(item?.scope) ? item.scope.map(String) : [],
80
+ evidence_path: item?.evidence_path || item?.evidencePath || null,
81
+ summary: item?.summary || 'Build delegation entry',
82
+ }))
83
+ : [];
84
+ }
85
+
86
+ function normalizeLaneReport(name, iteration, raw = {}) {
87
+ const fallback = defaultLaneResult(name, iteration);
88
+ return {
89
+ ...fallback,
90
+ ...raw,
91
+ name,
92
+ status: normalizeStatus(raw.status, fallback.status),
93
+ summary: raw.summary || fallback.summary,
94
+ evidence: normalizeEvidence(raw.evidence, fallback.evidence),
95
+ delegations: normalizeDelegations(raw.delegations),
96
+ };
97
+ }
98
+
48
99
  function buildIterationData({ slug, iteration, noDeslop = false }, scriptEntry = {}) {
49
100
  const laneNames = Array.isArray(scriptEntry.lanes) && scriptEntry.lanes.length > 0
50
101
  ? scriptEntry.lanes.map((lane) => lane.name)
@@ -84,6 +135,7 @@ function buildIterationData({ slug, iteration, noDeslop = false }, scriptEntry =
84
135
  `deslop=${deslopStatus}`,
85
136
  `regression=${regressionStatus}`,
86
137
  ],
138
+ delegations: normalizeDelegations(scriptEntry.delegations),
87
139
  architectFindings: scriptEntry.architectFindings || (
88
140
  architectVerdict === 'approve'
89
141
  ? ['Architect gate approved the build iteration.']
@@ -93,42 +145,267 @@ function buildIterationData({ slug, iteration, noDeslop = false }, scriptEntry =
93
145
  };
94
146
  }
95
147
 
148
+ async function runJsonReport(executor, options, fallback) {
149
+ try {
150
+ return await executor(options);
151
+ } catch (error) {
152
+ const message = error instanceof Error ? error.message : String(error);
153
+ return {
154
+ ...fallback,
155
+ error: message,
156
+ summary: `${fallback.summary || 'Codex execution failed'}: ${message}`,
157
+ limitations: [
158
+ ...normalizeArray(fallback.limitations),
159
+ message,
160
+ ],
161
+ };
162
+ }
163
+ }
164
+
96
165
  export function createDefaultBuildAdapter() {
97
166
  return createRealBuildAdapter();
98
167
  }
99
168
 
100
- export function createRealBuildAdapter({ model } = {}) {
169
+ export function buildContextPromptLines(context) {
170
+ return [
171
+ `workflow: ${context.slug}`,
172
+ `iteration: ${context.iteration}`,
173
+ `noDeslop: ${Boolean(context.noDeslop)}`,
174
+ `planArtifactPath: ${context.planArtifactPath}`,
175
+ `testSpecArtifactPath: ${context.testSpecArtifactPath}`,
176
+ `reviewReworkArtifactPath: ${context.reviewReworkArtifactPath || ''}`,
177
+ `contextManifestStatus: ${context.contextManifestStatus || 'fallback'}`,
178
+ `contextManifestPath: ${context.contextManifestPath || ''}`,
179
+ `contextManifestRows: ${JSON.stringify((context.contextManifestRows || []).map((row) => ({
180
+ kind: row.kind,
181
+ path: row.path,
182
+ reason: row.reason,
183
+ priority: row.priority,
184
+ })))}`,
185
+ ];
186
+ }
187
+
188
+ function lanePrompt(context, laneName) {
189
+ const laneInstructions = {
190
+ execution: [
191
+ 'You are the implementation lane. Continue executing the approved plan in the repository.',
192
+ 'If reviewReworkArtifactPath is present, treat that review artifact as the direct implementation-fix contract while keeping the approved plan and test spec as supporting context.',
193
+ 'You are the build owner for critical-path implementation. You may use native Codex subagents for independent sidecar work, but you remain responsible for integrating results.',
194
+ 'If you delegate work, report each active or completed delegation in the delegations array with a stable id, role, status, blocking flag, scope, and evidence_path.',
195
+ 'Do not report final completion while a blocking delegated task remains active, pending, failed, or blocked.',
196
+ 'Real code edits are allowed. Do not stop because approved plan phases remain; keep working until implementation is complete or a real blocker prevents progress.',
197
+ 'Return status "pending" only when approved work remains but cannot be completed in this lane result, and explain the concrete blocker in limitations.',
198
+ ],
199
+ evidence: [
200
+ 'You are the evidence lane. Independently inspect the current implementation and collect evidence that the approved plan is or is not satisfied.',
201
+ 'You may use native Codex subagents for independent evidence gathering. If you do, report each delegation in the delegations array.',
202
+ 'Do not edit files. Focus on artifacts, changed files, API surface coverage, and gaps between the plan and the current worktree.',
203
+ 'Do not treat the live workflow state from the build currently in progress, such as current_stage=build, stage_status=blocked, execution_record_status=partial, or pre-existing build_blockers, as evidence that this current iteration is incomplete.',
204
+ 'Use live state only for locating artifacts or confirming context manifest paths; judge this iteration from current code, fresh artifacts, tests, and concrete acceptance gaps.',
205
+ ],
206
+ verification: [
207
+ 'You are the verification lane. Independently run or identify the strongest practical verification for the current implementation.',
208
+ 'You may use native Codex subagents for independent verification checks. If you do, report each delegation in the delegations array.',
209
+ 'Do not edit files. Read actual command output when you run tests/builds/checks. Report failed, pending, skipped, or complete accurately.',
210
+ ],
211
+ };
212
+
213
+ return [
214
+ `You are acting as the real loopx build ${laneName} lane.`,
215
+ ...buildContextPromptLines(context),
216
+ '',
217
+ ...(laneInstructions[laneName] || []),
218
+ '',
219
+ 'Return only raw JSON matching this shape:',
220
+ '{',
221
+ ' "status": "complete" | "failed" | "pending" | "skipped",',
222
+ ' "summary": string,',
223
+ ' "evidence": [{"id": string, "kind": string, "summary": string, "ref": string}],',
224
+ ' "delegations": [{"id": string, "role": string, "status": "active" | "complete" | "failed" | "blocked" | "pending" | "skipped", "blocking": boolean, "scope": string[], "evidence_path": string | null, "summary": string}],',
225
+ ' "executionEvidence": string[],',
226
+ ' "verificationEvidence": string[],',
227
+ ' "limitations": string[]',
228
+ '}',
229
+ 'Do not ask questions. Do not wrap JSON in markdown.',
230
+ ].join('\n');
231
+ }
232
+
233
+ function architectPrompt(context, lanes) {
234
+ return [
235
+ `You are the independent loopx build architect gate for workflow "${context.slug}".`,
236
+ ...buildContextPromptLines(context),
237
+ '',
238
+ 'Review the implementation lane plus evidence and verification lane reports.',
239
+ 'Do not edit files. Return only raw JSON matching this shape:',
240
+ '{',
241
+ ' "verdict": "approve" | "reject" | "iterate",',
242
+ ' "findings": string[],',
243
+ ' "limitations": string[]',
244
+ '}',
245
+ '',
246
+ 'Reject or iterate when approved work remains, evidence is thin, verification is not fresh, or architecture risks remain.',
247
+ 'Do not reject or iterate solely because a lane cites the live workflow state from the build currently in progress, such as current_stage=build, stage_status=blocked, execution_record_status=partial, or pre-existing build_blockers.',
248
+ 'Treat that self-referential live-state evidence as stale unless it is tied to a concrete code, artifact, test, or acceptance gap.',
249
+ 'Lane reports:',
250
+ JSON.stringify(lanes, null, 2),
251
+ ].join('\n');
252
+ }
253
+
254
+ function deslopPrompt(context, changedEvidence) {
255
+ return [
256
+ `You are the loopx deslop lane for workflow "${context.slug}".`,
257
+ ...buildContextPromptLines(context),
258
+ '',
259
+ 'Run a focused cleanup pass on build-owned changes only. Real edits are allowed, but do not widen scope beyond this build iteration.',
260
+ 'Return only raw JSON matching this shape:',
261
+ '{',
262
+ ' "status": "complete" | "failed" | "pending" | "skipped",',
263
+ ' "summary": string,',
264
+ ' "evidence": [{"id": string, "kind": string, "summary": string, "ref": string}],',
265
+ ' "limitations": string[]',
266
+ '}',
267
+ '',
268
+ 'Build evidence:',
269
+ JSON.stringify(changedEvidence, null, 2),
270
+ ].join('\n');
271
+ }
272
+
273
+ function regressionPrompt(context, deslopReport) {
274
+ return [
275
+ `You are the loopx post-deslop regression lane for workflow "${context.slug}".`,
276
+ ...buildContextPromptLines(context),
277
+ '',
278
+ 'Run fresh regression verification after the latest implementation/deslop changes. Do not edit files.',
279
+ 'Read actual command output when running verification.',
280
+ 'Return only raw JSON matching this shape:',
281
+ '{',
282
+ ' "status": "complete" | "failed" | "pending" | "skipped",',
283
+ ' "summary": string,',
284
+ ' "evidence": [{"id": string, "kind": string, "summary": string, "ref": string}],',
285
+ ' "verificationEvidence": string[],',
286
+ ' "limitations": string[]',
287
+ '}',
288
+ '',
289
+ 'Deslop report:',
290
+ JSON.stringify(deslopReport, null, 2),
291
+ ].join('\n');
292
+ }
293
+
294
+ export function createRealBuildAdapter({ model, codexExecJson = runCodexExecJson } = {}) {
101
295
  return {
102
296
  maxIterations: DEFAULT_BUILD_MAX_ITERATIONS,
103
297
  async executeLanes(context) {
104
- const outputPath = join(context.root || context.cwd, 'build-support', `runtime-build-iteration-${context.iteration}.json`);
105
- await mkdir(join(context.root || context.cwd, 'build-support'), { recursive: true });
106
- const prompt = [
107
- `You are acting as the real loopx build runtime for workflow "${context.slug}".`,
108
- 'Execute the approved build work in this repository and return only raw JSON with this shape:',
109
- '{',
110
- ' "lanes": [{"name": string, "status": "complete" | "failed" | "pending" | "skipped", "summary": string, "evidence": [{"id": string, "kind": string, "summary": string, "ref": string}]}],',
111
- ' "verificationStatus": "complete" | "failed" | "pending" | "skipped",',
112
- ' "architectVerdict": "approve" | "reject" | "iterate",',
113
- ' "deslopStatus": "complete" | "failed" | "pending" | "skipped",',
114
- ' "regressionStatus": "complete" | "failed" | "pending" | "skipped",',
115
- ' "executionEvidence": string[],',
116
- ' "verificationEvidence": string[],',
117
- ' "architectFindings": string[],',
118
- ' "limitations": string[]',
119
- '}',
120
- `noDeslop: ${Boolean(context.noDeslop)}`,
121
- `planArtifactPath: ${context.planArtifactPath}`,
122
- `testSpecArtifactPath: ${context.testSpecArtifactPath}`,
123
- 'Do not ask questions. Real code edits are allowed. Keep execution-record.md as the sole canonical execution artifact; return JSON only, no markdown.',
124
- ].join('\n');
125
- const report = await runCodexExecJson({
298
+ const supportRoot = join(context.root || context.cwd, 'build-support');
299
+ await mkdir(supportRoot, { recursive: true });
300
+ const timeoutMs = Number(process.env.LOOPX_BUILD_CODEX_TIMEOUT_MS || DEFAULT_BUILD_CODEX_TIMEOUT_MS);
301
+
302
+ const runLane = async (laneName) => {
303
+ const raw = await runJsonReport(codexExecJson, {
304
+ cwd: context.cwd,
305
+ prompt: lanePrompt(context, laneName),
306
+ outputPath: join(supportRoot, `runtime-${laneName}-iteration-${context.iteration}.json`),
307
+ model,
308
+ timeoutMs,
309
+ }, {
310
+ status: 'failed',
311
+ summary: `${laneName} lane failed`,
312
+ evidence: [],
313
+ executionEvidence: [],
314
+ verificationEvidence: [],
315
+ limitations: [`${laneName} lane failed before returning structured evidence.`],
316
+ });
317
+ return normalizeLaneReport(laneName, context.iteration, raw);
318
+ };
319
+
320
+ const executionLane = await runLane('execution');
321
+ const [evidenceLane, verificationLane] = await Promise.all([
322
+ runLane('evidence'),
323
+ runLane('verification'),
324
+ ]);
325
+ const lanes = [executionLane, evidenceLane, verificationLane];
326
+
327
+ const architectReport = await runJsonReport(codexExecJson, {
126
328
  cwd: context.cwd,
127
- prompt,
128
- outputPath,
329
+ prompt: architectPrompt(context, lanes),
330
+ outputPath: join(supportRoot, `runtime-architect-iteration-${context.iteration}.json`),
129
331
  model,
332
+ timeoutMs,
333
+ }, {
334
+ verdict: 'reject',
335
+ findings: ['Architect gate failed before returning structured evidence.'],
336
+ limitations: ['Architect gate did not complete.'],
337
+ });
338
+
339
+ const deslopReport = context.noDeslop
340
+ ? {
341
+ status: 'skipped',
342
+ summary: 'Deslop skipped by --no-deslop.',
343
+ evidence: [],
344
+ limitations: [],
345
+ }
346
+ : await runJsonReport(codexExecJson, {
347
+ cwd: context.cwd,
348
+ prompt: deslopPrompt(context, lanes.flatMap((lane) => lane.evidence || [])),
349
+ outputPath: join(supportRoot, `runtime-deslop-iteration-${context.iteration}.json`),
350
+ model,
351
+ timeoutMs,
352
+ }, {
353
+ status: 'failed',
354
+ summary: 'Deslop lane failed before returning structured evidence.',
355
+ evidence: [],
356
+ limitations: ['Deslop lane did not complete.'],
357
+ });
358
+
359
+ const regressionReport = context.noDeslop
360
+ ? {
361
+ status: 'skipped',
362
+ summary: 'Regression skipped because --no-deslop skipped deslop.',
363
+ evidence: [],
364
+ verificationEvidence: [],
365
+ limitations: [],
366
+ }
367
+ : await runJsonReport(codexExecJson, {
368
+ cwd: context.cwd,
369
+ prompt: regressionPrompt(context, deslopReport),
370
+ outputPath: join(supportRoot, `runtime-regression-iteration-${context.iteration}.json`),
371
+ model,
372
+ timeoutMs,
373
+ }, {
374
+ status: 'failed',
375
+ summary: 'Regression lane failed before returning structured evidence.',
376
+ evidence: [],
377
+ verificationEvidence: [],
378
+ limitations: ['Regression lane did not complete.'],
379
+ });
380
+
381
+ return buildIterationData(context, {
382
+ lanes,
383
+ verificationStatus: verificationLane.status,
384
+ architectVerdict: normalizeVerdict(architectReport.verdict, 'reject'),
385
+ deslopStatus: normalizeStatus(deslopReport.status, context.noDeslop ? 'skipped' : 'failed'),
386
+ regressionStatus: normalizeStatus(regressionReport.status, context.noDeslop ? 'skipped' : 'failed'),
387
+ executionEvidence: [
388
+ ...normalizeArray(executionLane.executionEvidence),
389
+ ...normalizeArray(evidenceLane.executionEvidence),
390
+ ...lanes.map((lane) => `${lane.name}:${lane.status}:${lane.summary}`),
391
+ ],
392
+ verificationEvidence: [
393
+ ...normalizeArray(verificationLane.verificationEvidence),
394
+ ...normalizeArray(regressionReport.verificationEvidence),
395
+ ...normalizeEvidence(verificationLane.evidence).map((item) => `${item.kind}:${item.summary}:${item.ref}`),
396
+ ...normalizeEvidence(regressionReport.evidence).map((item) => `${item.kind}:${item.summary}:${item.ref}`),
397
+ ],
398
+ architectFindings: normalizeArray(architectReport.findings, ['Architect gate returned no findings.']),
399
+ delegations: lanes.flatMap((lane) => normalizeDelegations(lane.delegations)),
400
+ limitations: [
401
+ ...normalizeArray(executionLane.limitations),
402
+ ...normalizeArray(evidenceLane.limitations),
403
+ ...normalizeArray(verificationLane.limitations),
404
+ ...normalizeArray(architectReport.limitations),
405
+ ...normalizeArray(deslopReport.limitations),
406
+ ...normalizeArray(regressionReport.limitations),
407
+ ],
130
408
  });
131
- return buildIterationData(context, report);
132
409
  },
133
410
  };
134
411
  }
@@ -0,0 +1,94 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { readFile, writeFile } from 'node:fs/promises';
3
+ import { join, resolve } from 'node:path';
4
+
5
+ const ACTIVE_PHASES = new Set(['starting', 'executing', 'verifying', 'fixing']);
6
+ const READY_PHASES = new Set(['review-ready', 'complete']);
7
+ const TERMINAL_PHASES = new Set(['blocked', 'failed', 'cancelled', 'review-ready', 'complete']);
8
+
9
+ export function buildActivePath(cwd) {
10
+ return join(resolve(cwd), '.loopx', 'build-active.json');
11
+ }
12
+
13
+ function nowIso() {
14
+ return new Date().toISOString();
15
+ }
16
+
17
+ export async function writeBuildActiveState(cwd, patch) {
18
+ const path = buildActivePath(cwd);
19
+ let existing = {};
20
+ if (existsSync(path)) {
21
+ try {
22
+ existing = JSON.parse(await readFile(path, 'utf8'));
23
+ } catch {
24
+ existing = {};
25
+ }
26
+ }
27
+ const next = {
28
+ schema_version: 1,
29
+ updated_at: nowIso(),
30
+ ...existing,
31
+ ...patch,
32
+ };
33
+ await writeFile(path, `${JSON.stringify(next, null, 2)}\n`);
34
+ return next;
35
+ }
36
+
37
+ export async function readBuildActiveState(cwd) {
38
+ const path = buildActivePath(cwd);
39
+ if (!existsSync(path)) {
40
+ return null;
41
+ }
42
+ return JSON.parse(await readFile(path, 'utf8'));
43
+ }
44
+
45
+ export function evaluateBuildStopGate(state) {
46
+ if (!state || state.active !== true) {
47
+ return {
48
+ allow: true,
49
+ reason: 'no_active_build',
50
+ };
51
+ }
52
+
53
+ if (READY_PHASES.has(state.phase) && state.review_handoff_ready === true) {
54
+ return {
55
+ allow: true,
56
+ reason: 'build_review_handoff_ready',
57
+ state,
58
+ };
59
+ }
60
+
61
+ if (TERMINAL_PHASES.has(state.phase) && state.phase !== 'review-ready') {
62
+ return {
63
+ allow: true,
64
+ reason: `build_${state.phase}`,
65
+ state,
66
+ };
67
+ }
68
+
69
+ if (ACTIVE_PHASES.has(state.phase) || state.review_handoff_ready !== true) {
70
+ const blockers = Array.isArray(state.blockers) ? state.blockers.filter(Boolean) : [];
71
+ const blockerText = blockers.length > 0 ? ` blockers=${blockers.join(',')}` : '';
72
+ const ownerText = state.build_owner_id ? ` owner: ${state.build_owner_id}.` : '';
73
+ const delegationCount = Number.isFinite(Number(state.active_delegation_count)) ? Number(state.active_delegation_count) : null;
74
+ const delegationText = delegationCount !== null ? ` active delegations=${delegationCount}.` : '';
75
+ const auditText = state.completion_audit_status ? ` completion audit: ${state.completion_audit_status}.` : '';
76
+ const nextAction = state.next_action ? ` next action: ${state.next_action}` : ' next action: continue the contract-covered next step in $build.';
77
+ const completionSignal = state.completion_signal ? ` completion signal: ${state.completion_signal}` : ' completion signal: review handoff readiness, a real blocker, user stop, or a return to plan/clarify.';
78
+ return {
79
+ allow: false,
80
+ reason: `loopx build is still active for workflow "${state.slug ?? 'unknown'}" (phase: ${state.phase ?? 'unknown'}; iteration: ${state.iteration ?? 0}/${state.max_iterations ?? '?'}; state: .loopx/build-active.json).${ownerText}${delegationText}${auditText} Do not stop while a contract-covered next step remains.${nextAction}${completionSignal} If the work is genuinely blocked, record the blocker and leave build in a blocked state. If new evidence changes the contract, return to plan/clarify instead of stopping.${blockerText}`,
81
+ state,
82
+ };
83
+ }
84
+
85
+ return {
86
+ allow: true,
87
+ reason: 'build_state_not_active',
88
+ state,
89
+ };
90
+ }
91
+
92
+ export async function evaluateBuildStopGateForCwd(cwd) {
93
+ return evaluateBuildStopGate(await readBuildActiveState(cwd));
94
+ }