@tpsdev-ai/flair 0.59.0 → 0.62.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 (259) hide show
  1. package/README.md +4 -4
  2. package/SECURITY.md +36 -0
  3. package/config.yaml +12 -1
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/import-runner.js +12 -0
  6. package/dist/bridges/runtime/load-plugin.js +42 -13
  7. package/dist/bridges/runtime/yaml-loader.js +4 -2
  8. package/dist/build-info.json +3 -3
  9. package/dist/cli.js +991 -248
  10. package/dist/commands/agent.js +224 -43
  11. package/dist/commands/attention.js +4 -3
  12. package/dist/commands/backup.js +202 -34
  13. package/dist/commands/bridge.js +172 -119
  14. package/dist/commands/deploy.js +37 -4
  15. package/dist/commands/doctor.js +592 -146
  16. package/dist/commands/export.js +54 -19
  17. package/dist/commands/federation.js +141 -21
  18. package/dist/commands/hook.js +155 -2
  19. package/dist/commands/idp.js +14 -1
  20. package/dist/commands/import.js +7 -3
  21. package/dist/commands/init.js +462 -193
  22. package/dist/commands/integrity.js +388 -0
  23. package/dist/commands/keys.js +247 -58
  24. package/dist/commands/mcp.js +97 -35
  25. package/dist/commands/memory.js +171 -21
  26. package/dist/commands/migrate-harness-memory.js +3 -2
  27. package/dist/commands/orgevent.js +46 -37
  28. package/dist/commands/presence.js +4 -3
  29. package/dist/commands/principal.js +426 -48
  30. package/dist/commands/quality.js +10 -1
  31. package/dist/commands/reembed.js +141 -17
  32. package/dist/commands/relationship.js +2 -1
  33. package/dist/commands/rem.js +56 -18
  34. package/dist/commands/restore.js +101 -61
  35. package/dist/commands/search.js +6 -4
  36. package/dist/commands/service.js +151 -38
  37. package/dist/commands/soul.js +4 -3
  38. package/dist/commands/status.js +43 -5
  39. package/dist/commands/test.js +3 -2
  40. package/dist/commands/upgrade.js +24 -1
  41. package/dist/commands/workspace.js +6 -3
  42. package/dist/component-env.js +31 -41
  43. package/dist/deploy.js +77 -1
  44. package/dist/doctor-client.js +529 -92
  45. package/dist/engine-version-contract.js +1 -0
  46. package/dist/engine-version.js +23 -3
  47. package/dist/federation-verify.js +4 -3
  48. package/dist/hook-install.js +670 -6
  49. package/dist/keystore.js +72 -0
  50. package/dist/lib/action-recall-runtime.js +328 -0
  51. package/dist/lib/agent-home-fields.js +132 -0
  52. package/dist/lib/agent-home.js +427 -0
  53. package/dist/lib/agent-id-rule.js +46 -0
  54. package/dist/lib/agent-roster.js +33 -0
  55. package/dist/lib/auth-resolve.js +49 -16
  56. package/dist/lib/capture-runtime.js +124 -0
  57. package/dist/lib/credential-status-rule.js +78 -0
  58. package/dist/lib/daemon-liveness.js +41 -10
  59. package/dist/lib/doctor-run.js +75 -37
  60. package/dist/lib/durability-copy.js +10 -0
  61. package/dist/lib/embedding-space-doctor.js +75 -0
  62. package/dist/lib/flair-agent-role.js +4 -0
  63. package/dist/lib/hub-url.js +12 -0
  64. package/dist/lib/init-admin-pass.js +88 -12
  65. package/dist/lib/init-listener-environ.js +1 -2
  66. package/dist/lib/init-occupied-listener.js +15 -111
  67. package/dist/lib/init-spawn-attribution.js +73 -0
  68. package/dist/lib/init-tcp-probe.js +33 -0
  69. package/dist/lib/instance-identity-row.js +20 -0
  70. package/dist/lib/launchd-management.js +24 -0
  71. package/dist/lib/listener-table.js +268 -0
  72. package/dist/lib/local-delete-instance.js +27 -0
  73. package/dist/lib/local-instance-pair.js +256 -0
  74. package/dist/lib/mcp-enable.js +1168 -326
  75. package/dist/lib/mcp-oauth-env-core.js +133 -0
  76. package/dist/lib/mcp-oauth-env.js +125 -0
  77. package/dist/lib/mcp-spec.js +17 -1
  78. package/dist/lib/memory-attributes.js +2 -0
  79. package/dist/lib/memory-id-policy.js +46 -0
  80. package/dist/lib/memory-integrity.js +309 -0
  81. package/dist/lib/memory-purge-response.js +20 -0
  82. package/dist/lib/ops-table-count.js +25 -0
  83. package/dist/lib/owned-pins.js +67 -10
  84. package/dist/lib/peer-status.js +27 -0
  85. package/dist/lib/principal-status.js +29 -0
  86. package/dist/lib/process-start-time.js +76 -12
  87. package/dist/lib/proto-safe-record.js +42 -0
  88. package/dist/lib/record-id-path.js +25 -0
  89. package/dist/lib/reembed-server-support.js +66 -0
  90. package/dist/lib/restore-verify.js +104 -0
  91. package/dist/lib/scheduler-platform.js +10 -6
  92. package/dist/lib/secret-keys.js +25 -0
  93. package/dist/lib/secrets-push.js +50 -22
  94. package/dist/lib/skill-seed-pending.js +24 -0
  95. package/dist/lib/skill-seed.js +365 -0
  96. package/dist/lib/stop-start-recovery.js +54 -0
  97. package/dist/lib/using-flair-skill.js +87 -0
  98. package/dist/mcp-client-assertion.js +112 -4
  99. package/dist/memory-id-checkpoint.js +326 -0
  100. package/dist/memory-node-compare.js +207 -0
  101. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  102. package/dist/rem/restore.js +6 -5
  103. package/dist/rem/runner.js +103 -44
  104. package/dist/resources/Agent.js +321 -1
  105. package/dist/resources/AgentKeyRegister.js +214 -0
  106. package/dist/resources/AgentKeyRegistration.js +28 -0
  107. package/dist/resources/AgentSeed.js +10 -4
  108. package/dist/resources/AutoPromoteCandidates.js +7 -1
  109. package/dist/resources/Credential.js +177 -2
  110. package/dist/resources/Federation.js +751 -143
  111. package/dist/resources/FederationRetry.js +140 -0
  112. package/dist/resources/InstructionVersion.js +220 -0
  113. package/dist/resources/Integration.js +300 -25
  114. package/dist/resources/Memory.js +2113 -604
  115. package/dist/resources/MemoryArchive.js +75 -42
  116. package/dist/resources/MemoryBootstrap.js +110 -39
  117. package/dist/resources/MemoryCandidate.js +21 -1
  118. package/dist/resources/MemoryDedupStats.js +30 -1
  119. package/dist/resources/MemoryFeed.js +327 -45
  120. package/dist/resources/MemoryGrant.js +21 -1
  121. package/dist/resources/MemoryMaintenance.js +129 -25
  122. package/dist/resources/MemoryPurge.js +232 -0
  123. package/dist/resources/MemoryReflect.js +7 -2
  124. package/dist/resources/MemoryReindex.js +24 -8
  125. package/dist/resources/Message.js +5 -3
  126. package/dist/resources/OAuth.js +186 -9
  127. package/dist/resources/OrgEvent.js +126 -3
  128. package/dist/resources/Presence.js +144 -49
  129. package/dist/resources/PromoteMemoryCandidate.js +18 -7
  130. package/dist/resources/Relationship.js +23 -0
  131. package/dist/resources/SemanticSearch.js +63 -32
  132. package/dist/resources/Soul.js +189 -76
  133. package/dist/resources/TeamDirectory.js +35 -0
  134. package/dist/resources/WorkspaceState.js +21 -1
  135. package/dist/resources/XAA.js +181 -63
  136. package/dist/resources/agent-auth.js +40 -15
  137. package/dist/resources/auth-middleware.js +400 -161
  138. package/dist/resources/ed25519-auth.js +1 -1
  139. package/dist/resources/embedding-space-guard.js +366 -72
  140. package/dist/resources/engine-version-stamp-boot.js +53 -0
  141. package/dist/resources/federation-classify.js +72 -0
  142. package/dist/resources/federation-crypto.js +5 -5
  143. package/dist/resources/federation-retry-lib.js +135 -0
  144. package/dist/resources/grant-visibility.js +135 -0
  145. package/dist/resources/harper-routing.js +83 -0
  146. package/dist/resources/health.js +120 -18
  147. package/dist/resources/host-source-citation.js +49 -0
  148. package/dist/resources/host-source-visibility.js +7 -6
  149. package/dist/resources/instance-create-lock.js +17 -0
  150. package/dist/resources/instance-identity.js +23 -0
  151. package/dist/resources/instruction-version-record.js +343 -0
  152. package/dist/resources/key-lock.js +3 -3
  153. package/dist/resources/mcp-handler.js +36 -8
  154. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  155. package/dist/resources/mcp-oauth.js +23 -6
  156. package/dist/resources/mcp-tool-arguments.js +4 -6
  157. package/dist/resources/mcp-tools.js +128 -19
  158. package/dist/resources/memory-bootstrap-lib.js +5 -15
  159. package/dist/resources/memory-declared-attributes.js +3 -1
  160. package/dist/resources/memory-deletion-history.js +55 -0
  161. package/dist/resources/memory-durability.js +54 -0
  162. package/dist/resources/memory-embed-hash.js +88 -0
  163. package/dist/resources/memory-embedding-value.js +8 -0
  164. package/dist/resources/memory-host-source.js +27 -5
  165. package/dist/resources/memory-id-guard.js +75 -0
  166. package/dist/resources/memory-redaction.js +236 -0
  167. package/dist/resources/memory-supplied-vector.js +72 -0
  168. package/dist/resources/memory-write-lock.js +310 -0
  169. package/dist/resources/memory-write-response.js +139 -0
  170. package/dist/resources/migrations/data-dir.js +74 -16
  171. package/dist/resources/migrations/dir-safety.js +1 -1
  172. package/dist/resources/migrations/embedding-stamp.js +193 -79
  173. package/dist/resources/migrations/export.js +1 -0
  174. package/dist/resources/migrations/graph-heal.js +18 -25
  175. package/dist/resources/migrations/lock.js +7 -1
  176. package/dist/resources/migrations/snapshot.js +1 -0
  177. package/dist/resources/migrations/source-fields.js +5 -5
  178. package/dist/resources/migrations/synthetic-test-migration.js +14 -11
  179. package/dist/resources/migrations/visibility-backfill.js +29 -29
  180. package/dist/resources/object-body-guard.js +33 -0
  181. package/dist/resources/org-event-created-at.js +133 -0
  182. package/dist/resources/originator-instance.js +39 -7
  183. package/dist/resources/owner-delete-recheck.js +78 -0
  184. package/dist/resources/owner-field-guard.js +39 -5
  185. package/dist/resources/owner-scoped-write-policy.js +212 -0
  186. package/dist/resources/owner-scoped-writes.js +58 -0
  187. package/dist/resources/presence-receipt.js +236 -0
  188. package/dist/resources/promotion-stamp.js +47 -12
  189. package/dist/resources/record-owner-guard.js +74 -26
  190. package/dist/resources/record-types.js +1 -1
  191. package/dist/resources/relay-ops.js +78 -6
  192. package/dist/resources/replay-store.js +96 -19
  193. package/dist/resources/request-target.js +136 -0
  194. package/dist/resources/request-transaction.js +35 -0
  195. package/dist/resources/search-readiness.js +4 -1
  196. package/dist/resources/seed-ids.js +9 -0
  197. package/dist/resources/seed-reservation.js +117 -0
  198. package/dist/resources/semantic-retrieval-core.js +20 -9
  199. package/dist/resources/skill-manifest.js +20 -11
  200. package/dist/resources/skill-subject.js +53 -0
  201. package/dist/resources/skill-version-write.js +432 -0
  202. package/dist/resources/skill-write-fault.js +17 -0
  203. package/dist/resources/skill-write-policy.js +67 -0
  204. package/dist/resources/skill-write.js +67 -7
  205. package/dist/resources/table-helpers.js +10 -7
  206. package/dist/resources/team-directory.js +248 -0
  207. package/dist/resources/tool-descriptors/index.js +69 -8
  208. package/dist/resources/txn-pause-point.js +118 -0
  209. package/dist/resources/usage-recording.js +171 -63
  210. package/dist/resources/write-back.js +218 -0
  211. package/dist/src/engine-version-contract.js +1 -0
  212. package/dist/src/keystore.js +72 -0
  213. package/dist/src/lib/agent-home-fields.js +132 -0
  214. package/dist/src/lib/agent-id-rule.js +46 -0
  215. package/dist/src/lib/agent-key-register.js +80 -0
  216. package/dist/src/lib/atomic-write.js +256 -0
  217. package/dist/src/lib/credential-status-rule.js +78 -0
  218. package/dist/src/lib/expired-by-agent.js +37 -0
  219. package/dist/src/lib/flair-agent-role.js +4 -0
  220. package/dist/src/lib/idp-mapping-rule.js +81 -0
  221. package/dist/src/lib/instance-identity-row.js +20 -0
  222. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  223. package/dist/src/lib/memory-attributes.js +2 -0
  224. package/dist/src/lib/memory-id-policy.js +46 -0
  225. package/dist/src/lib/principal-status.js +29 -0
  226. package/dist/src/lib/proto-safe-record.js +42 -0
  227. package/dist/src/lib/reembed-server-support.js +66 -0
  228. package/dist/src/lib/scheduler-platform.js +10 -6
  229. package/dist/src/lib/systemd-agent-id.js +38 -0
  230. package/docs/access-control.md +146 -45
  231. package/docs/api-reference.md +46 -11
  232. package/docs/auth.md +6 -12
  233. package/docs/bridges.md +11 -0
  234. package/docs/claude-code.md +34 -4
  235. package/docs/deploying-on-fabric.md +70 -0
  236. package/docs/deployment.md +2 -0
  237. package/docs/embedding-in-a-harper-app.md +1 -1
  238. package/docs/federation.md +33 -2
  239. package/docs/hosted-on-fabric.md +43 -36
  240. package/docs/integrations.md +5 -5
  241. package/docs/mcp-clients.md +5 -2
  242. package/docs/n8n.md +17 -11
  243. package/docs/notes/mcp-agent-auth-consumer.md +12 -4
  244. package/docs/notes/mcp-oauth-model2.md +34 -5
  245. package/docs/quickstart-fabric.md +2 -2
  246. package/docs/quickstart.md +9 -1
  247. package/docs/releasing.md +12 -6
  248. package/docs/rem.md +8 -0
  249. package/docs/secrets-and-keys.md +19 -2
  250. package/docs/standalone-local.md +1 -0
  251. package/docs/supply-chain-policy.md +13 -3
  252. package/docs/upgrade.md +32 -6
  253. package/package.json +10 -5
  254. package/schemas/agent-key-registration.graphql +22 -0
  255. package/schemas/agent.graphql +3 -0
  256. package/schemas/federation.graphql +38 -1
  257. package/schemas/memory.graphql +84 -5
  258. package/schemas/oauth.graphql +19 -0
  259. package/schemas/schema.graphql +2 -0
@@ -9,7 +9,7 @@
9
9
  // fixSessionStartHook, driven by `applyOrReportSessionStartHook`) — but that
10
10
  // wiring is a side effect of a broader diagnostic/setup flow, not a
11
11
  // standalone, symmetric, testable command a user or an automation can run on
12
- // its own. This module is the pure (no network, no process spawn) decision
12
+ // its own. This module is the decision
13
13
  // logic behind the new top-level `flair hook install|uninstall|status`
14
14
  // command family (wired into src/cli.ts). It intentionally reuses
15
15
  // doctor-client.ts's SESSION_START_HOOK_MARKER as the single source of truth
@@ -52,9 +52,11 @@
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 { existsSync, mkdirSync, readFileSync } from "node:fs";
55
+ import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
56
+ import { actionRecallInstallRoot, plannedActionRecallRuntime, probeActionRecallRuntime, provisionActionRecallRuntime } from "./lib/action-recall-runtime.js";
57
+ import { captureInstallRoot, plannedCaptureRuntime, probeCaptureRuntime, provisionCaptureRuntime, } from "./lib/capture-runtime.js";
56
58
  import { dirname, join } from "node:path";
57
- import { SESSION_START_HOOK_MARKER, buildSessionStartHookCommand, buildContinuityCaptureHookCommand, checkContinuityCaptureHooks, computeContinuityHookInstall, computeContinuityHookRemoval, hookCommandIsSilenced, hookCommandDiscardsStderr, isFlairHookCommand, isHookCommandValueSafe, isSessionStartHookInvocation, readClientMcpBlock, } from "./doctor-client.js";
59
+ import { SESSION_START_HOOK_MARKER, ACTION_RECALL_HOOK_MARKER, CAPTURE_HOOK_MARKER, ACTION_RECALL_PRE_TOOL_USE_MATCHER, buildSessionStartHookCommand, buildActionRecallHookCommand, parseActionRecallCommand, buildContinuityCaptureHookCommand, buildCaptureHookCommand, captureFlushSpec, parseCaptureCommand, isFlairCaptureCommand, CAPTURE_HOOK_EVENTS, CAPTURE_HOOK_MATCHERS, checkContinuityCaptureHooks, computeContinuityHookInstall, computeContinuityHookRemoval, hookCommandIsSilenced, hookCommandDiscardsStderr, isFlairActionRecallCommand, isFlairHookCommand, isHookCommandValueSafe, isSessionStartHookInvocation, readClientMcpBlock, sessionStartEnablesActionRecall, } from "./doctor-client.js";
58
60
  import { FLAIR_MCP_PACKAGE, flairCliVersion, mcpServerSpec } from "./lib/mcp-spec.js";
59
61
  import { decidePinWrite } from "./lib/pin-write-guard.js";
60
62
  import { withConfigCriticalSection } from "./lib/config-critical-section.js";
@@ -414,7 +416,7 @@ function findHookMatches(config) {
414
416
  * (round 2).
415
417
  */
416
418
  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;
419
+ const HOOK_CLAUDE_FORM_RE = /^sh -c 'out=\$\((?:FLAIR_ACTION_RECALL=1 )?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
420
  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
421
  function formFromMatch(harness, m) {
420
422
  const span = m.indices?.[3];
@@ -667,6 +669,12 @@ export function uninstallHook(opts) {
667
669
  * FLAIR_HOOK_PROBE's `{}` as success. This is not harness delivery.
668
670
  */
669
671
  export function classifyHookDelivery(outcome) {
672
+ if (outcome.cleanupError) {
673
+ return { delivered: false, reason: `not delivered: probe could not confirm the command's process group ended (${outcome.cleanupError})` };
674
+ }
675
+ if (outcome.outputOverflow) {
676
+ return { delivered: false, reason: "not delivered: probe output exceeded its size limit" };
677
+ }
670
678
  if (outcome.timedOut) {
671
679
  return { delivered: false, reason: "not delivered: probe timed out" };
672
680
  }
@@ -801,12 +809,14 @@ export function hookStatusFailureLine(status) {
801
809
  /** Read-only report: is the hook wired, does it look right, and which agent
802
810
  * / Flair instance does it point at (recovered from the wired command). */
803
811
  export function hookStatus(homeDir, harness, opts = {}) {
812
+ const pinStale = opts.stalePinFinding?.direction === "behind";
813
+ const stalePin = pinStale ? opts.stalePinFinding?.pin ?? null : null;
804
814
  const path = hookSettingsPath(homeDir, harness);
805
815
  const read = readSettingsFile(path);
806
816
  if (read.parseError) {
807
817
  return {
808
818
  harness, path, wired: false, correctShape: false, silenced: false, stderrDiscarded: false,
809
- parseError: read.parseError, delivery: "absent", deliveryReasons: [],
819
+ parseError: read.parseError, delivery: "absent", deliveryReasons: [], pinStale: false, stalePin: null,
810
820
  };
811
821
  }
812
822
  const config = read.parsed ?? {};
@@ -814,7 +824,7 @@ export function hookStatus(homeDir, harness, opts = {}) {
814
824
  if (!existing) {
815
825
  return {
816
826
  harness, path, wired: false, correctShape: false, silenced: false, stderrDiscarded: false,
817
- parseError: null, delivery: "absent", deliveryReasons: [],
827
+ parseError: null, delivery: "absent", deliveryReasons: [], pinStale: false, stalePin: null,
818
828
  };
819
829
  }
820
830
  const hookEntry = config.hooks.SessionStart[existing.groupIndex].hooks[existing.hookIndex];
@@ -828,6 +838,7 @@ export function hookStatus(homeDir, harness, opts = {}) {
828
838
  stderrDiscarded: hookCommandDiscardsStderr(command),
829
839
  agentId: env.agentId, flairUrl: env.flairUrl, command, parseError: null,
830
840
  delivery: assessed.delivery, deliveryReasons: assessed.deliveryReasons,
841
+ pinStale, stalePin,
831
842
  };
832
843
  }
833
844
  // ── continuity capture hooks (flair#1257 slice 2) ──────────────────────────
@@ -850,6 +861,315 @@ export function hookStatus(homeDir, harness, opts = {}) {
850
861
  export function buildContinuityHookCommand(agentId, flairUrl) {
851
862
  return buildContinuityCaptureHookCommand(agentId, flairUrl);
852
863
  }
864
+ function hookGroupIsFlairOnly(group, isOurs) {
865
+ const hooks = group?.hooks;
866
+ return Array.isArray(hooks) && hooks.length > 0 && hooks.every((h) => isOurs(h?.command));
867
+ }
868
+ /** Find the PreToolUse group carrying an action-recall hook command. */
869
+ function findActionRecallEntry(config) {
870
+ const groups = config?.hooks?.PreToolUse;
871
+ if (!Array.isArray(groups))
872
+ return null;
873
+ for (let gi = 0; gi < groups.length; gi++) {
874
+ const hooks = groups[gi]?.hooks;
875
+ if (!Array.isArray(hooks))
876
+ continue;
877
+ for (let hi = 0; hi < hooks.length; hi++) {
878
+ if (isFlairActionRecallCommand(hooks[hi]?.command)) {
879
+ return { groupIndex: gi, hookIndex: hi, group: groups[gi] };
880
+ }
881
+ }
882
+ }
883
+ return null;
884
+ }
885
+ /**
886
+ * Compute the action-recall install delta. The SessionStart refresh flag is
887
+ * only ever added to an installer-form command.
888
+ */
889
+ function computeActionRecallInstall(config, runtime, agentId, flairUrl) {
890
+ const command = buildActionRecallHookCommand(runtime.bunPath, runtime.artifactPath, agentId, flairUrl);
891
+ const newConfig = deepClone(config);
892
+ let preToolUse = "noop";
893
+ const groups = newConfig.hooks?.PreToolUse;
894
+ if (Array.isArray(groups)) {
895
+ for (const group of groups) {
896
+ if (!Array.isArray(group?.hooks) || hookGroupIsFlairOnly(group, isFlairActionRecallCommand))
897
+ continue;
898
+ const retained = group.hooks.filter((hook) => !isFlairActionRecallCommand(hook?.command));
899
+ if (retained.length !== group.hooks.length) {
900
+ group.hooks = retained;
901
+ preToolUse = "update";
902
+ }
903
+ }
904
+ }
905
+ const existing = findActionRecallEntry(newConfig);
906
+ if (existing) {
907
+ const group = existing.group;
908
+ const hook = group.hooks[existing.hookIndex];
909
+ if (hook.type !== "command" || hook.command !== command || group.matcher !== ACTION_RECALL_PRE_TOOL_USE_MATCHER) {
910
+ hook.command = command;
911
+ hook.type = "command";
912
+ group.matcher = ACTION_RECALL_PRE_TOOL_USE_MATCHER;
913
+ preToolUse = "update";
914
+ }
915
+ }
916
+ else {
917
+ newConfig.hooks = newConfig.hooks && typeof newConfig.hooks === "object" && !Array.isArray(newConfig.hooks) ? newConfig.hooks : {};
918
+ newConfig.hooks.PreToolUse = Array.isArray(newConfig.hooks.PreToolUse) ? newConfig.hooks.PreToolUse : [];
919
+ newConfig.hooks.PreToolUse.push({
920
+ matcher: ACTION_RECALL_PRE_TOOL_USE_MATCHER,
921
+ hooks: [{ type: "command", command }],
922
+ });
923
+ if (preToolUse !== "update")
924
+ preToolUse = "add";
925
+ }
926
+ let sessionStart = "skipped";
927
+ let sessionStartBefore = null;
928
+ const ss = findHookEntry(newConfig);
929
+ if (ss) {
930
+ const current = newConfig.hooks.SessionStart[ss.groupIndex].hooks[ss.hookIndex].command;
931
+ sessionStartBefore = current;
932
+ const form = parseInstallerHookForm(current);
933
+ if (!form) {
934
+ sessionStart = "skipped";
935
+ }
936
+ else {
937
+ const rebuilt = buildSessionStartHookCommand(agentId, flairUrl, {
938
+ actionRecall: true,
939
+ });
940
+ if (rebuilt === current && newConfig.hooks.SessionStart[ss.groupIndex].hooks[ss.hookIndex].type === "command") {
941
+ sessionStart = "noop";
942
+ }
943
+ else {
944
+ newConfig.hooks.SessionStart[ss.groupIndex].hooks[ss.hookIndex] = { type: "command", command: rebuilt };
945
+ sessionStart = "update";
946
+ }
947
+ }
948
+ }
949
+ else {
950
+ newConfig.hooks.SessionStart = Array.isArray(newConfig.hooks.SessionStart) ? newConfig.hooks.SessionStart : [];
951
+ newConfig.hooks.SessionStart.push({ hooks: [{ type: "command", command: buildSessionStartHookCommand(agentId, flairUrl, { actionRecall: true }) }] });
952
+ sessionStart = "add";
953
+ }
954
+ return { changed: preToolUse !== "noop" || sessionStart === "update" || sessionStart === "add", newConfig, actions: { preToolUse, sessionStart }, sessionStartBefore };
955
+ }
956
+ function actionRecallInstallRefusal(delta, path) {
957
+ if (delta.actions.sessionStart === "skipped")
958
+ return `SessionStart in ${path} is not a compatible installer command — nothing written`;
959
+ if (delta.actions.sessionStart === "add" || delta.actions.sessionStart === "update") {
960
+ const decision = decidePinWrite({ pkg: FLAIR_MCP_PACKAGE, entry: `SessionStart hook in ${path}`, existingText: guardedPinSpan(delta.sessionStartBefore ?? null), runningVersion: flairCliVersion() });
961
+ if (decision.action !== "write")
962
+ return decision.line;
963
+ }
964
+ return null;
965
+ }
966
+ function actionRecallCommandFailure(command) {
967
+ if (typeof command !== "string")
968
+ return "action-recall command is not an installer command";
969
+ const parts = parseActionRecallCommand(command);
970
+ if (!parts)
971
+ return "action-recall command is not an installer command";
972
+ const { bunPath: bun, artifactPath: artifact, agentId: agent, flairUrl: url } = parts;
973
+ try {
974
+ if (command !== buildActionRecallHookCommand(bun, artifact, agent, url))
975
+ return "action-recall command is not an installer command";
976
+ return probeActionRecallRuntime({ bunPath: bun, artifactPath: artifact }, agent, url, command);
977
+ }
978
+ catch {
979
+ return "action-recall command is not an installer command";
980
+ }
981
+ }
982
+ export function actionRecallHookStatus(homeDir, harness) {
983
+ const path = hookSettingsPath(homeDir, harness);
984
+ const read = readSettingsFile(path);
985
+ const config = read.parsed ?? {};
986
+ const entry = findActionRecallEntry(config);
987
+ const hook = entry ? entry.group.hooks[entry.hookIndex] : null;
988
+ const candidates = findCaptureEntries(config, "PreToolUse", command => isHookStatusCandidate(command, ACTION_RECALL_HOOK_MARKER));
989
+ const noncanonical = candidates.filter(candidate => !isFlairActionRecallCommand(candidate.group.hooks[candidate.hookIndex]?.command));
990
+ const problems = noncanonical.map(candidate => `PreToolUse[${candidate.groupIndex}].hooks[${candidate.hookIndex}]: noncanonical action-recall command`);
991
+ const runtimeFailure = hook ? actionRecallCommandFailure(hook.command) : null;
992
+ const installed = harness === "claude-code" && hook?.type === "command" && entry?.group.matcher === ACTION_RECALL_PRE_TOOL_USE_MATCHER && runtimeFailure === null && problems.length === 0;
993
+ let refreshEnabled = false;
994
+ const ss = findHookEntry(config);
995
+ if (ss) {
996
+ const hook = config.hooks.SessionStart[ss.groupIndex].hooks[ss.hookIndex];
997
+ const form = parseInstallerHookForm(hook.command);
998
+ refreshEnabled = hook.type === "command" && form?.harness === "claude-code" && sessionStartEnablesActionRecall(hook.command);
999
+ }
1000
+ return { path, harness, installed, refreshEnabled, problems, ...(runtimeFailure ? { runtimeFailure } : {}) };
1001
+ }
1002
+ /** Install (or repair) the action-recall PreToolUse hook + SessionStart refresh. */
1003
+ export function installActionRecall(opts) {
1004
+ const { homeDir, harness, agentId, flairUrl, runtime } = opts;
1005
+ const dryRun = !!opts.dryRun;
1006
+ const path = hookSettingsPath(homeDir, harness);
1007
+ if (harness !== "claude-code") {
1008
+ return {
1009
+ ok: false, path, harness, dryRun,
1010
+ message: `action recall is Claude Code only — ${harness} has no PreToolUse Bash hook`, backupPath: null, actions: null,
1011
+ };
1012
+ }
1013
+ for (const [label, value] of [["agent id", agentId], ["Flair URL", flairUrl]]) {
1014
+ if (!isHookCommandValueSafe(value)) {
1015
+ return {
1016
+ ok: false, path, harness, dryRun,
1017
+ message: `${label} '${value}' contains characters that cannot be safely written into a shell hook command — refusing to write it`,
1018
+ backupPath: null, actions: null,
1019
+ };
1020
+ }
1021
+ }
1022
+ const runtimeFailure = probeActionRecallRuntime(runtime, agentId, flairUrl);
1023
+ if (runtimeFailure) {
1024
+ return { ok: false, path, harness, dryRun, message: `${runtimeFailure} — nothing written`, backupPath: null, actions: null };
1025
+ }
1026
+ if (dryRun) {
1027
+ let planned;
1028
+ try {
1029
+ planned = plannedActionRecallRuntime(runtime, homeDir);
1030
+ }
1031
+ catch (error) {
1032
+ return { ok: false, path, harness, dryRun, message: `${error instanceof Error ? error.message : String(error)} — nothing written`, backupPath: null, actions: null };
1033
+ }
1034
+ const read = readSettingsFile(path);
1035
+ if (read.parseError) {
1036
+ return { ok: false, path, harness, dryRun, message: `${read.parseError} — dry run: nothing would be written until this is fixed`, backupPath: null, actions: null };
1037
+ }
1038
+ const delta = computeActionRecallInstall(read.parsed ?? {}, planned, agentId, flairUrl);
1039
+ const refusal = actionRecallInstallRefusal(delta, path);
1040
+ if (refusal)
1041
+ return { ok: false, path, harness, dryRun, message: refusal, backupPath: null, actions: delta.actions };
1042
+ const message = delta.changed
1043
+ ? `would wire the action-recall hook (PreToolUse: ${delta.actions.preToolUse}, SessionStart: ${delta.actions.sessionStart}) in ${path} (dry run — nothing written)`
1044
+ : `action-recall hook already current in ${path} — no changes`;
1045
+ return { ok: true, path, harness, dryRun, message, backupPath: null, actions: delta.actions };
1046
+ }
1047
+ mkdirSync(dirname(path), { recursive: true });
1048
+ let actions = null;
1049
+ let refused = false;
1050
+ const result = withConfigCriticalSection(path, (bytes) => {
1051
+ const read = parseSettingsBytes(bytes, path);
1052
+ if (read.parseError) {
1053
+ refused = true;
1054
+ return { hold: `${read.parseError} — refusing to modify a file we can't safely parse. Original left untouched at ${path}.` };
1055
+ }
1056
+ const delta = computeActionRecallInstall(read.parsed ?? {}, runtime, agentId, flairUrl);
1057
+ actions = delta.actions;
1058
+ const refusal = actionRecallInstallRefusal(delta, path);
1059
+ if (refusal)
1060
+ return { hold: refusal };
1061
+ let installed;
1062
+ try {
1063
+ installed = provisionActionRecallRuntime(runtime, homeDir, agentId, flairUrl);
1064
+ }
1065
+ catch (error) {
1066
+ return { hold: `${error instanceof Error ? error.message : String(error)} — nothing written` };
1067
+ }
1068
+ const durableDelta = computeActionRecallInstall(read.parsed ?? {}, installed, agentId, flairUrl);
1069
+ actions = durableDelta.actions;
1070
+ if (!durableDelta.changed)
1071
+ return { noop: `action-recall hook already current in ${path}` };
1072
+ return { write: encodeConfig(durableDelta.newConfig) };
1073
+ }, { backup: (bytes) => backupBytesTo(path, bytes) });
1074
+ const backupPath = result.backupPath ?? null;
1075
+ if (result.status === "written") {
1076
+ return { ok: true, path, harness, dryRun, message: `wired the action-recall hook (PreToolUse: ${actions.preToolUse}, SessionStart: ${actions.sessionStart}) in ${path}`, backupPath, actions };
1077
+ }
1078
+ if (result.status === "noop") {
1079
+ return { ok: true, path, harness, dryRun, message: result.message, backupPath, actions };
1080
+ }
1081
+ if (result.status === "held") {
1082
+ return { ok: false, path, harness, dryRun, message: result.message, backupPath, actions: refused ? null : actions };
1083
+ }
1084
+ return { ok: false, path, harness, dryRun, message: result.message, backupPath, actions: null };
1085
+ }
1086
+ function computeActionRecallRemoval(config) {
1087
+ const newConfig = deepClone(config);
1088
+ let preToolUse = "noop";
1089
+ const groups = newConfig.hooks?.PreToolUse;
1090
+ if (Array.isArray(groups)) {
1091
+ for (let gi = groups.length - 1; gi >= 0; gi--) {
1092
+ const group = groups[gi];
1093
+ if (!Array.isArray(group?.hooks))
1094
+ continue;
1095
+ const retained = group.hooks.filter((hook) => !isFlairActionRecallCommand(hook?.command));
1096
+ if (retained.length === group.hooks.length)
1097
+ continue;
1098
+ group.hooks = retained;
1099
+ if (retained.length === 0)
1100
+ groups.splice(gi, 1);
1101
+ preToolUse = "remove";
1102
+ }
1103
+ if (preToolUse === "remove" && groups.length === 0)
1104
+ delete newConfig.hooks.PreToolUse;
1105
+ }
1106
+ let sessionStart = "skipped";
1107
+ const ss = findHookEntry(newConfig);
1108
+ if (ss) {
1109
+ const current = newConfig.hooks.SessionStart[ss.groupIndex].hooks[ss.hookIndex].command;
1110
+ const form = parseInstallerHookForm(current);
1111
+ if (form && sessionStartEnablesActionRecall(current)) {
1112
+ const rebuilt = buildSessionStartHookCommand(form.agentId, form.flairUrl, { harness: form.harness });
1113
+ newConfig.hooks.SessionStart[ss.groupIndex].hooks[ss.hookIndex] = { type: "command", command: rebuilt };
1114
+ sessionStart = "update";
1115
+ }
1116
+ else {
1117
+ sessionStart = "noop";
1118
+ }
1119
+ }
1120
+ return { changed: preToolUse === "remove" || sessionStart === "update", newConfig, actions: { preToolUse, sessionStart } };
1121
+ }
1122
+ export function uninstallActionRecall(opts) {
1123
+ const { homeDir, harness } = opts;
1124
+ const dryRun = !!opts.dryRun;
1125
+ const path = hookSettingsPath(homeDir, harness);
1126
+ if (harness !== "claude-code") {
1127
+ return { ok: false, path, harness, dryRun, message: `action recall is Claude Code only`, backupPath: null, actions: null };
1128
+ }
1129
+ if (!existsSync(path)) {
1130
+ if (!dryRun)
1131
+ rmSync(actionRecallInstallRoot(homeDir), { recursive: true, force: true });
1132
+ return { ok: true, path, harness, dryRun, message: `no action-recall hook found in ${path} — nothing to remove`, backupPath: null, actions: { preToolUse: "noop", sessionStart: "noop" } };
1133
+ }
1134
+ if (dryRun) {
1135
+ const read = readSettingsFile(path);
1136
+ if (read.parseError)
1137
+ return { ok: false, path, harness, dryRun, message: read.parseError, backupPath: null, actions: null };
1138
+ const delta = computeActionRecallRemoval(read.parsed ?? {});
1139
+ const message = delta.changed
1140
+ ? `would remove the action-recall hook (PreToolUse: ${delta.actions.preToolUse}, SessionStart: ${delta.actions.sessionStart}) from ${path} (dry run — nothing written)`
1141
+ : `no action-recall hook found in ${path} — nothing to remove (dry run)`;
1142
+ return { ok: true, path, harness, dryRun, message, backupPath: null, actions: delta.actions };
1143
+ }
1144
+ let actions = null;
1145
+ let refused = false;
1146
+ const result = withConfigCriticalSection(path, (bytes) => {
1147
+ const read = parseSettingsBytes(bytes, path);
1148
+ if (read.parseError) {
1149
+ refused = true;
1150
+ return { hold: `${read.parseError} — refusing to modify a file we can't safely parse. Original left untouched at ${path}.` };
1151
+ }
1152
+ const delta = computeActionRecallRemoval(read.parsed ?? {});
1153
+ actions = delta.actions;
1154
+ if (!delta.changed)
1155
+ return { noop: `no action-recall hook found in ${path} — nothing to remove` };
1156
+ return { write: encodeConfig(delta.newConfig) };
1157
+ }, { backup: (bytes) => backupBytesTo(path, bytes) });
1158
+ if (result.status === "written" || result.status === "noop") {
1159
+ rmSync(actionRecallInstallRoot(homeDir), { recursive: true, force: true });
1160
+ }
1161
+ const backupPath = result.backupPath ?? null;
1162
+ if (result.status === "written") {
1163
+ return { ok: true, path, harness, dryRun, message: `removed the action-recall hook from ${path}`, backupPath, actions };
1164
+ }
1165
+ if (result.status === "noop") {
1166
+ return { ok: true, path, harness, dryRun, message: result.message, backupPath, actions };
1167
+ }
1168
+ if (result.status === "held") {
1169
+ return { ok: false, path, harness, dryRun, message: result.message, backupPath, actions: refused ? null : actions };
1170
+ }
1171
+ return { ok: false, path, harness, dryRun, message: result.message, backupPath, actions: null };
1172
+ }
853
1173
  /** Install (or repair to current form) the continuity capture pair. */
854
1174
  export function installContinuityHooks(opts) {
855
1175
  const { homeDir, harness, agentId, flairUrl } = opts;
@@ -992,3 +1312,347 @@ export function uninstallContinuityHooks(opts) {
992
1312
  export function continuityHookStatus(homeDir, harness) {
993
1313
  return checkContinuityCaptureHooks(homeDir, hookSettingsPath(homeDir, harness));
994
1314
  }
1315
+ function noCaptureActions() {
1316
+ return Object.fromEntries(CAPTURE_HOOK_EVENTS.map((event) => [event, "noop"]));
1317
+ }
1318
+ function describeCaptureActions(actions) {
1319
+ return CAPTURE_HOOK_EVENTS.map((event) => `${event}: ${actions[event]}`).join(", ");
1320
+ }
1321
+ function isHookStatusCandidate(command, marker) {
1322
+ if (typeof command !== "string")
1323
+ return false;
1324
+ const prefix = marker === ACTION_RECALL_HOOK_MARKER ? "sh -c 'out=$(" : "sh -c '";
1325
+ const redirect = marker === ACTION_RECALL_HOOK_MARKER ? "2>/dev/null)" : ">/dev/null";
1326
+ const tokens = command.split(" ");
1327
+ return command.startsWith(prefix) && tokens.some((token, index) => token.split("/").at(-1) === marker && tokens[index + 1] === redirect);
1328
+ }
1329
+ function findCaptureEntries(config, event, isMatch = isFlairCaptureCommand) {
1330
+ const entries = [];
1331
+ const groups = config?.hooks?.[event];
1332
+ if (!Array.isArray(groups))
1333
+ return entries;
1334
+ for (let gi = 0; gi < groups.length; gi++) {
1335
+ const hooks = groups[gi]?.hooks;
1336
+ if (!Array.isArray(hooks))
1337
+ continue;
1338
+ for (let hi = 0; hi < hooks.length; hi++) {
1339
+ if (isMatch(hooks[hi]?.command))
1340
+ entries.push({ group: groups[gi], hookIndex: hi, groupIndex: gi });
1341
+ }
1342
+ }
1343
+ return entries;
1344
+ }
1345
+ /** Most common command among each event's first match; ties go to the earliest event. */
1346
+ function expectedCaptureCommand(commands) {
1347
+ const counts = new Map();
1348
+ for (const command of commands) {
1349
+ if (command !== null)
1350
+ counts.set(command, (counts.get(command) ?? 0) + 1);
1351
+ }
1352
+ let best = "";
1353
+ let bestCount = 0;
1354
+ for (const [command, count] of counts) {
1355
+ if (count > bestCount) {
1356
+ best = command;
1357
+ bestCount = count;
1358
+ }
1359
+ }
1360
+ return best;
1361
+ }
1362
+ /** Pure merge of the capture hooks into a parsed settings object. */
1363
+ export function computeCaptureHookInstall(config, runtime, agentId, flairUrl) {
1364
+ const command = buildCaptureHookCommand(runtime.bunPath, runtime.artifactPath, agentId, flairUrl, captureFlushSpec());
1365
+ const newConfig = deepClone(config ?? {});
1366
+ newConfig.hooks = newConfig.hooks && typeof newConfig.hooks === "object" && !Array.isArray(newConfig.hooks) ? newConfig.hooks : {};
1367
+ const actions = noCaptureActions();
1368
+ let changed = false;
1369
+ for (const event of CAPTURE_HOOK_EVENTS) {
1370
+ const entries = findCaptureEntries(newConfig, event);
1371
+ const existing = entries[0];
1372
+ const wantMatcher = CAPTURE_HOOK_MATCHERS[event];
1373
+ if (existing) {
1374
+ if (entries.length > 1) {
1375
+ for (const duplicate of entries.slice(1).reverse()) {
1376
+ duplicate.group.hooks.splice(duplicate.hookIndex, 1);
1377
+ }
1378
+ newConfig.hooks[event] = newConfig.hooks[event].filter((group) => !Array.isArray(group?.hooks) || group.hooks.length > 0);
1379
+ actions[event] = "update";
1380
+ changed = true;
1381
+ }
1382
+ const group = existing.group;
1383
+ const hook = group.hooks[existing.hookIndex];
1384
+ if (hookGroupIsFlairOnly(group, isFlairCaptureCommand)) {
1385
+ const matcherCurrent = wantMatcher === null
1386
+ ? group.matcher == null || group.matcher === ""
1387
+ : group.matcher === wantMatcher;
1388
+ if (hook.type !== "command" || hook.command !== command || !matcherCurrent) {
1389
+ hook.command = command;
1390
+ hook.type = "command";
1391
+ if (wantMatcher === null)
1392
+ delete group.matcher;
1393
+ else
1394
+ group.matcher = wantMatcher;
1395
+ actions[event] = "update";
1396
+ changed = true;
1397
+ }
1398
+ }
1399
+ else {
1400
+ group.hooks.splice(existing.hookIndex, 1);
1401
+ const dedicated = { hooks: [{ type: "command", command }] };
1402
+ if (wantMatcher !== null)
1403
+ dedicated.matcher = wantMatcher;
1404
+ newConfig.hooks[event].push(dedicated);
1405
+ actions[event] = "update";
1406
+ changed = true;
1407
+ }
1408
+ }
1409
+ else {
1410
+ newConfig.hooks[event] = Array.isArray(newConfig.hooks[event]) ? newConfig.hooks[event] : [];
1411
+ const group = { hooks: [{ type: "command", command }] };
1412
+ if (wantMatcher !== null)
1413
+ group.matcher = wantMatcher;
1414
+ newConfig.hooks[event].push(group);
1415
+ actions[event] = "add";
1416
+ changed = true;
1417
+ }
1418
+ }
1419
+ return { changed, newConfig, actions };
1420
+ }
1421
+ export function computeCaptureHookRemoval(config) {
1422
+ const newConfig = deepClone(config ?? {});
1423
+ const actions = noCaptureActions();
1424
+ for (const event of CAPTURE_HOOK_EVENTS) {
1425
+ const groups = newConfig.hooks?.[event];
1426
+ if (!Array.isArray(groups))
1427
+ continue;
1428
+ let removedAny = false;
1429
+ const kept = [];
1430
+ for (const group of groups) {
1431
+ const isGroup = group && typeof group === "object" && Array.isArray(group.hooks);
1432
+ if (isGroup) {
1433
+ const before = group.hooks.length;
1434
+ group.hooks = group.hooks.filter((hook) => !isFlairCaptureCommand(hook?.command));
1435
+ if (group.hooks.length !== before)
1436
+ removedAny = true;
1437
+ }
1438
+ if (!isGroup || group.hooks.length > 0)
1439
+ kept.push(group);
1440
+ }
1441
+ if (!removedAny)
1442
+ continue;
1443
+ actions[event] = "remove";
1444
+ if (kept.length > 0)
1445
+ newConfig.hooks[event] = kept;
1446
+ else
1447
+ delete newConfig.hooks[event];
1448
+ }
1449
+ if (newConfig.hooks && typeof newConfig.hooks === "object" && Object.keys(newConfig.hooks).length === 0) {
1450
+ delete newConfig.hooks;
1451
+ }
1452
+ return { changed: CAPTURE_HOOK_EVENTS.some((event) => actions[event] !== "noop"), newConfig, actions };
1453
+ }
1454
+ /** Reproduce + re-probe a wired capture command, or a reason it is not one. */
1455
+ function captureCommandFailure(command) {
1456
+ const parts = parseCaptureCommand(typeof command === "string" ? command : "");
1457
+ if (!parts)
1458
+ return "capture command is not an installer command";
1459
+ if (parts.flushSpec !== captureFlushSpec())
1460
+ return "capture command requires the current flush spec";
1461
+ try {
1462
+ const rebuilt = buildCaptureHookCommand(parts.bunPath, parts.artifactPath, parts.agentId, parts.flairUrl, parts.flushSpec);
1463
+ if (command !== rebuilt)
1464
+ return "capture command is not an installer command";
1465
+ return probeCaptureRuntime({ bunPath: parts.bunPath, artifactPath: parts.artifactPath }, parts.agentId, parts.flairUrl ?? "http://localhost:19926", command);
1466
+ }
1467
+ catch {
1468
+ return "capture command is not an installer command";
1469
+ }
1470
+ }
1471
+ /** Install (or repair) the capture hooks. */
1472
+ export function installCaptureHooks(opts) {
1473
+ const { homeDir, harness, agentId, flairUrl, runtime } = opts;
1474
+ const dryRun = !!opts.dryRun;
1475
+ const path = hookSettingsPath(homeDir, harness);
1476
+ if (harness !== "claude-code") {
1477
+ return {
1478
+ ok: false, path, harness, dryRun,
1479
+ message: `capture is Claude Code only — ${harness} has no PostToolUseFailure/PostToolUse/Stop matcher Flair can capture from`, backupPath: null, actions: null,
1480
+ };
1481
+ }
1482
+ for (const [label, value] of [["agent id", agentId], ["Flair URL", flairUrl]]) {
1483
+ if (!isHookCommandValueSafe(value)) {
1484
+ return {
1485
+ ok: false, path, harness, dryRun,
1486
+ message: `${label} '${value}' contains characters that cannot be safely written into a shell hook command — refusing to write it`,
1487
+ backupPath: null, actions: null,
1488
+ };
1489
+ }
1490
+ }
1491
+ const runtimeFailure = probeCaptureRuntime(runtime, agentId, flairUrl);
1492
+ if (runtimeFailure) {
1493
+ return { ok: false, path, harness, dryRun, message: `${runtimeFailure} — nothing written`, backupPath: null, actions: null };
1494
+ }
1495
+ if (dryRun) {
1496
+ let planned;
1497
+ try {
1498
+ planned = plannedCaptureRuntime(runtime, homeDir);
1499
+ }
1500
+ catch (error) {
1501
+ return { ok: false, path, harness, dryRun, message: `${error instanceof Error ? error.message : String(error)} — nothing written`, backupPath: null, actions: null };
1502
+ }
1503
+ const read = readSettingsFile(path);
1504
+ if (read.parseError) {
1505
+ return { ok: false, path, harness, dryRun, message: `${read.parseError} — dry run: nothing would be written until this is fixed`, backupPath: null, actions: null };
1506
+ }
1507
+ const delta = computeCaptureHookInstall(read.parsed ?? {}, planned, agentId, flairUrl);
1508
+ const message = delta.changed
1509
+ ? `would wire the capture hooks (${describeCaptureActions(delta.actions)}) in ${path} (dry run — nothing written)`
1510
+ : `capture hooks already current in ${path} — no changes`;
1511
+ return { ok: true, path, harness, dryRun, message, backupPath: null, actions: delta.actions };
1512
+ }
1513
+ mkdirSync(dirname(path), { recursive: true });
1514
+ let actions = null;
1515
+ let refused = false;
1516
+ const result = withConfigCriticalSection(path, (bytes) => {
1517
+ const read = parseSettingsBytes(bytes, path);
1518
+ if (read.parseError) {
1519
+ refused = true;
1520
+ return { hold: `${read.parseError} — refusing to modify a file we can't safely parse. Original left untouched at ${path}.` };
1521
+ }
1522
+ let installed;
1523
+ try {
1524
+ installed = provisionCaptureRuntime(runtime, homeDir, agentId, flairUrl);
1525
+ }
1526
+ catch (error) {
1527
+ return { hold: `${error instanceof Error ? error.message : String(error)} — nothing written` };
1528
+ }
1529
+ const delta = computeCaptureHookInstall(read.parsed ?? {}, installed, agentId, flairUrl);
1530
+ actions = delta.actions;
1531
+ if (!delta.changed)
1532
+ return { noop: `capture hooks already current in ${path}` };
1533
+ return { write: encodeConfig(delta.newConfig) };
1534
+ }, { backup: (bytes) => backupBytesTo(path, bytes) });
1535
+ const backupPath = result.backupPath ?? null;
1536
+ if (result.status === "written") {
1537
+ return { ok: true, path, harness, dryRun, message: `wired the capture hooks (${describeCaptureActions(actions)}) in ${path}`, backupPath, actions };
1538
+ }
1539
+ if (result.status === "noop") {
1540
+ return { ok: true, path, harness, dryRun, message: result.message, backupPath, actions };
1541
+ }
1542
+ if (result.status === "held") {
1543
+ return { ok: false, path, harness, dryRun, message: result.message, backupPath, actions: refused ? null : actions };
1544
+ }
1545
+ return { ok: false, path, harness, dryRun, message: result.message, backupPath, actions: null };
1546
+ }
1547
+ /** Symmetric removal of the capture hooks + their provisioned runtime. */
1548
+ export function uninstallCaptureHooks(opts) {
1549
+ const { homeDir, harness } = opts;
1550
+ const dryRun = !!opts.dryRun;
1551
+ const path = hookSettingsPath(homeDir, harness);
1552
+ if (harness !== "claude-code") {
1553
+ return { ok: false, path, harness, dryRun, message: `capture is Claude Code only`, backupPath: null, actions: null };
1554
+ }
1555
+ if (!existsSync(path)) {
1556
+ if (!dryRun)
1557
+ rmSync(captureInstallRoot(homeDir), { recursive: true, force: true });
1558
+ return { ok: true, path, harness, dryRun, message: `no capture hooks found in ${path} — nothing to remove`, backupPath: null, actions: noCaptureActions() };
1559
+ }
1560
+ if (dryRun) {
1561
+ const read = readSettingsFile(path);
1562
+ if (read.parseError)
1563
+ return { ok: false, path, harness, dryRun, message: read.parseError, backupPath: null, actions: null };
1564
+ const delta = computeCaptureHookRemoval(read.parsed ?? {});
1565
+ const message = delta.changed
1566
+ ? `would remove the capture hooks (${describeCaptureActions(delta.actions)}) from ${path} (dry run — nothing written)`
1567
+ : `no capture hooks found in ${path} — nothing to remove (dry run)`;
1568
+ return { ok: true, path, harness, dryRun, message, backupPath: null, actions: delta.actions };
1569
+ }
1570
+ let actions = null;
1571
+ let refused = false;
1572
+ const result = withConfigCriticalSection(path, (bytes) => {
1573
+ const read = parseSettingsBytes(bytes, path);
1574
+ if (read.parseError) {
1575
+ refused = true;
1576
+ return { hold: `${read.parseError} — refusing to modify a file we can't safely parse. Original left untouched at ${path}.` };
1577
+ }
1578
+ const delta = computeCaptureHookRemoval(read.parsed ?? {});
1579
+ actions = delta.actions;
1580
+ if (!delta.changed)
1581
+ return { noop: `no capture hooks found in ${path} — nothing to remove` };
1582
+ return { write: encodeConfig(delta.newConfig) };
1583
+ }, { backup: (bytes) => backupBytesTo(path, bytes) });
1584
+ if (result.status === "written" || result.status === "noop") {
1585
+ rmSync(captureInstallRoot(homeDir), { recursive: true, force: true });
1586
+ }
1587
+ const backupPath = result.backupPath ?? null;
1588
+ if (result.status === "written") {
1589
+ return { ok: true, path, harness, dryRun, message: `removed the capture hooks from ${path}`, backupPath, actions };
1590
+ }
1591
+ if (result.status === "noop") {
1592
+ return { ok: true, path, harness, dryRun, message: result.message, backupPath, actions };
1593
+ }
1594
+ if (result.status === "held") {
1595
+ return { ok: false, path, harness, dryRun, message: result.message, backupPath, actions: refused ? null : actions };
1596
+ }
1597
+ return { ok: false, path, harness, dryRun, message: result.message, backupPath, actions: null };
1598
+ }
1599
+ /** Read-only capture status; names missing events in partial installations. */
1600
+ export function captureHookStatus(homeDir, harness) {
1601
+ const path = hookSettingsPath(homeDir, harness);
1602
+ const read = readSettingsFile(path);
1603
+ const config = read.parsed ?? {};
1604
+ const matching = CAPTURE_HOOK_EVENTS.map((event) => findCaptureEntries(config, event, command => isHookStatusCandidate(command, CAPTURE_HOOK_MARKER)));
1605
+ const entries = matching.map((entries) => entries[0] ?? null);
1606
+ const commands = CAPTURE_HOOK_EVENTS.map((event, i) => {
1607
+ const entry = entries[i];
1608
+ if (!entry)
1609
+ return null;
1610
+ const command = entry.group.hooks[entry.hookIndex]?.command;
1611
+ return typeof command === "string" ? command : "";
1612
+ });
1613
+ const problems = [];
1614
+ const presentCount = commands.filter((command) => command !== null).length;
1615
+ if (presentCount === 0)
1616
+ return { path, harness, installed: false, state: "absent", problems };
1617
+ const expected = expectedCaptureCommand(commands);
1618
+ let runtimeFailure = null;
1619
+ const checked = new Map();
1620
+ for (const [i, event] of CAPTURE_HOOK_EVENTS.entries()) {
1621
+ const matches = matching[i];
1622
+ if (matches.length === 0)
1623
+ problems.push(`${event} missing`);
1624
+ if (matches.length > 1)
1625
+ problems.push(`${event} has duplicate capture entries`);
1626
+ for (const entry of matches) {
1627
+ const hook = entry.group.hooks[entry.hookIndex];
1628
+ if (hook.type !== "command")
1629
+ problems.push(`${event} carries an unexpected type`);
1630
+ const command = hook.command;
1631
+ if (!isFlairCaptureCommand(command)) {
1632
+ problems.push(`${event}[${entry.groupIndex}].hooks[${entry.hookIndex}]: noncanonical capture command`);
1633
+ continue;
1634
+ }
1635
+ if (command !== expected)
1636
+ problems.push(`${event} carries a different command`);
1637
+ const want = CAPTURE_HOOK_MATCHERS[event];
1638
+ const matcher = entry.group.matcher;
1639
+ if (want === null ? matcher != null && matcher !== "" : matcher !== want) {
1640
+ problems.push(`${event} carries an unexpected matcher`);
1641
+ }
1642
+ if (!checked.has(command))
1643
+ checked.set(command, captureCommandFailure(command));
1644
+ const failure = checked.get(command);
1645
+ if (failure) {
1646
+ runtimeFailure ??= failure;
1647
+ problems.push(`${event}: ${failure}`);
1648
+ }
1649
+ }
1650
+ }
1651
+ if (presentCount < CAPTURE_HOOK_EVENTS.length) {
1652
+ return { path, harness, installed: false, state: "partial", problems };
1653
+ }
1654
+ if (runtimeFailure || problems.length > 0) {
1655
+ return { path, harness, installed: false, state: "stale", ...(runtimeFailure ? { runtimeFailure } : {}), problems };
1656
+ }
1657
+ return { path, harness, installed: true, state: "installed", problems };
1658
+ }