cclaw-cli 0.55.2 → 2.0.0

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 (92) hide show
  1. package/README.md +3 -3
  2. package/dist/artifact-linter/brainstorm.js +59 -1
  3. package/dist/artifact-linter/design.js +46 -1
  4. package/dist/artifact-linter/plan.js +22 -1
  5. package/dist/artifact-linter/review.js +35 -1
  6. package/dist/artifact-linter/scope.js +33 -9
  7. package/dist/artifact-linter/shared.d.ts +12 -10
  8. package/dist/artifact-linter/shared.js +102 -41
  9. package/dist/artifact-linter/ship.js +36 -0
  10. package/dist/artifact-linter/spec.js +23 -1
  11. package/dist/artifact-linter/tdd.js +74 -0
  12. package/dist/artifact-linter.d.ts +1 -1
  13. package/dist/artifact-linter.js +11 -1
  14. package/dist/constants.d.ts +1 -1
  15. package/dist/constants.js +1 -0
  16. package/dist/content/closeout-guidance.d.ts +1 -1
  17. package/dist/content/closeout-guidance.js +10 -11
  18. package/dist/content/core-agents.d.ts +35 -36
  19. package/dist/content/core-agents.js +189 -99
  20. package/dist/content/diff-command.js +1 -1
  21. package/dist/content/examples.d.ts +0 -3
  22. package/dist/content/examples.js +197 -752
  23. package/dist/content/hook-events.js +1 -2
  24. package/dist/content/hook-manifest.d.ts +3 -4
  25. package/dist/content/hook-manifest.js +22 -25
  26. package/dist/content/hooks.js +54 -14
  27. package/dist/content/idea.d.ts +60 -0
  28. package/dist/content/idea.js +404 -0
  29. package/dist/content/learnings.d.ts +2 -4
  30. package/dist/content/learnings.js +10 -26
  31. package/dist/content/meta-skill.js +4 -3
  32. package/dist/content/node-hooks.js +368 -164
  33. package/dist/content/observe.js +3 -3
  34. package/dist/content/opencode-plugin.js +12 -32
  35. package/dist/content/reference-patterns.js +2 -2
  36. package/dist/content/runtime-shared-snippets.d.ts +8 -0
  37. package/dist/content/runtime-shared-snippets.js +80 -0
  38. package/dist/content/session-hooks.js +1 -1
  39. package/dist/content/skills-elicitation.d.ts +1 -0
  40. package/dist/content/skills-elicitation.js +123 -0
  41. package/dist/content/skills.d.ts +1 -0
  42. package/dist/content/skills.js +54 -2
  43. package/dist/content/stage-schema.js +107 -63
  44. package/dist/content/stages/brainstorm.js +7 -3
  45. package/dist/content/stages/design.js +4 -0
  46. package/dist/content/stages/review.js +8 -8
  47. package/dist/content/stages/schema-types.d.ts +2 -2
  48. package/dist/content/stages/scope.js +7 -3
  49. package/dist/content/stages/ship.js +1 -1
  50. package/dist/content/start-command.js +4 -4
  51. package/dist/content/status-command.js +3 -3
  52. package/dist/content/subagent-context-skills.js +156 -1
  53. package/dist/content/subagents.d.ts +0 -5
  54. package/dist/content/subagents.js +12 -82
  55. package/dist/content/templates.js +108 -6
  56. package/dist/content/utility-skills.js +26 -97
  57. package/dist/flow-state.d.ts +12 -6
  58. package/dist/flow-state.js +5 -6
  59. package/dist/gate-evidence.d.ts +0 -31
  60. package/dist/gate-evidence.js +3 -181
  61. package/dist/harness-adapters.js +1 -1
  62. package/dist/hook-schemas/claude-hooks.v1.json +2 -3
  63. package/dist/hook-schemas/codex-hooks.v1.json +1 -1
  64. package/dist/hook-schemas/cursor-hooks.v1.json +1 -1
  65. package/dist/install.js +50 -7
  66. package/dist/internal/advance-stage/advance.js +22 -2
  67. package/dist/internal/advance-stage/parsers.d.ts +1 -0
  68. package/dist/internal/advance-stage/parsers.js +6 -0
  69. package/dist/internal/advance-stage/review-loop.js +1 -10
  70. package/dist/knowledge-store.d.ts +2 -20
  71. package/dist/knowledge-store.js +43 -57
  72. package/dist/policy.js +3 -3
  73. package/dist/retro-gate.js +8 -90
  74. package/dist/run-archive.js +1 -4
  75. package/dist/run-persistence.d.ts +1 -1
  76. package/dist/run-persistence.js +43 -111
  77. package/dist/runtime/run-hook.entry.d.ts +3 -0
  78. package/dist/runtime/run-hook.entry.js +5 -0
  79. package/dist/runtime/run-hook.mjs +9647 -0
  80. package/dist/track-heuristics.d.ts +7 -1
  81. package/dist/track-heuristics.js +12 -0
  82. package/package.json +4 -2
  83. package/dist/content/hook-inline-snippets.d.ts +0 -96
  84. package/dist/content/hook-inline-snippets.js +0 -515
  85. package/dist/content/idea-command.d.ts +0 -8
  86. package/dist/content/idea-command.js +0 -322
  87. package/dist/content/idea-frames.d.ts +0 -31
  88. package/dist/content/idea-frames.js +0 -140
  89. package/dist/content/idea-ranking.d.ts +0 -25
  90. package/dist/content/idea-ranking.js +0 -65
  91. package/dist/trace-matrix.d.ts +0 -27
  92. package/dist/trace-matrix.js +0 -226
@@ -1,4 +1,4 @@
1
- import type { FlowTrack, TrackHeuristicRule, TrackHeuristicsConfig } from "./types.js";
1
+ import type { FlowStage, FlowTrack, TrackHeuristicRule, TrackHeuristicsConfig } from "./types.js";
2
2
  export interface TrackResolution {
3
3
  track: FlowTrack;
4
4
  reason: string;
@@ -6,6 +6,11 @@ export interface TrackResolution {
6
6
  confidence: "high" | "medium" | "low";
7
7
  overrideGuidance: string;
8
8
  }
9
+ export interface QuestionBudgetHint {
10
+ min: number;
11
+ recommended: number;
12
+ hardCapWarning: number;
13
+ }
9
14
  /**
10
15
  * Reference implementation of the track classifier the /cc skill prose
11
16
  * describes. Tests pin its behavior so the built-in defaults stay honest.
@@ -14,6 +19,7 @@ export interface TrackResolution {
14
19
  * "advisory" language.
15
20
  */
16
21
  export declare function resolveTrackFromPrompt(prompt: string, config: TrackHeuristicsConfig | undefined): TrackResolution;
22
+ export declare function questionBudgetHint(track: FlowTrack, stage: FlowStage): QuestionBudgetHint;
17
23
  export declare const TRACK_HEURISTICS_DEFAULTS: {
18
24
  readonly fallback: "standard";
19
25
  readonly evaluationOrder: readonly ("quick" | "medium" | "standard")[];
@@ -54,6 +54,12 @@ const DEFAULT_RULES = {
54
54
  // into runtime, so cclaw stopped offering the knob in v0.38.0.
55
55
  const EVALUATION_ORDER = ["standard", "medium", "quick"];
56
56
  const DEFAULT_FALLBACK = "standard";
57
+ const ADAPTIVE_ELICITATION_STAGES = new Set(["brainstorm", "scope", "design"]);
58
+ const QUESTION_BUDGET_HINTS_BY_TRACK = {
59
+ quick: { min: 2, recommended: 3, hardCapWarning: 4 },
60
+ medium: { min: 5, recommended: 6, hardCapWarning: 8 },
61
+ standard: { min: 10, recommended: 12, hardCapWarning: 14 }
62
+ };
57
63
  function hasToken(promptLower, token) {
58
64
  return promptLower.includes(token.toLowerCase());
59
65
  }
@@ -130,6 +136,12 @@ export function resolveTrackFromPrompt(prompt, config) {
130
136
  overrideGuidance: "Confirm or override before state is written; choose quick only for known low-blast-radius work, medium for known architecture with product framing, standard for uncertainty."
131
137
  };
132
138
  }
139
+ export function questionBudgetHint(track, stage) {
140
+ if (!ADAPTIVE_ELICITATION_STAGES.has(stage)) {
141
+ return { min: 0, recommended: 0, hardCapWarning: 0 };
142
+ }
143
+ return QUESTION_BUDGET_HINTS_BY_TRACK[track];
144
+ }
133
145
  export const TRACK_HEURISTICS_DEFAULTS = {
134
146
  fallback: DEFAULT_FALLBACK,
135
147
  evaluationOrder: EVALUATION_ORDER,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cclaw-cli",
3
- "version": "0.55.2",
3
+ "version": "2.0.0",
4
4
  "description": "Installer-first flow toolkit for coding agents",
5
5
  "type": "module",
6
6
  "bin": {
@@ -17,7 +17,8 @@
17
17
  },
18
18
  "scripts": {
19
19
  "clean:dist": "node -e \"import('node:fs/promises').then((fs) => fs.rm('dist', { recursive: true, force: true }))\"",
20
- "build": "npm run clean:dist && tsc -p tsconfig.json && node scripts/chmod-bin.mjs",
20
+ "build": "npm run clean:dist && tsc -p tsconfig.json && npm run build:hook-bundle && node scripts/chmod-bin.mjs",
21
+ "build:hook-bundle": "esbuild src/runtime/run-hook.entry.ts --bundle --platform=node --format=esm --outfile=dist/runtime/run-hook.mjs",
21
22
  "test": "vitest run",
22
23
  "test:watch": "vitest",
23
24
  "test:coverage": "vitest run --coverage",
@@ -47,6 +48,7 @@
47
48
  "@stryker-mutator/vitest-runner": "^9.6.1",
48
49
  "@types/node": "^24.7.2",
49
50
  "@vitest/coverage-v8": "^3.2.4",
51
+ "esbuild": "^0.28.0",
50
52
  "typescript": "^5.9.3",
51
53
  "vitest": "^3.2.4"
52
54
  }
@@ -1,96 +0,0 @@
1
- /**
2
- * hook-inline-snippets.ts
3
- *
4
- * Runtime `.cclaw/hooks/run-hook.mjs` is a **standalone Node script** that
5
- * cannot import from `cclaw-cli` — it must work inside the end-user's
6
- * project even when the CLI is not installed. Two derived computations,
7
- * though, must remain 1:1 with the canonical TS implementations:
8
- *
9
- * 1. `computeCompoundReadinessInline` mirrors
10
- * `src/knowledge-store.ts::computeCompoundReadiness`.
11
- * 2. `computeRalphLoopStatusInline` mirrors
12
- * `src/tdd-cycle.ts::computeRalphLoopStatus`.
13
- * 3. `computeEarlyLoopStatusInline` mirrors
14
- * `src/early-loop.ts::computeEarlyLoopStatus`.
15
- *
16
- * Previously those bodies lived inline in `src/content/node-hooks.ts` — a
17
- * ~2000-line file — next to unrelated hook-handler code. Any silent drift
18
- * only surfaced when someone remembered to update both sides.
19
- *
20
- * This module centralizes the inline JavaScript snippets so:
21
- *
22
- * - There is exactly **one place** (this file) that holds each inline
23
- * JS body.
24
- * - Each snippet carries an explicit "mirrors X, parity enforced by Y"
25
- * header comment and is emitted into `run-hook.mjs` verbatim.
26
- * - `src/content/node-hooks.ts` only interpolates the snippets, it no
27
- * longer owns their source code.
28
- *
29
- * Parity with the TypeScript canonical implementations is enforced by
30
- * `tests/unit/ralph-loop-parity.test.ts` and
31
- * `tests/unit/early-loop-parity.test.ts`. Any structural change to the
32
- * canonical TS code MUST:
33
- *
34
- * 1. Update the matching snippet below.
35
- * 2. Re-run parity tests for the touched snippet.
36
- *
37
- * DO NOT inline tests here — keep the parity check in its dedicated test
38
- * file.
39
- */
40
- /**
41
- * Inline JS helpers used by both compound-readiness and ralph-loop
42
- * snippets. Kept small and locked: they are shared across the two inline
43
- * routines and must not grow into a hidden utility namespace.
44
- *
45
- * - `normalizeCompoundLastUpdatedAt` produces a stable ISO-8601 UTC
46
- * timestamp so the hook-written `compound-readiness.json` is byte-equal
47
- * to the CLI-written version for the same input.
48
- * - `countArchivedRunsInline` counts immediate subdirectories of
49
- * `<root>/.cclaw/archive/` so both the hook and the CLI see the same
50
- * `archivedRunsCount` for the small-project relaxation.
51
- * - `formatCompoundReadinessLineInline` mirrors the one-line summary shape
52
- * used by `src/internal/compound-readiness.ts::formatCompoundReadinessLine`
53
- * so session-start and internal CLI command stay wording-compatible.
54
- */
55
- export declare const HOOK_INLINE_SHARED_HELPERS = "\nfunction normalizeCompoundLastUpdatedAt(date) {\n return date.toISOString().replace(/\\.\\d{3}Z$/u, \"Z\");\n}\n\n// Count archived runs as sub-directories under `.cclaw/archive/`. Missing\n// dir returns 0; unexpected errors return undefined so the caller can\n// skip the small-project relaxation rather than guess.\nasync function countArchivedRunsInline(root) {\n const dir = path.join(root, RUNTIME_ROOT, \"archive\");\n try {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n return entries.filter((entry) => entry.isDirectory()).length;\n } catch (error) {\n const code = error && typeof error === \"object\" && \"code\" in error ? error.code : null;\n if (code === \"ENOENT\") return 0;\n return undefined;\n }\n}\n\nfunction formatCompoundReadinessLineInline(readiness) {\n if (!readiness || typeof readiness !== \"object\") {\n return \"\";\n }\n const ready = Array.isArray(readiness.ready) ? readiness.ready : [];\n const readyCount =\n typeof readiness.readyCount === \"number\" && Number.isFinite(readiness.readyCount)\n ? Math.trunc(readiness.readyCount)\n : ready.length;\n const clusterCount =\n typeof readiness.clusterCount === \"number\" && Number.isFinite(readiness.clusterCount)\n ? Math.trunc(readiness.clusterCount)\n : 0;\n const threshold =\n typeof readiness.threshold === \"number\" && Number.isFinite(readiness.threshold)\n ? Math.trunc(readiness.threshold)\n : COMPOUND_RECURRENCE_THRESHOLD;\n if (readyCount === 0) {\n return \"Compound readiness: no candidates (clusters=\" +\n String(clusterCount) + \", threshold=\" + String(threshold) + \")\";\n }\n const critical = ready.filter(\n (entry) => entry && typeof entry === \"object\" && entry.severity === \"critical\"\n ).length;\n const criticalSuffix = critical > 0 ? \" (critical=\" + String(critical) + \")\" : \"\";\n return \"Compound readiness: clusters=\" + String(clusterCount) +\n \", ready=\" + String(readyCount) + criticalSuffix;\n}\n";
56
- /**
57
- * Inline mirror of `src/knowledge-store.ts::computeCompoundReadiness`.
58
- *
59
- * Parity enforced by
60
- * `tests/unit/ralph-loop-parity.test.ts::compound-readiness parity`.
61
- *
62
- * Signature contract:
63
- * async function computeCompoundReadinessInline(root, options) -> CompoundReadiness
64
- *
65
- * Accepted options (all optional):
66
- * - prereadRaw: string | undefined — pre-read `knowledge.jsonl` contents.
67
- * - threshold: integer >= 1 — default recurrence threshold.
68
- * - archivedRunsCount: integer >= 0 — enables small-project relaxation.
69
- * - maxReady: integer >= 1 — cap on returned `ready` cluster count
70
- * (default 10).
71
- *
72
- * Depends on: `SMALL_PROJECT_ARCHIVE_RUNS_THRESHOLD`,
73
- * `SMALL_PROJECT_RECURRENCE_THRESHOLD`, `COMPOUND_RECURRENCE_THRESHOLD`,
74
- * and `HOOK_INLINE_SHARED_HELPERS` being in the same runtime scope.
75
- */
76
- export declare const COMPOUND_READINESS_INLINE_SOURCE = "\nasync function computeCompoundReadinessInline(root, options) {\n const filePath = path.join(root, RUNTIME_ROOT, \"knowledge.jsonl\");\n // Caller may supply pre-read raw to avoid double-reading knowledge.jsonl.\n const raw = typeof (options && options.prereadRaw) === \"string\"\n ? options.prereadRaw\n : await readTextFile(filePath, \"\");\n const baseThresholdRaw = options && options.threshold;\n const baseThreshold = Number.isInteger(baseThresholdRaw) && baseThresholdRaw >= 1\n ? baseThresholdRaw\n : COMPOUND_RECURRENCE_THRESHOLD;\n const archivedRunsCount =\n typeof (options && options.archivedRunsCount) === \"number\" &&\n Number.isFinite(options.archivedRunsCount) &&\n options.archivedRunsCount >= 0\n ? Math.floor(options.archivedRunsCount)\n : undefined;\n const smallProjectRelaxationApplied =\n archivedRunsCount !== undefined &&\n archivedRunsCount < SMALL_PROJECT_ARCHIVE_RUNS_THRESHOLD &&\n baseThreshold > SMALL_PROJECT_RECURRENCE_THRESHOLD;\n const threshold = smallProjectRelaxationApplied\n ? SMALL_PROJECT_RECURRENCE_THRESHOLD\n : baseThreshold;\n const maxReady = Number.isInteger(options && options.maxReady) && options.maxReady >= 1\n ? options.maxReady\n : 10;\n const normalize = (value) => String(value == null ? \"\" : value).trim().replace(/\\s+/gu, \" \").toLowerCase();\n const severityWeight = (sev) => {\n if (sev === \"critical\") return 3;\n if (sev === \"important\") return 2;\n if (sev === \"suggestion\") return 1;\n return 0;\n };\n const buckets = new Map();\n for (const rawLine of raw.split(/\\r?\\n/gu)) {\n const line = rawLine.trim();\n if (line.length === 0) continue;\n let row;\n try { row = JSON.parse(line); } catch { continue; }\n if (!row || typeof row !== \"object\" || Array.isArray(row)) continue;\n if (row.maturity === \"lifted-to-enforcement\" || typeof row.superseded_by === \"string\") continue;\n const type = typeof row.type === \"string\" ? row.type : \"\";\n const trigger = typeof row.trigger === \"string\" ? row.trigger : \"\";\n const action = typeof row.action === \"string\" ? row.action : \"\";\n if (type.length === 0 || trigger.length === 0 || action.length === 0) continue;\n const key = type + \"||\" + normalize(trigger) + \"||\" + normalize(action);\n const frequency = Number.isInteger(row.frequency) && row.frequency > 0 ? Math.floor(row.frequency) : 1;\n const lastSeen = typeof row.last_seen_ts === \"string\" ? row.last_seen_ts : \"\";\n let bucket = buckets.get(key);\n if (!bucket) {\n bucket = {\n trigger,\n action,\n recurrence: frequency,\n entryCount: 1,\n severity: typeof row.severity === \"string\" ? row.severity : undefined,\n lastSeenTs: lastSeen,\n types: new Set([type]),\n maturity: new Set([typeof row.maturity === \"string\" ? row.maturity : \"raw\"])\n };\n buckets.set(key, bucket);\n continue;\n }\n bucket.recurrence += frequency;\n bucket.entryCount += 1;\n bucket.types.add(type);\n bucket.maturity.add(typeof row.maturity === \"string\" ? row.maturity : \"raw\");\n if (row.severity === \"critical\") {\n bucket.severity = \"critical\";\n } else if (row.severity === \"important\" && bucket.severity !== \"critical\") {\n bucket.severity = \"important\";\n }\n if (lastSeen && Date.parse(lastSeen) > Date.parse(bucket.lastSeenTs || \"0\")) {\n bucket.lastSeenTs = lastSeen;\n }\n }\n const ready = [];\n for (const bucket of buckets.values()) {\n const criticalOverride = bucket.severity === \"critical\";\n const meetsRecurrence = bucket.recurrence >= threshold;\n if (!criticalOverride && !meetsRecurrence) continue;\n ready.push({\n trigger: bucket.trigger,\n action: bucket.action,\n recurrence: bucket.recurrence,\n entryCount: bucket.entryCount,\n qualification: criticalOverride && !meetsRecurrence ? \"critical_override\" : \"recurrence\",\n ...(bucket.severity ? { severity: bucket.severity } : {}),\n lastSeenTs: bucket.lastSeenTs,\n types: Array.from(bucket.types).sort(),\n maturity: Array.from(bucket.maturity).sort()\n });\n }\n ready.sort((a, b) => {\n const sevDiff = severityWeight(b.severity) - severityWeight(a.severity);\n if (sevDiff !== 0) return sevDiff;\n if (b.recurrence !== a.recurrence) return b.recurrence - a.recurrence;\n const recencyDiff = Date.parse(b.lastSeenTs || \"0\") - Date.parse(a.lastSeenTs || \"0\");\n if (!Number.isNaN(recencyDiff) && recencyDiff !== 0) return recencyDiff;\n return String(a.trigger).localeCompare(String(b.trigger));\n });\n return {\n schemaVersion: 2,\n threshold,\n baseThreshold,\n ...(archivedRunsCount !== undefined ? { archivedRunsCount } : {}),\n smallProjectRelaxationApplied,\n clusterCount: buckets.size,\n readyCount: ready.length,\n ready: ready.slice(0, maxReady),\n lastUpdatedAt: normalizeCompoundLastUpdatedAt(new Date())\n };\n}\n";
77
- /**
78
- * Inline mirror of `src/tdd-cycle.ts::computeRalphLoopStatus`.
79
- *
80
- * Parity enforced by
81
- * `tests/unit/ralph-loop-parity.test.ts::ralph-loop parity`.
82
- *
83
- * Signature contract:
84
- * async function computeRalphLoopStatusInline(stateDir, runId) -> RalphLoopStatus
85
- */
86
- export declare const RALPH_LOOP_INLINE_SOURCE = "\nasync function computeRalphLoopStatusInline(stateDir, runId) {\n const filePath = path.join(stateDir, \"tdd-cycle-log.jsonl\");\n const raw = await readTextFile(filePath, \"\");\n const sliceMap = new Map();\n const acClosed = new Set();\n const redOpenSlices = [];\n let loopIteration = 0;\n for (const rawLine of raw.split(/\\r?\\n/gu)) {\n const line = rawLine.trim();\n if (line.length === 0) continue;\n let row;\n try { row = JSON.parse(line); } catch { continue; }\n if (!row || typeof row !== \"object\" || Array.isArray(row)) continue;\n const rowRun = typeof row.runId === \"string\" && row.runId.length > 0 ? row.runId : runId;\n if (rowRun !== runId) continue;\n const slice = typeof row.slice === \"string\" && row.slice.length > 0 ? row.slice : \"S-unknown\";\n let state = sliceMap.get(slice);\n if (!state) {\n state = { slice, redCount: 0, greenCount: 0, refactorCount: 0, redOpen: false, acIds: [] };\n sliceMap.set(slice, state);\n }\n const exitCode = typeof row.exitCode === \"number\" ? row.exitCode : undefined;\n if (row.phase === \"red\") {\n state.redCount += 1;\n if (exitCode !== undefined && exitCode !== 0) state.redOpen = true;\n } else if (row.phase === \"green\") {\n state.greenCount += 1;\n state.redOpen = false;\n loopIteration += 1;\n if (Array.isArray(row.acIds)) {\n for (const acId of row.acIds) {\n if (typeof acId !== \"string\" || acId.length === 0) continue;\n acClosed.add(acId);\n if (!state.acIds.includes(acId)) state.acIds.push(acId);\n }\n }\n } else if (row.phase === \"refactor\") {\n state.refactorCount += 1;\n }\n }\n for (const state of sliceMap.values()) {\n if (state.redOpen) redOpenSlices.push(state.slice);\n }\n const slices = Array.from(sliceMap.values()).sort((a, b) => a.slice.localeCompare(b.slice, \"en\"));\n return {\n schemaVersion: 1,\n runId,\n loopIteration,\n redOpen: redOpenSlices.length > 0,\n redOpenSlices,\n acClosed: Array.from(acClosed).sort(),\n sliceCount: slices.length,\n slices,\n lastUpdatedAt: new Date().toISOString()\n };\n}\n";
87
- /**
88
- * Inline mirror of `src/early-loop.ts::computeEarlyLoopStatus`.
89
- *
90
- * Parity enforced by
91
- * `tests/unit/early-loop-parity.test.ts::early-loop parity`.
92
- *
93
- * Signature contract:
94
- * async function computeEarlyLoopStatusInline(stateDir, stageId, runId, maxIterations) -> EarlyLoopStatus
95
- */
96
- export declare const EARLY_LOOP_INLINE_SOURCE = "\nfunction normalizeEarlyLoopSeverityInline(value) {\n if (value === \"critical\" || value === \"important\" || value === \"suggestion\") {\n return value;\n }\n return \"important\";\n}\n\nfunction normalizeEarlyLoopTextInline(value, fallback) {\n if (typeof value !== \"string\") return fallback;\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : fallback;\n}\n\nfunction stableConcernFallbackIdInline(locator, summary) {\n const seed = (String(locator) + \"::\" + String(summary)).trim().toLowerCase();\n let hash = 0;\n for (let index = 0; index < seed.length; index += 1) {\n hash = (Math.imul(31, hash) + seed.charCodeAt(index)) >>> 0;\n }\n return \"C-\" + hash.toString(16).padStart(8, \"0\");\n}\n\nfunction normalizeEarlyLoopConcernInline(row) {\n if (!row || typeof row !== \"object\" || Array.isArray(row)) return null;\n const locator = normalizeEarlyLoopTextInline(row.locator, \"unknown-location\");\n const summary = normalizeEarlyLoopTextInline(row.summary, \"missing-summary\");\n const id = typeof row.id === \"string\" && row.id.trim().length > 0\n ? row.id.trim()\n : stableConcernFallbackIdInline(locator, summary);\n return {\n id,\n severity: normalizeEarlyLoopSeverityInline(row.severity),\n locator,\n summary\n };\n}\n\nfunction normalizeEarlyLoopMaxIterationsInline(value) {\n return Number.isInteger(value) && value >= 1 ? value : 3;\n}\n\nfunction earlyLoopSeverityWeightInline(value) {\n if (value === \"critical\") return 3;\n if (value === \"important\") return 2;\n return 1;\n}\n\nfunction sortEarlyLoopConcernsInline(a, b) {\n const severityDiff = earlyLoopSeverityWeightInline(b.severity) - earlyLoopSeverityWeightInline(a.severity);\n if (severityDiff !== 0) return severityDiff;\n if (a.firstSeenIteration !== b.firstSeenIteration) {\n return a.firstSeenIteration - b.firstSeenIteration;\n }\n if (a.lastSeenIteration !== b.lastSeenIteration) {\n return a.lastSeenIteration - b.lastSeenIteration;\n }\n return String(a.id).localeCompare(String(b.id), \"en\");\n}\n\nfunction formatEarlyLoopStatusLineInline(status) {\n if (!status || typeof status !== \"object\") return \"\";\n const convergence = status.convergenceTripped ? \"tripped\" : \"clear\";\n return \"Early Loop: stage=\" + String(status.stage) +\n \", iter=\" + String(status.iteration) + \"/\" + String(status.maxIterations) +\n \", open=\" + String(Array.isArray(status.openConcerns) ? status.openConcerns.length : 0) +\n \", convergence=\" + convergence;\n}\n\nasync function computeEarlyLoopStatusInline(stateDir, stageId, runId, maxIterations) {\n const filePath = path.join(stateDir, \"early-loop-log.jsonl\");\n const raw = await readTextFile(filePath, \"\");\n const maxIters = normalizeEarlyLoopMaxIterationsInline(maxIterations);\n const concernsMap = new Map();\n let previousSnapshotKey = \"\";\n let sameConcernStreak = 0;\n let convergenceTripped = false;\n let escalationReason = undefined;\n let currentIteration = 0;\n let lastSeenConcernIds = [];\n\n for (const rawLine of raw.split(/\\r?\\n/gu)) {\n const line = rawLine.trim();\n if (line.length === 0) continue;\n let parsed;\n try {\n parsed = JSON.parse(line);\n } catch {\n continue;\n }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) continue;\n const rowRunId = typeof parsed.runId === \"string\" && parsed.runId.trim().length > 0\n ? parsed.runId.trim()\n : \"active\";\n const rowStage = typeof parsed.stage === \"string\" && parsed.stage.trim().length > 0\n ? parsed.stage.trim()\n : \"brainstorm\";\n if (rowRunId !== runId || rowStage !== stageId) continue;\n\n currentIteration += 1;\n const iteration = Number.isInteger(parsed.iteration) && parsed.iteration >= 1\n ? parsed.iteration\n : currentIteration;\n const seenThisIteration = new Set();\n const concerns = Array.isArray(parsed.concerns) ? parsed.concerns : [];\n for (const rawConcern of concerns) {\n const concern = normalizeEarlyLoopConcernInline(rawConcern);\n if (!concern) continue;\n seenThisIteration.add(concern.id);\n const existing = concernsMap.get(concern.id);\n if (!existing) {\n concernsMap.set(concern.id, {\n id: concern.id,\n severity: concern.severity,\n locator: concern.locator,\n summary: concern.summary,\n firstSeenIteration: iteration,\n lastSeenIteration: iteration\n });\n continue;\n }\n existing.lastSeenIteration = iteration;\n existing.locator = concern.locator;\n existing.summary = concern.summary;\n if (earlyLoopSeverityWeightInline(concern.severity) >= earlyLoopSeverityWeightInline(existing.severity)) {\n existing.severity = concern.severity;\n }\n delete existing.resolvedAtIteration;\n }\n\n const resolvedConcernIds = Array.isArray(parsed.resolvedConcernIds)\n ? parsed.resolvedConcernIds\n .filter((entry) => typeof entry === \"string\" && entry.trim().length > 0)\n .map((entry) => entry.trim())\n : [];\n for (const concernId of resolvedConcernIds) {\n const existing = concernsMap.get(concernId);\n if (!existing) continue;\n if (seenThisIteration.has(concernId)) continue;\n if (existing.resolvedAtIteration === undefined) {\n existing.resolvedAtIteration = iteration;\n }\n }\n\n for (const concern of concernsMap.values()) {\n if (concern.resolvedAtIteration !== undefined) continue;\n if (seenThisIteration.has(concern.id)) continue;\n concern.resolvedAtIteration = iteration;\n }\n\n const openConcernIds = Array.from(concernsMap.values())\n .filter((concern) => concern.resolvedAtIteration === undefined)\n .map((concern) => concern.id)\n .sort((a, b) => String(a).localeCompare(String(b), \"en\"));\n lastSeenConcernIds = openConcernIds;\n const snapshotKey = openConcernIds.join(\"|\");\n if (snapshotKey.length > 0 && snapshotKey === previousSnapshotKey) {\n sameConcernStreak += 1;\n if (!convergenceTripped && sameConcernStreak >= 2) {\n convergenceTripped = true;\n escalationReason = \"same concerns \" + String(sameConcernStreak) + \" iterations in a row\";\n }\n } else {\n sameConcernStreak = snapshotKey.length > 0 ? 1 : 0;\n }\n previousSnapshotKey = snapshotKey;\n }\n\n const openConcerns = Array.from(concernsMap.values())\n .filter((concern) => concern.resolvedAtIteration === undefined)\n .sort(sortEarlyLoopConcernsInline);\n const resolvedConcerns = Array.from(concernsMap.values())\n .filter((concern) => concern.resolvedAtIteration !== undefined)\n .sort((a, b) => {\n if (a.resolvedAtIteration !== b.resolvedAtIteration) {\n return a.resolvedAtIteration - b.resolvedAtIteration;\n }\n return sortEarlyLoopConcernsInline(a, b);\n });\n\n if (!convergenceTripped && openConcerns.length > 0 && currentIteration >= maxIters) {\n convergenceTripped = true;\n escalationReason = \"max iterations \" + String(maxIters) +\n \" reached with \" + String(openConcerns.length) + \" open concern(s)\";\n }\n\n return {\n schemaVersion: 1,\n stage: stageId,\n runId,\n iteration: currentIteration,\n maxIterations: maxIters,\n openConcerns,\n resolvedConcerns,\n lastSeenConcernIds,\n convergenceTripped,\n ...(escalationReason ? { escalationReason } : {}),\n lastUpdatedAt: new Date().toISOString()\n };\n}\n";