harnessed 4.32.12 → 4.32.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/harnessed-inject-state.mjs +358 -363
- package/dist/cli.mjs +5 -4
- package/dist/cli.mjs.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -1,443 +1,438 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// G4 UserPromptSubmit hook — print the per-turn injection for the active harnessed
|
|
3
|
-
// workflow: a <workflow-state> breadcrumb + (Phase 17) a relevance-filtered
|
|
4
|
-
// <project-context> block (recent, phase/sub-relevant learnings from the repo's
|
|
5
|
-
// .planning/LEARNINGS.md + the current phase's CONTEXT.md excerpt). Silent exit 0
|
|
6
|
-
// on any error (fail-soft — a hook must never block the prompt).
|
|
7
|
-
//
|
|
8
|
-
// Self-contained plain JS (no project imports, no subprocess, no LLM) for hot-path
|
|
9
|
-
// speed. This MUST stay equivalent to src/checkpoint/injectState.ts `buildInjection`
|
|
10
|
-
// — the parity test in tests/checkpoint/injectState.test.ts runs this file and
|
|
11
|
-
// compares its stdout to the TS builder.
|
|
12
|
-
//
|
|
13
|
-
// Phase 15 repo-aware: resolves the active repo's slot from
|
|
14
|
-
// workflows.json[repoKey(cwd)]. No legacy current-workflow.json fallback
|
|
15
|
-
// (removed 4.32.6 — it leaked cross-repo; see readWorkflow).
|
|
16
|
-
// Root: HARNESSED_ROOT_OVERRIDE if set, else <homedir>/.claude/harnessed.
|
|
17
|
-
import { createHash } from 'node:crypto'
|
|
18
|
-
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
|
|
19
|
-
import { homedir } from 'node:os'
|
|
20
|
-
import { dirname, join, resolve } from 'node:path'
|
|
21
2
|
|
|
22
|
-
|
|
23
|
-
|
|
3
|
+
// src/checkpoint/injectStateMain.ts
|
|
4
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
5
|
+
import { existsSync as existsSync3, readFileSync as readFileSync4, statSync } from "node:fs";
|
|
6
|
+
import { homedir } from "node:os";
|
|
7
|
+
import { dirname, join as join4, resolve } from "node:path";
|
|
24
8
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
9
|
+
// src/checkpoint/injectCache.ts
|
|
10
|
+
import { createHash } from "node:crypto";
|
|
11
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
var DEFAULT_REFRESH_TURNS = 10;
|
|
14
|
+
function decidePcEmission(cache, pcHash, refreshN, nowMs) {
|
|
15
|
+
if (cache && cache.pcHash === pcHash && cache.turns < refreshN) {
|
|
16
|
+
return { emit: false, next: { pcHash, ts: cache.ts, turns: cache.turns + 1 } };
|
|
32
17
|
}
|
|
33
|
-
return
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
function harnessedRoot() {
|
|
37
|
-
const override = process.env.HARNESSED_ROOT_OVERRIDE
|
|
38
|
-
return override !== undefined && override !== ''
|
|
39
|
-
? override
|
|
40
|
-
: join(homedir(), '.claude', 'harnessed')
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
// Phase 35 — mirror PlatformDescriptor.sessionIdEnv (src/installers/lib/platform.ts)
|
|
44
|
-
// for the hot path: which env var carries the active session id. Minimal replica —
|
|
45
|
-
// HARNESSED_PLATFORM selects (default claude); codex has none. State-root selection
|
|
46
|
-
// (.platform pin / auto-probe) is orthogonal and already handled via
|
|
47
|
-
// HARNESSED_ROOT_OVERRIDE, so it is not re-derived here. The TS `activeKey` uses the
|
|
48
|
-
// full descriptor; the parity test sets matching signals.
|
|
49
|
-
function sessionIdEnvName() {
|
|
50
|
-
const platform = (process.env.HARNESSED_PLATFORM || 'claude').trim()
|
|
51
|
-
if (platform === 'codex') return null
|
|
52
|
-
return 'CLAUDE_CODE_SESSION_ID' // claude (default)
|
|
18
|
+
return { emit: true, next: { pcHash, ts: nowMs, turns: 0 } };
|
|
53
19
|
}
|
|
54
|
-
|
|
55
|
-
// ── 4.25.0 (intel B1) — session-scoped delta cache for <project-context>.
|
|
56
|
-
// Inline mirror of src/checkpoint/injectCache.ts (this file is self-contained
|
|
57
|
-
// plain JS by contract); the delta cells in tests/checkpoint/injectState.test.ts
|
|
58
|
-
// hold the two implementations together. Fail-soft: the cache may only ever
|
|
59
|
-
// SAVE tokens, never lose context — a skip is honored only when the
|
|
60
|
-
// incremented entry was persisted (else `turns` would freeze and the periodic
|
|
61
|
-
// compaction-hedge refresh would never fire). ──
|
|
62
|
-
|
|
63
|
-
const DEFAULT_REFRESH_TURNS = 10
|
|
64
|
-
|
|
65
20
|
function parseRefreshTurns(raw) {
|
|
66
|
-
const n = Number.parseInt(raw ??
|
|
67
|
-
return Number.isInteger(n) && n > 0 ? n : DEFAULT_REFRESH_TURNS
|
|
21
|
+
const n = Number.parseInt(raw ?? "", 10);
|
|
22
|
+
return Number.isInteger(n) && n > 0 ? n : DEFAULT_REFRESH_TURNS;
|
|
68
23
|
}
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
if (cache && cache.pcHash === pcHash && cache.turns < refreshN) {
|
|
72
|
-
return { emit: false, next: { pcHash, ts: cache.ts, turns: cache.turns + 1 } }
|
|
73
|
-
}
|
|
74
|
-
return { emit: true, next: { pcHash, ts: nowMs, turns: 0 } }
|
|
24
|
+
function injectCacheKey(repoKey2, sid) {
|
|
25
|
+
return createHash("sha256").update(`${repoKey2}::${sid}`).digest("hex").slice(0, 16);
|
|
75
26
|
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
27
|
+
function cacheFile(root, key) {
|
|
28
|
+
return join(root, "inject-cache", `${key}.json`);
|
|
29
|
+
}
|
|
30
|
+
function readInjectCache(root, key) {
|
|
79
31
|
try {
|
|
80
|
-
const
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
if (
|
|
86
|
-
parsed &&
|
|
87
|
-
typeof parsed.pcHash === 'string' &&
|
|
88
|
-
typeof parsed.ts === 'number' &&
|
|
89
|
-
typeof parsed.turns === 'number'
|
|
90
|
-
) {
|
|
91
|
-
cache = parsed
|
|
32
|
+
const parsed = JSON.parse(readFileSync(cacheFile(root, key), "utf8"));
|
|
33
|
+
if (parsed && typeof parsed === "object") {
|
|
34
|
+
const e = parsed;
|
|
35
|
+
if (typeof e.pcHash === "string" && typeof e.ts === "number" && typeof e.turns === "number") {
|
|
36
|
+
return { pcHash: e.pcHash, ts: e.ts, turns: e.turns };
|
|
92
37
|
}
|
|
93
|
-
} catch {}
|
|
94
|
-
const pcHash = createHash('sha256').update(pc).digest('hex')
|
|
95
|
-
const refreshN = parseRefreshTurns(process.env.HARNESSED_INJECT_REFRESH_TURNS)
|
|
96
|
-
const d = decidePcEmission(cache, pcHash, refreshN, Date.now())
|
|
97
|
-
try {
|
|
98
|
-
mkdirSync(join(root, 'inject-cache'), { recursive: true })
|
|
99
|
-
writeFileSync(file, `${JSON.stringify(d.next)}\n`, 'utf8')
|
|
100
|
-
} catch {
|
|
101
|
-
return true // could not persist the increment — never skip on an unpersisted decision
|
|
102
38
|
}
|
|
103
|
-
return d.emit
|
|
104
39
|
} catch {
|
|
105
|
-
return true
|
|
106
40
|
}
|
|
41
|
+
return null;
|
|
107
42
|
}
|
|
108
|
-
|
|
109
|
-
// Phase 35 — try the session-scoped slot first, then the bare repoKey slot.
|
|
110
|
-
// `keys` is ordered most→least specific. No legacy-singleton fallback (see below).
|
|
111
|
-
// 4.22.0 — also surfaces the intent sidecar (same key order) for the freestyle nag.
|
|
112
|
-
function readWorkflow(root, keys) {
|
|
113
|
-
let wf = null
|
|
114
|
-
let intent = null
|
|
115
|
-
let ledgerAgeMs = null
|
|
116
|
-
const ageOf = (p) => {
|
|
117
|
-
try {
|
|
118
|
-
return Date.now() - statSync(p).mtimeMs
|
|
119
|
-
} catch {
|
|
120
|
-
return null
|
|
121
|
-
}
|
|
122
|
-
}
|
|
43
|
+
function writeInjectCache(root, key, entry) {
|
|
123
44
|
try {
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
ledgerAgeMs = ageOf(storePath)
|
|
132
|
-
break
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
if (store?.intents) {
|
|
137
|
-
for (const k of keys) {
|
|
138
|
-
if (store.intents[k]) {
|
|
139
|
-
intent = store.intents[k]
|
|
140
|
-
break
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
} catch {}
|
|
145
|
-
// NO legacy `current-workflow.json` fallback here (removed 4.32.6): the
|
|
146
|
-
// pre-Phase-15 global singleton carries no repo identity, so an unconditional
|
|
147
|
-
// fallback leaked one repo's workflow-state into EVERY repo lacking a slot —
|
|
148
|
-
// an independent new project would get a phantom <workflow-state> every turn.
|
|
149
|
-
// Migration of a genuine pre-Phase-15 root is owned by readStoreRaw
|
|
150
|
-
// (workflowStore.ts), which only reads the singleton when workflows.json is
|
|
151
|
-
// wholly absent; the hot-path hook only ever reads the per-repo store.
|
|
152
|
-
return { wf, intent, ledgerAgeMs }
|
|
45
|
+
mkdirSync(join(root, "inject-cache"), { recursive: true });
|
|
46
|
+
writeFileSync(cacheFile(root, key), `${JSON.stringify(entry)}
|
|
47
|
+
`, "utf8");
|
|
48
|
+
return true;
|
|
49
|
+
} catch {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
153
52
|
}
|
|
154
53
|
|
|
155
|
-
//
|
|
156
|
-
|
|
157
|
-
|
|
54
|
+
// src/checkpoint/injectState.ts
|
|
55
|
+
import { existsSync as existsSync2, readdirSync as readdirSync2, readFileSync as readFileSync3 } from "node:fs";
|
|
56
|
+
import { join as join3 } from "node:path";
|
|
158
57
|
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
return `${Math.floor(m / 60)}h`
|
|
58
|
+
// src/checkpoint/breakLoop.ts
|
|
59
|
+
var LOOP_THRESHOLD = 3;
|
|
60
|
+
function detectLoop(ledger) {
|
|
61
|
+
return ledger.filter((e) => (e.fail_count ?? 0) >= LOOP_THRESHOLD).map((e) => ({ sub: e.sub, count: e.fail_count }));
|
|
164
62
|
}
|
|
165
63
|
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
'
|
|
181
|
-
|
|
64
|
+
// src/checkpoint/ledger.ts
|
|
65
|
+
function nextPending(entries) {
|
|
66
|
+
return entries.find((e) => e.status === "pending")?.sub ?? null;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// src/checkpoint/deriveNext.ts
|
|
70
|
+
function deriveNext(snapshot) {
|
|
71
|
+
const pendingSub = nextPending(snapshot.subProgress);
|
|
72
|
+
if (pendingSub !== null) return { kind: "sub", sub: pendingSub };
|
|
73
|
+
const failed = snapshot.subProgress.find((e) => e.status === "failed" && (e.fail_count ?? 0) > 0);
|
|
74
|
+
if (failed) {
|
|
75
|
+
return {
|
|
76
|
+
kind: "blocked",
|
|
77
|
+
unit: failed.sub,
|
|
78
|
+
reason: `sub '${failed.sub}' failed ${failed.fail_count}x \u2014 resolve before advancing`
|
|
79
|
+
};
|
|
182
80
|
}
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
81
|
+
const firstIncomplete = snapshot.phases.find((p) => !p.complete);
|
|
82
|
+
if (firstIncomplete) {
|
|
83
|
+
const task = firstIncomplete.tasks?.nextUnchecked;
|
|
84
|
+
if (task) return { kind: "task", phase: firstIncomplete.phase, task };
|
|
85
|
+
return { kind: "phase", phase: firstIncomplete.phase, name: firstIncomplete.name };
|
|
86
|
+
}
|
|
87
|
+
return { kind: "done" };
|
|
189
88
|
}
|
|
190
89
|
|
|
191
|
-
//
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
90
|
+
// src/checkpoint/forwardStep.ts
|
|
91
|
+
function describeUnit(unit) {
|
|
92
|
+
switch (unit.kind) {
|
|
93
|
+
case "phase":
|
|
94
|
+
return `phase ${unit.phase} '${unit.name}'`;
|
|
95
|
+
case "task":
|
|
96
|
+
return `task '${unit.task}' in phase ${unit.phase}`;
|
|
97
|
+
case "sub":
|
|
98
|
+
return `sub '${unit.sub}'`;
|
|
99
|
+
case "blocked":
|
|
100
|
+
return unit.unit;
|
|
101
|
+
case "done":
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
197
105
|
|
|
198
|
-
|
|
106
|
+
// src/checkpoint/planningScan.ts
|
|
107
|
+
import { existsSync, readdirSync, readFileSync as readFileSync2 } from "node:fs";
|
|
108
|
+
import { join as join2 } from "node:path";
|
|
109
|
+
var PHASE_DIR = /^(\d+(?:\.\d+)?)-(.*)$/;
|
|
110
|
+
function scanPlanning(opts = {}) {
|
|
111
|
+
const repoRoot = opts.repoRoot ?? process.cwd();
|
|
112
|
+
const wf = opts.currentWorkflow ?? null;
|
|
113
|
+
return {
|
|
114
|
+
subProgress: wf?.sub_progress ?? [],
|
|
115
|
+
currentPhase: wf?.phase ?? null,
|
|
116
|
+
phases: scanPhases(repoRoot, opts.includeTasks ?? false)
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
function scanPhases(repoRoot, includeTasks) {
|
|
199
120
|
try {
|
|
200
|
-
const phasesDir =
|
|
201
|
-
if (!existsSync(phasesDir)) return []
|
|
202
|
-
const out = []
|
|
121
|
+
const phasesDir = join2(repoRoot, ".planning", "phases");
|
|
122
|
+
if (!existsSync(phasesDir)) return [];
|
|
123
|
+
const out = [];
|
|
203
124
|
for (const dir of readdirSync(phasesDir)) {
|
|
204
|
-
const m = PHASE_DIR.exec(dir)
|
|
205
|
-
const num = m?.[1]
|
|
206
|
-
if (!num) continue
|
|
207
|
-
const dirPath =
|
|
208
|
-
let entries
|
|
125
|
+
const m = PHASE_DIR.exec(dir);
|
|
126
|
+
const num = m?.[1];
|
|
127
|
+
if (!num) continue;
|
|
128
|
+
const dirPath = join2(phasesDir, dir);
|
|
129
|
+
let entries;
|
|
209
130
|
try {
|
|
210
|
-
entries = readdirSync(dirPath)
|
|
131
|
+
entries = readdirSync(dirPath);
|
|
211
132
|
} catch {
|
|
212
|
-
continue
|
|
133
|
+
continue;
|
|
213
134
|
}
|
|
214
|
-
let plans = 0
|
|
215
|
-
let summaries = 0
|
|
216
|
-
const prefix = `${num}
|
|
135
|
+
let plans = 0;
|
|
136
|
+
let summaries = 0;
|
|
137
|
+
const prefix = `${num}-`;
|
|
217
138
|
for (const f of entries) {
|
|
218
|
-
if (!f.startsWith(prefix)) continue
|
|
219
|
-
if (f.endsWith(
|
|
220
|
-
else if (f.endsWith(
|
|
139
|
+
if (!f.startsWith(prefix)) continue;
|
|
140
|
+
if (f.endsWith("-PLAN.md")) plans++;
|
|
141
|
+
else if (f.endsWith("-SUMMARY.md")) summaries++;
|
|
221
142
|
}
|
|
222
|
-
const complete = plans > 0 && summaries >= plans
|
|
223
|
-
|
|
143
|
+
const complete = plans > 0 && summaries >= plans;
|
|
144
|
+
const phase = {
|
|
224
145
|
phase: num,
|
|
225
|
-
name: m?.[2] ??
|
|
146
|
+
name: m?.[2] ?? "",
|
|
226
147
|
plans,
|
|
227
148
|
summaries,
|
|
228
149
|
complete,
|
|
229
|
-
order: Number.parseFloat(num)
|
|
230
|
-
}
|
|
150
|
+
order: Number.parseFloat(num)
|
|
151
|
+
};
|
|
152
|
+
if (includeTasks && !complete) phase.tasks = scanTasks(dirPath);
|
|
153
|
+
out.push(phase);
|
|
231
154
|
}
|
|
232
|
-
out.sort((a, b) => a.order - b.order)
|
|
233
|
-
return out
|
|
155
|
+
out.sort((a, b) => a.order - b.order);
|
|
156
|
+
return out;
|
|
234
157
|
} catch {
|
|
235
|
-
return []
|
|
158
|
+
return [];
|
|
236
159
|
}
|
|
237
160
|
}
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
return null
|
|
161
|
+
function scanTasks(dirPath) {
|
|
162
|
+
for (const fname of ["task_plan.md", "progress.md"]) {
|
|
163
|
+
try {
|
|
164
|
+
const p = join2(dirPath, fname);
|
|
165
|
+
if (!existsSync(p)) continue;
|
|
166
|
+
const m = /^[ \t]*- \[ \]\s+(.+)$/m.exec(readFileSync2(p, "utf8"));
|
|
167
|
+
const task = m?.[1];
|
|
168
|
+
if (task) return { nextUnchecked: task.trim() };
|
|
169
|
+
} catch {
|
|
170
|
+
}
|
|
249
171
|
}
|
|
172
|
+
return { nextUnchecked: null };
|
|
250
173
|
}
|
|
251
174
|
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
function
|
|
255
|
-
const
|
|
256
|
-
|
|
257
|
-
if (
|
|
258
|
-
|
|
259
|
-
if (failed) return { kind: 'blocked', unit: failed.sub, reason: '' }
|
|
260
|
-
const firstIncomplete = phases.find((p) => !p.complete)
|
|
261
|
-
if (firstIncomplete)
|
|
262
|
-
return { kind: 'phase', phase: firstIncomplete.phase, name: firstIncomplete.name }
|
|
263
|
-
return { kind: 'done' }
|
|
175
|
+
// src/checkpoint/injectState.ts
|
|
176
|
+
var INTENT_TTL_MS = 24 * 60 * 60 * 1e3;
|
|
177
|
+
function formatIntentAge(ms) {
|
|
178
|
+
const m = Math.floor(ms / 6e4);
|
|
179
|
+
if (m < 1) return "<1m";
|
|
180
|
+
if (m < 60) return `${m}m`;
|
|
181
|
+
return `${Math.floor(m / 60)}h`;
|
|
264
182
|
}
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
const
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
183
|
+
function buildIntentBlock(intent, nowMs) {
|
|
184
|
+
if (!intent) return "";
|
|
185
|
+
const born = Date.parse(intent.ts);
|
|
186
|
+
if (Number.isNaN(born)) return "";
|
|
187
|
+
const age = nowMs - born;
|
|
188
|
+
if (age < 0 || age > INTENT_TTL_MS) return "";
|
|
189
|
+
const m = intent.master;
|
|
190
|
+
if (intent.kind === "leaf") {
|
|
191
|
+
return [
|
|
192
|
+
"<workflow-intent>",
|
|
193
|
+
`intent: /${m} invoked ${formatIntentAge(age)} ago \u2014 sub NOT checkpointed`,
|
|
194
|
+
`ENGINE: /${m} is registered but not engaged \u2014 freestyle risk. Run: \`harnessed prompt ${m} --task "<spec>" --json\` \u2192 spawn per SOP \u2192 \`harnessed checkpoint complete ${m}\` (or \`harnessed checkpoint fail ${m}\`).`,
|
|
195
|
+
"</workflow-intent>"
|
|
196
|
+
].join("\n");
|
|
197
|
+
}
|
|
198
|
+
return [
|
|
199
|
+
"<workflow-intent>",
|
|
200
|
+
`intent: /${m} invoked ${formatIntentAge(age)} ago \u2014 ledger NOT seeded`,
|
|
201
|
+
`ENGINE: /${m} is registered but not engaged \u2014 freestyle risk. Run: \`harnessed gates ${m} --task "<locked spec>"\` \u2192 \`harnessed checkpoint start ${m} --plan '<gates JSON>'\`; then drive each sub via \`harnessed prompt\` / \`harnessed checkpoint complete|fail\`.`,
|
|
202
|
+
"</workflow-intent>"
|
|
203
|
+
].join("\n");
|
|
273
204
|
}
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
const
|
|
280
|
-
const next = ledger.find((e) => e.status === 'pending')?.sub ?? null
|
|
205
|
+
var STALE_LEDGER_MS = 24 * 60 * 60 * 1e3;
|
|
206
|
+
function buildWorkflowStateBlock(wf, forward, ledgerAgeMs) {
|
|
207
|
+
if (!wf) return "";
|
|
208
|
+
const ledger = wf.sub_progress ?? [];
|
|
209
|
+
const next = nextPending(ledger);
|
|
210
|
+
const loops = detectLoop(ledger);
|
|
281
211
|
const lines = [
|
|
282
|
-
|
|
212
|
+
"<workflow-state>",
|
|
283
213
|
`phase: ${wf.phase}`,
|
|
284
214
|
`status: ${wf.status}`,
|
|
285
|
-
next ? `next: ${next}` :
|
|
286
|
-
]
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
const days = Math.floor(ledgerAgeMs / (24 * 60 * 60 * 1000))
|
|
215
|
+
next ? `next: ${next}` : "next: (none \u2014 all subs resolved)"
|
|
216
|
+
];
|
|
217
|
+
if (next && typeof ledgerAgeMs === "number" && ledgerAgeMs > STALE_LEDGER_MS) {
|
|
218
|
+
const days = Math.floor(ledgerAgeMs / (24 * 60 * 60 * 1e3));
|
|
290
219
|
lines.push(
|
|
291
|
-
`ENGINE: STALE state machine
|
|
292
|
-
)
|
|
220
|
+
`ENGINE: STALE state machine \u2014 sub '${next}' has been pending with NO checkpoint activity for >${days}d. This ledger may belong to an abandoned/bypassed run (issue #3 class). Run \`harnessed status --recover\` to re-orient, then either resume the sub or close it out with \`harnessed checkpoint fail ${next} --summary "<why>"\`.`
|
|
221
|
+
);
|
|
293
222
|
} else if (next) {
|
|
294
223
|
lines.push(
|
|
295
|
-
`ENGINE: mid state-machine
|
|
296
|
-
)
|
|
224
|
+
`ENGINE: mid state-machine \u2014 drive sub '${next}' via \`harnessed prompt ${next}\` \u2192 spawn \u2192 \`harnessed checkpoint complete/fail\`. Do NOT freestyle the orchestration or skip the ledger; run \`harnessed status --recover\` if unsure where you are.`
|
|
225
|
+
);
|
|
297
226
|
}
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
const n = forward.remainingPhases
|
|
227
|
+
if (!next && forward && (forward.unit.kind === "phase" || forward.unit.kind === "task")) {
|
|
228
|
+
const n = forward.remainingPhases;
|
|
301
229
|
lines.push(
|
|
302
|
-
`NEXT-UNIT: current workflow complete
|
|
303
|
-
)
|
|
230
|
+
`NEXT-UNIT: current workflow complete \u2192 next is ${describeUnit(forward.unit)} (run /auto or \`harnessed advance\`); ${n} phase${n === 1 ? "" : "s"} remain`
|
|
231
|
+
);
|
|
304
232
|
}
|
|
305
|
-
for (const
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
)
|
|
233
|
+
for (const l of loops) {
|
|
234
|
+
lines.push(
|
|
235
|
+
`BREAK-LOOP: sub '${l.sub}' failed ${l.count}x \u2014 stop retrying, run break-loop skill`
|
|
236
|
+
);
|
|
310
237
|
}
|
|
311
|
-
// Phase 22 — smart-reminder lines from envelope flags (parity with injectState.ts).
|
|
312
238
|
if (wf.ship_ready) {
|
|
313
239
|
lines.push(
|
|
314
|
-
`SHIP-READY: ${wf.ship_commits ?? 0} commit(s) since the last release tag
|
|
315
|
-
)
|
|
240
|
+
`SHIP-READY: ${wf.ship_commits ?? 0} commit(s) since the last release tag \u2014 consider shipping (harnessed release-preflight, then /ship)`
|
|
241
|
+
);
|
|
316
242
|
}
|
|
317
243
|
if (wf.retro_due) {
|
|
318
244
|
lines.push(
|
|
319
|
-
|
|
320
|
-
)
|
|
245
|
+
"RETRO-DUE: enough phases completed since the last retro \u2014 run /retro, then `harnessed retro --done`"
|
|
246
|
+
);
|
|
321
247
|
}
|
|
322
|
-
|
|
323
|
-
if (wf.verify_mode === 'full') {
|
|
248
|
+
if (wf.verify_mode === "full") {
|
|
324
249
|
lines.push(
|
|
325
|
-
|
|
326
|
-
)
|
|
327
|
-
} else if (wf.verify_mode ===
|
|
328
|
-
lines.push(
|
|
250
|
+
"VERIFY-MODE: full \u2014 run full verification (large/risky change: >5 files / >4 subs / >3 reqs)"
|
|
251
|
+
);
|
|
252
|
+
} else if (wf.verify_mode === "light") {
|
|
253
|
+
lines.push("VERIFY-MODE: light \u2014 scope verification to the changed surface (small change)");
|
|
329
254
|
}
|
|
330
|
-
lines.push(
|
|
331
|
-
return lines.join(
|
|
255
|
+
lines.push("</workflow-state>");
|
|
256
|
+
return lines.join("\n");
|
|
332
257
|
}
|
|
333
|
-
|
|
258
|
+
var DEFAULT_INJECT_BUDGET = 1500;
|
|
259
|
+
var tok = (s) => Math.ceil(Buffer.byteLength(s, "utf8") / 4);
|
|
334
260
|
function parseLearnings(md) {
|
|
335
|
-
const blocks = md.split(/^### /m).slice(1)
|
|
261
|
+
const blocks = md.split(/^### /m).slice(1);
|
|
336
262
|
return blocks.map((b) => {
|
|
337
|
-
const raw = `### ${b}`.trimEnd()
|
|
338
|
-
const phase = /phase (\S+)/.exec(b)?.[1] ??
|
|
339
|
-
const subs = []
|
|
340
|
-
for (const m of b.matchAll(/^- (?:looped|rejected|failed): (\S+)/gm))
|
|
341
|
-
|
|
342
|
-
|
|
263
|
+
const raw = `### ${b}`.trimEnd();
|
|
264
|
+
const phase = /phase (\S+)/.exec(b)?.[1] ?? "";
|
|
265
|
+
const subs = [];
|
|
266
|
+
for (const m of b.matchAll(/^- (?:looped|rejected|failed): (\S+)/gm)) {
|
|
267
|
+
if (m[1]) subs.push(m[1]);
|
|
268
|
+
}
|
|
269
|
+
return { raw, phase, subs };
|
|
270
|
+
});
|
|
343
271
|
}
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
272
|
+
function filterRelevantLearnings(entries, ctx) {
|
|
273
|
+
const rel = entries.filter(
|
|
274
|
+
(e) => e.phase === ctx.phase || e.subs.some((s) => ctx.ledgerSubs.includes(s))
|
|
275
|
+
);
|
|
276
|
+
const ordered = [...rel].reverse();
|
|
277
|
+
if (ordered.length === 0) {
|
|
278
|
+
const last = entries[entries.length - 1];
|
|
279
|
+
return last ? [last] : [];
|
|
280
|
+
}
|
|
281
|
+
return ordered;
|
|
350
282
|
}
|
|
351
|
-
|
|
352
283
|
function selectWithinBudget(entries, budget) {
|
|
353
|
-
const out = []
|
|
354
|
-
let acc = 0
|
|
284
|
+
const out = [];
|
|
285
|
+
let acc = 0;
|
|
355
286
|
for (const e of entries) {
|
|
356
|
-
const cost = tok(e.raw)
|
|
357
|
-
if (acc + cost > budget) break
|
|
358
|
-
acc += cost
|
|
359
|
-
out.push(e)
|
|
287
|
+
const cost = tok(e.raw);
|
|
288
|
+
if (acc + cost > budget) break;
|
|
289
|
+
acc += cost;
|
|
290
|
+
out.push(e);
|
|
360
291
|
}
|
|
361
|
-
return out
|
|
292
|
+
return out;
|
|
293
|
+
}
|
|
294
|
+
function buildProjectContextBlock(input) {
|
|
295
|
+
const parts = [];
|
|
296
|
+
for (const l of input.learnings) parts.push(l.raw.trim());
|
|
297
|
+
if (input.contextExcerpt) parts.push(input.contextExcerpt.trim());
|
|
298
|
+
if (parts.length === 0) return "";
|
|
299
|
+
return ["<project-context>", ...parts, "</project-context>"].join("\n");
|
|
362
300
|
}
|
|
363
|
-
|
|
364
301
|
function findPhaseContextExcerpt(repoRoot, phase, budget) {
|
|
365
302
|
try {
|
|
366
|
-
const phasesDir =
|
|
367
|
-
if (!
|
|
368
|
-
for (const dir of
|
|
369
|
-
const num = /^(\d+)/.exec(dir)?.[1]
|
|
370
|
-
if (!num || !phase.includes(num)) continue
|
|
371
|
-
const ctxFile =
|
|
372
|
-
if (!
|
|
373
|
-
const body =
|
|
374
|
-
const goalIdx = body.indexOf(
|
|
375
|
-
const slice = goalIdx >= 0 ? body.slice(goalIdx) : body
|
|
376
|
-
const
|
|
377
|
-
const excerpt = (
|
|
378
|
-
return excerpt.length > budget * 4 ? excerpt.slice(0, budget * 4) : excerpt
|
|
303
|
+
const phasesDir = join3(repoRoot, ".planning", "phases");
|
|
304
|
+
if (!existsSync2(phasesDir)) return null;
|
|
305
|
+
for (const dir of readdirSync2(phasesDir)) {
|
|
306
|
+
const num = /^(\d+)/.exec(dir)?.[1];
|
|
307
|
+
if (!num || !phase.includes(num)) continue;
|
|
308
|
+
const ctxFile = join3(phasesDir, dir, `${num}-CONTEXT.md`);
|
|
309
|
+
if (!existsSync2(ctxFile)) continue;
|
|
310
|
+
const body = readFileSync3(ctxFile, "utf8");
|
|
311
|
+
const goalIdx = body.indexOf("## Goal");
|
|
312
|
+
const slice = goalIdx >= 0 ? body.slice(goalIdx) : body;
|
|
313
|
+
const next = slice.indexOf("\n## ", 1);
|
|
314
|
+
const excerpt = (next > 0 ? slice.slice(0, next) : slice).trim();
|
|
315
|
+
return excerpt.length > budget * 4 ? excerpt.slice(0, budget * 4) : excerpt;
|
|
379
316
|
}
|
|
380
|
-
} catch {
|
|
381
|
-
|
|
317
|
+
} catch {
|
|
318
|
+
}
|
|
319
|
+
return null;
|
|
382
320
|
}
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
const
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
321
|
+
function buildInjection(repoRoot, wf, learningsMd, budget = DEFAULT_INJECT_BUDGET, intent = null, nowMs = Date.now(), opts = {}) {
|
|
322
|
+
const ledgerEmpty = (wf?.sub_progress ?? []).length === 0;
|
|
323
|
+
const intentBlock = ledgerEmpty ? buildIntentBlock(intent, nowMs) : "";
|
|
324
|
+
if (!wf) return intentBlock;
|
|
325
|
+
const forward = nextPending(wf.sub_progress ?? []) === null ? forwardPointer(repoRoot, wf) : null;
|
|
326
|
+
const ws = buildWorkflowStateBlock(wf, forward, opts.ledgerAgeMs);
|
|
327
|
+
const ledgerSubs = (wf.sub_progress ?? []).map((e) => e.sub);
|
|
328
|
+
const rel = selectWithinBudget(
|
|
329
|
+
filterRelevantLearnings(parseLearnings(learningsMd), { phase: wf.phase, ledgerSubs }),
|
|
330
|
+
budget
|
|
331
|
+
);
|
|
332
|
+
const usedTokens = rel.reduce((a, e) => a + tok(e.raw), 0);
|
|
333
|
+
const ctx = findPhaseContextExcerpt(repoRoot, wf.phase, Math.max(0, budget - usedTokens));
|
|
334
|
+
const pcRaw = buildProjectContextBlock({ learnings: rel, contextExcerpt: ctx ?? void 0 });
|
|
335
|
+
const pc = pcRaw && opts.pcGate ? opts.pcGate(pcRaw) ? pcRaw : "" : pcRaw;
|
|
336
|
+
const normal = pc ? `${ws}
|
|
337
|
+
${pc}` : ws;
|
|
338
|
+
return intentBlock ? `${intentBlock}
|
|
339
|
+
${normal}` : normal;
|
|
340
|
+
}
|
|
341
|
+
function forwardPointer(repoRoot, wf) {
|
|
342
|
+
const snapshot = scanPlanning({ repoRoot, currentWorkflow: wf, includeTasks: false });
|
|
343
|
+
const unit = deriveNext(snapshot);
|
|
344
|
+
if (unit.kind !== "phase" && unit.kind !== "task") return null;
|
|
345
|
+
return { unit, remainingPhases: snapshot.phases.filter((p) => !p.complete).length };
|
|
390
346
|
}
|
|
391
347
|
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
const sid = envName ? process.env[envName]?.trim() : undefined
|
|
401
|
-
const { wf, intent, ledgerAgeMs } = readWorkflow(root, sid ? [`${key}::${sid}`, key] : [key])
|
|
402
|
-
// 4.22.0 — freestyle nag: a fresh intent whose ledger was never seeded (start
|
|
403
|
-
// absorbs the intent) keeps reminding until steps 2-3 (gates → start) run.
|
|
404
|
-
const ledgerEmpty = (wf?.sub_progress ?? []).length === 0
|
|
405
|
-
const ib = ledgerEmpty ? intentBlock(intent, Date.now()) : ''
|
|
406
|
-
if (!wf) {
|
|
407
|
-
if (ib) process.stdout.write(`${ib}\n`)
|
|
408
|
-
process.exit(0)
|
|
348
|
+
// src/checkpoint/injectStateMain.ts
|
|
349
|
+
function repoKey(cwd) {
|
|
350
|
+
let dir = resolve(cwd);
|
|
351
|
+
for (; ; ) {
|
|
352
|
+
if (existsSync3(join4(dir, ".git"))) return dir;
|
|
353
|
+
const parent = dirname(dir);
|
|
354
|
+
if (parent === dir) break;
|
|
355
|
+
dir = parent;
|
|
409
356
|
}
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
357
|
+
return resolve(cwd);
|
|
358
|
+
}
|
|
359
|
+
function harnessedRoot() {
|
|
360
|
+
const override = process.env.HARNESSED_ROOT_OVERRIDE;
|
|
361
|
+
return override !== void 0 && override !== "" ? override : join4(homedir(), ".claude", "harnessed");
|
|
362
|
+
}
|
|
363
|
+
function sessionIdEnvName() {
|
|
364
|
+
const platform = (process.env.HARNESSED_PLATFORM || "claude").trim();
|
|
365
|
+
if (platform === "codex") return null;
|
|
366
|
+
return "CLAUDE_CODE_SESSION_ID";
|
|
367
|
+
}
|
|
368
|
+
function readWorkflow(root, keys) {
|
|
369
|
+
let wf = null;
|
|
370
|
+
let intent = null;
|
|
371
|
+
let ledgerAgeMs = null;
|
|
372
|
+
const ageOf = (p) => {
|
|
373
|
+
try {
|
|
374
|
+
return Date.now() - statSync(p).mtimeMs;
|
|
375
|
+
} catch {
|
|
376
|
+
return null;
|
|
377
|
+
}
|
|
378
|
+
};
|
|
419
379
|
try {
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
}
|
|
441
|
-
|
|
380
|
+
const storePath = join4(root, "workflows.json");
|
|
381
|
+
const store = JSON.parse(readFileSync4(storePath, "utf8"));
|
|
382
|
+
if (store?.workflows) {
|
|
383
|
+
for (const k of keys) {
|
|
384
|
+
if (store.workflows[k]) {
|
|
385
|
+
wf = store.workflows[k];
|
|
386
|
+
ledgerAgeMs = ageOf(storePath);
|
|
387
|
+
break;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
if (store?.intents) {
|
|
392
|
+
for (const k of keys) {
|
|
393
|
+
if (store.intents[k]) {
|
|
394
|
+
intent = store.intents[k];
|
|
395
|
+
break;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
} catch {
|
|
400
|
+
}
|
|
401
|
+
return { wf, intent, ledgerAgeMs };
|
|
402
|
+
}
|
|
403
|
+
function shouldEmitPc(root, repoRoot, sid, pc) {
|
|
404
|
+
try {
|
|
405
|
+
const key = injectCacheKey(repoRoot, sid);
|
|
406
|
+
const cache = readInjectCache(root, key);
|
|
407
|
+
const pcHash = createHash2("sha256").update(pc).digest("hex");
|
|
408
|
+
const refreshN = parseRefreshTurns(process.env.HARNESSED_INJECT_REFRESH_TURNS);
|
|
409
|
+
const d = decidePcEmission(cache, pcHash, refreshN, Date.now());
|
|
410
|
+
if (!writeInjectCache(root, key, d.next)) return true;
|
|
411
|
+
return d.emit;
|
|
412
|
+
} catch {
|
|
413
|
+
return true;
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
function main() {
|
|
417
|
+
try {
|
|
418
|
+
const root = harnessedRoot();
|
|
419
|
+
const key = repoKey(process.cwd());
|
|
420
|
+
const envName = sessionIdEnvName();
|
|
421
|
+
const sid = envName ? process.env[envName]?.trim() : void 0;
|
|
422
|
+
const { wf, intent, ledgerAgeMs } = readWorkflow(root, sid ? [`${key}::${sid}`, key] : [key]);
|
|
423
|
+
let learningsMd = "";
|
|
424
|
+
try {
|
|
425
|
+
learningsMd = readFileSync4(join4(key, ".planning", "LEARNINGS.md"), "utf8");
|
|
426
|
+
} catch {
|
|
427
|
+
}
|
|
428
|
+
const budget = Number(process.env.HARNESSED_INJECT_BUDGET) || DEFAULT_INJECT_BUDGET;
|
|
429
|
+
const out = buildInjection(key, wf, learningsMd, budget, intent, Date.now(), {
|
|
430
|
+
ledgerAgeMs,
|
|
431
|
+
pcGate: sid ? (pc) => shouldEmitPc(root, key, sid, pc) : void 0
|
|
432
|
+
});
|
|
433
|
+
if (out) process.stdout.write(`${out}
|
|
434
|
+
`);
|
|
435
|
+
} catch {
|
|
436
|
+
}
|
|
442
437
|
}
|
|
443
|
-
|
|
438
|
+
main();
|