@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,151 +0,0 @@
1
- 'use strict';
2
- /**
3
- * GSD-T Stream Feed Client (M40 D4-T3)
4
- *
5
- * Orchestrator/worker-side push helper. Opens a single keep-alive chunked
6
- * HTTP POST to /ingest?workerPid=&taskId=; each pushFrame writes one JSON line.
7
- * On server unreachable: spools to .gsd-t/stream-feed/spool-{pid}.jsonl and
8
- * stays in spool mode. close() flushes + ends the HTTP stream.
9
- *
10
- * Contract: .gsd-t/contracts/stream-json-sink-contract.md
11
- * Zero external deps — node http + fs only.
12
- */
13
- const http = require('http');
14
- const fs = require('fs');
15
- const path = require('path');
16
-
17
- const DEFAULT_PORT = 7842;
18
-
19
- function createStreamFeedClient(opts = {}) {
20
- const port = Number(opts.port || process.env.GSD_T_STREAM_FEED_PORT || DEFAULT_PORT);
21
- const host = opts.host || '127.0.0.1';
22
- const projectDir = opts.projectDir || process.cwd();
23
- const workerPid = opts.workerPid || process.pid;
24
- const taskId = opts.taskId || '';
25
- const spoolDir = path.join(projectDir, '.gsd-t', 'stream-feed');
26
- const spoolPath = path.join(spoolDir, `spool-${workerPid}.jsonl`);
27
- const httpImpl = opts.httpImpl || http;
28
-
29
- let req = null;
30
- let spooling = false;
31
- let closed = false;
32
- let spoolStream = null;
33
- const pendingLines = []; // lines written to req before confirmed delivery
34
- const stats = { pushed: 0, spooled: 0, dropped: 0 };
35
-
36
- function ensureSpoolDir() {
37
- try { fs.mkdirSync(spoolDir, { recursive: true }); } catch { /* exists */ }
38
- }
39
-
40
- function switchToSpool(reason) {
41
- if (spooling) return;
42
- spooling = true;
43
- ensureSpoolDir();
44
- try {
45
- spoolStream = fs.createWriteStream(spoolPath, { flags: 'a' });
46
- } catch (e) {
47
- spoolStream = null;
48
- }
49
- try { process.stderr.write(`[stream-feed-client] switching to spool mode (${reason}) → ${spoolPath}\n`); } catch { /* noop */ }
50
- // Flush any pending lines (written to req but never ack'd) into spool.
51
- while (pendingLines.length > 0) {
52
- writeToSpool(pendingLines.shift());
53
- if (stats.pushed > 0) stats.pushed -= 1;
54
- }
55
- if (req) {
56
- try { req.destroy(); } catch { /* noop */ }
57
- req = null;
58
- }
59
- }
60
-
61
- function openRequest() {
62
- if (closed || spooling) return;
63
- try {
64
- req = httpImpl.request({
65
- host, port,
66
- method: 'POST',
67
- path: `/ingest?workerPid=${encodeURIComponent(String(workerPid))}&taskId=${encodeURIComponent(String(taskId))}`,
68
- headers: {
69
- 'Content-Type': 'application/x-ndjson',
70
- 'Transfer-Encoding': 'chunked',
71
- 'Connection': 'keep-alive',
72
- },
73
- });
74
- req.on('error', (err) => {
75
- switchToSpool(err.code || err.message || 'http-error');
76
- });
77
- req.on('socket', (sock) => {
78
- // Clear pending once the socket is actually usable (connected).
79
- sock.once('connect', () => { pendingLines.length = 0; });
80
- });
81
- req.on('response', (res) => {
82
- pendingLines.length = 0; // response means server accepted delivery
83
- res.resume();
84
- });
85
- } catch (e) {
86
- switchToSpool('request-ctor-error');
87
- }
88
- }
89
-
90
- function writeToSpool(line) {
91
- ensureSpoolDir();
92
- if (!spoolStream) {
93
- try { spoolStream = fs.createWriteStream(spoolPath, { flags: 'a' }); }
94
- catch { stats.dropped += 1; return; }
95
- }
96
- try { spoolStream.write(line + '\n'); stats.spooled += 1; }
97
- catch { stats.dropped += 1; }
98
- }
99
-
100
- function pushFrame(frame) {
101
- if (closed) return;
102
- let line;
103
- if (typeof frame === 'string') line = frame;
104
- else {
105
- try { line = JSON.stringify(frame); }
106
- catch { stats.dropped += 1; return; }
107
- }
108
- if (spooling) { writeToSpool(line); return; }
109
- if (!req) openRequest();
110
- if (spooling) { writeToSpool(line); return; }
111
- try {
112
- pendingLines.push(line);
113
- const ok = req.write(line + '\n');
114
- if (!ok) {
115
- // Drain if needed; we don't backpressure the caller.
116
- }
117
- stats.pushed += 1;
118
- } catch (e) {
119
- switchToSpool('write-error');
120
- writeToSpool(line);
121
- }
122
- }
123
-
124
- function close() {
125
- if (closed) return Promise.resolve();
126
- closed = true;
127
- return new Promise((resolve) => {
128
- const done = () => resolve();
129
- if (req && !spooling) {
130
- try { req.end(done); }
131
- catch { done(); }
132
- } else if (spoolStream) {
133
- try { spoolStream.end(done); }
134
- catch { done(); }
135
- } else {
136
- done();
137
- }
138
- });
139
- }
140
-
141
- return {
142
- pushFrame,
143
- close,
144
- get mode() { return closed ? 'closed' : (spooling ? 'spool' : 'http'); },
145
- get stats() { return { ...stats }; },
146
- get spoolPath() { return spoolPath; },
147
- _internal: { switchToSpool },
148
- };
149
- }
150
-
151
- module.exports = { createStreamFeedClient };
@@ -1,366 +0,0 @@
1
- 'use strict';
2
- /**
3
- * GSD-T Historical Token Backfill (M41 D3)
4
- *
5
- * Walks past headless stream-json logs + event-stream JSONL and recovers
6
- * `usage` envelopes for spawns that ran before M41 (when pre-M41 rows
7
- * wrote `N/A` or `0` because no caller parsed `usage`).
8
- *
9
- * Idempotent: re-running produces the same JSONL line count as running
10
- * once; backfill records are tagged `source: "backfill"` per schema v1.
11
- *
12
- * Zero external deps. `.cjs` for ESM/CJS compat.
13
- */
14
-
15
- const fs = require('fs');
16
- const path = require('path');
17
-
18
- const capture = require('./gsd-t-token-capture.cjs');
19
-
20
- // ── Envelope parsing (assistant-vs-result precedence; inline fallback) ──
21
-
22
- function _parseJsonLine(line) {
23
- const s = String(line || '').trim();
24
- if (!s || s[0] !== '{') return null;
25
- try { return JSON.parse(s); } catch (_) { return null; }
26
- }
27
-
28
- function _pickUsageFromFrame(frame) {
29
- if (!frame || typeof frame !== 'object') return undefined;
30
- if (frame.usage && typeof frame.usage === 'object') return frame.usage;
31
- if (frame.message && typeof frame.message === 'object' && frame.message.usage && typeof frame.message.usage === 'object') {
32
- return frame.message.usage;
33
- }
34
- if (frame.result && typeof frame.result === 'object' && frame.result.usage && typeof frame.result.usage === 'object') {
35
- return frame.result.usage;
36
- }
37
- return undefined;
38
- }
39
-
40
- // ── Async log walker ──────────────────────────────────────────────────
41
-
42
- function* _walkDir(dir) {
43
- if (!fs.existsSync(dir)) return;
44
- const entries = fs.readdirSync(dir, { withFileTypes: true });
45
- for (const e of entries) {
46
- const p = path.join(dir, e.name);
47
- if (e.isFile()) yield p;
48
- }
49
- }
50
-
51
- function _listCandidateFiles(projectDir) {
52
- const files = [];
53
- const eventsDir = path.join(projectDir, '.gsd-t', 'events');
54
- for (const f of _walkDir(eventsDir)) if (f.endsWith('.jsonl')) files.push(f);
55
- const streamFeedDir = path.join(projectDir, '.gsd-t', 'stream-feed');
56
- for (const f of _walkDir(streamFeedDir)) if (f.endsWith('.jsonl')) files.push(f);
57
- const gsdDir = path.join(projectDir, '.gsd-t');
58
- for (const f of _walkDir(gsdDir)) {
59
- const base = path.basename(f);
60
- if (base.startsWith('headless-') && (base.endsWith('.log') || base.endsWith('.jsonl'))) files.push(f);
61
- }
62
- return files;
63
- }
64
-
65
- function _mtime(filePath) {
66
- try { return fs.statSync(filePath).mtimeMs; } catch (_) { return 0; }
67
- }
68
-
69
- function _parseSinceFilter(since) {
70
- if (!since) return 0;
71
- if (since instanceof Date) return since.getTime();
72
- const ms = Date.parse(since);
73
- return Number.isFinite(ms) ? ms : 0;
74
- }
75
-
76
- function pad2(n) { return String(n).padStart(2, '0'); }
77
- function _fmtDateTime(ms) {
78
- const d = new Date(ms);
79
- if (isNaN(d.getTime())) return null;
80
- return `${d.getFullYear()}-${pad2(d.getMonth()+1)}-${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
81
- }
82
-
83
- /**
84
- * Scan log files for spawn envelopes.
85
- *
86
- * @param {object} opts
87
- * @param {string} opts.projectDir
88
- * @param {string|Date} [opts.since]
89
- * @returns {AsyncIterable<{envelope, sourceFile, startedAt, endedAt, command, step, model, raw}>}
90
- */
91
- async function* scanLogs(opts) {
92
- const projectDir = opts.projectDir || '.';
93
- const sinceMs = _parseSinceFilter(opts.since);
94
- const files = _listCandidateFiles(projectDir).filter((f) => _mtime(f) >= sinceMs);
95
-
96
- for (const file of files) {
97
- let text;
98
- try { text = fs.readFileSync(file, 'utf8'); } catch (_) { continue; }
99
- const lines = text.split('\n');
100
-
101
- // Per-file scan state: track the most recent `init` frame so `result`
102
- // frames inherit command/step/model/session context.
103
- let ctx = { command: null, step: null, model: null, startedAt: null };
104
- let firstSeenMs = null;
105
-
106
- for (const line of lines) {
107
- const frame = _parseJsonLine(line);
108
- if (!frame) continue;
109
-
110
- const frameTsMs = (typeof frame.ts === 'string' && Date.parse(frame.ts)) || null;
111
- if (frameTsMs && firstSeenMs == null) firstSeenMs = frameTsMs;
112
-
113
- // Event-stream frames (UserPromptSubmit, command_invoked, etc.)
114
- if (frame.type === 'command_invoked' && frame.command) {
115
- ctx.command = frame.command;
116
- if (frameTsMs) ctx.startedAt = _fmtDateTime(frameTsMs);
117
- }
118
- if (frame.type === 'spawn' && typeof frame.data === 'object' && frame.data) {
119
- ctx.command = frame.data.command || ctx.command;
120
- ctx.step = frame.data.step || ctx.step;
121
- ctx.model = frame.data.model || ctx.model;
122
- if (frameTsMs) ctx.startedAt = _fmtDateTime(frameTsMs);
123
- }
124
-
125
- // Stream-json init (headless)
126
- if (frame.type === 'system' && frame.subtype === 'init') {
127
- if (frame.model) ctx.model = frame.model;
128
- if (frame.session_id && !ctx.step) ctx.step = '-';
129
- if (frameTsMs && !ctx.startedAt) ctx.startedAt = _fmtDateTime(frameTsMs);
130
- }
131
-
132
- // Result frame with usage → yield envelope
133
- if (frame.type === 'result') {
134
- const usage = _pickUsageFromFrame(frame);
135
- if (!usage) continue;
136
- const endedAtMs = frameTsMs || _mtime(file);
137
- const startedAtFinal = ctx.startedAt || _fmtDateTime(firstSeenMs || endedAtMs) || '';
138
- const endedAt = _fmtDateTime(endedAtMs) || startedAtFinal;
139
- yield {
140
- envelope: usage,
141
- sourceFile: file,
142
- startedAt: startedAtFinal,
143
- endedAt,
144
- command: ctx.command || _inferCommandFromPath(file),
145
- step: ctx.step || '-',
146
- model: ctx.model || frame.model || 'sonnet',
147
- raw: frame,
148
- };
149
- // Reset per-result context so multi-spawn logs don't cross-contaminate
150
- ctx = { command: ctx.command, step: null, model: ctx.model, startedAt: null };
151
- firstSeenMs = null;
152
- }
153
-
154
- // Spawn-result event-stream frames carry the envelope directly
155
- if (frame.type === 'spawn_result' && frame.data && frame.data.usage) {
156
- const endedAtMs = frameTsMs || _mtime(file);
157
- const startedAtFinal = (frame.data.startedAt) || _fmtDateTime(endedAtMs) || '';
158
- const endedAt = (frame.data.endedAt) || _fmtDateTime(endedAtMs) || startedAtFinal;
159
- yield {
160
- envelope: frame.data.usage,
161
- sourceFile: file,
162
- startedAt: startedAtFinal,
163
- endedAt,
164
- command: frame.data.command || ctx.command || _inferCommandFromPath(file),
165
- step: frame.data.step || ctx.step || '-',
166
- model: frame.data.model || ctx.model || 'sonnet',
167
- raw: frame,
168
- };
169
- }
170
- }
171
- }
172
- }
173
-
174
- function _inferCommandFromPath(file) {
175
- const base = path.basename(file);
176
- const m = /^headless-(gsd-t-[a-z-]+)-/.exec(base);
177
- return m ? m[1] : 'gsd-t-unknown';
178
- }
179
-
180
- // ── Matcher + writer ─────────────────────────────────────────────────
181
-
182
- function _loadExistingJsonl(jsonlPath) {
183
- if (!fs.existsSync(jsonlPath)) return [];
184
- const text = fs.readFileSync(jsonlPath, 'utf8');
185
- return text.split('\n').filter(Boolean).map((l) => {
186
- try { return JSON.parse(l); } catch (_) { return null; }
187
- }).filter(Boolean);
188
- }
189
-
190
- function _indexKey(startedAt, command, step, model) {
191
- return `${startedAt}|${command}|${step}|${model}`;
192
- }
193
-
194
- function _parseTokenLogRows(text) {
195
- // Returns array of {line, idx, startedAt, endedAt, command, step, model, tokensCell}
196
- const lines = text.split('\n');
197
- const out = [];
198
- for (let i = 0; i < lines.length; i++) {
199
- const l = lines[i];
200
- if (!l.startsWith('| ')) continue;
201
- if (/^\|\s*Datetime-start\s*\|/.test(l)) continue;
202
- if (/^\|[\s\-|]+\|\s*$/.test(l)) continue;
203
- const cols = l.split('|').slice(1, -1).map((c) => c.trim());
204
- if (cols.length < 7) continue;
205
- out.push({
206
- line: l,
207
- idx: i,
208
- startedAt: cols[0],
209
- endedAt: cols[1],
210
- command: cols[2],
211
- step: cols[3],
212
- model: cols[4],
213
- duration: cols[5],
214
- tokensCell: cols[6],
215
- notes: cols[7] || '-',
216
- domain: cols[8] || '-',
217
- task: cols[9] || '-',
218
- ctxPct: cols[10] || 'N/A',
219
- });
220
- }
221
- return { lines, rows: out };
222
- }
223
-
224
- function _writeAtomic(filePath, content) {
225
- const tmp = `${filePath}.tmp-${process.pid}-${Date.now()}`;
226
- fs.writeFileSync(tmp, content);
227
- fs.renameSync(tmp, filePath);
228
- }
229
-
230
- /**
231
- * Match envelopes against token-log.md + token-usage.jsonl.
232
- *
233
- * @param {object} opts
234
- * @param {string} opts.projectDir
235
- * @param {AsyncIterable|Array} opts.envelopes
236
- * @param {boolean} [opts.patchLog]
237
- * @param {boolean} [opts.dryRun]
238
- * @returns {Promise<{scanned, parsed, matched, patched, new: number, unmatched}>}
239
- */
240
- async function matchAndWrite(opts) {
241
- const projectDir = opts.projectDir || '.';
242
- const tokenLogPath = path.join(projectDir, '.gsd-t', 'token-log.md');
243
- const jsonlPath = path.join(projectDir, '.gsd-t', 'metrics', 'token-usage.jsonl');
244
- const patchLog = !!opts.patchLog;
245
- const dryRun = !!opts.dryRun;
246
-
247
- const counters = { scanned: 0, parsed: 0, matched: 0, patched: 0, new: 0, unmatched: 0 };
248
-
249
- const existing = _loadExistingJsonl(jsonlPath);
250
- const existingKeys = new Set();
251
- for (const r of existing) {
252
- if (r && r.source === 'backfill') {
253
- existingKeys.add(_indexKey(r.startedAt, r.command, r.step, r.model));
254
- }
255
- }
256
-
257
- let tokenLogText = '';
258
- let parsedLog = { lines: [], rows: [] };
259
- if (fs.existsSync(tokenLogPath)) {
260
- tokenLogText = fs.readFileSync(tokenLogPath, 'utf8');
261
- parsedLog = _parseTokenLogRows(tokenLogText);
262
- }
263
-
264
- // Iterate envelopes
265
- for await (const env of opts.envelopes) {
266
- counters.parsed += 1;
267
- const key = _indexKey(env.startedAt, env.command, env.step, env.model);
268
-
269
- if (existingKeys.has(key)) continue;
270
-
271
- // Try to match against a token-log.md row by (startedAt, command, step, model)
272
- const matchRow = parsedLog.rows.find((r) =>
273
- r.startedAt === env.startedAt &&
274
- r.command === env.command &&
275
- r.step === env.step &&
276
- r.model === env.model
277
- );
278
-
279
- if (matchRow) {
280
- counters.matched += 1;
281
- const cellIsEmpty = !matchRow.tokensCell || matchRow.tokensCell === 'N/A' || matchRow.tokensCell === '0' || matchRow.tokensCell === '—';
282
- if (cellIsEmpty && patchLog && !dryRun) {
283
- const newCell = capture._formatTokensCell(env.envelope);
284
- const cols = matchRow.line.split('|');
285
- // Columns indexing: [empty, startedAt, endedAt, command, step, model, duration, tokens, ...]
286
- cols[7] = ` ${newCell} `;
287
- parsedLog.lines[matchRow.idx] = cols.join('|');
288
- counters.patched += 1;
289
- }
290
- } else {
291
- counters.unmatched += 1;
292
- }
293
-
294
- // Write JSONL record (backfill source) whether matched or unmatched
295
- if (!dryRun) {
296
- const durationMs = Math.max(0, (Date.parse(env.endedAt.replace(' ', 'T') + ':00') || 0) - (Date.parse(env.startedAt.replace(' ', 'T') + ':00') || 0));
297
- const record = capture._buildJsonlRecord({
298
- command: env.command,
299
- step: env.step,
300
- model: env.model,
301
- startedAt: env.startedAt,
302
- endedAt: env.endedAt,
303
- durationSec: Math.round(durationMs / 1000),
304
- usage: env.envelope,
305
- domain: null,
306
- task: null,
307
- notes: matchRow ? 'backfill: matched original row' : 'backfill: no original row',
308
- ctxPct: null,
309
- milestone: null,
310
- source: 'backfill',
311
- });
312
- if (!fs.existsSync(path.dirname(jsonlPath))) fs.mkdirSync(path.dirname(jsonlPath), { recursive: true });
313
- fs.appendFileSync(jsonlPath, JSON.stringify(record) + '\n');
314
- counters.new += 1;
315
- existingKeys.add(key);
316
- }
317
- }
318
-
319
- counters.scanned = _listCandidateFiles(projectDir).length;
320
-
321
- if (patchLog && !dryRun && counters.patched > 0) {
322
- _writeAtomic(tokenLogPath, parsedLog.lines.join('\n'));
323
- }
324
-
325
- return counters;
326
- }
327
-
328
- function _printSummary(counters) {
329
- const msg = `Scanned: ${counters.scanned} files | Parsed: ${counters.parsed} envelopes | Matched: ${counters.matched} | Patched: ${counters.patched} | New JSONL: ${counters.new} | Unmatched: ${counters.unmatched}`;
330
- process.stdout.write(msg + '\n');
331
- }
332
-
333
- /**
334
- * CLI entrypoint.
335
- *
336
- * @param {object} opts
337
- * @returns {Promise<{counters, exitCode}>}
338
- */
339
- async function main(opts) {
340
- const projectDir = opts.projectDir || '.';
341
- if (!fs.existsSync(projectDir)) {
342
- process.stderr.write(`gsd-t backfill-tokens: project dir not found: ${projectDir}\n`);
343
- return { counters: null, exitCode: 3 };
344
- }
345
-
346
- const envelopes = scanLogs({ projectDir, since: opts.since });
347
- const counters = await matchAndWrite({
348
- projectDir,
349
- envelopes,
350
- patchLog: !!opts.patchLog,
351
- dryRun: !!opts.dryRun,
352
- });
353
-
354
- _printSummary(counters);
355
- return { counters, exitCode: 0 };
356
- }
357
-
358
- module.exports = {
359
- scanLogs,
360
- matchAndWrite,
361
- main,
362
- _parseJsonLine,
363
- _pickUsageFromFrame,
364
- _listCandidateFiles,
365
- _parseTokenLogRows,
366
- };