@tekyzinc/gsd-t 3.29.10 → 4.0.12

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 (112) hide show
  1. package/CHANGELOG.md +176 -0
  2. package/bin/gsd-t-parallel.cjs +64 -13
  3. package/bin/gsd-t-test-data-adapters/file-json-array.cjs +27 -3
  4. package/bin/gsd-t-test-data-adapters/localstorage-key-prefix.cjs +6 -1
  5. package/bin/gsd-t-test-data-adapters/sqlite-table-where.cjs +16 -1
  6. package/bin/gsd-t-test-data-ledger.cjs +1 -0
  7. package/bin/gsd-t.js +48 -376
  8. package/bin/journey-coverage.cjs +6 -3
  9. package/bin/parallel-cli.cjs +13 -1
  10. package/commands/gsd-t-debug.md +47 -533
  11. package/commands/gsd-t-design-decompose.md +24 -497
  12. package/commands/gsd-t-doc-ripple.md +23 -139
  13. package/commands/gsd-t-execute.md +41 -958
  14. package/commands/gsd-t-help.md +0 -2
  15. package/commands/gsd-t-impact.md +26 -295
  16. package/commands/gsd-t-integrate.md +44 -369
  17. package/commands/gsd-t-milestone.md +25 -124
  18. package/commands/gsd-t-partition.md +28 -539
  19. package/commands/gsd-t-plan.md +26 -472
  20. package/commands/gsd-t-prd.md +25 -311
  21. package/commands/gsd-t-quick.md +1 -1
  22. package/commands/gsd-t-resume.md +0 -33
  23. package/commands/gsd-t-verify.md +52 -569
  24. package/commands/gsd-t-wave.md +41 -430
  25. package/package.json +1 -1
  26. package/scripts/gsd-t-calibration-hook.js +3 -1
  27. package/scripts/hooks/pre-commit-journey-coverage +0 -2
  28. package/scripts/hooks/pre-commit-playwright-gate +0 -2
  29. package/templates/CLAUDE-global.md +43 -173
  30. package/templates/CLAUDE-project.md +118 -104
  31. package/templates/prompts/design-verify-subagent.md +3 -0
  32. package/templates/prompts/qa-subagent.md +3 -0
  33. package/templates/prompts/red-team-subagent.md +5 -2
  34. package/templates/workflows/_lib.js +176 -0
  35. package/templates/workflows/gsd-t-debug.workflow.js +86 -0
  36. package/templates/workflows/gsd-t-execute.workflow.js +206 -0
  37. package/templates/workflows/gsd-t-integrate.workflow.js +71 -0
  38. package/templates/workflows/gsd-t-phase.workflow.js +94 -0
  39. package/templates/workflows/gsd-t-quick.workflow.js +72 -0
  40. package/templates/workflows/gsd-t-verify.workflow.js +348 -0
  41. package/templates/workflows/gsd-t-wave.workflow.js +43 -0
  42. package/bin/check-headless-sessions.js +0 -140
  43. package/bin/context-budget-audit.cjs +0 -447
  44. package/bin/context-meter-config.cjs +0 -101
  45. package/bin/context-meter-config.test.cjs +0 -101
  46. package/bin/event-stream.cjs +0 -205
  47. package/bin/gsd-t-benchmark-orchestrator.js +0 -437
  48. package/bin/gsd-t-capture-lint.cjs +0 -440
  49. package/bin/gsd-t-economics.cjs +0 -315
  50. package/bin/gsd-t-in-session-usage.cjs +0 -213
  51. package/bin/gsd-t-orchestrator-config.cjs +0 -161
  52. package/bin/gsd-t-orchestrator-queue.cjs +0 -180
  53. package/bin/gsd-t-orchestrator-recover.cjs +0 -231
  54. package/bin/gsd-t-orchestrator-worker.cjs +0 -219
  55. package/bin/gsd-t-orchestrator.js +0 -535
  56. package/bin/gsd-t-parallel-probe.cjs +0 -132
  57. package/bin/gsd-t-ratelimit-probe-worker.cjs +0 -237
  58. package/bin/gsd-t-ratelimit-probe.cjs +0 -648
  59. package/bin/gsd-t-report-tokens.cjs +0 -549
  60. package/bin/gsd-t-stream-feed-client.cjs +0 -151
  61. package/bin/gsd-t-token-backfill.cjs +0 -366
  62. package/bin/gsd-t-token-capture.cjs +0 -321
  63. package/bin/gsd-t-token-dashboard.cjs +0 -353
  64. package/bin/gsd-t-token-regenerate-log.cjs +0 -129
  65. package/bin/gsd-t-tool-attribution.cjs +0 -377
  66. package/bin/gsd-t-tool-cost.cjs +0 -195
  67. package/bin/gsd-t-transcript-tee.cjs +0 -246
  68. package/bin/gsd-t-unattended-heartbeat.cjs +0 -188
  69. package/bin/gsd-t-unattended-platform.cjs +0 -551
  70. package/bin/gsd-t-unattended-platform.js +0 -381
  71. package/bin/gsd-t-unattended-safety.cjs +0 -773
  72. package/bin/gsd-t-unattended-safety.js +0 -788
  73. package/bin/gsd-t-unattended.cjs +0 -2109
  74. package/bin/gsd-t-unattended.js +0 -1367
  75. package/bin/gsd-t-worker-dispatch.cjs +0 -211
  76. package/bin/handoff-lock.cjs +0 -249
  77. package/bin/handoff-lock.js +0 -249
  78. package/bin/headless-auto-spawn.cjs +0 -711
  79. package/bin/headless-auto-spawn.js +0 -373
  80. package/bin/headless-exit-codes.cjs +0 -67
  81. package/bin/live-activity-report.cjs +0 -615
  82. package/bin/log-tail.cjs +0 -81
  83. package/bin/m44-proof-measure.cjs +0 -285
  84. package/bin/m46-iter-proof.cjs +0 -149
  85. package/bin/m46-worker-proof.cjs +0 -201
  86. package/bin/m55-substrate-proof.cjs +0 -134
  87. package/bin/metrics-rollup.js +0 -200
  88. package/bin/model-windows.cjs +0 -99
  89. package/bin/model-windows.test.cjs +0 -75
  90. package/bin/parallelism-report.cjs +0 -535
  91. package/bin/runway-estimator.cjs +0 -242
  92. package/bin/spawn-plan-derive.cjs +0 -163
  93. package/bin/spawn-plan-status-updater.cjs +0 -292
  94. package/bin/spawn-plan-writer.cjs +0 -204
  95. package/bin/supervisor-pid-fingerprint.cjs +0 -126
  96. package/bin/token-budget.cjs +0 -265
  97. package/bin/unattended-watch-format.cjs +0 -178
  98. package/bin/watch-progress.js +0 -155
  99. package/commands/gsd-t-unattended-stop.md +0 -85
  100. package/commands/gsd-t-unattended-watch.md +0 -465
  101. package/commands/gsd-t-unattended.md +0 -476
  102. package/commands/gsd-t-visualize.md +0 -116
  103. package/scripts/gsd-t-context-meter.e2e.test.js +0 -364
  104. package/scripts/gsd-t-context-meter.js +0 -341
  105. package/scripts/gsd-t-context-meter.test.js +0 -471
  106. package/scripts/gsd-t-dashboard-server.js +0 -1203
  107. package/scripts/gsd-t-post-commit-spawn-plan.sh +0 -86
  108. package/scripts/gsd-t-transcript.html +0 -1821
  109. package/scripts/hooks/gsd-t-conversation-capture.js +0 -439
  110. package/scripts/hooks/gsd-t-in-session-usage-hook.js +0 -84
  111. package/scripts/spawn-plan-fmt-tokens.cjs +0 -80
  112. package/templates/hooks/post-commit-spawn-plan.sh +0 -85
@@ -1,364 +0,0 @@
1
- /**
2
- * gsd-t-context-meter.e2e.test.js — black-box E2E integration test for M34.
3
- *
4
- * TEST-ONLY FILE. Not shipped to users. Does not participate in production
5
- * require graphs. Spawned as part of `node --test` only.
6
- *
7
- * Exercises the real child-process hook as Claude Code would invoke it:
8
- *
9
- * 1. A temporary project root is constructed under os.tmpdir() containing:
10
- * - .gsd-t/context-meter-config.json (real config loader target)
11
- * - transcript.jsonl (minimal Claude-Code-shaped transcript)
12
- * 2. `node scripts/gsd-t-context-meter.js` is spawned as a child process
13
- * with cwd = tempdir.
14
- * 3. We write the PostToolUse JSON payload to the child's stdin, close
15
- * stdin, collect stdout, and assert both the stdout shape and the
16
- * on-disk state file.
17
- *
18
- * Since v3.12 the context meter uses local token estimation (no API call),
19
- * so no stub HTTP server is needed. The transcript content determines the
20
- * estimated token count via chars/3.5 heuristic.
21
- *
22
- * @module scripts/gsd-t-context-meter.e2e.test
23
- */
24
-
25
- "use strict";
26
-
27
- const { test, beforeEach, afterEach } = require("node:test");
28
- const assert = require("node:assert/strict");
29
- const { spawn } = require("node:child_process");
30
- const fs = require("node:fs");
31
- const path = require("node:path");
32
- const os = require("node:os");
33
-
34
- const HOOK_SCRIPT = path.resolve(__dirname, "gsd-t-context-meter.js");
35
- const HARD_TIMEOUT_MS = 12000;
36
-
37
- /* ──────────────────────────── test fixtures ──────────────────────────── */
38
-
39
- class Sandbox {
40
- constructor() {
41
- this.tempdir = null;
42
- this.childProcs = [];
43
- }
44
-
45
- async setup() {
46
- this.tempdir = fs.mkdtempSync(path.join(os.tmpdir(), "gsd-t-cm-e2e-"));
47
- fs.mkdirSync(path.join(this.tempdir, ".gsd-t"), { recursive: true });
48
- }
49
-
50
- writeConfig(config) {
51
- const full = Object.assign(
52
- {
53
- version: 1,
54
- thresholdPct: 75,
55
- modelWindowSize: 200000,
56
- checkFrequency: 1,
57
- apiKeyEnvVar: "ANTHROPIC_API_KEY",
58
- statePath: ".gsd-t/.context-meter-state.json",
59
- logPath: ".gsd-t/context-meter.log",
60
- timeoutMs: 2000,
61
- },
62
- config || {}
63
- );
64
- fs.writeFileSync(
65
- path.join(this.tempdir, ".gsd-t", "context-meter-config.json"),
66
- JSON.stringify(full, null, 2),
67
- "utf8"
68
- );
69
- return full;
70
- }
71
-
72
- /**
73
- * Write a Claude-Code transcript JSONL with configurable content size.
74
- * The charCount parameter controls how many characters of text content
75
- * are in the transcript, which determines the estimated token count.
76
- */
77
- writeTranscript(filename = "transcript.jsonl", charCount = 100, model = "claude-opus-4-6") {
78
- const userText = "x".repeat(Math.floor(charCount / 2));
79
- const assistantText = "y".repeat(Math.ceil(charCount / 2));
80
- const lines = [
81
- JSON.stringify({
82
- type: "user",
83
- message: { role: "user", content: userText },
84
- uuid: "u1",
85
- sessionId: "sess-1",
86
- }),
87
- JSON.stringify({
88
- type: "assistant",
89
- message: {
90
- role: "assistant",
91
- content: [{ type: "text", text: assistantText }],
92
- model,
93
- },
94
- uuid: "a1",
95
- sessionId: "sess-1",
96
- }),
97
- ];
98
- const p = path.join(this.tempdir, filename);
99
- fs.writeFileSync(p, lines.join("\n") + "\n", "utf8");
100
- return p;
101
- }
102
-
103
- writeState(state) {
104
- const full = Object.assign(
105
- {
106
- version: 1,
107
- timestamp: null,
108
- inputTokens: 0,
109
- modelWindowSize: 0,
110
- pct: 0,
111
- threshold: "normal",
112
- checkCount: 0,
113
- lastError: null,
114
- },
115
- state || {}
116
- );
117
- fs.writeFileSync(
118
- path.join(this.tempdir, ".gsd-t", ".context-meter-state.json"),
119
- JSON.stringify(full, null, 2),
120
- "utf8"
121
- );
122
- }
123
-
124
- async runHook({ payload, env }) {
125
- const fullEnv = Object.assign({}, process.env, {});
126
- if (env) {
127
- for (const [k, v] of Object.entries(env)) {
128
- if (v === null || v === undefined) {
129
- delete fullEnv[k];
130
- } else {
131
- fullEnv[k] = v;
132
- }
133
- }
134
- }
135
-
136
- const child = spawn(process.execPath, [HOOK_SCRIPT], {
137
- cwd: this.tempdir,
138
- env: fullEnv,
139
- stdio: ["pipe", "pipe", "pipe"],
140
- });
141
- this.childProcs.push(child);
142
-
143
- const stdoutChunks = [];
144
- const stderrChunks = [];
145
- child.stdout.on("data", (c) => stdoutChunks.push(c));
146
- child.stderr.on("data", (c) => stderrChunks.push(c));
147
-
148
- child.stdin.write(JSON.stringify(payload || {}));
149
- child.stdin.end();
150
-
151
- const result = await new Promise((resolve, reject) => {
152
- const killTimer = setTimeout(() => {
153
- try {
154
- child.kill("SIGKILL");
155
- } catch (_) {
156
- /* ignore */
157
- }
158
- reject(new Error(`hook child process timeout after ${HARD_TIMEOUT_MS}ms`));
159
- }, HARD_TIMEOUT_MS);
160
-
161
- child.on("close", (code) => {
162
- clearTimeout(killTimer);
163
- resolve({
164
- stdout: Buffer.concat(stdoutChunks).toString("utf8"),
165
- stderr: Buffer.concat(stderrChunks).toString("utf8"),
166
- code,
167
- });
168
- });
169
- child.on("error", (err) => {
170
- clearTimeout(killTimer);
171
- reject(err);
172
- });
173
- });
174
-
175
- return result;
176
- }
177
-
178
- readState() {
179
- const p = path.join(this.tempdir, ".gsd-t", ".context-meter-state.json");
180
- if (!fs.existsSync(p)) return null;
181
- return JSON.parse(fs.readFileSync(p, "utf8"));
182
- }
183
-
184
- stateFileExists() {
185
- const p = path.join(this.tempdir, ".gsd-t", ".context-meter-state.json");
186
- return fs.existsSync(p);
187
- }
188
-
189
- tmpFileExists() {
190
- const p = path.join(this.tempdir, ".gsd-t", ".context-meter-state.json.tmp");
191
- return fs.existsSync(p);
192
- }
193
-
194
- async dispose() {
195
- for (const c of this.childProcs) {
196
- try {
197
- if (!c.killed) c.kill("SIGKILL");
198
- } catch (_) {
199
- /* ignore */
200
- }
201
- }
202
- this.childProcs = [];
203
-
204
- if (this.tempdir) {
205
- try {
206
- fs.rmSync(this.tempdir, { recursive: true, force: true });
207
- } catch (_) {
208
- /* ignore */
209
- }
210
- this.tempdir = null;
211
- }
212
- }
213
- }
214
-
215
- /* ──────────────────────────── shared state ──────────────────────────── */
216
-
217
- let sandbox;
218
-
219
- beforeEach(async () => {
220
- sandbox = new Sandbox();
221
- await sandbox.setup();
222
- });
223
-
224
- afterEach(async () => {
225
- if (sandbox) {
226
- await sandbox.dispose();
227
- sandbox = null;
228
- }
229
- });
230
-
231
- /* ──────────────────────────── tests ──────────────────────────── */
232
-
233
- test("E2E 1. below threshold — stdout {} and state reflects estimate", async () => {
234
- // 100 chars → ~29 tokens. The transcript declares claude-opus-4-6, so the
235
- // EFFECTIVE window is the real 1M (model-aware sizing), not the config's
236
- // legacy 200K — ~0.003% of 1M, well below threshold.
237
- sandbox.writeConfig({ thresholdPct: 75, modelWindowSize: 200000, checkFrequency: 1 });
238
- const transcriptPath = sandbox.writeTranscript("transcript.jsonl", 100);
239
-
240
- const { stdout, code } = await sandbox.runHook({
241
- payload: { session_id: "test-below", transcript_path: transcriptPath },
242
- });
243
-
244
- assert.equal(code, 0, "hook should always exit 0");
245
- const parsed = JSON.parse(stdout || "{}");
246
- assert.deepEqual(parsed, {}, "below-threshold stdout must be exactly {}");
247
-
248
- const state = sandbox.readState();
249
- assert.ok(state, "state file should exist");
250
- assert.equal(state.version, 1);
251
- assert.ok(state.inputTokens > 0, "should have estimated some tokens");
252
- assert.ok(state.inputTokens < 1000, "small transcript should estimate < 1K tokens");
253
- assert.equal(
254
- state.modelWindowSize,
255
- 1_000_000,
256
- "window resolved from the transcript's claude-opus-4-6 model (1M), not config 200K"
257
- );
258
- assert.ok(state.pct < 1, "pct should be well below threshold");
259
- assert.equal(state.threshold, "normal");
260
- assert.equal(state.checkCount, 1);
261
- assert.equal(state.lastError, null);
262
- assert.ok(typeof state.timestamp === "string" && state.timestamp.length > 0);
263
- assert.equal(sandbox.tmpFileExists(), false, "no leftover .tmp file");
264
- });
265
-
266
- test("E2E 2. above threshold — stdout additionalContext with large transcript", async () => {
267
- // Haiku → real 200K window. 600K chars → ~171K tokens → ~85.7% of 200K →
268
- // threshold band + additionalContext. (Model-aware sizing means we pin a
269
- // 200K-window model here rather than relying on a stale config default.)
270
- sandbox.writeConfig({ thresholdPct: 75, modelWindowSize: 200000, checkFrequency: 1 });
271
- const transcriptPath = sandbox.writeTranscript(
272
- "transcript.jsonl",
273
- 600000,
274
- "claude-haiku-4-5-20251001"
275
- );
276
-
277
- const { stdout, code } = await sandbox.runHook({
278
- payload: { session_id: "test-above", transcript_path: transcriptPath },
279
- });
280
-
281
- assert.equal(code, 0);
282
- const parsed = JSON.parse(stdout || "{}");
283
- assert.ok(parsed.additionalContext, "must emit additionalContext");
284
- // v3.12 (M38): additionalContext is a short silent marker, not a MANDATORY STOP banner.
285
- assert.equal(parsed.additionalContext, "next-spawn-headless:true");
286
- assert.ok(!/MANDATORY STOP/.test(parsed.additionalContext));
287
- assert.ok(!/\/gsd-t-pause/.test(parsed.additionalContext));
288
-
289
- const state = sandbox.readState();
290
- assert.ok(state);
291
- assert.ok(state.inputTokens > 100000, "large transcript should estimate >100K tokens");
292
- assert.ok(state.pct > 50, "pct should be above threshold");
293
- assert.equal(state.checkCount, 1);
294
- assert.equal(state.lastError, null);
295
- assert.equal(sandbox.tmpFileExists(), false);
296
- });
297
-
298
- test("E2E 2b. REGRESSION — large Opus transcript stays 'normal' on the 1M window", async () => {
299
- // The reported bug, end-to-end: ~600K chars → ~171K tokens. Under the old
300
- // hardcoded 200K window this read as ~85% → false headless handoff while
301
- // ~64% of context REMAINED. With model-aware sizing (claude-opus-4-7 → 1M),
302
- // 171K is only ~17% → stdout {} → no premature handoff.
303
- sandbox.writeConfig({ thresholdPct: 75, modelWindowSize: 200000, checkFrequency: 1 });
304
- const transcriptPath = sandbox.writeTranscript(
305
- "transcript.jsonl",
306
- 600000,
307
- "claude-opus-4-7"
308
- );
309
-
310
- const { stdout, code } = await sandbox.runHook({
311
- payload: { session_id: "test-regression", transcript_path: transcriptPath },
312
- });
313
-
314
- assert.equal(code, 0);
315
- const parsed = JSON.parse(stdout || "{}");
316
- assert.deepEqual(parsed, {}, "must NOT hand off — the reported regression");
317
-
318
- const state = sandbox.readState();
319
- assert.equal(state.modelWindowSize, 1_000_000);
320
- assert.ok(state.inputTokens > 100000, "large transcript, >100K tokens");
321
- assert.ok(state.pct < 75, `pct ${state.pct} must be below threshold on a 1M window`);
322
- assert.equal(state.threshold, "normal");
323
- });
324
-
325
- test("E2E 3. missing transcript — stdout {}, state has parse error", async () => {
326
- sandbox.writeConfig({ thresholdPct: 75, checkFrequency: 1 });
327
-
328
- const { stdout, code } = await sandbox.runHook({
329
- payload: {
330
- session_id: "test-nofile",
331
- transcript_path: path.join(sandbox.tempdir, "nonexistent.jsonl"),
332
- },
333
- });
334
-
335
- assert.equal(code, 0);
336
- const parsed = JSON.parse(stdout || "{}");
337
- assert.deepEqual(parsed, {});
338
-
339
- const state = sandbox.readState();
340
- assert.ok(state);
341
- assert.equal(state.checkCount, 1);
342
- assert.ok(state.lastError && typeof state.lastError === "object");
343
- assert.equal(state.lastError.code, "parse_failure");
344
- });
345
-
346
- test("E2E 4. checkFrequency skip — estimation not run, checkCount increments", async () => {
347
- sandbox.writeConfig({ thresholdPct: 75, checkFrequency: 5 });
348
- const transcriptPath = sandbox.writeTranscript("transcript.jsonl", 100);
349
- sandbox.writeState({ checkCount: 3 });
350
-
351
- const { stdout, code } = await sandbox.runHook({
352
- payload: { session_id: "test-skip", transcript_path: transcriptPath },
353
- });
354
-
355
- assert.equal(code, 0);
356
- const parsed = JSON.parse(stdout || "{}");
357
- assert.deepEqual(parsed, {});
358
-
359
- const state = sandbox.readState();
360
- assert.ok(state);
361
- assert.equal(state.checkCount, 4, "counter increments even on skipped turn");
362
- assert.equal(state.inputTokens, 0);
363
- assert.equal(sandbox.tmpFileExists(), false);
364
- });
@@ -1,341 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * gsd-t-context-meter.js
4
- *
5
- * PostToolUse hook entry point for GSD-T's Context Meter (M34).
6
- *
7
- * Wires together:
8
- * - bin/context-meter-config.cjs (loadConfig)
9
- * - scripts/context-meter/transcript-parser.js (parseTranscript)
10
- * - scripts/context-meter/estimate-tokens.js (estimateTokens — local, zero API cost)
11
- * - scripts/context-meter/threshold.js (computePct/bandFor/buildAdditionalContext)
12
- *
13
- * Contract: .gsd-t/contracts/context-meter-contract.md
14
- *
15
- * CRITICAL INVARIANT — FAIL OPEN:
16
- * Every failure path resolves to `{}` on stdout and exits 0. This hook must
17
- * NEVER throw, NEVER exit non-zero, and NEVER log message content. The
18
- * entire `runMeter` body is wrapped in a try/catch that swallows anything
19
- * unexpected and returns `{}` — the same shape the CLI shim emits on parse
20
- * failure of its own stdin. See contract rule #1.
21
- *
22
- * Testability:
23
- * `runMeter({ payload, projectRoot, env, clock?, _parseTranscript?,
24
- * _estimateTokens?, _loadConfig? })` is the pure async core. Tests
25
- * fabricate payloads and inject stubs; production code uses only the CLI
26
- * shim at the bottom of the file (runs when `require.main === module`).
27
- *
28
- * @module scripts/gsd-t-context-meter
29
- */
30
-
31
- "use strict";
32
-
33
- const fs = require("fs");
34
- const path = require("path");
35
-
36
- const { loadConfig: realLoadConfig } = require("../bin/context-meter-config.cjs");
37
- const { parseTranscript: realParseTranscript } = require("./context-meter/transcript-parser");
38
- const { estimateTokens: realEstimateTokens } = require("./context-meter/estimate-tokens");
39
- const { computePct, bandFor, buildAdditionalContext } = require("./context-meter/threshold");
40
- const { windowForModel } = require("../bin/model-windows.cjs");
41
-
42
- const STATE_VERSION = 1;
43
-
44
- /* ─────────────────────────── state file helpers ─────────────────────────── */
45
-
46
- /**
47
- * Read the current state file. Returns a fresh default on missing file or
48
- * corruption (never throws).
49
- */
50
- function readState(statePath) {
51
- try {
52
- const raw = fs.readFileSync(statePath, "utf8");
53
- const parsed = JSON.parse(raw);
54
- if (!parsed || typeof parsed !== "object" || parsed.version !== STATE_VERSION) {
55
- return defaultState();
56
- }
57
- return parsed;
58
- } catch (_) {
59
- return defaultState();
60
- }
61
- }
62
-
63
- function defaultState() {
64
- return {
65
- version: STATE_VERSION,
66
- timestamp: null,
67
- inputTokens: 0,
68
- modelWindowSize: 0,
69
- pct: 0,
70
- threshold: "normal",
71
- checkCount: 0,
72
- lastError: null,
73
- };
74
- }
75
-
76
- /**
77
- * Atomically write state to disk: write to `{statePath}.tmp` → rename to
78
- * `{statePath}`. Creates parent directories as needed. Never throws.
79
- */
80
- function writeStateAtomic(statePath, state) {
81
- try {
82
- const dir = path.dirname(statePath);
83
- fs.mkdirSync(dir, { recursive: true });
84
- const tmp = `${statePath}.tmp`;
85
- fs.writeFileSync(tmp, JSON.stringify(state, null, 2), "utf8");
86
- fs.renameSync(tmp, statePath);
87
- } catch (_) {
88
- /* fail open — logging will also be best-effort */
89
- }
90
- }
91
-
92
- /* ──────────────────────────── logging helper ─────────────────────────── */
93
-
94
- /**
95
- * Append a short line-based diagnostic to logPath. Line format:
96
- * "{ISO-timestamp} {LEVEL} {category} {short-detail}"
97
- *
98
- * NEVER logs transcript content, message text, or API request bodies.
99
- */
100
- function appendLog(logPath, level, category, detail, clock) {
101
- try {
102
- const dir = path.dirname(logPath);
103
- fs.mkdirSync(dir, { recursive: true });
104
- const ts = (clock ? clock() : new Date()).toISOString();
105
- const line = `${ts} ${level} ${category} ${detail || ""}\n`;
106
- fs.appendFileSync(logPath, line, "utf8");
107
- } catch (_) {
108
- /* logging failure must not affect fail-open behavior */
109
- }
110
- }
111
-
112
- /* ──────────────────────── core: runMeter() ──────────────────────── */
113
-
114
- /**
115
- * Run the context meter once.
116
- *
117
- * @param {object} opts
118
- * @param {object} opts.payload parsed PostToolUse JSON (with transcript_path)
119
- * @param {string} opts.projectRoot normally process.cwd()
120
- * @param {object} opts.env normally process.env
121
- * @param {Function} [opts.clock] optional () => Date (test seam)
122
- * @param {Function} [opts._loadConfig] optional loadConfig stub (test seam)
123
- * @param {Function} [opts._parseTranscript] optional parseTranscript stub (test seam)
124
- * @param {Function} [opts._estimateTokens] optional estimateTokens stub (test seam)
125
- * @returns {Promise<object>} `{}` or `{ additionalContext: "..." }`
126
- */
127
- async function runMeter(opts) {
128
- // Outer try/catch guarantees we NEVER throw. Any unexpected error → `{}`.
129
- try {
130
- const {
131
- payload,
132
- projectRoot,
133
- env,
134
- clock,
135
- _loadConfig = realLoadConfig,
136
- _parseTranscript = realParseTranscript,
137
- _estimateTokens = realEstimateTokens,
138
- } = opts || {};
139
-
140
- const root = projectRoot || process.cwd();
141
- const envObj = env || {};
142
- const now = () => (clock ? clock() : new Date());
143
-
144
- // 1. Load config (missing file → defaults). Any throw → bail out fail-open.
145
- let cfg;
146
- try {
147
- cfg = _loadConfig(root);
148
- } catch (_) {
149
- return {};
150
- }
151
-
152
- const statePath = path.isAbsolute(cfg.statePath)
153
- ? cfg.statePath
154
- : path.join(root, cfg.statePath);
155
- const logPath = path.isAbsolute(cfg.logPath)
156
- ? cfg.logPath
157
- : path.join(root, cfg.logPath);
158
-
159
- // 2. Read (possibly corrupt) state, increment checkCount immediately.
160
- const state = readState(statePath);
161
- state.version = STATE_VERSION;
162
- state.modelWindowSize = cfg.modelWindowSize;
163
- state.checkCount = (Number.isInteger(state.checkCount) ? state.checkCount : 0) + 1;
164
-
165
- // 3. Check-frequency gate: not our turn → persist counter and bail out `{}`.
166
- if (state.checkCount % cfg.checkFrequency !== 0) {
167
- writeStateAtomic(statePath, state);
168
- return {};
169
- }
170
-
171
- // 4. Extract transcript_path from payload (fail open if missing).
172
- const transcriptPath =
173
- payload && typeof payload === "object" && typeof payload.transcript_path === "string"
174
- ? payload.transcript_path
175
- : null;
176
-
177
- if (!transcriptPath) {
178
- state.lastError = {
179
- code: "no_transcript",
180
- message: "payload missing transcript_path",
181
- timestamp: now().toISOString(),
182
- };
183
- writeStateAtomic(statePath, state);
184
- appendLog(logPath, "ERROR", "no_transcript", "payload missing transcript_path", clock);
185
- return {};
186
- }
187
-
188
- // 5. Parse transcript (streaming, async). null → bail out.
189
- let parsed;
190
- try {
191
- parsed = await _parseTranscript(transcriptPath);
192
- } catch (_) {
193
- parsed = null;
194
- }
195
- if (!parsed || !Array.isArray(parsed.messages)) {
196
- state.lastError = {
197
- code: "parse_failure",
198
- message: `parseTranscript returned null for ${path.basename(transcriptPath)}`,
199
- timestamp: now().toISOString(),
200
- };
201
- writeStateAtomic(statePath, state);
202
- appendLog(
203
- logPath,
204
- "ERROR",
205
- "parse_failure",
206
- `${path.basename(transcriptPath)}`,
207
- clock
208
- );
209
- return {};
210
- }
211
-
212
- // 5b. Resolve the EFFECTIVE context window from the model the orchestrator
213
- // session is actually running (parsed.model). Opus 4.6/4.7 and Sonnet 4.x
214
- // ship a 1M window; the config default (200k) is a legacy fallback that
215
- // overcounts usage 5× and fires the headless handoff far too early. We
216
- // only override when the transcript reports a model — a missing model or
217
- // an explicit project config value falls through to cfg.modelWindowSize.
218
- const effectiveWindow =
219
- typeof parsed.model === "string" && parsed.model.length > 0
220
- ? windowForModel(parsed.model)
221
- : cfg.modelWindowSize;
222
- state.modelWindowSize = effectiveWindow;
223
-
224
- // 6. Estimate tokens locally (no API call, zero cost).
225
- let tokenResp;
226
- try {
227
- tokenResp = _estimateTokens({
228
- system: parsed.system || "",
229
- messages: parsed.messages,
230
- });
231
- } catch (_) {
232
- tokenResp = null;
233
- }
234
-
235
- if (!tokenResp || !Number.isFinite(tokenResp.inputTokens)) {
236
- state.inputTokens = 0;
237
- state.pct = 0;
238
- state.threshold = "normal";
239
- state.timestamp = now().toISOString();
240
- state.lastError = {
241
- code: "estimate_error",
242
- message: "estimateTokens returned null",
243
- timestamp: state.timestamp,
244
- };
245
- writeStateAtomic(statePath, state);
246
- appendLog(logPath, "ERROR", "estimate_error", "estimateTokens null", clock);
247
- return {};
248
- }
249
-
250
- // 8. Success path — compute pct, band, possibly emit additionalContext.
251
- const pct = computePct({
252
- inputTokens: tokenResp.inputTokens,
253
- modelWindowSize: effectiveWindow,
254
- });
255
- const band = bandFor(pct, cfg.thresholdPct);
256
-
257
- state.inputTokens = tokenResp.inputTokens;
258
- state.pct = pct;
259
- state.threshold = band;
260
- state.timestamp = now().toISOString();
261
- state.lastError = null;
262
- writeStateAtomic(statePath, state);
263
- appendLog(
264
- logPath,
265
- "INFO",
266
- "measure",
267
- `tokens=${tokenResp.inputTokens} pct=${pct.toFixed(1)} band=${band} ` +
268
- `window=${effectiveWindow}${parsed.model ? ` model=${parsed.model}` : ""}`,
269
- clock
270
- );
271
-
272
- const additionalContext = buildAdditionalContext({
273
- pct,
274
- modelWindowSize: effectiveWindow,
275
- thresholdPct: cfg.thresholdPct,
276
- });
277
- if (additionalContext) {
278
- return { additionalContext };
279
- }
280
- return {};
281
- } catch (_) {
282
- // Absolute safety net — fail open no matter what.
283
- return {};
284
- }
285
- }
286
-
287
- /* ──────────────────────────── CLI shim ──────────────────────────── */
288
-
289
- function readStdin() {
290
- return new Promise((resolve) => {
291
- let data = "";
292
- try {
293
- if (process.stdin.isTTY) {
294
- resolve("");
295
- return;
296
- }
297
- process.stdin.setEncoding("utf8");
298
- process.stdin.on("data", (chunk) => {
299
- data += chunk;
300
- });
301
- process.stdin.on("end", () => resolve(data));
302
- process.stdin.on("error", () => resolve(""));
303
- } catch (_) {
304
- resolve("");
305
- }
306
- });
307
- }
308
-
309
- async function main() {
310
- let payload = null;
311
- try {
312
- const raw = await readStdin();
313
- payload = raw ? JSON.parse(raw) : null;
314
- } catch (_) {
315
- payload = null;
316
- }
317
-
318
- let out = {};
319
- try {
320
- out = await runMeter({
321
- payload: payload || {},
322
- projectRoot: process.cwd(),
323
- env: process.env,
324
- });
325
- } catch (_) {
326
- out = {};
327
- }
328
-
329
- try {
330
- process.stdout.write(JSON.stringify(out || {}));
331
- } catch (_) {
332
- process.stdout.write("{}");
333
- }
334
- process.exit(0);
335
- }
336
-
337
- module.exports = { runMeter, readState, writeStateAtomic, defaultState };
338
-
339
- if (require.main === module) {
340
- main();
341
- }