@tpsdev-ai/flair 0.56.0 → 0.58.0

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 (153) hide show
  1. package/README.md +19 -20
  2. package/SECURITY.md +4 -1
  3. package/dist/build-info.json +3 -3
  4. package/dist/cli.js +1800 -293
  5. package/dist/commands/agent.js +22 -15
  6. package/dist/commands/bridge.js +40 -3
  7. package/dist/commands/doctor.js +214 -4
  8. package/dist/commands/federation.js +265 -38
  9. package/dist/commands/hook.js +10 -2
  10. package/dist/commands/init.js +179 -48
  11. package/dist/commands/memory.js +24 -2
  12. package/dist/commands/quality.js +26 -18
  13. package/dist/commands/service.js +137 -22
  14. package/dist/commands/status.js +114 -3
  15. package/dist/commands/upgrade.js +204 -84
  16. package/dist/doctor-client.js +50 -4
  17. package/dist/federation/scheduler.js +253 -4
  18. package/dist/install/clients.js +89 -23
  19. package/dist/install/global-bin-path.js +26 -6
  20. package/dist/lib/atomic-write.js +256 -0
  21. package/dist/lib/auth-resolve.js +46 -0
  22. package/dist/lib/daemon-liveness.js +61 -0
  23. package/dist/lib/doctor-run.js +5 -0
  24. package/dist/lib/embed-gpu-doctor.js +49 -26
  25. package/dist/lib/federation-memory-attributes.js +15 -0
  26. package/dist/lib/init-admin-pass.js +4 -2
  27. package/dist/lib/init-listener-environ.js +38 -0
  28. package/dist/lib/init-occupied-listener.js +165 -0
  29. package/dist/lib/instance-identity-row.js +580 -0
  30. package/dist/lib/launchd-domain-preflight.js +448 -0
  31. package/dist/lib/launchd-management.js +176 -6
  32. package/dist/lib/launchd-repair.js +95 -0
  33. package/dist/lib/memory-attributes.js +77 -0
  34. package/dist/lib/node-alias-path.js +95 -0
  35. package/dist/lib/npm-registry.js +119 -6
  36. package/dist/lib/owned-pins.js +20 -6
  37. package/dist/lib/redact-token-id.js +197 -0
  38. package/dist/lib/service-repoint-apply.js +267 -0
  39. package/dist/lib/service-repoint.js +575 -0
  40. package/dist/lib/toml-string-array.js +104 -0
  41. package/dist/lib/tree-divergence.js +716 -0
  42. package/dist/lib/upgrade-plain-tree.js +18 -8
  43. package/dist/lib/upgrade-prior-liveness.js +69 -0
  44. package/dist/lib/upgrade-rollback.js +116 -0
  45. package/dist/rem/runner.js +11 -0
  46. package/dist/resources/Agent.js +27 -14
  47. package/dist/resources/AgentSeed.js +39 -2
  48. package/dist/resources/Asset.js +3 -11
  49. package/dist/resources/Credential.js +4 -10
  50. package/dist/resources/Federation.js +299 -127
  51. package/dist/resources/Integration.js +8 -32
  52. package/dist/resources/Memory.js +623 -86
  53. package/dist/resources/MemoryArchive.js +9 -0
  54. package/dist/resources/MemoryBootstrap.js +23 -12
  55. package/dist/resources/MemoryCandidate.js +3 -11
  56. package/dist/resources/MemoryDedupStats.js +1 -1
  57. package/dist/resources/MemoryFeed.js +214 -5
  58. package/dist/resources/MemoryGrant.js +19 -40
  59. package/dist/resources/MemoryHostSource.js +90 -0
  60. package/dist/resources/MemoryMaintenance.js +121 -32
  61. package/dist/resources/MemoryReflect.js +4 -1
  62. package/dist/resources/MemoryReindex.js +7 -4
  63. package/dist/resources/MemoryUsage.js +55 -18
  64. package/dist/resources/Presence.js +18 -10
  65. package/dist/resources/RecordUsage.js +30 -40
  66. package/dist/resources/Relationship.js +170 -89
  67. package/dist/resources/SemanticSearch.js +44 -19
  68. package/dist/resources/Soul.js +31 -19
  69. package/dist/resources/XAA.js +7 -3
  70. package/dist/resources/agent-auth.js +16 -10
  71. package/dist/resources/auth-middleware.js +164 -50
  72. package/dist/resources/auto-promote-lib.js +4 -4
  73. package/dist/resources/bm25-index-service.js +246 -32
  74. package/dist/resources/bm25-status.js +132 -0
  75. package/dist/resources/bm25.js +13 -14
  76. package/dist/resources/ed25519-auth.js +11 -54
  77. package/dist/resources/embed-gpu.js +262 -47
  78. package/dist/resources/embeddings-boot.js +52 -17
  79. package/dist/resources/federation-classify.js +12 -0
  80. package/dist/resources/federation-cleanup.js +289 -51
  81. package/dist/resources/federation-crypto.js +65 -19
  82. package/dist/resources/health.js +105 -22
  83. package/dist/resources/host-pointer/registry.js +35 -0
  84. package/dist/resources/host-pointer-adapter.js +15 -0
  85. package/dist/resources/host-source-visibility.js +167 -0
  86. package/dist/resources/host-source.js +151 -0
  87. package/dist/resources/in-process-api.js +2 -1
  88. package/dist/resources/instance-create-lock.js +363 -0
  89. package/dist/resources/instance-identity-rows.js +43 -0
  90. package/dist/resources/instance-identity.js +97 -12
  91. package/dist/resources/mcp-handler.js +155 -51
  92. package/dist/resources/mcp-tool-arguments.js +83 -0
  93. package/dist/resources/mcp-tools.js +28 -25
  94. package/dist/resources/memory-consolidate-lib.js +3 -1
  95. package/dist/resources/memory-declared-attributes.js +103 -0
  96. package/dist/resources/memory-feed-lib.js +5 -1
  97. package/dist/resources/memory-host-source.js +163 -0
  98. package/dist/resources/memory-visibility.js +10 -7
  99. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  100. package/dist/resources/migrations/visibility-backfill.js +4 -1
  101. package/dist/resources/originator-instance.js +235 -0
  102. package/dist/resources/promotion-stamp.js +2 -0
  103. package/dist/resources/provenance.js +111 -11
  104. package/dist/resources/rate-limit.js +6 -4
  105. package/dist/resources/record-owner-guard.js +19 -0
  106. package/dist/resources/record-type-kit.js +44 -23
  107. package/dist/resources/record-types.js +6 -6
  108. package/dist/resources/relay-ops.js +28 -3
  109. package/dist/resources/replay-store.js +289 -0
  110. package/dist/resources/request-transaction.js +78 -0
  111. package/dist/resources/search-readiness.js +26 -22
  112. package/dist/resources/semantic-retrieval-core.js +103 -4
  113. package/dist/resources/table-helpers.js +33 -0
  114. package/dist/resources/table-patch-policy.js +109 -0
  115. package/dist/resources/table-patches.js +17 -0
  116. package/dist/resources/table-post-policy.js +138 -0
  117. package/dist/resources/table-posts.js +22 -0
  118. package/dist/resources/table-subscription-policy.js +135 -0
  119. package/dist/resources/table-subscriptions.js +19 -0
  120. package/dist/resources/tool-descriptors/index.js +15 -15
  121. package/dist/resources/trust-block.js +10 -3
  122. package/dist/resources/usage-recording.js +169 -41
  123. package/dist/src/lib/instance-identity-row.js +580 -0
  124. package/dist/src/lib/memory-attributes.js +77 -0
  125. package/dist/src/lib/redact-token-id.js +197 -0
  126. package/docs/api-reference.md +80 -16
  127. package/docs/auth.md +5 -5
  128. package/docs/claude-code.md +137 -6
  129. package/docs/deploying-on-fabric.md +6 -3
  130. package/docs/deployment.md +1 -1
  131. package/docs/embedding-in-a-harper-app.md +3 -3
  132. package/docs/federation.md +17 -10
  133. package/docs/hosted-on-fabric.md +4 -3
  134. package/docs/integrations.md +28 -19
  135. package/docs/mcp-clients.md +26 -32
  136. package/docs/n8n.md +8 -8
  137. package/docs/notes/mcp-oauth-model2.md +27 -18
  138. package/docs/openclaw.md +29 -28
  139. package/docs/quickstart.md +5 -0
  140. package/docs/releasing.md +134 -2
  141. package/docs/spoke-bringup.md +14 -11
  142. package/docs/standalone-local.md +2 -2
  143. package/docs/supply-chain-policy.md +28 -10
  144. package/docs/system-requirements.md +1 -1
  145. package/docs/troubleshooting.md +11 -0
  146. package/docs/upgrade.md +189 -63
  147. package/package.json +9 -5
  148. package/schemas/agent.graphql +9 -6
  149. package/schemas/federation.graphql +2 -11
  150. package/schemas/memory.graphql +106 -17
  151. package/schemas/replay.graphql +18 -0
  152. package/templates/launchd/start-flair-with-admin-pass.sh +22 -0
  153. package/dist/resources/federation-nonce-store.js +0 -195
@@ -43,7 +43,36 @@
43
43
  * so the executor only writes when the planner says it is proven.
44
44
  */
45
45
  import { resolve } from "node:path";
46
+ import { verifyLaunchdManagement } from "./launchd-management.js";
47
+ import { healthIndicatesListener } from "./daemon-liveness.js";
46
48
  import { preserveHttpPortValue, preserveSecurePort } from "./http-bind.js";
49
+ import { renderDomainUnavailableMessage, } from "./launchd-domain-preflight.js";
50
+ // ─── launchd preflight gate (flair#2040) ──────────────────────────────────
51
+ /**
52
+ * The `doctor --fix` refusal when this instance's launchd job cannot be loaded
53
+ * from this session — a PURE gate the executor runs BEFORE it stops, unloads or
54
+ * writes anything (flair#2040).
55
+ *
56
+ * Returns null when the preflight allows an attempt (`available`, or
57
+ * `not-applicable` off macOS), so the executor proceeds. Returns a `refused`
58
+ * result — doctor reports an ISSUE, never "fixed", and exits non-zero — when
59
+ * the GUI domain is `unavailable` or `unknown` (fail closed: a probe we could
60
+ * not interpret must not license stopping a healthy instance), or when the
61
+ * job's label is `disabled` in that domain (launchd would refuse the load).
62
+ *
63
+ * The refusal carries actor + state + remedy in its `detail` (a refusal is a
64
+ * verdict, not a failure, so there is no structured remedy), and says that
65
+ * nothing was touched.
66
+ */
67
+ export function domainPreflightRefusal(loadability, uid) {
68
+ if (loadability.state === "available" || loadability.state === "not-applicable")
69
+ return null;
70
+ return {
71
+ kind: "refused",
72
+ reason: loadability.state === "disabled" ? "launchd-job-disabled" : "launchd-domain-unavailable",
73
+ detail: renderDomainUnavailableMessage(loadability, uid),
74
+ };
75
+ }
47
76
  /**
48
77
  * Classify the plist at `plistPath` against `dataDir`.
49
78
  *
@@ -104,6 +133,19 @@ export function planLaunchdRepair(input) {
104
133
  if (observation.state === "managed") {
105
134
  return { kind: "no-op", reason: "already-managed", detail: observation.detail };
106
135
  }
136
+ // flair#2040: launchd runs the job, but the process serving this instance
137
+ // could not be identified. Regenerating would boot out a job that may be the
138
+ // one serving; adopting has no direct process to stop. Unknown evidence
139
+ // licenses neither: refuse, touching nothing.
140
+ if (observation.state === "unverified") {
141
+ return {
142
+ kind: "refuse",
143
+ reason: "unverifiable",
144
+ detail: `cannot repair launchd management: ${observation.detail}. Nothing was touched. ` +
145
+ "Restart Flair ('flair restart') so it rewrites its hdb.pid, or make lsof available, then re-run 'flair doctor'.",
146
+ plistPath,
147
+ };
148
+ }
107
149
  // Config authority (flair#914): no readable harper-config.yaml means no safe
108
150
  // ROOTPATH/ports, so the repair cannot proceed without inventing them.
109
151
  if (!configReadable) {
@@ -427,3 +469,56 @@ export async function decideAdoptStopWithWait(state, opts) {
427
469
  }
428
470
  return { health: poll.value, decision, timedOut: poll.timedOut, waitedMs: poll.waitedMs, observations: poll.observations };
429
471
  }
472
+ /**
473
+ * Still starting: launchd runs the job (it reported a pid) and nothing answers
474
+ * HTTP on the port yet (`refused`, or a probe that could not tell:
475
+ * `unreachable`) — whatever the management state says, because a pid file can
476
+ * name launchd's pid before the port is bound. Every other observation is
477
+ * final: launchd reports no pid (detached), or something answers the port
478
+ * (then the strict verifier and the health result decide, at once).
479
+ */
480
+ export function launchdJobStillStarting(o) {
481
+ return typeof o.management.launchdPid === "number" && !healthIndicatesListener(o.health);
482
+ }
483
+ /**
484
+ * Poll `observe` while the job is still starting (launchdJobStillStarting), up
485
+ * to `deadlineMs`, and return the final observation. It decides nothing: the
486
+ * caller judges what this returns with judgeLaunchdJobServing (health `ok` and
487
+ * the strict verifier UNCHANGED), so a job that never serves still fails — at
488
+ * the deadline, with the wait named.
489
+ */
490
+ export async function awaitLaunchdJobServing(opts) {
491
+ const poll = await pollUntil({
492
+ observe: opts.observe,
493
+ until: (o) => !launchdJobStillStarting(o),
494
+ deadlineMs: opts.deadlineMs,
495
+ intervalMs: opts.intervalMs,
496
+ now: opts.now,
497
+ sleep: opts.sleep,
498
+ });
499
+ const detail = poll.timedOut
500
+ ? `${poll.value.management.detail} (waited ${poll.waitedMs}ms for the launchd job to start serving; its port still did not answer: ${poll.value.health.kind})`
501
+ : poll.value.management.detail;
502
+ return { observation: poll.value, detail, timedOut: poll.timedOut, waitedMs: poll.waitedMs, observations: poll.observations };
503
+ }
504
+ /**
505
+ * The success test for the job just loaded (flair#2040): Flair's /Health
506
+ * answers `ok` on the instance's port AND the strict verifier passes on the
507
+ * same observation (launchd's pid is the identified serving pid). A matching
508
+ * pid with a port that does not serve Flair is NOT repaired — a pid file can be
509
+ * written before the port is bound, and one that never binds is not serving.
510
+ */
511
+ export function judgeLaunchdJobServing(w) {
512
+ const verdict = verifyLaunchdManagement(w.observation.management);
513
+ if (!verdict.verified)
514
+ return { verified: false, detail: w.detail };
515
+ if (w.observation.health.kind !== "ok") {
516
+ const waited = w.timedOut ? ` after waiting ${w.waitedMs}ms for it to start serving` : "";
517
+ return {
518
+ verified: false,
519
+ detail: `${verdict.detail}, but Flair's /Health on its port did not answer ok${waited} ` +
520
+ `(last health probe: ${w.observation.health.kind}), so the job is NOT serving this instance`,
521
+ };
522
+ }
523
+ return verdict;
524
+ }
@@ -0,0 +1,77 @@
1
+ /** Shared Memory field contract for resource writers and federation readers.
2
+ * Kept under src so the CLI build can include it within its rootDir; the
3
+ * server build also emits this dependency under dist/src/lib.
4
+ * Pure data: importing this contract never loads Harper.
5
+ */
6
+ /** Every DECLARED attribute of `type Memory` in schemas/memory.graphql, in
7
+ * schema order. Keep in sync with the schema (the drift test enforces it). */
8
+ export const DECLARED_MEMORY_ATTRIBUTES = Object.freeze([
9
+ "id",
10
+ "agentId",
11
+ "content",
12
+ "contentHash",
13
+ "trigger",
14
+ "visibility",
15
+ "embedding",
16
+ "embeddingModel",
17
+ "tags",
18
+ "durability",
19
+ "source",
20
+ "type",
21
+ "createdAt",
22
+ "updatedAt",
23
+ "instanceToken",
24
+ "expiresAt",
25
+ "retrievalCount",
26
+ "lastRetrieved",
27
+ "usageCount",
28
+ "promotionStatus",
29
+ "promotedAt",
30
+ "promotedBy",
31
+ "archived",
32
+ "archivedAt",
33
+ "archivedBy",
34
+ "parentId",
35
+ "derivedFrom",
36
+ "sessionId",
37
+ "lastReflected",
38
+ "supersedes",
39
+ "subject",
40
+ "summary",
41
+ "validFrom",
42
+ "validTo",
43
+ "_safetyFlags",
44
+ "provenance",
45
+ "originatorInstanceId",
46
+ "metadata",
47
+ "entities",
48
+ ]);
49
+ /** Pre-existing UNDECLARED attributes the codebase deliberately stores on a
50
+ * Memory row and must keep (the guard's job is the POINTER, not these).
51
+ * This is an EXPLICIT, NAMED list measured against a live store (A1'' item 1)
52
+ * — never derived from the schema, because the schema is not the source of
53
+ * truth for what is on disk:
54
+ * - `meta` — the continuity-journal payload {seq, processUUID, sessionId,
55
+ * hook} written by the capture path (PUT /Memory/<id>,
56
+ * flair#1257 slice 3); Kern's slice-2 ruling settled that it
57
+ * round-trips as an undeclared field, and
58
+ * test/integration/continuity-rem-promotion-1257.test.ts pins
59
+ * that. It is not a flat String, so declaring it would change
60
+ * the stored shape.
61
+ * - `kind` — carried on a couple of older rows.
62
+ * - `_originatorInstanceId`, `_syncedFrom`, `_syncedAt` — federation
63
+ * bookkeeping stamped by the RECEIVER at merge time
64
+ * (resources/Federation.ts's mergeRecord) on every synced row.
65
+ * Any OTHER undeclared key (in particular any pointer input) is stripped. */
66
+ export const UNDECLARED_ALLOWED = Object.freeze([
67
+ "meta",
68
+ "kind",
69
+ "_originatorInstanceId",
70
+ "_syncedFrom",
71
+ "_syncedAt",
72
+ ]);
73
+ /** Every field retained by Memory writers and the inbound federation guard. */
74
+ export const MEMORY_ATTRIBUTES = Object.freeze([
75
+ ...DECLARED_MEMORY_ATTRIBUTES,
76
+ ...UNDECLARED_ALLOWED,
77
+ ]);
@@ -0,0 +1,95 @@
1
+ /**
2
+ * node-alias-path.ts — the node binary path to write into a generated service
3
+ * unit or shim (flair#2034 §2).
4
+ *
5
+ * A version manager exposes each installed runtime under a path that carries
6
+ * its exact version (`…/installs/node/24.19.0/bin/node`). Some also expose a
7
+ * FLOATING alias that resolves to one of them. This module writes such an alias
8
+ * instead of the exact path when, and only when, the alias resolves (realpath)
9
+ * to the very binary we would otherwise write. When no alias resolves to the
10
+ * same binary, the exact path is written unchanged: a path that points at a
11
+ * DIFFERENT runtime would be worse than the bug.
12
+ *
13
+ * Where an alias exists, and where it does not:
14
+ *
15
+ * - mise: `$MISE_DATA_DIR | ~/.local/share/mise` + `/installs/node/<major>/bin/node`.
16
+ * mise keeps `installs/node/<major>` as a symlink to the newest installed
17
+ * runtime of that major, so it resolves to the same binary and is written.
18
+ * - Volta: `$VOLTA_HOME | ~/.volta` + `/bin/node`. Considered, but a standard
19
+ * Volta install makes that path a link to `volta-shim`, whose realpath is
20
+ * not a node binary, so the equality check rejects it and the exact path is
21
+ * written. It is chosen only on a setup where it really is the same binary.
22
+ * - nvm, fnm, asdf: no alias path of this kind (nvm's default alias is a text
23
+ * file; asdf's `shims/node` is a script), so the exact path is written.
24
+ *
25
+ * WHAT A FLOATING ALIAS DOES LATER. The alias is a moving pointer, by design:
26
+ * when mise retargets `installs/node/24` to a newer 24.x, a unit holding the
27
+ * alias runs THAT runtime from then on, without flair being re-run. That keeps
28
+ * the unit's node path from dangling after a patch/minor bump, but it is a
29
+ * different runtime than the one that was in use when the unit was written.
30
+ *
31
+ * WHAT IT DOES NOT DO. Only the node binary floats. The install tree a unit
32
+ * serves (its working directory, the Harper entry, the launcher, the flair
33
+ * script a shim runs) lives under the exact runtime's global prefix
34
+ * (`…/installs/node/24.19.0/lib/node_modules/@tpsdev-ai/flair`), and is written
35
+ * as that exact path. After a Node bump, `npm i -g @tpsdev-ai/flair` under the
36
+ * new runtime installs a NEW tree; the unit keeps serving the old one until it
37
+ * is re-pointed (`flair init && flair restart`).
38
+ */
39
+ import { existsSync, realpathSync } from "node:fs";
40
+ import { join } from "node:path";
41
+ import { resolveHome } from "./home.js";
42
+ /** `24.19.0` / `v24.19.0` → `24.19.0`; null when no version is present. */
43
+ export function parseNodeVersion(nodePath) {
44
+ const m = /(?:^|[/\\])v?(\d+\.\d+\.\d+)(?:[/\\]|$)/.exec(nodePath);
45
+ return m ? m[1] : null;
46
+ }
47
+ /**
48
+ * The floating aliases a version manager might expose for `nodeBin`'s runtime.
49
+ * Pure: derived from the path + env only, no filesystem access. Callers filter
50
+ * by existence + realpath equality.
51
+ */
52
+ export function aliasCandidates(nodeBin, hooks = {}) {
53
+ const home = hooks.home ?? resolveHome();
54
+ const env = hooks.env ?? process.env;
55
+ const version = parseNodeVersion(nodeBin);
56
+ const out = [];
57
+ if (!version || !home)
58
+ return out;
59
+ const major = version.split(".")[0];
60
+ const miseData = env.MISE_DATA_DIR ?? join(home, ".local", "share", "mise");
61
+ out.push({ manager: "mise", path: join(miseData, "installs", "node", major, "bin", "node") });
62
+ const voltaHome = env.VOLTA_HOME ?? join(home, ".volta");
63
+ out.push({ manager: "volta", path: join(voltaHome, "bin", "node") });
64
+ return out;
65
+ }
66
+ /**
67
+ * The node path to WRITE into a generated unit: a floating alias whose realpath
68
+ * is the same binary as `nodeBin`, when one exists; otherwise `nodeBin`
69
+ * unchanged. mise's major alias is preferred over Volta's when both match.
70
+ */
71
+ export function preferVersionManagerAlias(nodeBin, hooks = {}) {
72
+ const exists = hooks.exists ?? existsSync;
73
+ const realpath = hooks.realpath ?? ((p) => realpathSync(p));
74
+ let target;
75
+ try {
76
+ target = realpath(nodeBin);
77
+ }
78
+ catch {
79
+ return nodeBin; // the resolved binary is not readable — write it as given
80
+ }
81
+ for (const c of aliasCandidates(nodeBin, hooks)) {
82
+ try {
83
+ if (c.path === nodeBin)
84
+ continue;
85
+ if (!exists(c.path))
86
+ continue;
87
+ if (realpath(c.path) === target)
88
+ return c.path;
89
+ }
90
+ catch {
91
+ /* an unreadable candidate is not a match */
92
+ }
93
+ }
94
+ return nodeBin;
95
+ }
@@ -482,15 +482,59 @@ function runNpmViewJson(spec, field, registryUrl, timeoutMs) {
482
482
  const message = String(stderr || err.message || "npm view failed").trim();
483
483
  return resolve({ ok: false, message });
484
484
  }
485
- try {
486
- resolve({ ok: true, data: JSON.parse(String(stdout).trim()), message: "" });
487
- }
488
- catch {
489
- resolve({ ok: false, message: "npm view returned non-JSON output" });
490
- }
485
+ const parsed = parseNpmViewStdout(String(stdout));
486
+ resolve(parsed);
491
487
  });
492
488
  });
493
489
  }
490
+ /** Parse trimmed stdout as JSON; distinguish empty output from invalid JSON. */
491
+ export function parseNpmViewStdout(stdout) {
492
+ const text = stdout.trim();
493
+ if (text === "")
494
+ return { ok: false, message: "npm view returned empty output" };
495
+ try {
496
+ return { ok: true, data: JSON.parse(text), message: "" };
497
+ }
498
+ catch {
499
+ return { ok: false, message: "npm view returned malformed JSON" };
500
+ }
501
+ }
502
+ /** Remove characters in U+0000-U+001F and U+007F-U+009F. */
503
+ export function stripControlChars(value) {
504
+ return value.replace(/[\u0000-\u001F\u007F\u0080-\u009F]/g, "");
505
+ }
506
+ /** Accept a non-array object whose name and version equal the requested values. */
507
+ export function isExactVersionDocument(data, packageName, version) {
508
+ if (!data || typeof data !== "object" || Array.isArray(data))
509
+ return false;
510
+ const doc = data;
511
+ if (doc.version !== version)
512
+ return false;
513
+ if (doc.name !== packageName)
514
+ return false;
515
+ return true;
516
+ }
517
+ /**
518
+ * Empty-output errors and blank strings yield active; nonblank strings yield
519
+ * deprecated. Other errors and non-string values yield unavailable.
520
+ * Deprecation messages have control characters removed and a fallback if empty.
521
+ */
522
+ export function deprecationFromNpmView(parsed) {
523
+ if (!parsed.ok) {
524
+ if (parsed.message === "npm view returned empty output")
525
+ return { kind: "active" };
526
+ return { kind: "unavailable", message: parsed.message };
527
+ }
528
+ // Non-string JSON values yield unavailable, including null.
529
+ if (typeof parsed.data !== "string") {
530
+ return { kind: "unavailable", message: "npm view deprecated field was not a string" };
531
+ }
532
+ const raw = parsed.data;
533
+ const cleaned = stripControlChars(raw).trim();
534
+ if (!raw.trim())
535
+ return { kind: "active" };
536
+ return { kind: "deprecated", message: cleaned || "npm marked this version deprecated" };
537
+ }
494
538
  /** True when this registry should be queried through npm rather than fetch(). */
495
539
  async function useNpmTransport(registry, deps) {
496
540
  if (registry.url === DEFAULT_NPM_REGISTRY)
@@ -576,3 +620,72 @@ export async function fetchDeclaredDependencies(packageName, version, deps = {})
576
620
  : null;
577
621
  return { kind: "ok", dependencies, registry };
578
622
  }
623
+ /**
624
+ * Query deprecation for a strict semver version using the resolved registry.
625
+ * HTTP responses must pass isExactVersionDocument; npm output goes through
626
+ * deprecationFromNpmView. Absent HTTP fields and blank strings yield active;
627
+ * nonblank strings yield deprecated. Non-string fields yield unavailable.
628
+ * Registry resolution errors return refused; invalid versions return invalid.
629
+ * decideDeprecatedRollback refuses only a reported deprecated result.
630
+ */
631
+ export async function fetchVersionDeprecation(packageName, version, deps = {}) {
632
+ if (!isStrictSemver(version))
633
+ return { kind: "invalid", value: version };
634
+ let registry;
635
+ try {
636
+ registry = await resolveNpmRegistryDetailed(packageName, deps);
637
+ }
638
+ catch (err) {
639
+ if (err instanceof RegistryRefusalError)
640
+ return { kind: "refused", message: err.message };
641
+ return { kind: "refused", message: err instanceof Error ? err.message : String(err) };
642
+ }
643
+ deps.onRegistry?.(registry);
644
+ const timeoutMs = deps.timeoutMs ?? 5000;
645
+ if (await useNpmTransport(registry, deps)) {
646
+ const view = deps.npmViewJson ?? runNpmViewJson;
647
+ const out = await view(`${packageName}@${version}`, "deprecated", registry.url, timeoutMs);
648
+ const field = deprecationFromNpmView(out);
649
+ if (field.kind === "unavailable")
650
+ return { kind: "unavailable", message: field.message, registry };
651
+ if (field.kind === "deprecated")
652
+ return { kind: "deprecated", message: field.message, registry };
653
+ return { kind: "active", registry };
654
+ }
655
+ const out = await fetchRegistryJson(`${registry.url}/${packageName}/${version}`, timeoutMs, deps.fetchImpl);
656
+ if (!out.ok)
657
+ return { kind: "unavailable", message: out.message, registry };
658
+ if (!isExactVersionDocument(out.data, packageName, version)) {
659
+ return {
660
+ kind: "unavailable",
661
+ message: `registry response was not a version document for ${packageName}@${version}`,
662
+ registry,
663
+ };
664
+ }
665
+ const deprecated = out.data.deprecated;
666
+ if (!Object.prototype.hasOwnProperty.call(out.data, "deprecated")) {
667
+ return { kind: "active", registry };
668
+ }
669
+ if (typeof deprecated === "string" && !deprecated.trim())
670
+ return { kind: "active", registry };
671
+ if (deprecated === null) {
672
+ return {
673
+ kind: "unavailable",
674
+ message: `registry deprecated field for ${packageName}@${version} was null`,
675
+ registry,
676
+ };
677
+ }
678
+ if (typeof deprecated !== "string") {
679
+ return {
680
+ kind: "unavailable",
681
+ message: `registry deprecated field for ${packageName}@${version} was not a string`,
682
+ registry,
683
+ };
684
+ }
685
+ const cleaned = stripControlChars(deprecated).trim();
686
+ return {
687
+ kind: "deprecated",
688
+ message: cleaned || "npm marked this version deprecated",
689
+ registry,
690
+ };
691
+ }
@@ -16,11 +16,11 @@
16
16
  import { existsSync, lstatSync, readFileSync, statSync } from "node:fs";
17
17
  import { dirname, join } from "node:path";
18
18
  import { withHome } from "./home.js";
19
- import { ALL_CLIENTS, clientConfigPath, repinCodexPin, repinJsonMcpPin, } from "../install/clients.js";
20
- import { checkSessionStartHook, isFlairHookCommand, readClientMcpBlock, } from "../doctor-client.js";
19
+ import { ALL_CLIENTS, clientConfigPath, codexWiringPin, repinCodexPin, repinJsonMcpPin, } from "../install/clients.js";
20
+ import { checkSessionStartHook, isFlairHookCommand, SESSION_START_HOOK_INVOCATION_RE, readClientMcpBlock, } from "../doctor-client.js";
21
21
  import { decodeWiringSpec, decodeWiringSpecs, isComparableWiringPin, wiringPinString, } from "./wiring-spec.js";
22
22
  import { isUnsafeAdapterPin } from "./stale-client-pin.js";
23
- import { hookInstallHint, hookSettingsPath, repinSessionStartHook, SUPPORTED_HARNESSES, } from "../hook-install.js";
23
+ import { hookInstallHint, parseInstallerHookForm, hookSettingsPath, repinSessionStartHook, SUPPORTED_HARNESSES, } from "../hook-install.js";
24
24
  import { flairCliVersion, isResolvedVersion, FLAIR_MCP_PACKAGE } from "./mcp-spec.js";
25
25
  import { comparePinVersions, pinWriteWouldLowerOrIsUnknown } from "./upgrade-status.js";
26
26
  function displayHomePath(homeDir, path) {
@@ -87,7 +87,9 @@ export function readOwnedPin(target, homeDir) {
87
87
  entryExists: block.entryExists,
88
88
  // Read the pin whenever the ENTRY exists — an entry without an identity is
89
89
  // still a pin we own and may refresh (flair#1834 A1 item 1).
90
- pin: block.entryExists ? wiringPinString(decodeWiringSpec(text, FLAIR_MCP_PACKAGE)) : null,
90
+ pin: block.entryExists
91
+ ? wiringPinString(decodeWiringSpec(target.id === "codex" ? codexWiringPin(text) : text, FLAIR_MCP_PACKAGE))
92
+ : null,
91
93
  };
92
94
  }
93
95
  export function readOwnedPins(homeDir) {
@@ -280,8 +282,20 @@ export function repinSessionStartHookGuarded(homeDir, harness, target) {
280
282
  displayPath: hookSettingsPath(homeDir, harness),
281
283
  };
282
284
  const wouldWrite = flairCliVersion();
283
- const existing = readOwnedPin(resolved, homeDir).pin;
284
- if (pinWriteWouldLowerOrIsUnknown(existing, wouldWrite)) {
285
+ const command = checkSessionStartHook(homeDir, resolved.path).command;
286
+ const form = command ? parseInstallerHookForm(command) : null;
287
+ // A form supplies the exact span the writer replaces. For a rejected form,
288
+ // the status-only match may recover an unreadable pin for a HOLD; it cannot
289
+ // authorize a write. The writer still validates the full command in-lock.
290
+ const invocation = form ? undefined : command?.match(SESSION_START_HOOK_INVOCATION_RE)?.[0];
291
+ const spec = form?.pkgSpec
292
+ ?? invocation?.slice("npx -y -p ".length, -" flair-session-start".length);
293
+ const existing = spec ? wiringPinString(decodeWiringSpec(spec, FLAIR_MCP_PACKAGE)) : null;
294
+ // A comparable pin in a non-installer command is a shape refusal, not an
295
+ // unknown pin. Let the writer retain its "not one of the installer forms"
296
+ // classification. Unreadable pins retain their raw-value hold diagnostic.
297
+ if (pinWriteWouldLowerOrIsUnknown(existing, wouldWrite)
298
+ && (form !== null || comparePinVersions(existing, wouldWrite) === null)) {
285
299
  return {
286
300
  target: resolved,
287
301
  action: "hold",
@@ -0,0 +1,197 @@
1
+ /**
2
+ * redact-token-id.ts — the ONE pairing-token-id redactor (flair#1902).
3
+ *
4
+ * A pairing-token id IS the credential a spoke redeems, so only its 8-character
5
+ * prefix may ever reach a log line. Three sites grew their own copy of this rule
6
+ * in one day (the cleanup sweep's per-token lines, its table-level lines, and the
7
+ * rollback reporter), so the class is fixed here rather than at each site: one
8
+ * deep redactor every line that can carry a token id passes through.
9
+ *
10
+ * This is HYGIENE, not a security boundary — an operator holds admin credentials
11
+ * and can read the table directly. But a token id printed in full in a log is a
12
+ * credential handed to whoever reads the log, and the same gap reappearing at a
13
+ * new site is the failure this module exists to end.
14
+ *
15
+ * What "deep" means: a string (a message OR a string field at any depth, an array
16
+ * element, or an object KEY) has each secret replaced; numbers, booleans and null
17
+ * pass through untouched; a PLAIN object is rebuilt with redacted keys and values.
18
+ * Object keys are redacted too — a `{ "<token-id>": ... }` map is exactly as much
19
+ * a leak as one in a value. A NON-plain object — a Date, Error, Map, Set or class
20
+ * instance — passes through unchanged: rebuilding it through `Object.entries`
21
+ * would lose its message or entries, and its String form is what a caller should
22
+ * log. A cyclic value terminates: a container already on the path is returned
23
+ * as-is rather than recursed into (a log helper must never crash the sweep).
24
+ *
25
+ * Two properties the naive `split(secret).join(prefix)` gets wrong, and this
26
+ * module gets right:
27
+ *
28
+ * - LENGTH GUARD: a secret shorter than MIN_SECRET_LENGTH characters is
29
+ * replaced by "[redacted]" in full. Cutting an 11-character id to its
30
+ * 8-character prefix leaves most of the id visible, which is not a redaction.
31
+ * Empty secrets are ignored (never a replacement of "" that would splice the
32
+ * replacement between every character).
33
+ * - ONE PASS, LONGEST FIRST: the secrets are matched in a SINGLE pass over the
34
+ * original text, longest secret first. Sequential replaces let a short secret
35
+ * that is a prefix of a longer one match first and strand the longer id's
36
+ * suffix — and let a later secret match inside text a previous replacement
37
+ * just inserted. A single left-to-right scan avoids both, and it deliberately
38
+ * does NOT build a RegExp: a pattern assembled from the secrets would run on
39
+ * caller-supplied text, and a ReDoS there is a worse failure than the leak.
40
+ *
41
+ * `createTokenRedactor(secrets)` compiles the matcher once; the sweep reuses one
42
+ * per tick rather than rebuilding the replacement rules (or copying the id list)
43
+ * for every line it logs.
44
+ */
45
+ /** How many leading characters of a long secret are kept. */
46
+ export const TOKEN_ID_PREFIX_LENGTH = 8;
47
+ /**
48
+ * Below this length, a secret is replaced in full: its "prefix" would be most of
49
+ * it. Pairing-token ids are 32 characters (`randomBytes(24).toString("base64url")`),
50
+ * so this bound is an untested assumption made explicit, not a live path — the
51
+ * guard exists so a short id can never be printed whole by a prefix rule.
52
+ */
53
+ export const MIN_SECRET_LENGTH = 12;
54
+ /** What a secret too short to prefix-cut becomes. */
55
+ export const FULLY_REDACTED = "[redacted]";
56
+ /** The replacement text for one secret. */
57
+ function replacementFor(secret) {
58
+ return secret.length < MIN_SECRET_LENGTH
59
+ ? FULLY_REDACTED
60
+ : `${secret.slice(0, TOKEN_ID_PREFIX_LENGTH)}…`;
61
+ }
62
+ /** Non-empty, de-duplicated secrets paired with their replacement, longest first. */
63
+ function secretReplacements(secrets) {
64
+ const seen = new Set();
65
+ const out = [];
66
+ for (const secret of secrets) {
67
+ if (typeof secret !== "string" || secret.length === 0)
68
+ continue;
69
+ if (seen.has(secret))
70
+ continue;
71
+ seen.add(secret);
72
+ out.push([secret, replacementFor(secret)]);
73
+ }
74
+ // Longest-first: the scan takes the LONGEST secret that starts at a position,
75
+ // so where two secrets overlap the longer one wins and no suffix of it is left
76
+ // stranded by a shorter secret matching first.
77
+ out.sort((a, b) => b[0].length - a[0].length);
78
+ return out;
79
+ }
80
+ /**
81
+ * Compile `secrets` into a redactor. Build it ONCE for a batch of lines and reuse
82
+ * it — the sweep logs many lines per tick, and recompiling per line is the
83
+ * quadratic cost this avoids.
84
+ *
85
+ * The scan walks the ORIGINAL text once: at each position it takes the longest
86
+ * secret that starts there (the list is longest-first), emits that secret's
87
+ * replacement, and advances past it; otherwise it copies one character. Text a
88
+ * replacement inserts is never re-scanned, and no RegExp is built from the
89
+ * secrets (so a token id can never become a pattern).
90
+ */
91
+ export function createTokenRedactor(secrets) {
92
+ const replacements = secretReplacements(secrets);
93
+ const redactMessage = (message) => {
94
+ if (replacements.length === 0 || message.length === 0)
95
+ return message;
96
+ let out = "";
97
+ let i = 0;
98
+ while (i < message.length) {
99
+ let matched;
100
+ for (const pair of replacements) {
101
+ if (message.startsWith(pair[0], i)) {
102
+ matched = pair;
103
+ break;
104
+ }
105
+ }
106
+ if (matched) {
107
+ out += matched[1];
108
+ i += matched[0].length;
109
+ }
110
+ else {
111
+ out += message[i];
112
+ i += 1;
113
+ }
114
+ }
115
+ return out;
116
+ };
117
+ return {
118
+ redactMessage,
119
+ redactValue: (value) => (replacements.length === 0 ? value : walk(value, redactMessage)),
120
+ };
121
+ }
122
+ function walk(value, redact) {
123
+ return walkDeep(value, redact, new Map());
124
+ }
125
+ /**
126
+ * A plain object: its prototype is `Object.prototype` or null. A Date, Error,
127
+ * Map, Set or class instance is NOT a plain object, so it is not rebuilt — it
128
+ * passes through UNREDACTED, and its String form is what a caller should log
129
+ * (every call site stringifies an error before it reaches the redactor).
130
+ */
131
+ function isPlainObject(value) {
132
+ const proto = Object.getPrototypeOf(value);
133
+ return proto === Object.prototype || proto === null;
134
+ }
135
+ /**
136
+ * Rebuild `value` with every string redacted. `copies` maps each container
137
+ * already rebuilt to its REDACTED copy, and the copy is registered before its
138
+ * children are walked: a sub-object reached twice (an alias) is the same
139
+ * redacted copy both times, and a cyclic value terminates by pointing at its own
140
+ * redacted copy. Returning the original for a repeated reference would hand back
141
+ * the unredacted container — the leak flair#1905's review found.
142
+ */
143
+ function walkDeep(value, redact, copies) {
144
+ if (typeof value === "string")
145
+ return redact(value);
146
+ if (Array.isArray(value)) {
147
+ const known = copies.get(value);
148
+ if (known !== undefined)
149
+ return known;
150
+ const out = [];
151
+ copies.set(value, out);
152
+ for (const v of value)
153
+ out.push(walkDeep(v, redact, copies));
154
+ return out;
155
+ }
156
+ if (value && typeof value === "object") {
157
+ if (!isPlainObject(value))
158
+ return value;
159
+ const known = copies.get(value);
160
+ if (known !== undefined)
161
+ return known;
162
+ const out = {};
163
+ copies.set(value, out);
164
+ for (const [key, v] of Object.entries(value)) {
165
+ // Define each rebuilt key as an OWN property. A bracket assignment
166
+ // (`out[redact(key)] = …`) for the key `__proto__` would set the COPY's
167
+ // prototype instead of defining a key, dropping it and giving the copy an
168
+ // attacker-chosen prototype — reachable whenever the input came from
169
+ // JSON.parse or Object.defineProperty (flair#1907).
170
+ Object.defineProperty(out, redact(key), {
171
+ value: walkDeep(v, redact, copies),
172
+ enumerable: true,
173
+ writable: true,
174
+ configurable: true,
175
+ });
176
+ }
177
+ return out;
178
+ }
179
+ // Numbers, booleans, null, undefined, functions, symbols: untouched.
180
+ return value;
181
+ }
182
+ /**
183
+ * A string with every secret replaced by its prefix (or `[redacted]` when the
184
+ * secret is too short to cut). The string-only convenience over the same
185
+ * implementation the deep redactor uses.
186
+ */
187
+ export function redactTokenMessage(message, secrets) {
188
+ return createTokenRedactor(secrets).redactMessage(message);
189
+ }
190
+ /**
191
+ * `value` with every secret replaced in every string at any depth — a message, a
192
+ * string field, an array element, and an object KEY — rebuilt so keys and values
193
+ * are both redacted. Non-string scalars pass through untouched.
194
+ */
195
+ export function redactTokenIds(value, secrets) {
196
+ return createTokenRedactor(secrets).redactValue(value);
197
+ }