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.
@@ -0,0 +1,54 @@
1
+ /**
2
+ * tools/check-integrity.mjs — check_integrity tool.
3
+ *
4
+ * Read-only Tokenpull Integrity: runs the vendored checks over your LOCAL Claude Code
5
+ * transcripts and stored collector rows. Nothing is sent or signed.
6
+ */
7
+
8
+ import { INTEGRITY_OUTPUT, ANNOTATIONS } from "./_schemas.mjs";
9
+ import {
10
+ INTEGRITY_WINDOWS,
11
+ runIntegrity,
12
+ windowView,
13
+ flagCount,
14
+ overallLine,
15
+ } from "../lib/integrity.mjs";
16
+
17
+ export const TOOL_DEF = {
18
+ name: "check_integrity",
19
+ description:
20
+ "Run Tokenpull Integrity over your LOCAL data and report, per window (7d/30d/90d/all-time), each check's result: flags, score, flag codes, and a few samples as transcript-file ordinal + line number. Checks cover record integrity, agreement between transcripts and the live collector, cache pumping, and double counting. A flag means 'worth a look', not 'cheating'. Reads Claude Code session logs and stored collector rows on this machine; no text, paths or session ids are returned, and nothing is sent or signed. Returns the tool version and hash so a run can be reproduced. To attach a scores-and-counts summary to a signed submission, use submit_verified with integrity: true.",
21
+ annotations: { title: "Check integrity", ...ANNOTATIONS.readOnlyHint, ...ANNOTATIONS.openWorldHint },
22
+ inputSchema: {
23
+ type: "object",
24
+ properties: {
25
+ window: {
26
+ type: "string",
27
+ enum: ["7d", "30d", "90d", "all"],
28
+ description: "check only this window (default: all 4)",
29
+ },
30
+ },
31
+ },
32
+ outputSchema: INTEGRITY_OUTPUT,
33
+ };
34
+
35
+ export async function handleCheckIntegrity(args, ctx) {
36
+ const windows = args?.window !== undefined ? [args.window] : INTEGRITY_WINDOWS;
37
+ if (!INTEGRITY_WINDOWS.includes(windows[0])) {
38
+ return { status: "error", reason: "bad_window", detail: `window must be one of ${INTEGRITY_WINDOWS.join(", ")}.` };
39
+ }
40
+ const io = ctx?.opts?.integrity || {};
41
+ const res = await runIntegrity({ windows, roots: io.roots, dataDir: io.dataDir, now: ctx?.opts?.now ?? io.now });
42
+ const reps = windows.map((w) => res.reports[w]);
43
+ const total = reps.reduce((n, r) => n + flagCount(r), 0);
44
+ return {
45
+ tool: res.tool,
46
+ version: res.version,
47
+ hash: res.hash,
48
+ overall:
49
+ reps.length === 1
50
+ ? overallLine(reps[0])
51
+ : `${total} flag${total === 1 ? "" : "s"} across ${reps.length} windows · ${res.tool} v${res.version} (${res.hash}) · a flag means worth a look, not cheating · local only, nothing sent`,
52
+ windows: reps.map(windowView),
53
+ };
54
+ }
package/tools/index.mjs CHANGED
@@ -25,6 +25,7 @@ import { TOOL_DEF as tokenpullSubmitTool, handleTokenpullSubmit } from "./tokenp
25
25
  import { TOOL_DEF as rankWindowsTool, handleRankWindows } from "./rank-windows.mjs";
26
26
  import { TOOL_DEF as watchTokenpullTool, handleWatchTokenpull } from "./watch-tokenpull.mjs";
27
27
  import { TOOL_DEF as tokenpullCompareTool, handleTokenpullCompare } from "./tokenpull-compare.mjs";
28
+ import { TOOL_DEF as checkIntegrityTool, handleCheckIntegrity } from "./check-integrity.mjs";
28
29
  import { TOOL_DEF as enrollTool, handleEnroll } from "./enroll.mjs";
29
30
  import { TOOL_DEF as submitVerifiedTool, handleSubmitVerified } from "./submit-verified.mjs";
30
31
  import { TOOL_DEF as simulateChangeTool, handleSimulateChange } from "./simulate-change.mjs";
@@ -59,6 +60,7 @@ export const TOOLS = [
59
60
  rankWindowsTool,
60
61
  watchTokenpullTool,
61
62
  tokenpullCompareTool,
63
+ checkIntegrityTool,
62
64
  enrollTool,
63
65
  submitVerifiedTool,
64
66
  simulateChangeTool,
@@ -211,6 +213,8 @@ export async function callTool(name, args, opts = {}) {
211
213
  return handleWatchTokenpull(args, ctx);
212
214
  case "tokenpull_compare":
213
215
  return handleTokenpullCompare(args, ctx);
216
+ case "check_integrity":
217
+ return handleCheckIntegrity(args, ctx);
214
218
  case "enroll":
215
219
  return handleEnroll(args, ctx);
216
220
  case "submit_verified":
@@ -9,11 +9,20 @@ import { SUBMIT_OUTPUT, ANNOTATIONS } from "./_schemas.mjs";
9
9
  import { collectMultiPlatforms, multiAbortResult } from "./_multi.mjs";
10
10
  import { pullByPlatform, WINDOW_TYPE } from "./_helpers.mjs";
11
11
  import { _computeReportBlock } from "./_report.mjs";
12
+ import { runIntegrity, integrityBlock, INTEGRITY_SERVER_ACCEPTS } from "../lib/integrity.mjs";
13
+ import { normalizeSource, OTEL_SOURCE_TAG } from "../adapters/otel.mjs";
14
+ import {
15
+ evaluatePublication,
16
+ measureWindow,
17
+ otelSubmissionMeta,
18
+ publicationFields,
19
+ turnsBasis,
20
+ } from "../submit/publication.mjs";
12
21
 
13
22
  export const TOOL_DEF = {
14
23
  name: "submit_verified",
15
24
  description:
16
- "Publish your LOCAL token runs to the SigRank board as a VERIFIED operator — the enrolled, signed path. Reads your pillars (tokenpull), builds the canonical Schema 1.0 snapshot per window, ed25519-signs it with your device key, and POSTs to /api/v1/snapshots. Requires `npx sigrank enroll` first (a bound device). Only signed submissions from a trusted device rank on the board. Token-only; the private key never leaves your machine. Publishing requires `confirm: true` (ask the user first); pass dry_run:true to inspect the exact signed payload without publishing and without confirm.",
25
+ "Publish your LOCAL token runs to the SigRank board as a VERIFIED operator — the enrolled, signed path. Reads your pillars (tokenpull), builds the canonical Schema 1.0 snapshot per window, ed25519-signs it with your device key, and POSTs to /api/v1/snapshots. Requires `npx sigrank enroll` first (a bound device). Only signed submissions from a trusted device rank on the board. Token-only; the private key never leaves your machine. Publishing requires `confirm: true` (ask the user first); pass dry_run:true to inspect the exact signed payload without publishing and without confirm. Optional `integrity: true` (default off) adds a Tokenpull Integrity block to the signed snapshot: per-check flag counts and scores plus the tool version and hash, no text, line numbers or session ids (Claude only; run check_integrity first to see the detail).",
17
26
  annotations: {
18
27
  title: "Submit verified score",
19
28
  ...ANNOTATIONS.destructiveHint,
@@ -34,11 +43,22 @@ export const TOOL_DEF = {
34
43
  description:
35
44
  "source platform (default: claude). 'multi' = combined cascade summed across all locally-detected platforms (needs 2+ active); empty windows are skipped.",
36
45
  },
46
+ source: {
47
+ type: "string",
48
+ enum: ["auto", "otel", "transcripts"],
49
+ description:
50
+ "Default transcripts. auto/otel read the local collector (Claude only) and may publish only when every window reports complete coverage and real turns/sessions; otherwise they are dry-run preview only and the blockers are returned.",
51
+ },
37
52
  confirm: {
38
53
  type: "boolean",
39
54
  description:
40
55
  "REQUIRED to publish: must be true, set only after the user has explicitly approved submitting. Not needed with dry_run:true.",
41
56
  },
57
+ integrity: {
58
+ type: "boolean",
59
+ description:
60
+ "default false. When true, add an `integrity` block (tool, version, hash, window, per-check flags/score/codes, flagCount) to each signed snapshot. Scores and counts only. Claude platform only. Use dry_run:true to see the block before publishing.",
61
+ },
42
62
  dry_run: {
43
63
  type: "boolean",
44
64
  description:
@@ -66,6 +86,42 @@ export async function handleSubmitVerified(args, ctx) {
66
86
  };
67
87
  }
68
88
  const platform = args?.platform || "claude";
89
+ const source = normalizeSource(args?.source ?? ctx.opts.source);
90
+ if (source !== "transcripts" && platform !== "claude") {
91
+ return { status: "error", reason: "otel_preview_only", detail: "The collector source is Claude-only; use source: transcripts for other platforms and multi.", windows: [] };
92
+ }
93
+ const pullOpts = { ...ctx.opts, source };
94
+
95
+ // Optional integrity block (default off). Claude transcripts only: the checks read
96
+ // Claude Code logs, so a block on another platform or on the combined cascade would
97
+ // describe data the snapshot does not contain.
98
+ const wantIntegrity = args?.integrity === true;
99
+ if (wantIntegrity && platform !== "claude") {
100
+ return { status: "error", reason: "integrity_claude_only", detail: "integrity: true is available for platform: claude only.", windows: [] };
101
+ }
102
+ if (wantIntegrity && !args?.dry_run && !INTEGRITY_SERVER_ACCEPTS) {
103
+ return {
104
+ status: "error",
105
+ reason: "integrity_not_accepted_yet",
106
+ detail: "The board does not accept an integrity block yet (its snapshot schema is strict). Use dry_run: true to inspect the block, or publish without integrity.",
107
+ windows: [],
108
+ };
109
+ }
110
+ let integrityRun = null;
111
+ if (wantIntegrity) {
112
+ try {
113
+ integrityRun = await runIntegrity({
114
+ windows: args?.window ? [args.window] : undefined,
115
+ roots: ctx.opts.integrity?.roots,
116
+ dataDir: ctx.opts.integrity?.dataDir,
117
+ now: ctx.opts.now,
118
+ });
119
+ } catch (e) {
120
+ return { status: "error", reason: "integrity_failed", detail: `Integrity checks failed to run: ${e.message}. Nothing was sent; retry, or submit without integrity.`, windows: [] };
121
+ }
122
+ }
123
+ const integrityFor = (wk) =>
124
+ integrityRun?.reports?.[wk] ? { integrity: integrityBlock(integrityRun.reports[wk]) } : {};
69
125
 
70
126
  // MULTI: the combined cross-platform cascade. The dashboard already SUMS every
71
127
  // active platform's pillars (a "claude+codex" row) but never submitted it — this
@@ -73,7 +129,7 @@ export async function handleSubmitVerified(args, ctx) {
73
129
  // per window and publish as platform='multi' = the operator's TOTAL usage. Empty
74
130
  // windows are skipped so a no-activity window never lands as a degenerate row.
75
131
  if (platform === "multi") {
76
- const { detected, failed } = await collectMultiPlatforms(ctx.opts);
132
+ const { detected, failed } = await collectMultiPlatforms(pullOpts);
77
133
  if (failed.length) return multiAbortResult(failed, { codename: id.codename, operator_id: id.operator_id });
78
134
  if (detected.length < 2) {
79
135
  return {
@@ -93,6 +149,12 @@ export async function handleSubmitVerified(args, ctx) {
93
149
  for (const wk of winKeys) {
94
150
  const sum = { input: 0, output: 0, cacheCreate: 0, cacheRead: 0 };
95
151
  let msgs = 0;
152
+ // Per platform: real turns/sessions where the reader supplied them, the
153
+ // message proxy (turns = messages, sessions = messages/8) for the rest; summed.
154
+ let turns = 0,
155
+ sessions = 0,
156
+ realN = 0,
157
+ proxyN = 0;
96
158
  for (const d of detected) {
97
159
  const w = (d.windows || []).find((x) => x.window === wk);
98
160
  if (!w) continue;
@@ -101,6 +163,15 @@ export async function handleSubmitVerified(args, ctx) {
101
163
  sum.cacheCreate += w.pillars.cacheCreate || 0;
102
164
  sum.cacheRead += w.pillars.cacheRead || 0;
103
165
  msgs += w.messages || 0;
166
+ if (turnsBasis(w) === "real") {
167
+ turns += w.turns;
168
+ sessions += Math.max(1, w.sessions);
169
+ realN++;
170
+ } else if ((w.messages || 0) > 0) {
171
+ turns += w.messages;
172
+ sessions += Math.max(1, Math.round(w.messages / 8));
173
+ proxyN++;
174
+ }
104
175
  }
105
176
  if (sum.input + sum.output + sum.cacheCreate + sum.cacheRead <= 0)
106
177
  continue; // skip empty window
@@ -113,8 +184,15 @@ export async function handleSubmitVerified(args, ctx) {
113
184
  dryRun: !!args?.dry_run,
114
185
  force: !!ctx.opts.force,
115
186
  report,
187
+ turns,
188
+ sessions,
189
+ });
190
+ out.push({
191
+ window: wk,
192
+ pillars: sum,
193
+ turns_source: !proxyN ? "real" : realN ? "mixed" : "proxy",
194
+ ...r,
116
195
  });
117
- out.push({ window: wk, pillars: sum, ...r });
118
196
  }
119
197
  return {
120
198
  platform: "multi",
@@ -125,7 +203,24 @@ export async function handleSubmitVerified(args, ctx) {
125
203
  };
126
204
  }
127
205
 
128
- const pulled = await pullByPlatform(platform, ctx.opts);
206
+ const pulled = await pullByPlatform(platform, pullOpts);
207
+ // Collector claims never unlock publishing alone: cross-check against our own
208
+ // transcript count for the same platform (and use it for turns/sessions).
209
+ const local =
210
+ pulled.source === OTEL_SOURCE_TAG
211
+ ? await pullByPlatform(platform, { ...pullOpts, source: "transcripts" }).catch(() => null)
212
+ : undefined;
213
+ const pub = evaluatePublication(pulled, local, { window: args?.window });
214
+ if (!pub.eligible && !args?.dry_run) {
215
+ return {
216
+ status: "error",
217
+ reason: "otel_preview_only",
218
+ detail: `Collector data is not publication-verified (blocked: ${pub.blocked.join(", ") || "all"}): ${pub.reasons.join("; ")}. Fix the collector, or publish with source: transcripts.`,
219
+ blockers: pub.reasons,
220
+ source: pulled.source,
221
+ windows: [],
222
+ };
223
+ }
129
224
  const targets = args?.window
130
225
  ? pulled.windows.filter((w) => w.window === args.window)
131
226
  : pulled.windows;
@@ -142,14 +237,31 @@ export async function handleSubmitVerified(args, ctx) {
142
237
  dryRun: !!args?.dry_run,
143
238
  force: !!ctx.opts.force,
144
239
  report,
240
+ ...measureWindow(w, local),
241
+ ...integrityFor(w.window),
242
+ });
243
+ const sent = integrityFor(w.window);
244
+ if (sent.integrity && r.httpStatus >= 400 && r.httpStatus < 500) {
245
+ const why = r.detail || r.reason;
246
+ r.reason = "integrity_block_rejected";
247
+ r.detail = `The board rejected this snapshot with HTTP ${r.httpStatus} and it carried an integrity block (${why}). The integrity block may be the cause; retry without integrity: true.`;
248
+ }
249
+ out.push({
250
+ window: w.window,
251
+ pillars: w.pillars,
252
+ turns_source: measureWindow(w, local).turns_source,
253
+ ...(pulled.source === OTEL_SOURCE_TAG ? { source_meta: otelSubmissionMeta(w) } : {}),
254
+ ...r,
145
255
  });
146
- out.push({ window: w.window, pillars: w.pillars, ...r });
147
256
  }
148
257
  return {
149
258
  platform: pulled.platform,
150
259
  codename: id.codename,
151
260
  operator_id: id.operator_id,
152
261
  generatedAt: pulled.generatedAt,
262
+ source: pulled.source,
263
+ ...publicationFields(pulled, pub),
264
+ ...(pulled.otelFallback ? { otel_fallback: pulled.otelFallback } : {}),
153
265
  windows: out,
154
266
  };
155
267
  }
@@ -2,6 +2,7 @@
2
2
  * tools/tokenpull.mjs — tokenpull tool.
3
3
  */
4
4
 
5
+ import { publicationFields } from "../submit/publication.mjs";
5
6
  import { cascade } from "../analytics/cascade.mjs";
6
7
  import { narrate } from "../presentation/narrate.mjs";
7
8
  import { ALL_PLATFORMS } from "../adapters/index.mjs";
@@ -94,6 +95,9 @@ export async function handleTokenpull(args, ctx) {
94
95
  estimated: pulled.estimated || false,
95
96
  ...(pulled.ioRatio ? { ioRatio: pulled.ioRatio } : {}),
96
97
  generatedAt: pulled.generatedAt,
98
+ ...(pulled.source ? { source: pulled.source } : {}),
99
+ ...publicationFields(pulled),
100
+ ...(pulled.otelFallback ? { otel_fallback: pulled.otelFallback } : {}),
97
101
  files: pulled.files,
98
102
  totalMessages: pulled.totalMessages,
99
103
  windows,
@@ -8,6 +8,8 @@ import { ALL_PLATFORMS } from "../adapters/index.mjs";
8
8
  import { ensureIdentity } from "../identity/keystore.mjs";
9
9
  import { submitSignedWindow } from "../submit/index.mjs";
10
10
  import { TOKENPULL_OUTPUT, ANNOTATIONS } from "./_schemas.mjs";
11
+ import { normalizeSource, sourceMarker } from "../adapters/otel.mjs";
12
+ import { evaluatePublication, measureWindow, publicationFields } from "../submit/publication.mjs";
11
13
  import {
12
14
  pullByPlatform,
13
15
  WATCH_SUBMIT_COOLDOWN_MS,
@@ -42,6 +44,12 @@ export const TOOL_DEF = {
42
44
  description:
43
45
  "which window to watch (default: 7d — most sensitive to recent activity)",
44
46
  },
47
+ source: {
48
+ type: "string",
49
+ enum: ["auto", "otel", "transcripts"],
50
+ description:
51
+ "Default transcripts. auto = collector if reachable, else transcripts; otel = collector required. Collector sources publish only when coverage is complete and turns are real; otherwise preview-only.",
52
+ },
45
53
  submit: {
46
54
  type: "boolean",
47
55
  description:
@@ -69,7 +77,8 @@ export async function handleWatchTokenpull(args, ctx) {
69
77
  const watchWindow = args?.window || "7d";
70
78
  const intervalS = Math.max(10, Number(args?.interval_s) || 60);
71
79
 
72
- const pulled = await pullByPlatform(platform, ctx.opts);
80
+ const source = normalizeSource(args?.source ?? ctx.opts.source);
81
+ const pulled = await pullByPlatform(platform, { ...ctx.opts, source });
73
82
  const win = pulled.windows.find((w) => w.window === watchWindow);
74
83
  if (!win)
75
84
  throw new Error(
@@ -83,12 +92,20 @@ export async function handleWatchTokenpull(args, ctx) {
83
92
  // watched window to the verified ingest path. Default OFF = preview only. The server
84
93
  // dedups identical re-submits (exact snapshot_hash → 422), so re-calling is safe.
85
94
  let auth_submit = null;
95
+ // One evaluation for this window; the transcript cross-check runs only when publishing.
96
+ const local =
97
+ args?.submit === true && args?.confirm === true && pulled.source === "otel-cc"
98
+ ? await pullByPlatform(platform, { ...ctx.opts, source: "transcripts" }).catch(() => null)
99
+ : undefined;
100
+ const pub = evaluatePublication(pulled, local, { window: watchWindow });
86
101
  if (args?.submit === true && args?.confirm !== true) {
87
102
  auth_submit = {
88
103
  status: "confirmation_required",
89
104
  detail:
90
105
  "watch_tokenpull with submit:true publishes to the public board. Ask the user for approval, then call again with confirm: true.",
91
106
  };
107
+ } else if (args?.submit === true && !pub.eligible) {
108
+ auth_submit = { status: "error", reason: "otel_preview_only", detail: `Collector data is not publication-verified (blocked: ${pub.blocked.join(", ") || watchWindow}): ${pub.reasons.join("; ")}. Fix the collector, or use source: transcripts.`, blockers: pub.reasons };
92
109
  } else if (args?.submit === true) {
93
110
  const id = ctx.opts.identity || ensureIdentity();
94
111
  if (id.codename && id.operator_id && id.private_key_pkcs8_b64) {
@@ -118,6 +135,7 @@ export async function handleWatchTokenpull(args, ctx) {
118
135
  fetchImpl: ctx.doFetch,
119
136
  platform: pulled.platform,
120
137
  now: ctx.opts.now,
138
+ ...measureWindow(win, local),
121
139
  },
122
140
  );
123
141
  if (auth_submit?.status !== "error")
@@ -139,6 +157,10 @@ export async function handleWatchTokenpull(args, ctx) {
139
157
  card,
140
158
  generatedAt: pulled.generatedAt,
141
159
  poll_interval_s: intervalS,
160
+ source: pulled.source,
161
+ source_marker: sourceMarker(pulled),
162
+ ...(pulled.source === "otel-cc" ? { source_grade: win.grade, ...publicationFields(pulled, pub) } : {}),
163
+ ...(pulled.otelFallback ? { otel_fallback: pulled.otelFallback } : {}),
142
164
  auth_submit,
143
165
  note: "One snapshot per call — re-call at your poll interval to detect changes.",
144
166
  };