@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.
@@ -52,10 +52,18 @@
52
52
  // analysis and why the wrapper is `sh -c`, not a bare fragment).
53
53
  // 6. Size-budgeted payload — also owned by session-start-hook.ts, which
54
54
  // reuses bootstrap's own maxTokens machinery.
55
- import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
55
+ import { existsSync, mkdirSync, readFileSync } from "node:fs";
56
56
  import { dirname, join } from "node:path";
57
57
  import { SESSION_START_HOOK_MARKER, buildSessionStartHookCommand, buildContinuityCaptureHookCommand, checkContinuityCaptureHooks, computeContinuityHookInstall, computeContinuityHookRemoval, hookCommandIsSilenced, hookCommandDiscardsStderr, isFlairHookCommand, isHookCommandValueSafe, isSessionStartHookInvocation, readClientMcpBlock, } from "./doctor-client.js";
58
- import { mcpServerSpec } from "./lib/mcp-spec.js";
58
+ import { FLAIR_MCP_PACKAGE, flairCliVersion, mcpServerSpec } from "./lib/mcp-spec.js";
59
+ import { decidePinWrite } from "./lib/pin-write-guard.js";
60
+ import { withConfigCriticalSection } from "./lib/config-critical-section.js";
61
+ import { backupBytesTo, encodeConfig, hookBackupPath, parseSettingsBytes, } from "./lib/settings-bytes.js";
62
+ // flair#1778 2c-i-c: the bytes-level helpers (parse / encode / backup) moved to
63
+ // the shared leaf `./lib/settings-bytes.js` so this module and
64
+ // src/doctor-client.ts cannot drift. Re-exported here because `hookBackupPath`
65
+ // was a public export of this module and callers still import it from here.
66
+ export { hookBackupPath };
59
67
  // ── harness registry ────────────────────────────────────────────────────────
60
68
  /** SessionStart hook harnesses. A second harness is an additive registry
61
69
  * entry, not a rewrite (Kern's #719 verdict: "a switch statement... is
@@ -103,13 +111,7 @@ export function resolveHookAgentId(opts, homeDir, harness) {
103
111
  (harness !== "claude-code" ? readClientMcpBlock("claude-code", homeDir).agentId : undefined) ||
104
112
  undefined);
105
113
  }
106
- /** Backup path convention: a single sibling `<path>.bak`, overwritten on
107
- * every mutating run — recovery insurance for the mutation that's about to
108
- * happen, not a version history. Exported so tests assert against the same
109
- * constant this module uses internally. */
110
- export function hookBackupPath(settingsPath) {
111
- return `${settingsPath}.bak`;
112
- }
114
+ // `hookBackupPath` lives in `./lib/settings-bytes.js` now (re-exported above).
113
115
  // ── the hook command itself ─────────────────────────────────────────────────
114
116
  /** The exact `command` string written into the SessionStart hook entry.
115
117
  * Always carries both FLAIR_AGENT_ID and FLAIR_URL (see module doc above)
@@ -211,6 +213,7 @@ function findHookEntry(config) {
211
213
  }
212
214
  return null;
213
215
  }
216
+ // ── settings.json read (fail-closed) ────────────────────────────────────────
214
217
  function readSettingsFile(path) {
215
218
  if (!existsSync(path))
216
219
  return { exists: false, parsed: {}, parseError: null };
@@ -232,15 +235,6 @@ function readSettingsFile(path) {
232
235
  return { exists: true, parsed: null, parseError: `malformed JSON in ${path} (${reason})` };
233
236
  }
234
237
  }
235
- /** Copy the existing file to its backup path. Caller must only call this
236
- * when the file exists AND we're about to mutate for real (never during
237
- * --dry-run — a backup is itself a write). Throws on failure so the caller
238
- * can fail closed rather than silently proceeding without a safety copy. */
239
- function takeBackup(path) {
240
- const dest = hookBackupPath(path);
241
- copyFileSync(path, dest);
242
- return dest;
243
- }
244
238
  function computeInstallDelta(config, agentId, flairUrl, harness) {
245
239
  const command = buildHookCommand(agentId, flairUrl, harness);
246
240
  const after = makeHookGroup(command);
@@ -319,47 +313,151 @@ export function installHook(opts) {
319
313
  : withCodexReapproval(harness, `would ${action} the SessionStart hook in ${path} (dry run — nothing written)`);
320
314
  return { ok: true, path, harness, dryRun, message, backupPath: null, delta };
321
315
  }
322
- // Backup BEFORE the parse attempt (Sherlock condition 1) — only meaningful
323
- // when a file already exists; a fresh install has nothing to protect.
324
- let backupPath = null;
325
- if (existsSync(path)) {
326
- try {
327
- backupPath = takeBackup(path);
328
- }
329
- catch (err) {
330
- const reason = err instanceof Error ? err.message : String(err);
316
+ // Parent creation stays OUTSIDE the primitive: the primitive requires the
317
+ // resolved parent to exist before it can observe an absent destination
318
+ // (flair#1778 2c-i-b). Everything from here is ONE critical section.
319
+ mkdirSync(dirname(path), { recursive: true });
320
+ let delta = null;
321
+ let parseRefused = false;
322
+ const result = withConfigCriticalSection(path, (bytes) => {
323
+ const read = parseSettingsBytes(bytes, path);
324
+ if (read.parseError) {
325
+ parseRefused = true;
331
326
  return {
332
- ok: false, path, harness, dryRun,
333
- message: `could not back up ${path} before mutating it: ${reason} — refusing to touch it`,
334
- backupPath: null, delta: null,
327
+ hold: `${read.parseError} — refusing to modify a file we can't safely parse. Original left untouched at ${path}.`,
335
328
  };
336
329
  }
337
- }
338
- const read = readSettingsFile(path);
339
- if (read.parseError) {
340
- return {
341
- ok: false, path, harness, dryRun,
342
- message: `${read.parseError} — refusing to modify a file we can't safely parse. Original left untouched at ${path}` +
343
- (backupPath ? `; backup copy at ${backupPath}.` : "."),
344
- backupPath, delta: null,
345
- };
346
- }
347
- const { action, before, after, newConfig } = computeInstallDelta(read.parsed ?? {}, agentId, flairUrl, harness);
348
- const delta = { action, path, harness, before, after };
349
- if (action === "noop") {
330
+ const { action, before, after, newConfig } = computeInstallDelta(read.parsed ?? {}, agentId, flairUrl, harness);
331
+ delta = { action, path, harness, before, after };
332
+ if (action === "noop") {
333
+ return { noop: withCodexReapproval(harness, `SessionStart hook already correct in ${path}`) };
334
+ }
335
+ // flair#1778 2c-i-a3: the SessionStart command carries <pkg>@<spec> (the
336
+ // pin from buildHookCommand), so the write consults the ONE never-lower
337
+ // guard — on the IN-LOCK bytes, inside the critical section.
338
+ // flair#1834 PR-H round 2: hand the guard the SPAN it must prove safe —
339
+ // the captured `-p <pkg>@<ver>` span when the existing command is one of
340
+ // the installer forms, never the WHOLE command. The whole command can
341
+ // carry a DECOY `<pkg>@<ver>` inside a hand-edited id or URL; reading the
342
+ // first occurrence there proved a version the rebuild does not write,
343
+ // and the real pin was lowered (Kern BLOCKING).
344
+ const existingCommand = action === "update"
345
+ ? (before?.hooks?.find((h) => typeof h?.command === "string" && h.command.includes(SESSION_START_HOOK_MARKER))?.command ?? null)
346
+ : null;
347
+ const decision = decidePinWrite({
348
+ pkg: FLAIR_MCP_PACKAGE,
349
+ entry: `SessionStart hook in ${path}`,
350
+ existingText: guardedPinSpan(existingCommand),
351
+ runningVersion: flairCliVersion(),
352
+ });
353
+ if (decision.action !== "write")
354
+ return { hold: decision.line };
355
+ return { write: encodeConfig(newConfig) };
356
+ }, { backup: (bytes) => backupBytesTo(path, bytes) });
357
+ const backupPath = result.backupPath ?? null;
358
+ if (result.status === "written") {
350
359
  return {
351
360
  ok: true, path, harness, dryRun,
352
- message: withCodexReapproval(harness, `SessionStart hook already correct in ${path}`),
361
+ message: withCodexReapproval(harness, `${delta?.action === "add" ? "added" : "updated"} the SessionStart hook in ${path}`),
353
362
  backupPath, delta,
354
363
  };
355
364
  }
356
- mkdirSync(dirname(path), { recursive: true });
357
- writeFileSync(path, JSON.stringify(newConfig, null, 2) + "\n");
358
- return {
359
- ok: true, path, harness, dryRun,
360
- message: withCodexReapproval(harness, `${action === "add" ? "added" : "updated"} the SessionStart hook in ${path}`),
361
- backupPath, delta,
362
- };
365
+ if (result.status === "noop") {
366
+ return { ok: true, path, harness, dryRun, message: result.message, backupPath, delta };
367
+ }
368
+ if (result.status === "held") {
369
+ return { ok: !parseRefused, path, harness, dryRun, message: result.message, backupPath, delta: parseRefused ? null : delta };
370
+ }
371
+ return { ok: false, path, harness, dryRun, message: result.message, backupPath, delta: null };
372
+ }
373
+ /**
374
+ * Every hook entry whose command carries the Flair marker — install/uninstall
375
+ * mutate ONE by index, but re-pin must see them ALL: two matching entries are a
376
+ * HOLD, not a silent pick of the first (flair#1834 PR-H).
377
+ */
378
+ function findHookMatches(config) {
379
+ const groups = config?.hooks?.SessionStart;
380
+ if (!Array.isArray(groups))
381
+ return [];
382
+ const out = [];
383
+ for (let gi = 0; gi < groups.length; gi++) {
384
+ const hooks = groups[gi]?.hooks;
385
+ if (!Array.isArray(hooks))
386
+ continue;
387
+ for (let hi = 0; hi < hooks.length; hi++) {
388
+ if (typeof hooks[hi]?.command === "string" && hooks[hi].command.includes(SESSION_START_HOOK_MARKER)) {
389
+ out.push({ groupIndex: gi, hookIndex: hi });
390
+ }
391
+ }
392
+ }
393
+ return out;
394
+ }
395
+ /**
396
+ * The three EXACT installer forms `buildSessionStartHookCommand` emits
397
+ * (flair#1834 PR-H), anchored so the FULL command must match. `<id>`, `<url>`
398
+ * and `<ver>` are the only free variables; everything else — quoting, the
399
+ * wrapper, `2>/dev/null`, ordering — is the shape Flair itself wrote.
400
+ *
401
+ * Literal regexes (no composed pattern): each form is a constant. The
402
+ * unanchored SESSION_START_HOOK_INVOCATION_RE stays only for status display.
403
+ * Capture groups: 1 = agent id, 2 = optional URL, 3 = the pinned package span.
404
+ * The `d` flag exposes each group's OFFSET so the re-pin can substitute the
405
+ * CAPTURED `<ver>` span — never the first substring occurrence (round 2).
406
+ *
407
+ * `<ver>` is a SEMVER, not "anything up to the next delimiter": digits and
408
+ * dots with an OPTIONAL pre-release suffix AND an OPTIONAL build suffix
409
+ * (separate groups, flair#1834 PR-H round 4 — one `[-+]` group admitted only
410
+ * ONE of the two, so `0.54.0-rc.1+build.5` matched no form and a stale hook was
411
+ * HELD instead of updated). Each suffix is letters, digits, dots and hyphens.
412
+ * The looser `[^\s"')]+` admitted `;` and `$`, so `…@0.55.0;<cmd>` and
413
+ * `…@0.55.0$X` passed the FORM and were held only by the never-lower guard
414
+ * (round 2).
415
+ */
416
+ const HOOK_BARE_FORM_RE = /^FLAIR_AGENT_ID=([^\s'"$();|&<>]+)(?: FLAIR_URL=([^\s'"$();|&<>]+))? npx -y -p (@tpsdev-ai\/flair-mcp@\d+(?:\.\d+)*(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?) flair-session-start$/d;
417
+ const HOOK_CLAUDE_FORM_RE = /^sh -c 'out=\$\(FLAIR_AGENT_ID=([^\s'"$();|&<>]+)(?: FLAIR_URL=([^\s'"$();|&<>]+))? npx -y -p (@tpsdev-ai\/flair-mcp@\d+(?:\.\d+)*(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?) flair-session-start 2>\/dev\/null\) && printf %s "\$out" \|\| true'$/d;
418
+ const HOOK_CODEX_FORM_RE = /^sh -c 'out=\$\(FLAIR_HOOK_HARNESS=codex FLAIR_AGENT_ID=([^\s'"$();|&<>]+)(?: FLAIR_URL=([^\s'"$();|&<>]+))? npx -y -p (@tpsdev-ai\/flair-mcp@\d+(?:\.\d+)*(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?) flair-session-start\) && printf %s "\$out" \|\| true'$/d;
419
+ function formFromMatch(harness, m) {
420
+ const span = m.indices?.[3];
421
+ if (!span)
422
+ throw new Error("installer hook form matched without group indices");
423
+ return { harness, agentId: m[1], flairUrl: m[2], pkgSpec: m[3], pkgSpecStart: span[0], pkgSpecEnd: span[1] };
424
+ }
425
+ /**
426
+ * Match a FULL hook command against the three installer forms, or null. This is
427
+ * the strict replacement for the unanchored substring check: a duplicate
428
+ * `FLAIR_AGENT_ID=`, an appended shell command, or an extra env var does not
429
+ * match any form and is therefore a HOLD.
430
+ */
431
+ export function parseInstallerHookForm(command) {
432
+ if (typeof command !== "string")
433
+ return null;
434
+ let m = command.match(HOOK_CLAUDE_FORM_RE);
435
+ if (m)
436
+ return formFromMatch("claude-code", m);
437
+ m = command.match(HOOK_CODEX_FORM_RE);
438
+ if (m)
439
+ return formFromMatch("codex", m);
440
+ m = command.match(HOOK_BARE_FORM_RE);
441
+ if (m)
442
+ return formFromMatch("claude-code", m);
443
+ return null;
444
+ }
445
+ /**
446
+ * The span of an existing hook command whose VERSION the never-lower guard
447
+ * must prove safe — the exact text a rebuild would replace.
448
+ *
449
+ * When the command is one of the installer forms, that is the CAPTURED
450
+ * `-p <pkg>@<ver>` span (`form.pkgSpec`); the id and URL charsets can CONTAIN
451
+ * a `<pkg>@<ver>` string, so decoding the WHOLE command reads the FIRST
452
+ * occurrence — a possible decoy — while the rebuild writes the real pin
453
+ * (flair#1834 PR-H round 2, Kern BLOCKING). A command that is not a form keeps
454
+ * today's whole-command read: there is no captured span to narrow to, and its
455
+ * shape is handled by each writer's own fail-closed path.
456
+ */
457
+ function guardedPinSpan(command) {
458
+ if (command === null)
459
+ return null;
460
+ return parseInstallerHookForm(command)?.pkgSpec ?? command;
363
461
  }
364
462
  /**
365
463
  * Re-pin an ALREADY-WIRED Flair SessionStart hook to the current
@@ -382,62 +480,130 @@ export function installHook(opts) {
382
480
  * real write — the same Sherlock conditions installHook implements. Idempotent:
383
481
  * a second call is a `noop`.
384
482
  */
385
- export function repinSessionStartHook(homeDir, harness) {
483
+ export function repinSessionStartHook(homeDir, harness, testHooks) {
386
484
  const path = hookSettingsPath(homeDir, harness);
387
485
  const skip = (ok, message) => ({ ok, path, harness, action: "skip", message, backupPath: null });
388
- const read = readSettingsFile(path);
389
- if (read.parseError) {
390
- return skip(false, `${read.parseError} — refusing to re-pin a file we can't safely parse; left untouched`);
391
- }
392
- const config = read.parsed ?? {};
393
- const existing = findHookEntry(config);
394
- if (!existing) {
486
+ // Re-pin NEVER adds a hook and never creates the destination's parent — a
487
+ // home with no Flair hook is a clean `skip`. If the parent is absent there
488
+ // is nothing to observe, so return before the primitive (which requires a
489
+ // resolved parent).
490
+ if (!existsSync(dirname(path))) {
395
491
  return skip(true, `no Flair SessionStart hook in ${path} — nothing to re-pin`);
396
492
  }
397
- const current = config.hooks.SessionStart[existing.groupIndex].hooks[existing.hookIndex]?.command ?? "";
398
- // Only re-pin the canonical invocation Flair writes. A legacy (pre-#1143,
399
- // no `-p`) or hand-edited command is NOT version-bumped here — `flair
400
- // doctor`/`flair hook install` own the legacy → current rewrite, with their
401
- // own consent.
402
- if (!isSessionStartHookInvocation(current)) {
403
- return skip(true, `SessionStart hook in ${path} is not the canonical form Flair writes — left untouched`);
404
- }
405
- const env = parseHookCommandEnv(current);
406
- if (!env.agentId) {
407
- return skip(true, `could not read the agent id from the SessionStart hook in ${path} — left untouched`);
408
- }
409
- let next;
410
- try {
411
- next = buildSessionStartHookCommand(env.agentId, env.flairUrl, { harness });
412
- }
413
- catch (err) {
414
- const reason = err instanceof Error ? err.message : String(err);
415
- return skip(false, `could not rebuild the SessionStart hook command for ${path}: ${reason}`);
416
- }
417
- if (next === current) {
418
- return { ok: true, path, harness, action: "noop", message: `SessionStart hook in ${path} already pinned to ${mcpServerSpec()}`, backupPath: null };
419
- }
420
- let backupPath = null;
421
- try {
422
- backupPath = takeBackup(path);
423
- }
424
- catch (err) {
425
- const reason = err instanceof Error ? err.message : String(err);
426
- return skip(false, `could not back up ${path} before re-pinning it: ${reason} — refusing to touch it`);
493
+ let refused = false;
494
+ let outcome = null;
495
+ const result = withConfigCriticalSection(path, (bytes) => {
496
+ const read = parseSettingsBytes(bytes, path);
497
+ if (read.parseError) {
498
+ refused = true;
499
+ outcome = { action: "skip", message: `${read.parseError} — refusing to re-pin a file we can't safely parse; left untouched` };
500
+ return { hold: outcome.message };
501
+ }
502
+ const config = read.parsed ?? {};
503
+ // flair#1834 PR-H: enumerate EVERY matching hook — two is a HOLD, not a
504
+ // silent pick of the first (findHookEntry stays first-match for install/
505
+ // uninstall, which splice ONE entry by index).
506
+ const matches = findHookMatches(config);
507
+ if (matches.length === 0) {
508
+ outcome = { action: "skip", message: `no Flair SessionStart hook in ${path} — nothing to re-pin` };
509
+ return { hold: outcome.message };
510
+ }
511
+ if (matches.length > 1) {
512
+ outcome = { action: "hold", message: `${matches.length} Flair SessionStart hooks in ${path} match — re-pinning would change only one of them; left untouched` };
513
+ return { hold: outcome.message };
514
+ }
515
+ const { groupIndex, hookIndex } = matches[0];
516
+ const group = config.hooks.SessionStart[groupIndex];
517
+ const entry = group?.hooks?.[hookIndex];
518
+ // Unsupported hook metadata (anything Flair did not write). installHook
519
+ // emits exactly `{ hooks: [{ type: "command", command }] }`.
520
+ const groupKeys = group && typeof group === "object" ? Object.keys(group).sort().join(",") : "";
521
+ const entryKeys = entry && typeof entry === "object" ? Object.keys(entry).sort().join(",") : "";
522
+ if (groupKeys !== "hooks" || entryKeys !== "command,type" || entry.type !== "command") {
523
+ outcome = { action: "hold", message: `SessionStart hook in ${path} carries fields Flair did not write — left untouched` };
524
+ return { hold: outcome.message };
525
+ }
526
+ const current = entry.command ?? "";
527
+ // Strict FULL-command validation against the three installer forms. A
528
+ // duplicate assignment, an appended shell command or an extra env var
529
+ // does NOT match a form — it is a HOLD, byte-preserved.
530
+ const form = parseInstallerHookForm(current);
531
+ if (!form) {
532
+ outcome = { action: "hold", message: `SessionStart hook in ${path} is not one of the installer forms Flair writes — left untouched` };
533
+ return { hold: outcome.message };
534
+ }
535
+ // Rebuild by substituting ONLY the CAPTURED `<ver>` span — identity, URL
536
+ // and the wire format are preserved by construction. Substituting the
537
+ // captured OFFSET (not the first substring match) is what keeps a
538
+ // hand-edited id or URL that CONTAINS the package-spec string from being
539
+ // rewritten INSTEAD of the pin (flair#1834 PR-H round 2).
540
+ const next = current.slice(0, form.pkgSpecStart) + mcpServerSpec() + current.slice(form.pkgSpecEnd);
541
+ if (next === current) {
542
+ outcome = { action: "noop", message: `SessionStart hook in ${path} already pinned to ${mcpServerSpec()}` };
543
+ return { noop: outcome.message };
544
+ }
545
+ // flair#1778 2c-i-a3: this EXPORTED raw writer consults the ONE
546
+ // never-lower guard itself, so no caller can bypass it — on the in-lock
547
+ // bytes, inside the critical section.
548
+ // flair#1834 PR-H round 2 (Kern BLOCKING): hand the guard the CAPTURED
549
+ // span (form.pkgSpec), the exact version the substitution below writes.
550
+ // Passing the FULL command let a DECOY `<pkg>@<ver>` embedded in the id
551
+ // or URL be read as the pin: the guard proved the decoy safe while the
552
+ // substitution lowered the real (AHEAD) pin.
553
+ const decision = decidePinWrite({
554
+ pkg: FLAIR_MCP_PACKAGE,
555
+ entry: `SessionStart hook in ${path}`,
556
+ existingText: form.pkgSpec,
557
+ runningVersion: flairCliVersion(),
558
+ });
559
+ if (decision.action !== "write") {
560
+ outcome = { action: "hold", message: decision.line };
561
+ return { hold: decision.line };
562
+ }
563
+ const newConfig = deepClone(config);
564
+ newConfig.hooks.SessionStart[groupIndex].hooks[hookIndex] = { type: "command", command: next };
565
+ outcome = { action: "update", message: `re-pinned the SessionStart hook in ${path} to ${mcpServerSpec()}` };
566
+ return { write: encodeConfig(newConfig) };
567
+ }, { backup: (bytes) => backupBytesTo(path, bytes), testHooks });
568
+ // flair#1834 PR-H round 4 (CodeRabbit MAJOR): map result.status FIRST. A decided
569
+ // outcome is truthful ONLY for the status decide produced — the recorded
570
+ // "update" is set BEFORE the write, so it must never surface for a status that
571
+ // did not commit it. A refused atomicReplace (nothing written) is a FAILURE,
572
+ // never the stale "re-pinned".
573
+ const oc = outcome;
574
+ switch (result.status) {
575
+ case "written":
576
+ // decide returned `write` and the rename committed — the recorded update.
577
+ return {
578
+ ok: true, path, harness, action: "update",
579
+ message: oc?.message ?? `re-pinned the SessionStart hook in ${path} to ${mcpServerSpec()}`,
580
+ backupPath: result.backupPath ?? null,
581
+ };
582
+ case "noop":
583
+ // decide returned `noop`; use only that recorded outcome.
584
+ return { ok: true, path, harness, action: "noop", message: oc?.message ?? result.message, backupPath: result.backupPath ?? null };
585
+ case "held":
586
+ // decide returned a hold/skip (the recorded outcome) — OR the primitive
587
+ // held on its own before decide ran (an observation change, an unreadable
588
+ // destination), in which case there is no recorded outcome to use. A parse
589
+ // error is recorded as `refused` and stays a failure (`ok: false`).
590
+ return { ok: !refused, path, harness, action: oc?.action ?? "skip", message: oc?.message ?? result.message, backupPath: result.backupPath ?? null };
591
+ default:
592
+ // "refused" — a lock / backup / atomicReplace refusal: NOTHING was written.
593
+ // Never report the pre-write "update"; report a failure with the
594
+ // primitive's own message.
595
+ return { ok: false, path, harness, action: "skip", message: result.message, backupPath: result.backupPath ?? null };
427
596
  }
428
- const newConfig = deepClone(config);
429
- newConfig.hooks.SessionStart[existing.groupIndex].hooks[existing.hookIndex] = { type: "command", command: next };
430
- writeFileSync(path, JSON.stringify(newConfig, null, 2) + "\n");
431
- return {
432
- ok: true, path, harness, action: "update",
433
- message: `re-pinned the SessionStart hook in ${path} to ${mcpServerSpec()}`,
434
- backupPath,
435
- };
436
597
  }
437
598
  /** Symmetric removal — deletes ONLY our hook entry (found the same way
438
599
  * install finds it: SESSION_START_HOOK_MARKER substring match), never
439
600
  * touches unrelated hooks/keys. A no-op (ok:true, action "noop") when
440
- * nothing is installed — never creates a file that didn't already exist. */
601
+ * nothing is installed — never creates a file that didn't already exist.
602
+ *
603
+ * NOT a version writer (flair#1778 2c-i-a3): it only SPLICES OUT our entry —
604
+ * no version-carrying spec is written, and every other byte (a sibling hook's
605
+ * pin included) is preserved — so it carries no version and cannot lower one,
606
+ * which is why it needs no guard. */
441
607
  export function uninstallHook(opts) {
442
608
  const { homeDir, harness } = opts;
443
609
  const dryRun = !!opts.dryRun;
@@ -458,36 +624,42 @@ export function uninstallHook(opts) {
458
624
  : `would remove the Flair SessionStart hook from ${path} (dry run — nothing written)`;
459
625
  return { ok: true, path, harness, dryRun, message, backupPath: null, delta };
460
626
  }
461
- let backupPath = null;
462
- if (existsSync(path)) {
463
- try {
464
- backupPath = takeBackup(path);
465
- }
466
- catch (err) {
467
- const reason = err instanceof Error ? err.message : String(err);
627
+ // Removal never creates the destination's parent — if it is absent there is
628
+ // nothing to remove and nothing to observe.
629
+ if (!existsSync(dirname(path))) {
630
+ return {
631
+ ok: true, path, harness, dryRun,
632
+ message: `no Flair SessionStart hook found in ${path} — nothing to remove`,
633
+ backupPath: null, delta: { action: "noop", path, harness, before: null, after: null },
634
+ };
635
+ }
636
+ let delta = null;
637
+ let refused = false;
638
+ const result = withConfigCriticalSection(path, (bytes) => {
639
+ const read = parseSettingsBytes(bytes, path);
640
+ if (read.parseError) {
641
+ refused = true;
468
642
  return {
469
- ok: false, path, harness, dryRun,
470
- message: `could not back up ${path} before mutating it: ${reason} — refusing to touch it`,
471
- backupPath: null, delta: null,
643
+ hold: `${read.parseError} — refusing to modify a file we can't safely parse. Original left untouched at ${path}.`,
472
644
  };
473
645
  }
646
+ const { action, before, newConfig } = computeRemovalDelta(read.parsed ?? {});
647
+ delta = { action, path, harness, before, after: null };
648
+ if (action === "noop")
649
+ return { noop: `no Flair SessionStart hook found in ${path} — nothing to remove` };
650
+ return { write: encodeConfig(newConfig) };
651
+ }, { backup: (bytes) => backupBytesTo(path, bytes) });
652
+ const backupPath = result.backupPath ?? null;
653
+ if (result.status === "written") {
654
+ return { ok: true, path, harness, dryRun, message: `removed the Flair SessionStart hook from ${path}`, backupPath, delta };
474
655
  }
475
- const read = readSettingsFile(path);
476
- if (read.parseError) {
477
- return {
478
- ok: false, path, harness, dryRun,
479
- message: `${read.parseError} — refusing to modify a file we can't safely parse. Original left untouched at ${path}` +
480
- (backupPath ? `; backup copy at ${backupPath}.` : "."),
481
- backupPath, delta: null,
482
- };
656
+ if (result.status === "noop") {
657
+ return { ok: true, path, harness, dryRun, message: result.message, backupPath, delta };
483
658
  }
484
- const { action, before, newConfig } = computeRemovalDelta(read.parsed ?? {});
485
- const delta = { action, path, harness, before, after: null };
486
- if (action === "noop") {
487
- return { ok: true, path, harness, dryRun, message: `no Flair SessionStart hook found in ${path} — nothing to remove`, backupPath, delta };
659
+ if (result.status === "held") {
660
+ return { ok: !refused, path, harness, dryRun, message: result.message, backupPath, delta: refused ? null : delta };
488
661
  }
489
- writeFileSync(path, JSON.stringify(newConfig, null, 2) + "\n");
490
- return { ok: true, path, harness, dryRun, message: `removed the Flair SessionStart hook from ${path}`, backupPath, delta };
662
+ return { ok: false, path, harness, dryRun, message: result.message, backupPath, delta: null };
491
663
  }
492
664
  /**
493
665
  * Effect check: did the hook command produce SessionStart additionalContext?
@@ -714,43 +886,49 @@ export function installContinuityHooks(opts) {
714
886
  : `continuity capture hooks already current in ${path} — no changes`;
715
887
  return { ok: true, path, harness, dryRun, message, backupPath: null, actions };
716
888
  }
717
- let backupPath = null;
718
- if (existsSync(path)) {
719
- try {
720
- backupPath = takeBackup(path);
721
- }
722
- catch (err) {
723
- const reason = err instanceof Error ? err.message : String(err);
889
+ // Parent creation stays OUTSIDE the primitive; the whole mutation is ONE
890
+ // critical section.
891
+ mkdirSync(dirname(path), { recursive: true });
892
+ let actions = null;
893
+ let refused = false;
894
+ const result = withConfigCriticalSection(path, (bytes) => {
895
+ const read = parseSettingsBytes(bytes, path);
896
+ if (read.parseError) {
897
+ refused = true;
724
898
  return {
725
- ok: false, path, harness, dryRun,
726
- message: `could not back up ${path} before mutating it: ${reason} — refusing to touch it`,
727
- backupPath: null, actions: null,
899
+ hold: `${read.parseError} — refusing to modify a file we can't safely parse. Original left untouched at ${path}.`,
728
900
  };
729
901
  }
730
- }
731
- const read = readSettingsFile(path);
732
- if (read.parseError) {
902
+ const res = computeContinuityHookInstall(read.parsed ?? {}, agentId, flairUrl);
903
+ actions = res.actions;
904
+ if (res.decision)
905
+ return { hold: res.decision.line };
906
+ if (!res.changed)
907
+ return { noop: `continuity capture hooks already current in ${path}` };
908
+ return { write: encodeConfig(res.newConfig) };
909
+ }, { backup: (bytes) => backupBytesTo(path, bytes) });
910
+ const backupPath = result.backupPath ?? null;
911
+ if (result.status === "written") {
733
912
  return {
734
- ok: false, path, harness, dryRun,
735
- message: `${read.parseError} — refusing to modify a file we can't safely parse. Original left untouched at ${path}` +
736
- (backupPath ? `; backup copy at ${backupPath}.` : "."),
737
- backupPath, actions: null,
913
+ ok: true, path, harness, dryRun,
914
+ message: `wired the continuity capture hooks (PostToolUse: ${actions.PostToolUse}, Stop: ${actions.Stop}) in ${path}`,
915
+ backupPath, actions,
738
916
  };
739
917
  }
740
- const { changed, actions, newConfig } = computeContinuityHookInstall(read.parsed ?? {}, agentId, flairUrl);
741
- if (!changed) {
742
- return { ok: true, path, harness, dryRun, message: `continuity capture hooks already current in ${path}`, backupPath, actions };
918
+ if (result.status === "noop") {
919
+ return { ok: true, path, harness, dryRun, message: result.message, backupPath, actions };
743
920
  }
744
- mkdirSync(dirname(path), { recursive: true });
745
- writeFileSync(path, JSON.stringify(newConfig, null, 2) + "\n");
746
- return {
747
- ok: true, path, harness, dryRun,
748
- message: `wired the continuity capture hooks (PostToolUse: ${actions.PostToolUse}, Stop: ${actions.Stop}) in ${path}`,
749
- backupPath, actions,
750
- };
921
+ if (result.status === "held") {
922
+ return { ok: !refused, path, harness, dryRun, message: result.message, backupPath, actions: refused ? null : actions };
923
+ }
924
+ return { ok: false, path, harness, dryRun, message: result.message, backupPath, actions: null };
751
925
  }
752
926
  /** Symmetric removal of the continuity pair — only ours, everything else in
753
- * the file left untouched. A no-op when nothing is installed. */
927
+ * the file left untouched. A no-op when nothing is installed.
928
+ *
929
+ * NOT a version writer (flair#1778 2c-i-a3): like uninstallHook it only
930
+ * deletes our entries and preserves every other byte, so it cannot lower a
931
+ * pin and needs no guard. */
754
932
  export function uninstallContinuityHooks(opts) {
755
933
  const { homeDir, harness } = opts;
756
934
  const dryRun = !!opts.dryRun;
@@ -770,39 +948,44 @@ export function uninstallContinuityHooks(opts) {
770
948
  : `no continuity capture hooks found in ${path} — nothing to remove`;
771
949
  return { ok: true, path, harness, dryRun, message, backupPath: null, actions };
772
950
  }
773
- let backupPath = null;
774
- if (existsSync(path)) {
775
- try {
776
- backupPath = takeBackup(path);
777
- }
778
- catch (err) {
779
- const reason = err instanceof Error ? err.message : String(err);
951
+ if (!existsSync(dirname(path))) {
952
+ return {
953
+ ok: true, path, harness, dryRun,
954
+ message: `no continuity capture hooks found in ${path} — nothing to remove`,
955
+ backupPath: null, actions: { PostToolUse: "noop", Stop: "noop" },
956
+ };
957
+ }
958
+ let actions = null;
959
+ let refused = false;
960
+ const result = withConfigCriticalSection(path, (bytes) => {
961
+ const read = parseSettingsBytes(bytes, path);
962
+ if (read.parseError) {
963
+ refused = true;
780
964
  return {
781
- ok: false, path, harness, dryRun,
782
- message: `could not back up ${path} before mutating it: ${reason} — refusing to touch it`,
783
- backupPath: null, actions: null,
965
+ hold: `${read.parseError} — refusing to modify a file we can't safely parse. Original left untouched at ${path}.`,
784
966
  };
785
967
  }
786
- }
787
- const read = readSettingsFile(path);
788
- if (read.parseError) {
968
+ const res = computeContinuityHookRemoval(read.parsed ?? {});
969
+ actions = res.actions;
970
+ if (!res.changed)
971
+ return { noop: `no continuity capture hooks found in ${path} — nothing to remove` };
972
+ return { write: encodeConfig(res.newConfig) };
973
+ }, { backup: (bytes) => backupBytesTo(path, bytes) });
974
+ const backupPath = result.backupPath ?? null;
975
+ if (result.status === "written") {
789
976
  return {
790
- ok: false, path, harness, dryRun,
791
- message: `${read.parseError} — refusing to modify a file we can't safely parse. Original left untouched at ${path}` +
792
- (backupPath ? `; backup copy at ${backupPath}.` : "."),
793
- backupPath, actions: null,
977
+ ok: true, path, harness, dryRun,
978
+ message: `removed the continuity capture hooks (PostToolUse + Stop) from ${path}`,
979
+ backupPath, actions,
794
980
  };
795
981
  }
796
- const { changed, actions, newConfig } = computeContinuityHookRemoval(read.parsed ?? {});
797
- if (!changed) {
798
- return { ok: true, path, harness, dryRun, message: `no continuity capture hooks found in ${path} — nothing to remove`, backupPath, actions };
982
+ if (result.status === "noop") {
983
+ return { ok: true, path, harness, dryRun, message: result.message, backupPath, actions };
799
984
  }
800
- writeFileSync(path, JSON.stringify(newConfig, null, 2) + "\n");
801
- return {
802
- ok: true, path, harness, dryRun,
803
- message: `removed the continuity capture hooks (PostToolUse + Stop) from ${path}`,
804
- backupPath, actions,
805
- };
985
+ if (result.status === "held") {
986
+ return { ok: !refused, path, harness, dryRun, message: result.message, backupPath, actions: refused ? null : actions };
987
+ }
988
+ return { ok: false, path, harness, dryRun, message: result.message, backupPath, actions: null };
806
989
  }
807
990
  /** Read-only continuity status for `flair hook status` — the same report
808
991
  * doctor's check consumes, resolved through the harness's settings path. */