sigrank 0.0.175

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/connect.mjs ADDED
@@ -0,0 +1,13 @@
1
+ // connect.mjs — pure predicates for the TUI consolidation (the TUI is the whole app).
2
+ // No fs, no I/O, no side effects — unit-testable in isolation. Used by tui.mjs to
3
+ // decide sign-in state and to classify keystrokes while the Connect code field is focused.
4
+
5
+ /** True iff this device identity is signed in (bound to an operator). */
6
+ export function isSignedIn(id) {
7
+ return !!(id && id.codename && id.operator_id);
8
+ }
9
+
10
+ /** True iff `s` is a single character a connect code can contain ([A-Za-z0-9-]). */
11
+ export function isCodeChar(s) {
12
+ return typeof s === "string" && /^[A-Za-z0-9-]$/.test(s);
13
+ }
package/index.mjs ADDED
@@ -0,0 +1,390 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * SigRank MCP server + CLI entry point.
4
+ *
5
+ * The TUI is the whole app. Launch it and sign in inside it:
6
+ * npx sigrank full tabbed TUI (Dashboard / Trends / Compare /
7
+ * Board / Watch / Connect). Sign in on the Connect
8
+ * tab (paste a connect code), then [S] submits.
9
+ *
10
+ * CLI shortcuts (optional — the TUI never needs them):
11
+ * npx sigrank enroll sign in: redeem a connect code from signalaf.com
12
+ * npx sigrank submit publish your verified runs to the board
13
+ * npx sigrank board | compare | watch read / publish helpers
14
+ * npx sigrank --help full reference
15
+ *
16
+ * For AI clients (NOT human commands): in a piped/non-TTY context this starts an MCP
17
+ * stdio server; AI clients call its tools automatically. See ./tools.mjs.
18
+ *
19
+ * Pure cascade math: ./cascade.mjs | narration card: ./narrate.mjs
20
+ * Tool table + dispatcher: ./tools.mjs | Terminal UI: ./cli.mjs + ./tui.mjs
21
+ * Token-only — no transcript content.
22
+ */
23
+
24
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
25
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
26
+ import {
27
+ CallToolRequestSchema,
28
+ ListToolsRequestSchema,
29
+ ListPromptsRequestSchema,
30
+ GetPromptRequestSchema,
31
+ ListResourcesRequestSchema,
32
+ ReadResourceRequestSchema,
33
+ McpError,
34
+ ErrorCode,
35
+ } from "@modelcontextprotocol/sdk/types.js";
36
+ import { TOOLS, callTool } from "./tools.mjs";
37
+ import { runCli } from "./cli.mjs";
38
+ import { readFileSync } from "node:fs";
39
+
40
+ // FIX K: read the version from package.json (was hardcoded '0.7.0' — drifted from
41
+ // 0.11.0). The MCP server identity now tracks the published package version.
42
+ function serverVersion() {
43
+ try {
44
+ const pkg = JSON.parse(
45
+ readFileSync(new URL("./package.json", import.meta.url), "utf-8"),
46
+ );
47
+ return pkg.version || "0.0.0";
48
+ } catch {
49
+ return "0.0.0";
50
+ }
51
+ }
52
+
53
+ // Prevent silent crashes — log to stderr (MCP clients read stdout; stderr is safe for
54
+ // diagnostics). The process exits so the client can respawn with a clean slate rather
55
+ // than hanging on a broken connection.
56
+ process.on("uncaughtException", (err) => {
57
+ process.stderr.write(
58
+ `[sigrank-mcp] uncaughtException: ${err?.stack || err}\n`,
59
+ );
60
+ process.exit(1);
61
+ });
62
+ process.on("unhandledRejection", (reason) => {
63
+ process.stderr.write(
64
+ `[sigrank-mcp] unhandledRejection: ${reason?.stack || reason}\n`,
65
+ );
66
+ process.exit(1);
67
+ });
68
+
69
+ async function startMcpServer() {
70
+ const server = new Server(
71
+ { name: "sigrank", version: serverVersion() },
72
+ { capabilities: { tools: { listChanged: false }, prompts: { listChanged: false }, resources: { listChanged: false } } },
73
+ );
74
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
75
+ tools: TOOLS,
76
+ }));
77
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
78
+ // Unknown tool name = a client/host bug → JSON-RPC -32602 protocol error, per the MCP
79
+ // spec. isError results (below) are reserved for tools that ran and failed.
80
+ if (!TOOLS.some((t) => t.name === req.params.name)) {
81
+ throw new McpError(
82
+ ErrorCode.InvalidParams,
83
+ `Unknown tool: ${req.params.name}`,
84
+ );
85
+ }
86
+ try {
87
+ const out = await callTool(req.params.name, req.params.arguments);
88
+ return {
89
+ content: [{ type: "text", text: JSON.stringify(out, null, 2) }],
90
+ };
91
+ } catch (e) {
92
+ return {
93
+ content: [{ type: "text", text: `Error: ${e.message}` }],
94
+ isError: true,
95
+ };
96
+ }
97
+ });
98
+
99
+ // --- Prompts: interactive templates that agents can offer to users ---
100
+ const PROMPTS = [
101
+ {
102
+ name: "check-my-efficiency",
103
+ description:
104
+ "Pull your local token usage, compute your SigRank yield, and compare your efficiency against the leaderboard. Shows your class tier (Burner/Builder/10xer) and where you rank.",
105
+ arguments: [],
106
+ },
107
+ {
108
+ name: "simulate-improvement",
109
+ description:
110
+ 'Run a what-if analysis on your token mix: "if I increased my cache reads by 50k, how would my yield change?" Uses simulate_change to show the payoff before you change your workflow.',
111
+ arguments: [
112
+ {
113
+ name: "change",
114
+ description:
115
+ 'The change to simulate (e.g. "increase cache reads by 50000" or "reduce input by 100000")',
116
+ required: true,
117
+ },
118
+ ],
119
+ },
120
+ {
121
+ name: "compare-with-leader",
122
+ description:
123
+ "Fetch the top operator from the SigRank leaderboard and compare their token efficiency metrics against yours. Shows the gap and what you'd need to change to close it.",
124
+ arguments: [],
125
+ },
126
+ ];
127
+
128
+ server.setRequestHandler(ListPromptsRequestSchema, async () => ({
129
+ prompts: PROMPTS,
130
+ }));
131
+ server.setRequestHandler(GetPromptRequestSchema, async (req) => {
132
+ const name = req.params.name;
133
+ const args = req.params.arguments || {};
134
+ if (name === "check-my-efficiency") {
135
+ return {
136
+ messages: [
137
+ {
138
+ role: "user",
139
+ content: {
140
+ type: "text",
141
+ text: "Pull my local token usage with tokenpull, compute my yield, and then fetch the leaderboard so I can see where I rank. Show me my class tier and my key metrics (Yield, Leverage, Velocity).",
142
+ },
143
+ },
144
+ ],
145
+ };
146
+ }
147
+ if (name === "simulate-improvement") {
148
+ const change = args.change || "increase cache reads by 50000";
149
+ return {
150
+ messages: [
151
+ {
152
+ role: "user",
153
+ content: {
154
+ type: "text",
155
+ text: `First pull my local token usage with tokenpull to get my current pillars. Then use simulate_change to answer: "what if I ${change}?" Show me the yield delta and whether my class tier would change.`,
156
+ },
157
+ },
158
+ ],
159
+ };
160
+ }
161
+ if (name === "compare-with-leader") {
162
+ return {
163
+ messages: [
164
+ {
165
+ role: "user",
166
+ content: {
167
+ type: "text",
168
+ text: "Fetch the SigRank leaderboard with get_leaderboard, then pull my local token usage with tokenpull. Compare my yield, leverage, and velocity against the top operator. What's the gap and what would I need to change to close it?",
169
+ },
170
+ },
171
+ ],
172
+ };
173
+ }
174
+ throw new McpError(ErrorCode.InvalidParams, `Unknown prompt: ${name}`);
175
+ });
176
+
177
+ // --- Resources: static context agents can read without calling a tool ---
178
+ const RESOURCES = [
179
+ {
180
+ uri: "sigrank://scoring-formula",
181
+ name: "SigRank Scoring Formula",
182
+ description:
183
+ "The yield cascade formula and all derived metrics: Υ (Yield = Cache Reads × Output / Input²), SNR (signal-to-noise), Leverage (Cr/I), Velocity (O/I), 10xDEV score, and class tier thresholds (Burner / Builder / 10xer).",
184
+ mimeType: "text/markdown",
185
+ },
186
+ {
187
+ uri: "sigrank://class-tiers",
188
+ name: "Class Tier Definitions",
189
+ description:
190
+ "Definitions and thresholds for the three SigRank operator classes: Burner (raw volume), Builder (balanced efficiency), and 10xer (cascade-optimized). Includes the yield ranges that define each tier.",
191
+ mimeType: "text/markdown",
192
+ },
193
+ {
194
+ uri: "sigrank://install-guide",
195
+ name: "Quick Start Guide",
196
+ description:
197
+ "Step-by-step install and first submission: npx sigrank → enroll → submit. Covers ccusage/tokscale/tokendash bundled deps, privacy model (token counts only, never prompts), and dry-run workflow.",
198
+ mimeType: "text/markdown",
199
+ },
200
+ {
201
+ uri: "sigrank://privacy-model",
202
+ name: "Privacy Model",
203
+ description:
204
+ "How SigRank protects user privacy: runs locally, only four token counts (input, output, cacheCreate, cacheRead) leave the machine, ed25519-signed submissions, no prompt content ever transmitted.",
205
+ mimeType: "text/markdown",
206
+ },
207
+ ];
208
+
209
+ const RESOURCE_CONTENT = {
210
+ "sigrank://scoring-formula": `# SigRank Scoring Formula
211
+
212
+ ## Yield (Υ) — the headline metric
213
+
214
+ \`\`\`
215
+ Υ = Cache Reads × Output / Input²
216
+ \`\`\`
217
+
218
+ Yield rewards operators who maximize output while minimizing input — and who build cache to amortize that input across sessions. A high yield means you're getting more done with less, efficiently.
219
+
220
+ ## Derived Metrics
221
+
222
+ | Metric | Formula | Meaning |
223
+ |--------|---------|---------|
224
+ | **SNR** | Output / (Input + CacheCreate) | Signal-to-noise: how much of your token spend is productive output vs. overhead |
225
+ | **Leverage** | Cache Reads / Input | How well you reuse cached context — higher = better cache utilization |
226
+ | **Velocity** | Output / Input | Raw output efficiency — how much output you generate per token of input |
227
+ | **10xDEV** | Composite score | Weighted blend of yield, leverage, and velocity for cross-platform comparison |
228
+
229
+ ## Class Tier Thresholds
230
+
231
+ | Tier | Yield Range | Profile |
232
+ |------|-------------|---------|
233
+ | **Burner** | Υ < 1.0 | Raw volume — high input, low cache reuse, brute-force output |
234
+ | **Builder** | 1.0 ≤ Υ < 10.0 | Balanced — moderate cache, decent output efficiency |
235
+ | **10xer** | Υ ≥ 10.0 | Cascade-optimized — high cache reads, minimal input, efficient output |
236
+
237
+ The formula is deterministic and computed locally. No network calls needed for scoring.
238
+ `,
239
+
240
+ "sigrank://class-tiers": `# SigRank Class Tiers
241
+
242
+ Every operator is classified into one of three tiers based on their Yield (Υ = Cache Reads × Output / Input²).
243
+
244
+ ## Burner (Υ < 1.0)
245
+ - **Profile:** Raw volume operators. High input tokens, low cache reuse.
246
+ - **Behavior:** Brute-force — lots of context fed in, relatively little output back.
247
+ - **Typical:** New AI users, verbose prompters, no session continuity.
248
+ - **Fix:** Build cache across sessions. Stop re-explaining context. Use --continue.
249
+
250
+ ## Builder (1.0 ≤ Υ < 10.0)
251
+ - **Profile:** Balanced operators. Moderate cache, decent output efficiency.
252
+ - **Behavior:** Productive — reasonable input-to-output ratio, some cache leverage.
253
+ - **Typical:** Experienced AI coders who use CLAUDE.md, project context, and session continuity.
254
+ - **Fix:** Increase cache reads by reusing sessions. Reduce input by trimming unnecessary context.
255
+
256
+ ## 10xer (Υ ≥ 10.0)
257
+ - **Profile:** Cascade-optimized operators. High cache reads, minimal input, efficient output.
258
+ - **Behavior:** Surgical — minimal new input, maximum cache reuse, high-yield output.
259
+ - **Typical:** Power users with long-running sessions, tight context windows, and aggressive cache strategies.
260
+ - **Maintain:** Keep cache hit rate high. Avoid context bloat. Monitor with watch_tokenpull.
261
+
262
+ Tiers are recalculated on every submission. Your tier can change between windows (7d, 30d, 90d, all-time).
263
+ `,
264
+
265
+ "sigrank://install-guide": `# SigRank Quick Start
266
+
267
+ ## Install
268
+
269
+ \`\`\`bash
270
+ npx sigrank
271
+ \`\`\`
272
+
273
+ No global install needed. The MCP server starts automatically when an AI client (Claude, Cursor, Cline) connects.
274
+
275
+ ## First Submission
276
+
277
+ 1. **Enroll** — register your operator codename:
278
+ \`\`\`bash
279
+ npx sigrank enroll
280
+ \`\`\`
281
+
282
+ 2. **Pull + Submit** — scan your local AI session logs and publish:
283
+ \`\`\`bash
284
+ npx sigrank submit
285
+ \`\`\`
286
+
287
+ 3. **Dry Run** — see exactly what would be sent before publishing:
288
+ \`\`\`bash
289
+ npx sigrank submit --dry-run
290
+ \`\`\`
291
+
292
+ ## Token Pull Sources (bundled)
293
+
294
+ SigRank bundles three token readers as dependencies:
295
+ - **ccusage** — Claude Code session logs
296
+ - **tokscale** — multi-platform token telemetry
297
+ - **tokendash** — dashboard + TUI for token usage
298
+
299
+ No separate install needed. All three are called automatically by the tokenpull tools.
300
+
301
+ ## MCP Client Setup
302
+
303
+ Add to your MCP client config:
304
+ \`\`\`json
305
+ {
306
+ "mcpServers": {
307
+ "sigrank": {
308
+ "command": "npx",
309
+ "args": ["sigrank"]
310
+ }
311
+ }
312
+ }
313
+ \`\`\`
314
+
315
+ ## Live Board
316
+
317
+ Visit https://signalaf.com to see the global leaderboard.
318
+ `,
319
+
320
+ "sigrank://privacy-model": `# SigRank Privacy Model
321
+
322
+ ## What leaves your machine
323
+
324
+ **Only four numbers per submission:**
325
+ - Input tokens
326
+ - Output tokens
327
+ - Cache create tokens
328
+ - Cache read tokens
329
+
330
+ **That's it.** No prompts, no code, no file contents, no conversation text.
331
+
332
+ ## How it works
333
+
334
+ 1. **Local-first:** All token pulling happens on your machine. SigRank reads session logs from ~/.claude, ~/.codex, ~/.local/share/amp, etc.
335
+ 2. **Token counts only:** The MCP tools extract integer counts from log metadata. The actual content of your conversations is never read, parsed, or transmitted.
336
+ 3. **Signed submission:** Submissions are ed25519-signed. The board verifies authenticity without seeing your data.
337
+ 4. **No auth required:** No API keys, no OAuth, no account needed to read the leaderboard. Enrollment only requires a codename.
338
+
339
+ ## What SigRank can NOT see
340
+
341
+ - Your prompts or messages
342
+ - Your code or file contents
343
+ - Your tool calls or their results
344
+ - Which AI platform you use (beyond token counts)
345
+ - Your identity (only your chosen codename)
346
+
347
+ ## Verification
348
+
349
+ The submit_verified tool uses ed25519 signing. The board's source_attestations table records the signature for audit. You can verify your own submissions via get_operator.
350
+ `,
351
+ };
352
+
353
+ server.setRequestHandler(ListResourcesRequestSchema, async () => ({
354
+ resources: RESOURCES,
355
+ }));
356
+ server.setRequestHandler(ReadResourceRequestSchema, async (req) => {
357
+ const uri = req.params.uri;
358
+ const content = RESOURCE_CONTENT[uri];
359
+ if (!content) {
360
+ throw new McpError(ErrorCode.InvalidParams, `Unknown resource: ${uri}`);
361
+ }
362
+ return {
363
+ contents: [
364
+ {
365
+ uri,
366
+ mimeType: "text/markdown",
367
+ text: content,
368
+ },
369
+ ],
370
+ };
371
+ });
372
+
373
+ await server.connect(new StdioServerTransport());
374
+ }
375
+
376
+ // Route:
377
+ // any arg → the CLI (runCli shows help + exits non-zero on unknown commands,
378
+ // so a typo never silently starts a hung MCP stdio server on a TTY)
379
+ // no args + TTY stdout → full tabbed TUI (interactive use)
380
+ // no args + piped → MCP stdio server (AI client use)
381
+ const cliArgs = process.argv.slice(2);
382
+ if (cliArgs.length > 0) {
383
+ runCli(process.argv);
384
+ } else if (process.stdout.isTTY) {
385
+ // Interactive terminal — launch the full tabbed TUI
386
+ const { runTui } = await import("./tui.mjs");
387
+ runTui();
388
+ } else {
389
+ startMcpServer();
390
+ }
package/keystore.mjs ADDED
@@ -0,0 +1,242 @@
1
+ // keystore.mjs — local ed25519 device identity for SigRank signed submit (D7 §4.5).
2
+ //
3
+ // Persists a per-device keypair at ~/.sigrank-mcp/identity.json (dir 0700, file 0600).
4
+ // The PRIVATE key never leaves this machine; only the raw 32-byte public key (as
5
+ // "ed25519:<base64>") is sent to the server at enroll time. The device_id (uuid) is
6
+ // generated once and is the immutable binding target server-side.
7
+ //
8
+ // Public-key export MUST match the server's publicKeyFromAgent: generateKeyPairSync
9
+ // exports SPKI DER with a 12-byte prefix; we strip it to the raw 32 bytes, base64 it,
10
+ // and prefix "ed25519:". The server re-adds the SPKI prefix to verify. Round-trip is
11
+ // locked by sign.test.mjs + the canon-parity fixture.
12
+
13
+ import { homedir } from "node:os";
14
+ import { join } from "node:path";
15
+ import {
16
+ mkdirSync,
17
+ readFileSync,
18
+ writeFileSync,
19
+ existsSync,
20
+ chmodSync,
21
+ unlinkSync,
22
+ readdirSync,
23
+ copyFileSync,
24
+ } from "node:fs";
25
+ import { generateKeyPairSync, randomUUID } from "node:crypto";
26
+
27
+ const DIR = join(homedir(), ".sigrank-mcp");
28
+ const PATH = join(DIR, "identity.json");
29
+ const BACKUP_PREFIX = "identity.json.bak-";
30
+ const MAX_BACKUPS = 5;
31
+
32
+ /** SPKI DER prefix length for an ed25519 public key (12 bytes before the raw 32). */
33
+ const SPKI_PREFIX_LEN = 12;
34
+
35
+ /** Resolve this package's version for the agent_version stamp (best-effort). */
36
+ function agentVersion() {
37
+ try {
38
+ const pkg = JSON.parse(
39
+ readFileSync(new URL("./package.json", import.meta.url), "utf-8"),
40
+ );
41
+ return `sigrank-mcp/${pkg.version}`;
42
+ } catch {
43
+ return "sigrank-mcp";
44
+ }
45
+ }
46
+
47
+ export function keystorePath() {
48
+ return PATH;
49
+ }
50
+
51
+ /** Read the stored identity, or null if absent/corrupt. */
52
+ export function loadIdentity() {
53
+ if (!existsSync(PATH)) return null;
54
+ try {
55
+ return JSON.parse(readFileSync(PATH, "utf-8"));
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+
61
+ /** Write the identity with strict perms (dir 0700, file 0600). Backs up the existing
62
+ * file before overwriting so a corrupt write or accidental reset can be recovered. */
63
+ export function persistIdentity(identity) {
64
+ mkdirSync(DIR, { recursive: true });
65
+ try {
66
+ chmodSync(DIR, 0o700);
67
+ } catch {
68
+ /* best-effort on platforms without chmod */
69
+ }
70
+ // Back up the existing identity before overwriting (resilience: if the write
71
+ // fails or the file is later lost, the backup carries the binding + keys).
72
+ if (existsSync(PATH)) {
73
+ try {
74
+ const stamp = Date.now();
75
+ copyFileSync(PATH, join(DIR, `${BACKUP_PREFIX}${stamp}`));
76
+ pruneBackups();
77
+ } catch {
78
+ /* best-effort — don't block the write */
79
+ }
80
+ }
81
+ writeFileSync(PATH, `${JSON.stringify(identity, null, 2)}\n`, {
82
+ mode: 0o600,
83
+ });
84
+ try {
85
+ chmodSync(PATH, 0o600);
86
+ } catch {
87
+ /* best-effort */
88
+ }
89
+ return identity;
90
+ }
91
+
92
+ /** Build a fresh keypair record (pure — no fs). Exposed for tests. */
93
+ export function generateIdentity({ device_id } = {}) {
94
+ const { publicKey, privateKey } = generateKeyPairSync("ed25519");
95
+ const spki = publicKey.export({ type: "spki", format: "der" });
96
+ const rawPub = Buffer.from(spki).subarray(SPKI_PREFIX_LEN); // the raw 32 bytes
97
+ const pkcs8 = privateKey.export({ type: "pkcs8", format: "der" });
98
+ return {
99
+ device_id: device_id || randomUUID(),
100
+ codename: null,
101
+ operator_id: null,
102
+ public_key: `ed25519:${rawPub.toString("base64")}`,
103
+ private_key_pkcs8_b64: Buffer.from(pkcs8).toString("base64"),
104
+ agent_version: agentVersion(),
105
+ enrolled_at: null,
106
+ };
107
+ }
108
+
109
+ /**
110
+ * Decide the binding (codename/operator_id/enrolled_at) to carry onto a freshly
111
+ * generated identity. The binding is tied to device_id: if device_id is CHANGING
112
+ * (a new device, e.g. after a reset/re-enroll where the old file was deleted), the
113
+ * old binding is INVALIDATED — never preserve a stale codename/operator onto a
114
+ * different device. That mismatch is the "Frankenstein identity" root cause: a new
115
+ * device_id + an old codename → the server sees a mismatch → tags submissions
116
+ * `unverified` → never ranks, yet `isSignedIn` reads the local codename as present.
117
+ * Only reuse the binding when the SAME device_id is being kept. Pure — exposed for
118
+ * tests (no fs, so the owner's live identity is never at risk during a test run).
119
+ */
120
+ export function bindingForFreshIdentity(existing, fresh) {
121
+ if (!existing)
122
+ return { codename: null, operator_id: null, enrolled_at: null };
123
+ if (existing.device_id && fresh.device_id === existing.device_id) {
124
+ return {
125
+ codename: existing.codename ?? null,
126
+ operator_id: existing.operator_id ?? null,
127
+ enrolled_at: existing.enrolled_at ?? null,
128
+ };
129
+ }
130
+ // device_id changed → the old binding belongs to a different device; drop it.
131
+ return { codename: null, operator_id: null, enrolled_at: null };
132
+ }
133
+
134
+ /**
135
+ * Load the existing identity, or generate + persist a fresh one. Idempotent: a
136
+ * complete existing identity is returned untouched (never rotates a live key).
137
+ * Self-healing: if the identity has keys + device_id but no codename (binding
138
+ * lost via partial write / version transition), scans backups for a matching
139
+ * device_id and restores the binding before returning.
140
+ */
141
+ export function ensureIdentity() {
142
+ const existing = loadIdentity();
143
+ if (
144
+ existing?.private_key_pkcs8_b64 &&
145
+ existing?.public_key &&
146
+ existing?.device_id
147
+ ) {
148
+ // Self-healing: keys present but binding lost → try to restore from backups.
149
+ if (!existing.codename || !existing.operator_id) {
150
+ const restored = restoreBindingFromBackups(existing.device_id);
151
+ if (restored) {
152
+ existing.codename = restored.codename;
153
+ existing.operator_id = restored.operator_id;
154
+ existing.enrolled_at = restored.enrolled_at;
155
+ return persistIdentity(existing);
156
+ }
157
+ }
158
+ return existing;
159
+ }
160
+ // Regeneration path: a partial/corrupt record. The binding is tied to device_id —
161
+ // if a new device_id is generated, the old codename/operator MUST NOT carry over
162
+ // (bindingForFreshIdentity drops them). Only a reused device_id keeps its binding.
163
+ const fresh = generateIdentity({ device_id: existing?.device_id });
164
+ const binding = bindingForFreshIdentity(existing, fresh);
165
+ fresh.codename = binding.codename;
166
+ fresh.operator_id = binding.operator_id;
167
+ fresh.enrolled_at = binding.enrolled_at;
168
+ return persistIdentity(fresh);
169
+ }
170
+
171
+ /** Record a successful enrollment (codename/operator_id + enrolled_at) into the keystore. */
172
+ export function recordEnrollment({ codename, operator_id }) {
173
+ const id = ensureIdentity();
174
+ // OVERWRITE from the server's enroll response — a new enroll is a new binding, full
175
+ // stop. Never `??`-preserve a stale codename/operator onto this device (the other
176
+ // half of the Frankenstein bug: a re-enroll used to keep the old codename when the
177
+ // new one was absent). A 201 enrolled always carries both.
178
+ id.codename = codename ?? null;
179
+ id.operator_id = operator_id ?? null;
180
+ id.enrolled_at = new Date().toISOString();
181
+ return persistIdentity(id);
182
+ }
183
+
184
+ /** Clear the local identity (sign out). Next enroll provisions a fresh device_id. */
185
+ export function clearIdentity() {
186
+ try {
187
+ if (existsSync(PATH)) unlinkSync(PATH);
188
+ } catch {
189
+ /* best-effort */
190
+ }
191
+ }
192
+
193
+ /** Keep at most MAX_BACKUPS backup files (oldest deleted first). */
194
+ function pruneBackups() {
195
+ try {
196
+ const files = readdirSync(DIR)
197
+ .filter((f) => f.startsWith(BACKUP_PREFIX))
198
+ .sort(); // timestamp-suffixed → lexicographic = chronological
199
+ while (files.length > MAX_BACKUPS) {
200
+ unlinkSync(join(DIR, files.shift()));
201
+ }
202
+ } catch {
203
+ /* best-effort */
204
+ }
205
+ }
206
+
207
+ /** Scan backup files for one with the same device_id that carries a codename +
208
+ * operator_id binding. Returns { codename, operator_id, enrolled_at } or null.
209
+ * Used by ensureIdentity() to self-heal when the live file lost its binding
210
+ * (e.g. a partial write or version transition that preserved keys but dropped
211
+ * the binding metadata). Only restores from a backup with the SAME device_id —
212
+ * never crosses device boundaries (Frankenstein-identity guard). */
213
+ export function restoreBindingFromBackups(device_id) {
214
+ if (!device_id) return null;
215
+ try {
216
+ const files = readdirSync(DIR)
217
+ .filter((f) => f.startsWith(BACKUP_PREFIX))
218
+ .sort()
219
+ .reverse(); // newest first — prefer the most recent binding
220
+ for (const f of files) {
221
+ try {
222
+ const bak = JSON.parse(readFileSync(join(DIR, f), "utf-8"));
223
+ if (
224
+ bak.device_id === device_id &&
225
+ bak.codename &&
226
+ bak.operator_id
227
+ ) {
228
+ return {
229
+ codename: bak.codename,
230
+ operator_id: bak.operator_id,
231
+ enrolled_at: bak.enrolled_at ?? null,
232
+ };
233
+ }
234
+ } catch {
235
+ /* skip corrupt backups */
236
+ }
237
+ }
238
+ } catch {
239
+ /* best-effort */
240
+ }
241
+ return null;
242
+ }