@tpsdev-ai/flair 0.55.1 → 0.55.2

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.
@@ -13,13 +13,15 @@
13
13
  * Adding a client to ALL_CLIENTS or a harness to SUPPORTED_HARNESSES adds
14
14
  * it here automatically — no second list to forget on the next upgrade.
15
15
  */
16
- import { existsSync, readFileSync } from "node:fs";
17
- import { join } from "node:path";
18
- import { ALL_CLIENTS, clientConfigPath, } from "../install/clients.js";
19
- import { checkSessionStartHook, extractFlairMcpPin, extractFlairPackagePins, isFlairHookCommand, readClientMcpBlock, } from "../doctor-client.js";
16
+ import { existsSync, lstatSync, readFileSync, statSync } from "node:fs";
17
+ import { dirname, join } from "node:path";
18
+ import { ALL_CLIENTS, clientConfigPath, repinCodexPin, repinJsonMcpPin, } from "../install/clients.js";
19
+ import { checkSessionStartHook, isFlairHookCommand, readClientMcpBlock, } from "../doctor-client.js";
20
+ import { decodeWiringSpec, decodeWiringSpecs, isComparableWiringPin, wiringPinString, } from "./wiring-spec.js";
20
21
  import { isUnsafeAdapterPin } from "./stale-client-pin.js";
21
22
  import { hookInstallHint, hookSettingsPath, repinSessionStartHook, SUPPORTED_HARNESSES, } from "../hook-install.js";
22
- import { flairCliVersion, isResolvedVersion } from "./mcp-spec.js";
23
+ import { flairCliVersion, isResolvedVersion, FLAIR_MCP_PACKAGE } from "./mcp-spec.js";
24
+ import { comparePinVersions, pinWriteWouldLowerOrIsUnknown } from "./upgrade-status.js";
23
25
  function withHome(homeDir, fn) {
24
26
  const prev = process.env.HOME;
25
27
  process.env.HOME = homeDir;
@@ -85,7 +87,8 @@ export function readOwnedPin(target, homeDir) {
85
87
  return {
86
88
  target,
87
89
  present,
88
- pin: present ? extractFlairMcpPin(hook.command ?? "") : null,
90
+ entryExists: present,
91
+ pin: present ? wiringPinString(decodeWiringSpec(hook.command ?? "", FLAIR_MCP_PACKAGE)) : null,
89
92
  };
90
93
  }
91
94
  const block = readClientMcpBlock(target.id, homeDir);
@@ -93,7 +96,10 @@ export function readOwnedPin(target, homeDir) {
93
96
  return {
94
97
  target,
95
98
  present: block.present,
96
- pin: block.present ? extractFlairMcpPin(text) : null,
99
+ entryExists: block.entryExists,
100
+ // Read the pin whenever the ENTRY exists — an entry without an identity is
101
+ // still a pin we own and may refresh (flair#1834 A1 item 1).
102
+ pin: block.entryExists ? wiringPinString(decodeWiringSpec(text, FLAIR_MCP_PACKAGE)) : null,
97
103
  };
98
104
  }
99
105
  export function readOwnedPins(homeDir) {
@@ -106,7 +112,7 @@ export function readOwnedPins(homeDir) {
106
112
  export function staleOwnedPins(homeDir, expectedVersion = flairCliVersion()) {
107
113
  if (!isResolvedVersion(expectedVersion))
108
114
  return [];
109
- return readOwnedPins(homeDir).filter((r) => r.present && r.pin !== null && r.pin !== expectedVersion);
115
+ return readOwnedPins(homeDir).filter((r) => r.entryExists && r.pin !== null && r.pin !== expectedVersion);
110
116
  }
111
117
  export function staleSessionStartHookPins(homeDir, expectedVersion = flairCliVersion()) {
112
118
  return staleOwnedPins(homeDir, expectedVersion).filter((r) => r.target.kind === "session-start-hook");
@@ -130,36 +136,49 @@ export function findUnsafeWiredPins(homeDir, cwd) {
130
136
  };
131
137
  for (const target of listOwnedPinTargets(homeDir)) {
132
138
  const reading = readOwnedPin(target, homeDir);
133
- if (!reading.present)
139
+ if (!reading.entryExists)
134
140
  continue;
135
141
  const text = readFileText(target.path) ?? "";
136
142
  const surface = target.kind === "mcp-client" ? "MCP server" : "SessionStart hook";
137
- for (const pin of extractFlairPackagePins(text)) {
138
- if (!isUnsafeAdapterPin(pin.version))
139
- continue;
140
- add({
141
- source: target.kind,
142
- id: target.id,
143
- surface,
144
- package: pin.package,
145
- version: pin.version,
146
- });
143
+ for (const pkg of ["flair-mcp", "flair-client"]) {
144
+ for (const spec of decodeWiringSpecs(text, `@tpsdev-ai/${pkg}`)) {
145
+ // flair#1778 2c-i-a1: only a CONCRETE pin can be an unsafe (< 0.18.0)
146
+ // adapter pin; a range/tag/unsupported/malformed spec is present-not-
147
+ // comparable and is neither dropped nor treated as unsafe.
148
+ if (!isComparableWiringPin(spec))
149
+ continue;
150
+ const version = spec.token.value;
151
+ if (!isUnsafeAdapterPin(version))
152
+ continue;
153
+ add({
154
+ source: target.kind,
155
+ id: target.id,
156
+ surface,
157
+ package: pkg,
158
+ version,
159
+ });
160
+ }
147
161
  }
148
162
  }
149
163
  if (cwd) {
150
164
  const pkgPath = join(cwd, "package.json");
151
165
  const text = readFileText(pkgPath);
152
166
  if (text) {
153
- for (const pin of extractFlairPackagePins(text)) {
154
- if (!isUnsafeAdapterPin(pin.version))
155
- continue;
156
- add({
157
- source: "package.json",
158
- id: "cwd",
159
- surface: "package.json",
160
- package: pin.package,
161
- version: pin.version,
162
- });
167
+ for (const pkg of ["flair-mcp", "flair-client"]) {
168
+ for (const spec of decodeWiringSpecs(text, `@tpsdev-ai/${pkg}`)) {
169
+ if (!isComparableWiringPin(spec))
170
+ continue;
171
+ const version = spec.token.value;
172
+ if (!isUnsafeAdapterPin(version))
173
+ continue;
174
+ add({
175
+ source: "package.json",
176
+ id: "cwd",
177
+ surface: "package.json",
178
+ package: pkg,
179
+ version,
180
+ });
181
+ }
163
182
  }
164
183
  }
165
184
  }
@@ -176,6 +195,10 @@ export function findUnsafeWiredPins(homeDir, cwd) {
176
195
  export function ownedPinRefreshShouldReport(r) {
177
196
  if (!r.ok)
178
197
  return true;
198
+ // A HELD pin (a refresh that would LOWER an owned pin) always prints — the
199
+ // operator needs to see why the pin was not refreshed (flair#1778 D4).
200
+ if (r.action === "hold")
201
+ return true;
179
202
  if (r.target.kind === "mcp-client")
180
203
  return r.action !== "skip";
181
204
  return r.action === "update";
@@ -188,53 +211,193 @@ export function staleHookRemedy(readings) {
188
211
  return "flair hook install";
189
212
  return [...new Set(harnesses)].map((h) => hookInstallHint(h)).join(" ; ");
190
213
  }
214
+ /**
215
+ * Direction of an owned pin relative to `target` (the version a refresh would
216
+ * write — the running CLI's). Uses the ONE comparison (`comparePinVersions`) so
217
+ * no call site re-derives the ordering itself.
218
+ *
219
+ * pin > target -> "ahead" (writing target over it would LOWER it)
220
+ * pin < target -> "behind"
221
+ * equal / not comparable -> "unknown"
222
+ */
223
+ export function pinDirection(pin, target) {
224
+ const cmp = comparePinVersions(pin, target);
225
+ if (cmp === null)
226
+ return "unknown";
227
+ if (cmp > 0)
228
+ return "ahead";
229
+ if (cmp < 0)
230
+ return "behind";
231
+ return "unknown"; // equal — not stale, but not a direction either
232
+ }
233
+ /**
234
+ * Stale SessionStart-hook pins, each annotated with its direction — the ONE
235
+ * place a caller goes for "which way is this pin off" (flair#1778 follow-up).
236
+ * SessionStart hooks only: an MCP-client pin that is ahead is a different
237
+ * surface with its own rendering.
238
+ */
239
+ export function sessionStartHookPinFindings(homeDir, expectedVersion = flairCliVersion()) {
240
+ return staleSessionStartHookPins(homeDir, expectedVersion).map((reading) => ({
241
+ reading,
242
+ direction: pinDirection(reading.pin, expectedVersion),
243
+ }));
244
+ }
245
+ /**
246
+ * Stale MCP-client pins, each annotated with its direction — the client-side
247
+ * twin of `sessionStartHookPinFindings`, so `flair doctor`'s install-health
248
+ * catalog can give an MCP pin the same three-valued treatment as the
249
+ * SessionStart hook (flair#1789).
250
+ */
251
+ export function mcpClientPinFindings(homeDir, expectedVersion = flairCliVersion()) {
252
+ return staleMcpClientPins(homeDir, expectedVersion).map((reading) => ({
253
+ reading,
254
+ direction: pinDirection(reading.pin, expectedVersion),
255
+ }));
256
+ }
257
+ /**
258
+ * The ONE hold line a refresh prints when it refuses to rewrite an owned pin.
259
+ * Phrased neutrally ("a pin is never lowered") because both `flair upgrade`'s
260
+ * refresh and `flair doctor --fix` print it — no per-caller copy. An
261
+ * unreadable pin names the reason it is held (flair#1778): a pin we cannot
262
+ * compare is never lowered either.
263
+ */
264
+ function heldPinMessage(id, pin, runningCli) {
265
+ if (comparePinVersions(pin, runningCli) === null) {
266
+ return `${id}: keeping pinned ${pin} (the pin is not a version I can compare to running CLI ${runningCli} — a pin is never lowered)`;
267
+ }
268
+ return `${id}: keeping pinned ${pin} (running CLI ${runningCli} is older — a pin is never lowered)`;
269
+ }
270
+ /**
271
+ * The ONE SessionStart-hook re-pin guard (flair#1778 D4), shared by
272
+ * `flair upgrade`'s pin refresh and `flair doctor --fix`.
273
+ *
274
+ * Rebuilds an already-wired hook to the running CLI's version, but never
275
+ * LOWERS an owned pin: when the running CLI is older than the pin present, OR
276
+ * when the pin cannot be compared (not strict semver), it HOLDS — `action:
277
+ * "hold"`, with a line naming both versions — instead of rewriting. The guard
278
+ * FAILS CLOSED on an unreadable pin (`pinWriteWouldLowerOrIsUnknown`). There is
279
+ * no second copy of this decision:
280
+ * `flair doctor --fix`'s stale-hook repair routes through here too, so a
281
+ * `doctor --fix` on an ahead pin holds exactly as the upgrade refresh does
282
+ * (flair#1778 slice-1 follow-up, N4).
283
+ *
284
+ * NEVER adds a hook (repinSessionStartHook's contract); a home with no hook is
285
+ * a clean skip.
286
+ */
287
+ export function repinSessionStartHookGuarded(homeDir, harness, target) {
288
+ const resolved = target ?? listOwnedPinTargets(homeDir).find((t) => t.kind === "session-start-hook" && t.id === harness) ?? {
289
+ kind: "session-start-hook",
290
+ id: harness,
291
+ path: hookSettingsPath(homeDir, harness),
292
+ displayPath: hookSettingsPath(homeDir, harness),
293
+ };
294
+ const wouldWrite = flairCliVersion();
295
+ const existing = readOwnedPin(resolved, homeDir).pin;
296
+ if (pinWriteWouldLowerOrIsUnknown(existing, wouldWrite)) {
297
+ return {
298
+ target: resolved,
299
+ action: "hold",
300
+ ok: true,
301
+ message: heldPinMessage(resolved.id, existing, wouldWrite),
302
+ };
303
+ }
304
+ const repin = repinSessionStartHook(homeDir, harness);
305
+ return {
306
+ target: resolved,
307
+ action: repin.action,
308
+ ok: repin.ok,
309
+ message: repin.message,
310
+ };
311
+ }
191
312
  /**
192
313
  * Refresh every already-wired owned pin to the running CLI's spec.
193
314
  *
194
- * MCP client pins need `agentId` (the wire functions rewrite the env block).
195
- * SessionStart hooks do not — `repinSessionStartHook` reads the agent from
196
- * the existing command. A missing agentId therefore skips MCP only; it must
197
- * not skip hooks (that was the early-return hole in the inline upgrade path).
315
+ * PIN-ONLY (flair#1834 A1): the JSON MCP writer changes only the
316
+ * `@tpsdev-ai/flair-mcp` element of an entry's `args`, so a refresh needs NO
317
+ * agent id — it preserves each entry's OWN identity. SessionStart hooks were
318
+ * always identity-free here (`repinSessionStartHook` reads the agent from the
319
+ * existing command). Nothing here invents a host-wide identity.
320
+ *
321
+ * The MCP branch VISITS a target only when its entry exists or its directory
322
+ * exists (round 2): an absent parent (a Claude-Code-only home has no ~/.gemini
323
+ * etc.) is a quiet skip, while an EACCES / ELOOP / ENOTDIR parent still falls
324
+ * through so the refusal is reported.
198
325
  *
199
326
  * NEVER adds a hook or wires a new client.
200
327
  */
201
328
  export function refreshOwnedPins(opts) {
202
329
  const { homeDir } = opts;
203
- const flairUrl = opts.flairUrl ?? "http://127.0.0.1:9926";
204
- const agentId = opts.agentId ?? null;
205
330
  const targets = listOwnedPinTargets(homeDir);
206
331
  const results = [];
332
+ // flair#1779: an optional restriction to specific targets (kind + id).
333
+ // ONLY restricted targets are visited.
334
+ const restricted = opts.targets
335
+ ? new Map(opts.targets.map((t) => [`${t.kind}:${t.id}`, t]))
336
+ : null;
207
337
  return withHome(homeDir, () => {
208
338
  for (const target of targets) {
209
- if (target.kind === "session-start-hook") {
210
- const harness = target.id;
211
- const repin = repinSessionStartHook(homeDir, harness);
212
- results.push({
213
- target,
214
- action: repin.action,
215
- ok: repin.ok,
216
- message: repin.message,
217
- });
339
+ const override = restricted ? restricted.get(`${target.kind}:${target.id}`) : undefined;
340
+ if (restricted && !override)
218
341
  continue;
219
- }
220
- const block = readClientMcpBlock(target.id, homeDir);
221
- if (!block.present) {
222
- results.push({
223
- target,
224
- action: "skip",
225
- ok: true,
226
- message: `${target.id}: not wired — skip`,
227
- });
342
+ if (target.kind === "session-start-hook") {
343
+ // flair#1778 D4: never re-pin a hook DOWN. The guard lives in ONE place
344
+ // (repinSessionStartHookGuarded) so `flair doctor --fix` shares it
345
+ // rather than growing a second implementation.
346
+ results.push(repinSessionStartHookGuarded(homeDir, target.id, target));
228
347
  continue;
229
348
  }
230
- if (!agentId) {
231
- results.push({
232
- target,
233
- action: "skip",
234
- ok: true,
235
- message: `${target.id}: no agent id — skip MCP pin refresh`,
236
- });
237
- continue;
349
+ // flair#1834 A1: a JSON MCP refresh is PIN-ONLY — it changes only the
350
+ // `@tpsdev-ai/flair-mcp` element of the entry's args, preserving the
351
+ // entry's OWN identity (FLAIR_AGENT_ID, FLAIR_URL) and every other key.
352
+ // There is no host-wide identity to guess and no full re-wire here.
353
+ // flair#1834 A2: Codex (TOML) has its own pin-only writer
354
+ // (repinCodexPin), so its refresh no longer skips — it flows through the
355
+ // SAME visit gate and the SAME writer-result seam below.
356
+ // flair#1834 A1 round 2 (Kern BLOCKING): a VISIT gate. When the entry is
357
+ // not visible AND its directory is absent, there is nothing to visit —
358
+ // the primitive cannot resolve the parent and refuses, which the writer
359
+ // reported as a failure (2-3 such lines on every upgrade for a
360
+ // Claude-Code-only machine). Skip quietly. EACCES / ELOOP / ENOTDIR (the
361
+ // directory is present but broken) is NOT absence: fall through so the
362
+ // refusal stays LOUD.
363
+ if (!readOwnedPin(target, homeDir).entryExists) {
364
+ // flair#1834 A1 round 3: lstat does NOT follow a symlink, so a DANGLING
365
+ // symlink directory is caught here — statSync would follow it and report
366
+ // ENOENT, quiet-skipping a broken configuration. A genuinely absent
367
+ // parent (ENOENT on the link itself) stays a quiet skip; EACCES / ELOOP
368
+ // / ENOTDIR stay loud (fall through to the writer, below).
369
+ const parent = dirname(target.path);
370
+ let parentAbsent = false;
371
+ let dangling = false;
372
+ try {
373
+ const st = lstatSync(parent);
374
+ if (st.isSymbolicLink()) {
375
+ try {
376
+ statSync(parent);
377
+ }
378
+ catch (err) {
379
+ if (err?.code === "ENOENT")
380
+ dangling = true;
381
+ }
382
+ }
383
+ }
384
+ catch (err) {
385
+ if (err?.code === "ENOENT")
386
+ parentAbsent = true;
387
+ }
388
+ if (dangling) {
389
+ results.push({
390
+ target,
391
+ action: "skip",
392
+ ok: false,
393
+ message: `${target.id}: ${parent} is a dangling symlink (its target does not exist) — refusing to treat a broken configuration as unwired; fix the link`,
394
+ });
395
+ continue;
396
+ }
397
+ if (parentAbsent) {
398
+ results.push({ target, action: "skip", ok: true, message: `${target.id}: not wired — skip` });
399
+ continue;
400
+ }
238
401
  }
239
402
  const client = ALL_CLIENTS.find((c) => c.id === target.id);
240
403
  if (!client) {
@@ -246,26 +409,37 @@ export function refreshOwnedPins(opts) {
246
409
  });
247
410
  continue;
248
411
  }
249
- const env = {
250
- FLAIR_AGENT_ID: agentId,
251
- FLAIR_URL: flairUrl,
252
- FLAIR_CLIENT: target.id,
253
- };
254
- const before = extractFlairMcpPin(readFileText(target.path) ?? "");
255
- const wired = client.wire(env);
256
- const after = extractFlairMcpPin(readFileText(target.path) ?? "");
257
- // Failed write stays skip+ok:false (fail-closed, like hook re-pin).
258
- // ownedPinRefreshShouldReport treats !ok as printable — do not recode
259
- // this as a quiet skip.
260
- const action = !wired.ok ? "skip"
261
- : before !== after ? "update"
262
- : "noop";
263
- results.push({
264
- target,
265
- action,
266
- ok: wired.ok,
267
- message: wired.message,
268
- });
412
+ // Both writers fail closed on an ambiguous shape or a pin the never-lower
413
+ // guard cannot prove safe; neither wires an absent entry (a clean `skip`).
414
+ const repin = target.id === "codex"
415
+ ? repinCodexPin(target.path, client.label, opts.testHooks)
416
+ : repinJsonMcpPin(target.path, client.label, opts.testHooks);
417
+ switch (repin.kind) {
418
+ case "repinned":
419
+ results.push({
420
+ target,
421
+ action: "update",
422
+ ok: true,
423
+ message: `re-pinned ${client.label} (${repin.oldPin} -> ${repin.newPin})` +
424
+ (repin.noIdentity ? " — no identity configured" : ""),
425
+ });
426
+ break;
427
+ case "noop":
428
+ results.push({ target, action: "noop", ok: true, message: repin.line ?? `${client.label}: pin already current` });
429
+ break;
430
+ case "skip":
431
+ results.push({ target, action: "skip", ok: true, message: repin.line ?? `${target.id}: not wired — skip` });
432
+ break;
433
+ case "hold":
434
+ results.push({ target, action: "hold", ok: true, message: `HOLD ${client.label}: ${repin.line}` });
435
+ break;
436
+ case "failed":
437
+ // Failed write stays skip+ok:false (fail-closed, like hook re-pin).
438
+ // ownedPinRefreshShouldReport treats !ok as printable — do not recode
439
+ // this as a quiet skip.
440
+ results.push({ target, action: "skip", ok: false, message: `${client.label}: ${repin.line}` });
441
+ break;
442
+ }
269
443
  }
270
444
  return results;
271
445
  });
@@ -0,0 +1,87 @@
1
+ /**
2
+ * pin-write-guard.ts — the ONE decision a direct version writer makes before
3
+ * overwriting an existing wiring entry (flair#1778 slice 2c-i-a2).
4
+ *
5
+ * Spec I1: no writer LOWERS the version of the artifact it writes to unless
6
+ * the user typed that exact lower version on the command line. "Lowers"
7
+ * includes replacing a pinned spec with an unpinned or lower one.
8
+ *
9
+ * Before this, every direct writer (init.ts's ~/.claude.json; clients.ts's
10
+ * JSON / Codex-TOML / pi writers) asked only "does the entry carry the CURRENT
11
+ * spec?" and, on any mismatch, OVERWROTE it with the running CLI's spec —
12
+ * direction-blind. A CLI older than the entry it found (a downgrade, a config
13
+ * shared between installs, a hand-pinned newer version) silently replaced a
14
+ * higher pin with a lower one, and a `@^0.55.0` range / `@latest` tag / `file:`
15
+ * source was treated as merely stale and rewritten.
16
+ *
17
+ * This module reads the EXISTING entry through the a1 `WiringSpec` model
18
+ * (`./wiring-spec.js`) and compares its version token with the running CLI's
19
+ * version through the ONE comparison idiom (`pinWriteWouldLowerOrIsUnknown`,
20
+ * which wraps `comparePinVersions` — `./upgrade-status.js`). It writes NOTHING
21
+ * itself: it decides, and the caller either writes (with the pin returned) or
22
+ * leaves the bytes untouched and surfaces the returned line.
23
+ *
24
+ * Matrix (provision-wiring — pin to the running CLI):
25
+ * existing version AHEAD of the running CLI → HOLD (bytes unchanged)
26
+ * existing version BEHIND → write, repin UP
27
+ * existing version equal → write (shape repair, same pin)
28
+ * unpinned / absent → write, pinned to the running CLI
29
+ * range-or-tag / unsupported / malformed → HOLD (present, not comparable)
30
+ * running CLI version unreadable → REFUSE (nothing written)
31
+ *
32
+ * The REFUSE row is a NAMED intentional change: it replaces the fallback to
33
+ * the UNPINNED spec (mcpServerSpec's `version unknown` branch) at these
34
+ * writers, which would have turned a pinned entry into a weaker one on a
35
+ * broken install. A writer that cannot read its own version now declines to
36
+ * write rather than quietly unpinning. Note the row has a second,
37
+ * non-defect consequence (review carry-over): the same refusal also declines a
38
+ * legitimate FIRST install on a fresh home — nothing is created — until the
39
+ * version can be read again. The refused line names that.
40
+ */
41
+ import { isResolvedVersion } from "./mcp-spec.js";
42
+ import { pinWriteWouldLowerOrIsUnknown } from "./upgrade-status.js";
43
+ import { decodeWiringSpec, isComparableWiringPin, wiringPinString } from "./wiring-spec.js";
44
+ /** Decide whether a provision-wiring write would lower the entry (or cannot be proven not to). */
45
+ export function decidePinWrite(input) {
46
+ const { pkg, entry, existingText, runningVersion } = input;
47
+ // Running CLI version unreadable → REFUSE by name; nothing is written.
48
+ // (A broken install must not silently downgrade a pinned entry to unpinned.
49
+ // The same refusal also declines a legitimate FIRST install on a fresh home:
50
+ // nothing is created until the version can be read again — named here so the
51
+ // consequence is visible, not a surprise.)
52
+ if (!isResolvedVersion(runningVersion)) {
53
+ return {
54
+ action: "refuse",
55
+ pin: null,
56
+ line: `${entry}: REFUSING to write — this CLI cannot read its own version ` +
57
+ `(got "${runningVersion}"), so it cannot pin ${pkg} and must not overwrite the entry ` +
58
+ `unpinned; nothing written. On a fresh home this also declines a legitimate FIRST install ` +
59
+ `(nothing is created) until the version can be read again.`,
60
+ };
61
+ }
62
+ const spec = decodeWiringSpec(existingText ?? "", pkg);
63
+ if (isComparableWiringPin(spec)) {
64
+ const pinned = wiringPinString(spec);
65
+ if (pinWriteWouldLowerOrIsUnknown(pinned, runningVersion)) {
66
+ return {
67
+ action: "hold",
68
+ pin: null,
69
+ line: `${entry}: holding — it is pinned to ${pinned}, AHEAD of this CLI ${runningVersion}; never lowering a pin.`,
70
+ };
71
+ }
72
+ // BEHIND or equal → (re)pin UP to the running CLI.
73
+ return { action: "write", pin: runningVersion, line: null };
74
+ }
75
+ if (!spec || spec.token.kind === "none") {
76
+ // Absent, or wired without a version → pin UP to the running CLI (today's MCP policy).
77
+ return { action: "write", pin: runningVersion, line: null };
78
+ }
79
+ // range-or-tag / unsupported / malformed: PRESENT, and not comparable — a
80
+ // fail-closed HOLD that preserves the exact bytes it read.
81
+ return {
82
+ action: "hold",
83
+ pin: null,
84
+ line: `${entry}: holding — it names ${wiringPinString(spec)} (a range, tag or unsupported spec), ` +
85
+ `which this CLI cannot prove is not a lowering; bytes preserved.`,
86
+ };
87
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * settings-bytes.ts — the shared bytes-level half of the hook-settings
3
+ * writers (flair#1778 slice 2c-i-c).
4
+ *
5
+ * `src/hook-install.ts` and `src/doctor-client.ts` write the SAME two files
6
+ * (`~/.claude/settings.json` and `~/.codex/hooks.json`) with the SAME encode
7
+ * and backup conventions. Before this module each carried its own private
8
+ * copy of the parse / encode / backup helpers. The slice that put BOTH behind
9
+ * `withConfigCriticalSection` (invariant I3b) needs ONE of each so the two
10
+ * modules cannot drift: the lock serializes writers only if every writer
11
+ * parses the IN-LOCK bytes with the same parser, emits the same byte shape,
12
+ * and backs up to the same sibling path.
13
+ *
14
+ * Leaf module: imports only `node:fs` and `node:crypto`. NEVER import
15
+ * `src/cli.ts` here (its `writeFileAtomic` lacks exclusive temp creation,
16
+ * fsync, locking and identity checks — flair#1778 2c-i-b ruling).
17
+ * `parseSettingsBytes` must consume the bytes the primitive hands `decide` —
18
+ * never a pre-lock read.
19
+ */
20
+ import { closeSync, fsyncSync, openSync, renameSync, unlinkSync, } from "node:fs";
21
+ import { randomBytes } from "node:crypto";
22
+ import { writeAllSync } from "./config-critical-section.js";
23
+ /** Backup path convention: a single sibling `<path>.bak`, overwritten on
24
+ * every mutating run — recovery insurance for the mutation that's about to
25
+ * happen, not a version history. Exported so tests assert against the same
26
+ * constant this module uses internally. */
27
+ export function hookBackupPath(settingsPath) {
28
+ return `${settingsPath}.bak`;
29
+ }
30
+ /** Parse settings bytes read INSIDE the critical section (flair#1778
31
+ * 2c-i-b). The primitive hands `decide` the LOCKED snapshot, so parsing must
32
+ * consume those bytes — never a pre-lock read. */
33
+ export function parseSettingsBytes(bytes, path) {
34
+ if (bytes === null)
35
+ return { exists: false, parsed: {}, parseError: null };
36
+ const raw = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("utf-8");
37
+ if (!raw.trim())
38
+ return { exists: true, parsed: {}, parseError: null };
39
+ try {
40
+ return { exists: true, parsed: JSON.parse(raw), parseError: null };
41
+ }
42
+ catch (err) {
43
+ const reason = err instanceof Error ? err.message : String(err);
44
+ return { exists: true, parsed: null, parseError: `malformed JSON in ${path} (${reason})` };
45
+ }
46
+ }
47
+ export function backupBytesTo(path, bytes, io) {
48
+ const dest = hookBackupPath(path);
49
+ const tmp = `${dest}.tmp-${process.pid}-${randomBytes(6).toString("hex")}`;
50
+ let fd = -1;
51
+ const cleanupTemp = () => { try {
52
+ unlinkSync(tmp);
53
+ }
54
+ catch { /* nothing to remove */ } };
55
+ try {
56
+ fd = openSync(tmp, "wx", 0o600);
57
+ writeAllSync(fd, Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength), io?.write);
58
+ (io?.fsync ?? fsyncSync)(fd);
59
+ closeSync(fd);
60
+ fd = -1;
61
+ renameSync(tmp, dest);
62
+ return dest;
63
+ }
64
+ catch (err) {
65
+ if (fd >= 0) {
66
+ try {
67
+ closeSync(fd);
68
+ }
69
+ catch { /* already closed */ }
70
+ }
71
+ cleanupTemp();
72
+ throw err;
73
+ }
74
+ }
75
+ const CONFIG_ENCODER = new TextEncoder();
76
+ /** The exact bytes every hook config writer emits: 2-space JSON + newline. */
77
+ export function encodeConfig(config) {
78
+ return CONFIG_ENCODER.encode(JSON.stringify(config, null, 2) + "\n");
79
+ }
80
+ /** The exact bytes a TEXT config writer emits (Codex's TOML, flair#1778
81
+ * 2c-i-d2): the raw UTF-8 of the text the pure helpers produced — never a
82
+ * re-serialization. */
83
+ export function encodeText(text) {
84
+ return CONFIG_ENCODER.encode(text);
85
+ }