sigrank 1.0.52 → 1.0.54
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/CHANGELOG.md +7 -1
- package/README.md +11 -1
- package/adapters/otel.mjs +268 -0
- package/adapters/tokenpull.mjs +98 -1
- package/lib/integrity-worker.mjs +42 -0
- package/lib/integrity.mjs +402 -0
- package/lib/vendor/tokenpull-integrity/humanlike.mjs +257 -0
- package/lib/vendor/tokenpull-integrity/integrity.mjs +467 -0
- package/lib/vendor/tokenpull-integrity/model/human-v1.json +127 -0
- package/manifest.json +2 -2
- package/package.json +2 -2
- package/presentation/cli.mjs +76 -7
- package/presentation/tui.mjs +47 -4
- package/proxy.mjs +7 -4
- package/submit/index.mjs +33 -7
- package/submit/publication.mjs +140 -0
- package/tokenpull.mjs +1 -0
- package/tools/_helpers.mjs +13 -0
- package/tools/_schemas.mjs +53 -0
- package/tools/check-integrity.mjs +54 -0
- package/tools/index.mjs +4 -0
- package/tools/submit-verified.mjs +117 -5
- package/tools/tokenpull.mjs +4 -0
- package/tools/watch-tokenpull.mjs +23 -1
package/CHANGELOG.md
CHANGED
|
@@ -12,7 +12,13 @@
|
|
|
12
12
|
* "Update available" notice (header in the TUI, one line in plain CLI output). Non-blocking, 1.5s cap, silent offline, cached ~24h in `~/.sigrank-mcp/update-check.json`. Opt out with `SIGRANK_NO_UPDATE_CHECK=1` (also `NO_UPDATE_NOTIFIER`, `CI`).
|
|
13
13
|
* Dashboard: the Your Cascade table scrolls reliably (↑/↓, j/k, PgUp/PgDn, Home/End). Combined rows are part of the scrollable table, the ▲/▼ hints are exact, and the view stays on the same row while platforms load in.
|
|
14
14
|
|
|
15
|
-
##
|
|
15
|
+
## 1.0.54 (2026-12-04)
|
|
16
|
+
|
|
17
|
+
### Integrity
|
|
18
|
+
|
|
19
|
+
* New read-only MCP tool `check_integrity`: runs Tokenpull Integrity (record integrity, source agreement, cache pumping, double counting) over your local Claude Code logs and returns per-window flags, scores, codes, and a few samples as file ordinal + line. A flag means worth a look, not cheating. Nothing is sent or signed.
|
|
20
|
+
* `submit_verified` takes an optional `integrity: true` (default off). When on, the signed snapshot carries an `integrity` block of per-check flag counts and scores plus tool version and hash. No text, line numbers or session ids. `dry_run` shows it. With the flag off the payload is byte-identical. The board accepts the block (sigrank-app #521).
|
|
21
|
+
* TUI Dashboard: an integrity matrix (checks by windows; tick when clean, amber count when flagged, dash when not run) from a cached last result, refreshed by one detached background process at a time, with a 30-minute backoff after a failed run (`SIGRANK_NO_INTEGRITY=1` to opt out). Falls back to one line on small terminals and shows "not checked" until a result exists.
|
|
16
22
|
|
|
17
23
|
### TUI
|
|
18
24
|
|
package/README.md
CHANGED
|
@@ -36,6 +36,16 @@ npx sigrank board --window 7d --once
|
|
|
36
36
|
|
|
37
37
|
The dashboard includes Dashboard, Trends, Compare, Board, Watch, and Connect tabs. Use `1`–`6` or the arrow keys to switch, `R` to refresh, and `Q` to quit.
|
|
38
38
|
|
|
39
|
+
### Inspect live collector measurements
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
sigrank watch --platform claude --source otel # require local collector
|
|
43
|
+
sigrank watch --platform claude --source auto # collector, else transcripts
|
|
44
|
+
sigrank submit --source otel --dry-run # signed preview (publishes only with complete coverage)
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
The Claude collector exposes `/api/pillars` on `http://127.0.0.1:4318` (`SIGRANK_OTEL_URL` may select another loopback HTTP(S) origin). All four windows must validate or the entire `auto` pull falls back to transcripts. Explicit `otel` allows a longer bounded read for a cold collector. Newer collectors also report real `turns`/`sessions`, `provenance` and per-window `coverage` (all optional; absent on older collectors). Normal CLI/MCP reads default to transcripts. The TUI Watch tab may show collector data and labels it separately; its Dashboard and submit preview remain transcript-based. Non-Claude platforms retain their existing readers. A collector pull is publication-eligible per window only when its coverage is complete and self-consistent (no gap days, duplicates or missing requests), it reports real turns > 0, and it cross-checks against this machine's own transcript count: each pillar total within 2% of the transcripts path (collector history beyond the transcripts on disk cannot be verified) and turns within 10% / 5. Submitted turns/sessions are always the local transcript count, never the collector's. With `--window`/`window`, only that window gates; otherwise every window must pass. Otherwise it stays preview-only and the specific reasons are returned. Combined (`multi`) OTEL totals are not enabled, and `watch --submit` still uses transcripts. MCP publishing still requires explicit confirmation. Source, provenance and coverage appear in the tool/CLI response only; no field is added to the signed payload.
|
|
48
|
+
|
|
39
49
|
### Publish your own snapshot
|
|
40
50
|
|
|
41
51
|
1. Sign in at [signalaf.com](https://signalaf.com) and create a connect code in Settings.
|
|
@@ -76,7 +86,7 @@ The entry point automatically runs an MCP stdio server when launched without a t
|
|
|
76
86
|
|
|
77
87
|
| Task | Tools |
|
|
78
88
|
| --- | --- |
|
|
79
|
-
| Inspect local usage | `tokenpull`, `rank_windows`, `tokenpull_compare` |
|
|
89
|
+
| Inspect local usage | `tokenpull`, `rank_windows`, `tokenpull_compare`, `check_integrity` |
|
|
80
90
|
| Calculate from supplied counts | `rank_paste`, `get_sigrank_standard_record` |
|
|
81
91
|
| Read public results | `get_leaderboard`, `get_operator`, `discover_peers` |
|
|
82
92
|
| Explore possible changes | `diagnose_cascade`, `simulate_change`, `suggest_improvements` |
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* adapters/otel.mjs — the `otel` pillar source.
|
|
3
|
+
*
|
|
4
|
+
* Reads live Claude Code pillars from the local sigrank-otel collector instead of
|
|
5
|
+
* re-walking ~/.claude/projects transcripts. Contract (owned by the collector):
|
|
6
|
+
*
|
|
7
|
+
* GET http://127.0.0.1:<port>/api/pillars?window=7d|30d|90d|all
|
|
8
|
+
* → 200 { source:"otel-cc", window, sinceMs, total:{input,output,cacheRead,cacheWrite,requests},
|
|
9
|
+
* models:{ <model>: {same fields} },
|
|
10
|
+
* // optional (newer collectors; absent → null, never an error):
|
|
11
|
+
* turns, sessions, turnsSource:"real"|"none", provenance:{reported,logged},
|
|
12
|
+
* coverage:{complete,windowStartMs,firstLiveMs,firstAnyMs,duplicates,gapDays,reasons} }
|
|
13
|
+
*
|
|
14
|
+
* `input` is LOGGED API input tokens (the canonical pillar), never typed input.
|
|
15
|
+
* Platform = claude only. Base URL: opts.otelUrl → SIGRANK_OTEL_URL → http://127.0.0.1:4318.
|
|
16
|
+
*
|
|
17
|
+
* Source modes (`--source` / tool arg `source`):
|
|
18
|
+
* auto probe the collector (≤300 ms); use it when reachable, else transcripts
|
|
19
|
+
* otel collector required — an unreachable/malformed collector is an error
|
|
20
|
+
* transcripts (default) never probe; current behaviour
|
|
21
|
+
*
|
|
22
|
+
* All-or-nothing: if ANY of the four windows fails (timeout, non-200, bad JSON, bad shape)
|
|
23
|
+
* the whole pull falls back, so a result never mixes otel and transcript windows.
|
|
24
|
+
* Token-math is untouched: the collector's totals map 1:1 onto the four pillars
|
|
25
|
+
* (cacheWrite → cacheCreate) and `requests` becomes the window's message count.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
import { WINDOWS } from "./tokenpull.mjs";
|
|
29
|
+
import { evaluatePublication } from "../submit/publication.mjs";
|
|
30
|
+
|
|
31
|
+
export const OTEL_DEFAULT_URL = "http://127.0.0.1:4318";
|
|
32
|
+
export const OTEL_PROBE_TIMEOUT_MS = 300;
|
|
33
|
+
export const OTEL_FETCH_TIMEOUT_MS = 2000;
|
|
34
|
+
// Explicit collector inspection tolerates cold/large collector windows; auto stays fast.
|
|
35
|
+
export const OTEL_REQUIRED_PROBE_TIMEOUT_MS = 20000;
|
|
36
|
+
export const OTEL_REQUIRED_FETCH_TIMEOUT_MS = 30000;
|
|
37
|
+
export const OTEL_SOURCE_TAG = "otel-cc";
|
|
38
|
+
export const SOURCE_MODES = ["auto", "otel", "transcripts"];
|
|
39
|
+
|
|
40
|
+
const LOOPBACK = new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
|
|
41
|
+
|
|
42
|
+
/** Normalize a --source value. null/'' → 'transcripts'. Throws on anything unknown. */
|
|
43
|
+
export function normalizeSource(s) {
|
|
44
|
+
if (s == null || s === "") return "transcripts";
|
|
45
|
+
const v = String(s).toLowerCase();
|
|
46
|
+
if (!SOURCE_MODES.includes(v))
|
|
47
|
+
throw new Error(
|
|
48
|
+
`Unknown source "${s}". Valid: ${SOURCE_MODES.join(", ")}`,
|
|
49
|
+
);
|
|
50
|
+
return v;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Resolve the collector base URL. Loopback http(s) only — the collector is local. */
|
|
54
|
+
export function otelBaseUrl(opts = {}) {
|
|
55
|
+
const raw = (opts.otelUrl || process.env.SIGRANK_OTEL_URL || OTEL_DEFAULT_URL)
|
|
56
|
+
.toString()
|
|
57
|
+
.trim()
|
|
58
|
+
.replace(/\/+$/, "");
|
|
59
|
+
const u = new URL(raw); // throws on garbage → caller treats as unavailable
|
|
60
|
+
if (!/^https?:$/.test(u.protocol) || !LOOPBACK.has(u.hostname) || u.username || u.password || u.pathname !== "/" || u.search || u.hash)
|
|
61
|
+
throw new Error(
|
|
62
|
+
`SIGRANK_OTEL_URL must be a loopback http URL (got ${u.protocol}//${u.hostname})`,
|
|
63
|
+
);
|
|
64
|
+
return u.origin;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const nonNeg = (v) => Number.isSafeInteger(v) && v >= 0;
|
|
68
|
+
|
|
69
|
+
const optCount = (v) => (nonNeg(v) ? v : null);
|
|
70
|
+
const gapDay = (d) => typeof d === "string" && /^\d{4}-\d{2}-\d{2}$/.test(d);
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Lenient parse of the collector's real-turns / provenance / coverage fields.
|
|
74
|
+
* Every field is optional (older collectors omit them) and a malformed field
|
|
75
|
+
* degrades to null rather than failing the pull; publication treats null as
|
|
76
|
+
* "not verified". Never throws.
|
|
77
|
+
*/
|
|
78
|
+
function _parseExtras(body) {
|
|
79
|
+
const p = body.provenance;
|
|
80
|
+
const provenance =
|
|
81
|
+
p && typeof p === "object" && nonNeg(p.reported) && nonNeg(p.logged)
|
|
82
|
+
? { reported: p.reported, logged: p.logged }
|
|
83
|
+
: null;
|
|
84
|
+
const c = body.coverage;
|
|
85
|
+
const coverage =
|
|
86
|
+
c && typeof c === "object" && typeof c.complete === "boolean"
|
|
87
|
+
? {
|
|
88
|
+
complete: c.complete,
|
|
89
|
+
windowStartMs: optCount(c.windowStartMs),
|
|
90
|
+
firstLiveMs: optCount(c.firstLiveMs),
|
|
91
|
+
firstAnyMs: optCount(c.firstAnyMs),
|
|
92
|
+
duplicates: optCount(c.duplicates) ?? 0,
|
|
93
|
+
missingRequests: optCount(c.missingRequests),
|
|
94
|
+
gapDays: Array.isArray(c.gapDays) ? c.gapDays.filter(gapDay) : [],
|
|
95
|
+
reasons: Array.isArray(c.reasons)
|
|
96
|
+
? c.reasons.filter((r) => typeof r === "string").slice(0, 8)
|
|
97
|
+
: [],
|
|
98
|
+
}
|
|
99
|
+
: null;
|
|
100
|
+
return {
|
|
101
|
+
turns: optCount(body.turns),
|
|
102
|
+
sessions: optCount(body.sessions),
|
|
103
|
+
turnsSource:
|
|
104
|
+
body.turnsSource === "real" || body.turnsSource === "none"
|
|
105
|
+
? body.turnsSource
|
|
106
|
+
: null,
|
|
107
|
+
provenance,
|
|
108
|
+
coverage,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Validate one /api/pillars body → {pillars, messages} or throw with a reason. */
|
|
113
|
+
function _parseWindow(body, windowKey) {
|
|
114
|
+
if (!body || typeof body !== "object" || Array.isArray(body))
|
|
115
|
+
throw new Error("malformed body");
|
|
116
|
+
if (body.source !== OTEL_SOURCE_TAG) throw new Error("unexpected collector source");
|
|
117
|
+
if (body.window !== windowKey)
|
|
118
|
+
throw new Error(`window mismatch (${body.window} ≠ ${windowKey})`);
|
|
119
|
+
const t = body.total;
|
|
120
|
+
if (!t || typeof t !== "object") throw new Error("missing total");
|
|
121
|
+
for (const k of ["input", "output", "cacheRead", "cacheWrite"])
|
|
122
|
+
if (!nonNeg(t[k])) throw new Error(`bad total.${k}`);
|
|
123
|
+
const requests = t.requests;
|
|
124
|
+
if (!nonNeg(requests)) throw new Error("bad total.requests");
|
|
125
|
+
return {
|
|
126
|
+
window: windowKey,
|
|
127
|
+
..._parseExtras(body),
|
|
128
|
+
pillars: {
|
|
129
|
+
input: Math.round(t.input),
|
|
130
|
+
output: Math.round(t.output),
|
|
131
|
+
cacheCreate: Math.round(t.cacheWrite),
|
|
132
|
+
cacheRead: Math.round(t.cacheRead),
|
|
133
|
+
},
|
|
134
|
+
messages: Math.round(requests),
|
|
135
|
+
sinceMs: nonNeg(body.sinceMs) ? body.sinceMs : null,
|
|
136
|
+
grade: typeof body.grade === "string" && ["reported", "computed", "logged", "estimated", "native-log", "git-local", "derived", "mixed", "unknown"].includes(body.grade) ? body.grade : null,
|
|
137
|
+
_source: typeof body.source === "string" ? body.source : null,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async function _getWindow(base, windowKey, timeoutMs, fetchImpl) {
|
|
142
|
+
const ac = new AbortController();
|
|
143
|
+
const timer = setTimeout(() => ac.abort(), timeoutMs);
|
|
144
|
+
try {
|
|
145
|
+
const res = await fetchImpl(
|
|
146
|
+
`${base}/api/pillars?window=${encodeURIComponent(windowKey)}`,
|
|
147
|
+
{ headers: { accept: "application/json" }, signal: ac.signal, redirect: "error" },
|
|
148
|
+
);
|
|
149
|
+
if (!res || res.status !== 200) throw new Error(`HTTP ${res?.status}`);
|
|
150
|
+
let body;
|
|
151
|
+
try {
|
|
152
|
+
body = JSON.parse(await res.text());
|
|
153
|
+
} catch {
|
|
154
|
+
throw new Error("malformed JSON");
|
|
155
|
+
}
|
|
156
|
+
return _parseWindow(body, windowKey);
|
|
157
|
+
} catch (e) {
|
|
158
|
+
if (e?.name === "AbortError") throw new Error(`timeout after ${timeoutMs}ms`);
|
|
159
|
+
throw e;
|
|
160
|
+
} finally {
|
|
161
|
+
clearTimeout(timer);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Pull the four windows from the collector. Never throws — returns
|
|
167
|
+
* { ok:true, result } (a tokenpull-shaped result tagged source:'otel-cc') or
|
|
168
|
+
* { ok:false, url, reason }.
|
|
169
|
+
*/
|
|
170
|
+
export async function tokenpullOtel(opts = {}) {
|
|
171
|
+
let base;
|
|
172
|
+
try {
|
|
173
|
+
base = otelBaseUrl(opts);
|
|
174
|
+
} catch (e) {
|
|
175
|
+
return { ok: false, url: null, reason: e.message };
|
|
176
|
+
}
|
|
177
|
+
const fetchImpl = opts.otelFetch || fetch;
|
|
178
|
+
const probeMs = opts.otelProbeTimeoutMs ?? OTEL_PROBE_TIMEOUT_MS;
|
|
179
|
+
const fetchMs = opts.otelFetchTimeoutMs ?? OTEL_FETCH_TIMEOUT_MS;
|
|
180
|
+
const keys = WINDOWS.map((w) => w.key);
|
|
181
|
+
try {
|
|
182
|
+
// Probe on the first window with the short timeout; only then pull the rest.
|
|
183
|
+
const first = await _getWindow(base, keys[0], probeMs, fetchImpl);
|
|
184
|
+
const rest = await Promise.all(
|
|
185
|
+
keys.slice(1).map((k) => _getWindow(base, k, fetchMs, fetchImpl)),
|
|
186
|
+
);
|
|
187
|
+
const rows = [first, ...rest];
|
|
188
|
+
if (rows.some((row, i) => i > 0 && Object.keys(row.pillars).some(k => row.pillars[k] < rows[i-1].pillars[k]))) throw new Error("non-monotonic collector windows");
|
|
189
|
+
const nowMs =
|
|
190
|
+
opts.now == null
|
|
191
|
+
? Date.now()
|
|
192
|
+
: typeof opts.now === "number"
|
|
193
|
+
? opts.now
|
|
194
|
+
: Date.parse(opts.now);
|
|
195
|
+
const all = rows.find((r) => r.window === "all");
|
|
196
|
+
return {
|
|
197
|
+
ok: true,
|
|
198
|
+
result: {
|
|
199
|
+
platform: "claude",
|
|
200
|
+
source: OTEL_SOURCE_TAG,
|
|
201
|
+
root: base,
|
|
202
|
+
generatedAt: new Date(nowMs).toISOString(),
|
|
203
|
+
files: 0,
|
|
204
|
+
totalMessages: all ? all.messages : 0,
|
|
205
|
+
excludedTooling: [],
|
|
206
|
+
windows: rows.map(
|
|
207
|
+
({ window, pillars, messages, sinceMs, grade, turns, sessions, turnsSource, provenance, coverage }) => ({
|
|
208
|
+
window,
|
|
209
|
+
pillars,
|
|
210
|
+
messages,
|
|
211
|
+
sinceMs,
|
|
212
|
+
grade,
|
|
213
|
+
turns,
|
|
214
|
+
sessions,
|
|
215
|
+
turnsSource,
|
|
216
|
+
provenance,
|
|
217
|
+
coverage,
|
|
218
|
+
}),
|
|
219
|
+
),
|
|
220
|
+
},
|
|
221
|
+
};
|
|
222
|
+
} catch (e) {
|
|
223
|
+
return { ok: false, url: base, reason: e?.message || String(e) };
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Source-aware pull. `transcriptsPull` is a thunk for the existing adapter path.
|
|
229
|
+
* Only platform 'claude' is otel-backed; every other platform is always transcripts.
|
|
230
|
+
* Returns the pull result with `source` set ('otel-cc' | 'transcripts') and, on an
|
|
231
|
+
* auto-mode fallback, `otelFallback: '<reason>'` so the UI can say why.
|
|
232
|
+
*/
|
|
233
|
+
export async function pullWithSource(platform, opts = {}, transcriptsPull) {
|
|
234
|
+
const mode = normalizeSource(opts.source);
|
|
235
|
+
const tag = (r, extra = {}) =>
|
|
236
|
+
r && typeof r === "object" ? { ...r, source: "transcripts", ...extra } : r;
|
|
237
|
+
// Test injection: a mock adapter means "these are the transcripts" — never probe a
|
|
238
|
+
// real collector that may be running on the dev machine unless a URL is injected too.
|
|
239
|
+
const skipProbe = opts.adapter && !opts.otelUrl;
|
|
240
|
+
if ((platform || "claude") !== "claude") return transcriptsPull();
|
|
241
|
+
if (mode === "transcripts" || (skipProbe && mode === "auto"))
|
|
242
|
+
return tag(await transcriptsPull());
|
|
243
|
+
const o = await tokenpullOtel(mode === "otel" ? {
|
|
244
|
+
...opts,
|
|
245
|
+
otelProbeTimeoutMs: opts.otelProbeTimeoutMs ?? OTEL_REQUIRED_PROBE_TIMEOUT_MS,
|
|
246
|
+
otelFetchTimeoutMs: opts.otelFetchTimeoutMs ?? OTEL_REQUIRED_FETCH_TIMEOUT_MS,
|
|
247
|
+
} : opts);
|
|
248
|
+
if (o.ok) return o.result;
|
|
249
|
+
if (mode === "otel") {
|
|
250
|
+
const error = new Error(`source otel: sigrank-otel collector unavailable (${o.reason}). Start the collector or use --source auto|transcripts.`);
|
|
251
|
+
error.code = "SIGRANK_READ_FAILED";
|
|
252
|
+
throw error;
|
|
253
|
+
}
|
|
254
|
+
return tag(await transcriptsPull(), { otelFallback: o.reason });
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Human marker for watch/TUI rows. */
|
|
258
|
+
export function sourceMarker(pulled) {
|
|
259
|
+
if (!pulled) return null;
|
|
260
|
+
if (pulled.source === OTEL_SOURCE_TAG) {
|
|
261
|
+
const ev = evaluatePublication(pulled);
|
|
262
|
+
return ev.eligible
|
|
263
|
+
? "source: otel (live; complete coverage, real turns)"
|
|
264
|
+
: `source: otel (live; preview only — ${ev.reasons[0] || "coverage not verified"})`;
|
|
265
|
+
}
|
|
266
|
+
if (pulled.source === "transcripts") return "source: transcripts";
|
|
267
|
+
return null;
|
|
268
|
+
}
|
package/adapters/tokenpull.mjs
CHANGED
|
@@ -113,6 +113,40 @@ async function* _walkJsonl(dir, _counter = { n: 0 }) {
|
|
|
113
113
|
for (const p of paths) yield p;
|
|
114
114
|
}
|
|
115
115
|
|
|
116
|
+
/**
|
|
117
|
+
* typedPrompt — true when a Claude Code transcript record is a REAL user prompt.
|
|
118
|
+
* Owner definition (2026-12-01): a turn = A+B, one user prompt plus Claude's reply;
|
|
119
|
+
* the prompt (A) is what we count. Not prompts: tool results (also type "user"),
|
|
120
|
+
* meta records, compaction summaries, slash-command / local-command / task-notification /
|
|
121
|
+
* system-reminder wrappers, and any sidechain (subagent) record.
|
|
122
|
+
* Same rules as sigrank-otel src/backfill.mjs typed() + turnStats().
|
|
123
|
+
*/
|
|
124
|
+
const NON_PROMPT_PREFIXES = [
|
|
125
|
+
"<command-",
|
|
126
|
+
"<local-command",
|
|
127
|
+
"<task-notification",
|
|
128
|
+
"<system-reminder",
|
|
129
|
+
"Caveat:",
|
|
130
|
+
"[Request interrupted by user", // Claude Code's synthetic interrupt record, not something the operator typed
|
|
131
|
+
];
|
|
132
|
+
export function typedPrompt(rec) {
|
|
133
|
+
if (!rec || rec.type !== "user" || rec.isSidechain) return false;
|
|
134
|
+
if (rec.isMeta || rec.isCompactSummary) return false;
|
|
135
|
+
const c = rec.message?.content;
|
|
136
|
+
let t;
|
|
137
|
+
if (typeof c === "string") t = c;
|
|
138
|
+
else if (Array.isArray(c)) {
|
|
139
|
+
if (c.some((b) => b?.type === "tool_result")) return false;
|
|
140
|
+
t = c
|
|
141
|
+
.filter((b) => b?.type === "text")
|
|
142
|
+
.map((b) => b.text || "")
|
|
143
|
+
.join(" ");
|
|
144
|
+
} else return false;
|
|
145
|
+
if (!t.trim()) return false;
|
|
146
|
+
const s = t.trimStart();
|
|
147
|
+
return !NON_PROMPT_PREFIXES.some((p) => s.startsWith(p));
|
|
148
|
+
}
|
|
149
|
+
|
|
116
150
|
/**
|
|
117
151
|
* Claude Code adapter. Yields one record per billed assistant message:
|
|
118
152
|
* { id, sid, ts, input, output, cacheCreate, cacheRead, file }. Walks
|
|
@@ -159,6 +193,50 @@ export const claudeAdapter = {
|
|
|
159
193
|
}
|
|
160
194
|
}
|
|
161
195
|
},
|
|
196
|
+
/**
|
|
197
|
+
* prompts(root) — one { uuid, sid, ts } per real user prompt (see typedPrompt).
|
|
198
|
+
* Deduped by record uuid across files (resumed/forked sessions copy earlier
|
|
199
|
+
* records into new transcripts). Subagent transcripts are skipped. Reads
|
|
200
|
+
* counts only — never message text leaves this function. Unreadable files are
|
|
201
|
+
* counted in stats.unreadable (optional). It re-reads the transcripts rather than
|
|
202
|
+
* sharing messages()'s pass: messages() is the cross-adapter contract and
|
|
203
|
+
* changing what it yields would touch every adapter.
|
|
204
|
+
*/
|
|
205
|
+
async *prompts(root, stats) {
|
|
206
|
+
const seen = new Set();
|
|
207
|
+
for await (const path of _walkJsonl(root)) {
|
|
208
|
+
let text;
|
|
209
|
+
try {
|
|
210
|
+
text = await readFile(path, "utf8");
|
|
211
|
+
} catch {
|
|
212
|
+
if (stats) stats.unreadable = (stats.unreadable || 0) + 1; // counted, surfaced by tokenpull()
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
const rel = path.startsWith(root) ? path.slice(root.length + 1) : path;
|
|
216
|
+
if (EXCLUDE_TOOLING.test(rel)) continue;
|
|
217
|
+
if (/(^|[/\\])subagents[/\\]/.test(rel)) continue; // subagent transcripts are not prompts
|
|
218
|
+
for (const line of text.split("\n")) {
|
|
219
|
+
const s = line.trim();
|
|
220
|
+
if (!s || !s.includes('"user"')) continue;
|
|
221
|
+
let ev;
|
|
222
|
+
try {
|
|
223
|
+
ev = JSON.parse(s);
|
|
224
|
+
} catch {
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
if (!typedPrompt(ev)) continue;
|
|
228
|
+
if (ev.uuid) {
|
|
229
|
+
if (seen.has(ev.uuid)) continue;
|
|
230
|
+
seen.add(ev.uuid);
|
|
231
|
+
}
|
|
232
|
+
yield {
|
|
233
|
+
uuid: ev.uuid || null,
|
|
234
|
+
sid: ev.sessionId || null,
|
|
235
|
+
ts: ev.timestamp || ev.ts || null,
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
},
|
|
162
240
|
};
|
|
163
241
|
|
|
164
242
|
/**
|
|
@@ -191,6 +269,14 @@ export async function tokenpull({ adapter = claudeAdapter, root, now } = {}) {
|
|
|
191
269
|
}
|
|
192
270
|
const msgs = [...seen.values()];
|
|
193
271
|
|
|
272
|
+
// Real turns + sessions (owner 2026-12-01: turn = A+B = one user prompt + the reply).
|
|
273
|
+
// Only adapters that expose prompts() carry them; others keep the message-count proxy.
|
|
274
|
+
const prompts = [];
|
|
275
|
+
const hasPrompts = typeof adapter.prompts === "function";
|
|
276
|
+
const promptStats = { unreadable: 0 };
|
|
277
|
+
if (hasPrompts)
|
|
278
|
+
for await (const p of adapter.prompts(r, promptStats)) prompts.push(p);
|
|
279
|
+
|
|
194
280
|
const windows = WINDOWS.map((w) => {
|
|
195
281
|
const cutoff = w.days === Infinity ? -Infinity : nowMs - w.days * DAY_MS;
|
|
196
282
|
// NULL-TIMESTAMP WINDOW ASYMMETRY: the `all` window returns true unconditionally,
|
|
@@ -215,7 +301,17 @@ export async function tokenpull({ adapter = claudeAdapter, root, now } = {}) {
|
|
|
215
301
|
}),
|
|
216
302
|
{ input: 0, output: 0, cacheCreate: 0, cacheRead: 0 },
|
|
217
303
|
);
|
|
218
|
-
|
|
304
|
+
const win = { window: w.key, pillars, messages: inWin.length };
|
|
305
|
+
if (hasPrompts) {
|
|
306
|
+
const inP = prompts.filter((p) => {
|
|
307
|
+
if (w.days === Infinity) return true;
|
|
308
|
+
const t = p.ts ? Date.parse(p.ts) : NaN;
|
|
309
|
+
return Number.isFinite(t) && t >= cutoff && t <= nowMs;
|
|
310
|
+
});
|
|
311
|
+
win.turns = inP.length;
|
|
312
|
+
win.sessions = new Set(inP.map((p) => p.sid).filter(Boolean)).size;
|
|
313
|
+
}
|
|
314
|
+
return win;
|
|
219
315
|
});
|
|
220
316
|
|
|
221
317
|
// Auto-detect background tooling we excluded → report it (the MCP "asks" by telling).
|
|
@@ -235,6 +331,7 @@ export async function tokenpull({ adapter = claudeAdapter, root, now } = {}) {
|
|
|
235
331
|
generatedAt: new Date(nowMs).toISOString(),
|
|
236
332
|
files: files.size,
|
|
237
333
|
totalMessages: msgs.length,
|
|
334
|
+
...(hasPrompts ? { promptFilesUnreadable: promptStats.unreadable } : {}),
|
|
238
335
|
excludedTooling,
|
|
239
336
|
windows,
|
|
240
337
|
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// lib/integrity-worker.mjs — background runner for the TUI integrity status.
|
|
2
|
+
// Spawned detached by the TUI so the (seconds-long) transcript scan never shares its
|
|
3
|
+
// event loop. Runs the checks, writes ~/.sigrank-mcp/integrity-last.json (counts only,
|
|
4
|
+
// dir 0700, file 0600, same as the update-check cache), exits. No network.
|
|
5
|
+
import { chmodSync, mkdirSync, writeFileSync, renameSync } from "node:fs";
|
|
6
|
+
import { dirname } from "node:path";
|
|
7
|
+
import { runIntegrity, cacheEntry, integrityCachePath, acquireIntegrityLock, releaseIntegrityLock, writeIntegrityAttempt } from "./integrity.mjs";
|
|
8
|
+
|
|
9
|
+
const done = (code) => {
|
|
10
|
+
writeIntegrityAttempt(undefined, code === 0);
|
|
11
|
+
releaseIntegrityLock();
|
|
12
|
+
process.exit(code);
|
|
13
|
+
};
|
|
14
|
+
// One worker at a time; exit quietly if another is live.
|
|
15
|
+
if (!acquireIntegrityLock()) process.exit(0);
|
|
16
|
+
// Spawned detached so quitting the TUI does not kill a mid-scan worker; a hard time limit
|
|
17
|
+
// keeps a hung scan from lingering.
|
|
18
|
+
setTimeout(() => done(1), 10 * 60 * 1000).unref();
|
|
19
|
+
process.on("SIGTERM", () => done(1));
|
|
20
|
+
process.on("SIGINT", () => done(1));
|
|
21
|
+
|
|
22
|
+
async function main() {
|
|
23
|
+
const res = await runIntegrity();
|
|
24
|
+
const windows = {};
|
|
25
|
+
for (const [w, rep] of Object.entries(res.reports)) windows[w] = cacheEntry(rep);
|
|
26
|
+
const file = integrityCachePath();
|
|
27
|
+
const dir = dirname(file);
|
|
28
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
29
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
30
|
+
writeFileSync(tmp, JSON.stringify({ at: Date.now(), windows }), { mode: 0o600 });
|
|
31
|
+
try {
|
|
32
|
+
chmodSync(tmp, 0o600);
|
|
33
|
+
} catch {
|
|
34
|
+
/* best effort */
|
|
35
|
+
}
|
|
36
|
+
renameSync(tmp, file);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
main().then(
|
|
40
|
+
() => done(0),
|
|
41
|
+
() => done(1),
|
|
42
|
+
);
|