@tpsdev-ai/flair 0.57.0 → 0.59.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 (143) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +4 -1
  3. package/config.yaml +3 -0
  4. package/dist/build-info.json +3 -3
  5. package/dist/cli.js +1726 -376
  6. package/dist/commands/agent.js +160 -2
  7. package/dist/commands/doctor.js +177 -27
  8. package/dist/commands/federation.js +2 -1
  9. package/dist/commands/hook.js +10 -2
  10. package/dist/commands/init.js +150 -44
  11. package/dist/commands/mcp.js +53 -22
  12. package/dist/commands/memory.js +24 -2
  13. package/dist/commands/quality.js +26 -18
  14. package/dist/commands/service.js +137 -22
  15. package/dist/commands/status.js +114 -3
  16. package/dist/commands/upgrade.js +204 -84
  17. package/dist/doctor-client.js +50 -4
  18. package/dist/federation/scheduler.js +253 -4
  19. package/dist/install/clients.js +89 -23
  20. package/dist/install/global-bin-path.js +26 -6
  21. package/dist/lib/atomic-write.js +256 -0
  22. package/dist/lib/daemon-liveness.js +103 -0
  23. package/dist/lib/doctor-run.js +72 -0
  24. package/dist/lib/embed-gpu-doctor.js +49 -26
  25. package/dist/lib/federation-memory-attributes.js +15 -0
  26. package/dist/lib/flair-agent-role.js +116 -0
  27. package/dist/lib/init-admin-pass.js +4 -2
  28. package/dist/lib/init-listener-environ.js +38 -0
  29. package/dist/lib/init-occupied-listener.js +165 -0
  30. package/dist/lib/launchd-domain-preflight.js +448 -0
  31. package/dist/lib/launchd-management.js +179 -8
  32. package/dist/lib/launchd-repair.js +95 -0
  33. package/dist/lib/mcp-enable.js +667 -72
  34. package/dist/lib/memory-attributes.js +77 -0
  35. package/dist/lib/node-alias-path.js +95 -0
  36. package/dist/lib/npm-registry.js +119 -6
  37. package/dist/lib/owned-pins.js +20 -6
  38. package/dist/lib/process-start-time.js +32 -0
  39. package/dist/lib/service-repoint-apply.js +267 -0
  40. package/dist/lib/service-repoint.js +575 -0
  41. package/dist/lib/toml-string-array.js +104 -0
  42. package/dist/lib/tree-divergence.js +716 -0
  43. package/dist/lib/upgrade-plain-tree.js +18 -8
  44. package/dist/lib/upgrade-prior-liveness.js +69 -0
  45. package/dist/lib/upgrade-rollback.js +116 -0
  46. package/dist/rem/runner.js +11 -0
  47. package/dist/resources/Agent.js +54 -21
  48. package/dist/resources/AgentSeed.js +44 -1
  49. package/dist/resources/Federation.js +84 -54
  50. package/dist/resources/Memory.js +567 -72
  51. package/dist/resources/MemoryArchive.js +9 -0
  52. package/dist/resources/MemoryBootstrap.js +125 -29
  53. package/dist/resources/MemoryFeed.js +204 -3
  54. package/dist/resources/MemoryHostSource.js +90 -0
  55. package/dist/resources/MemoryMaintenance.js +121 -32
  56. package/dist/resources/MemoryReflect.js +4 -1
  57. package/dist/resources/MemoryReindex.js +7 -4
  58. package/dist/resources/MemoryUsage.js +53 -3
  59. package/dist/resources/OrgSkillAssignment.js +209 -0
  60. package/dist/resources/Presence.js +18 -10
  61. package/dist/resources/RecordUsage.js +30 -40
  62. package/dist/resources/Relationship.js +167 -78
  63. package/dist/resources/SemanticSearch.js +19 -6
  64. package/dist/resources/Soul.js +31 -19
  65. package/dist/resources/XAA.js +47 -14
  66. package/dist/resources/agent-auth.js +16 -10
  67. package/dist/resources/agent-status-guard.js +63 -0
  68. package/dist/resources/auth-middleware.js +137 -49
  69. package/dist/resources/auto-promote-lib.js +4 -4
  70. package/dist/resources/bm25-index-service.js +246 -32
  71. package/dist/resources/bm25-status.js +132 -0
  72. package/dist/resources/ed25519-auth.js +11 -54
  73. package/dist/resources/embed-gpu.js +262 -47
  74. package/dist/resources/embeddings-boot.js +52 -17
  75. package/dist/resources/federation-classify.js +34 -0
  76. package/dist/resources/federation-crypto.js +65 -19
  77. package/dist/resources/flair-agent-role-boot.js +26 -0
  78. package/dist/resources/health.js +67 -16
  79. package/dist/resources/host-pointer/registry.js +35 -0
  80. package/dist/resources/host-pointer-adapter.js +15 -0
  81. package/dist/resources/host-source-visibility.js +167 -0
  82. package/dist/resources/host-source.js +151 -0
  83. package/dist/resources/instance-identity.js +3 -2
  84. package/dist/resources/key-lock.js +31 -0
  85. package/dist/resources/mcp-handler.js +147 -51
  86. package/dist/resources/mcp-oauth.js +3 -6
  87. package/dist/resources/mcp-tools.js +47 -25
  88. package/dist/resources/memory-consolidate-lib.js +3 -1
  89. package/dist/resources/memory-declared-attributes.js +103 -0
  90. package/dist/resources/memory-feed-lib.js +5 -1
  91. package/dist/resources/memory-host-source.js +163 -0
  92. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  93. package/dist/resources/migrations/visibility-backfill.js +4 -1
  94. package/dist/resources/multi-worker-guard.js +121 -0
  95. package/dist/resources/oauth-discovery.js +1 -0
  96. package/dist/resources/oauth-wellknown.js +8 -4
  97. package/dist/resources/originator-instance.js +235 -0
  98. package/dist/resources/promotion-stamp.js +2 -0
  99. package/dist/resources/provenance.js +111 -11
  100. package/dist/resources/record-owner-guard.js +19 -0
  101. package/dist/resources/record-type-kit.js +9 -12
  102. package/dist/resources/record-types.js +22 -6
  103. package/dist/resources/relay-ops.js +28 -3
  104. package/dist/resources/replay-store.js +336 -0
  105. package/dist/resources/request-transaction.js +78 -0
  106. package/dist/resources/search-readiness.js +19 -21
  107. package/dist/resources/semantic-retrieval-core.js +5 -1
  108. package/dist/resources/skill-manifest.js +181 -0
  109. package/dist/resources/skill-provenance.js +15 -10
  110. package/dist/resources/table-patch-policy.js +109 -0
  111. package/dist/resources/table-patches.js +17 -0
  112. package/dist/resources/table-post-policy.js +138 -0
  113. package/dist/resources/table-posts.js +22 -0
  114. package/dist/resources/table-subscription-policy.js +135 -0
  115. package/dist/resources/table-subscriptions.js +19 -0
  116. package/dist/resources/tool-descriptors/index.js +15 -15
  117. package/dist/resources/trust-block.js +10 -3
  118. package/dist/resources/usage-recording.js +169 -41
  119. package/dist/src/lib/flair-agent-role.js +116 -0
  120. package/dist/src/lib/memory-attributes.js +77 -0
  121. package/docs/access-control.md +667 -0
  122. package/docs/api-reference.md +85 -17
  123. package/docs/auth.md +4 -0
  124. package/docs/claude-code.md +132 -0
  125. package/docs/deepseek-harness.md +1 -1
  126. package/docs/deployment.md +1 -1
  127. package/docs/federation.md +1 -1
  128. package/docs/integrations.md +6 -6
  129. package/docs/mcp-clients.md +16 -24
  130. package/docs/notes/mcp-oauth-model2.md +15 -1
  131. package/docs/quickstart.md +5 -0
  132. package/docs/releasing.md +152 -20
  133. package/docs/supply-chain-policy.md +10 -5
  134. package/docs/troubleshooting.md +11 -0
  135. package/docs/upgrade.md +187 -61
  136. package/package.json +10 -5
  137. package/schemas/agent.graphql +9 -6
  138. package/schemas/federation.graphql +2 -11
  139. package/schemas/memory.graphql +137 -17
  140. package/schemas/oauth.graphql +8 -4
  141. package/schemas/replay.graphql +18 -0
  142. package/templates/launchd/start-flair-with-admin-pass.sh +95 -0
  143. package/dist/resources/federation-nonce-store.js +0 -195
@@ -0,0 +1,77 @@
1
+ /** Shared Memory field contract for resource writers and federation readers.
2
+ * Kept under src so the CLI build can include it within its rootDir; the
3
+ * server build also emits this dependency under dist/src/lib.
4
+ * Pure data: importing this contract never loads Harper.
5
+ */
6
+ /** Every DECLARED attribute of `type Memory` in schemas/memory.graphql, in
7
+ * schema order. Keep in sync with the schema (the drift test enforces it). */
8
+ export const DECLARED_MEMORY_ATTRIBUTES = Object.freeze([
9
+ "id",
10
+ "agentId",
11
+ "content",
12
+ "contentHash",
13
+ "trigger",
14
+ "visibility",
15
+ "embedding",
16
+ "embeddingModel",
17
+ "tags",
18
+ "durability",
19
+ "source",
20
+ "type",
21
+ "createdAt",
22
+ "updatedAt",
23
+ "instanceToken",
24
+ "expiresAt",
25
+ "retrievalCount",
26
+ "lastRetrieved",
27
+ "usageCount",
28
+ "promotionStatus",
29
+ "promotedAt",
30
+ "promotedBy",
31
+ "archived",
32
+ "archivedAt",
33
+ "archivedBy",
34
+ "parentId",
35
+ "derivedFrom",
36
+ "sessionId",
37
+ "lastReflected",
38
+ "supersedes",
39
+ "subject",
40
+ "summary",
41
+ "validFrom",
42
+ "validTo",
43
+ "_safetyFlags",
44
+ "provenance",
45
+ "originatorInstanceId",
46
+ "metadata",
47
+ "entities",
48
+ ]);
49
+ /** Pre-existing UNDECLARED attributes the codebase deliberately stores on a
50
+ * Memory row and must keep (the guard's job is the POINTER, not these).
51
+ * This is an EXPLICIT, NAMED list measured against a live store (A1'' item 1)
52
+ * — never derived from the schema, because the schema is not the source of
53
+ * truth for what is on disk:
54
+ * - `meta` — the continuity-journal payload {seq, processUUID, sessionId,
55
+ * hook} written by the capture path (PUT /Memory/<id>,
56
+ * flair#1257 slice 3); Kern's slice-2 ruling settled that it
57
+ * round-trips as an undeclared field, and
58
+ * test/integration/continuity-rem-promotion-1257.test.ts pins
59
+ * that. It is not a flat String, so declaring it would change
60
+ * the stored shape.
61
+ * - `kind` — carried on a couple of older rows.
62
+ * - `_originatorInstanceId`, `_syncedFrom`, `_syncedAt` — federation
63
+ * bookkeeping stamped by the RECEIVER at merge time
64
+ * (resources/Federation.ts's mergeRecord) on every synced row.
65
+ * Any OTHER undeclared key (in particular any pointer input) is stripped. */
66
+ export const UNDECLARED_ALLOWED = Object.freeze([
67
+ "meta",
68
+ "kind",
69
+ "_originatorInstanceId",
70
+ "_syncedFrom",
71
+ "_syncedAt",
72
+ ]);
73
+ /** Every field retained by Memory writers and the inbound federation guard. */
74
+ export const MEMORY_ATTRIBUTES = Object.freeze([
75
+ ...DECLARED_MEMORY_ATTRIBUTES,
76
+ ...UNDECLARED_ALLOWED,
77
+ ]);
@@ -0,0 +1,95 @@
1
+ /**
2
+ * node-alias-path.ts — the node binary path to write into a generated service
3
+ * unit or shim (flair#2034 §2).
4
+ *
5
+ * A version manager exposes each installed runtime under a path that carries
6
+ * its exact version (`…/installs/node/24.19.0/bin/node`). Some also expose a
7
+ * FLOATING alias that resolves to one of them. This module writes such an alias
8
+ * instead of the exact path when, and only when, the alias resolves (realpath)
9
+ * to the very binary we would otherwise write. When no alias resolves to the
10
+ * same binary, the exact path is written unchanged: a path that points at a
11
+ * DIFFERENT runtime would be worse than the bug.
12
+ *
13
+ * Where an alias exists, and where it does not:
14
+ *
15
+ * - mise: `$MISE_DATA_DIR | ~/.local/share/mise` + `/installs/node/<major>/bin/node`.
16
+ * mise keeps `installs/node/<major>` as a symlink to the newest installed
17
+ * runtime of that major, so it resolves to the same binary and is written.
18
+ * - Volta: `$VOLTA_HOME | ~/.volta` + `/bin/node`. Considered, but a standard
19
+ * Volta install makes that path a link to `volta-shim`, whose realpath is
20
+ * not a node binary, so the equality check rejects it and the exact path is
21
+ * written. It is chosen only on a setup where it really is the same binary.
22
+ * - nvm, fnm, asdf: no alias path of this kind (nvm's default alias is a text
23
+ * file; asdf's `shims/node` is a script), so the exact path is written.
24
+ *
25
+ * WHAT A FLOATING ALIAS DOES LATER. The alias is a moving pointer, by design:
26
+ * when mise retargets `installs/node/24` to a newer 24.x, a unit holding the
27
+ * alias runs THAT runtime from then on, without flair being re-run. That keeps
28
+ * the unit's node path from dangling after a patch/minor bump, but it is a
29
+ * different runtime than the one that was in use when the unit was written.
30
+ *
31
+ * WHAT IT DOES NOT DO. Only the node binary floats. The install tree a unit
32
+ * serves (its working directory, the Harper entry, the launcher, the flair
33
+ * script a shim runs) lives under the exact runtime's global prefix
34
+ * (`…/installs/node/24.19.0/lib/node_modules/@tpsdev-ai/flair`), and is written
35
+ * as that exact path. After a Node bump, `npm i -g @tpsdev-ai/flair` under the
36
+ * new runtime installs a NEW tree; the unit keeps serving the old one until it
37
+ * is re-pointed (`flair init && flair restart`).
38
+ */
39
+ import { existsSync, realpathSync } from "node:fs";
40
+ import { join } from "node:path";
41
+ import { resolveHome } from "./home.js";
42
+ /** `24.19.0` / `v24.19.0` → `24.19.0`; null when no version is present. */
43
+ export function parseNodeVersion(nodePath) {
44
+ const m = /(?:^|[/\\])v?(\d+\.\d+\.\d+)(?:[/\\]|$)/.exec(nodePath);
45
+ return m ? m[1] : null;
46
+ }
47
+ /**
48
+ * The floating aliases a version manager might expose for `nodeBin`'s runtime.
49
+ * Pure: derived from the path + env only, no filesystem access. Callers filter
50
+ * by existence + realpath equality.
51
+ */
52
+ export function aliasCandidates(nodeBin, hooks = {}) {
53
+ const home = hooks.home ?? resolveHome();
54
+ const env = hooks.env ?? process.env;
55
+ const version = parseNodeVersion(nodeBin);
56
+ const out = [];
57
+ if (!version || !home)
58
+ return out;
59
+ const major = version.split(".")[0];
60
+ const miseData = env.MISE_DATA_DIR ?? join(home, ".local", "share", "mise");
61
+ out.push({ manager: "mise", path: join(miseData, "installs", "node", major, "bin", "node") });
62
+ const voltaHome = env.VOLTA_HOME ?? join(home, ".volta");
63
+ out.push({ manager: "volta", path: join(voltaHome, "bin", "node") });
64
+ return out;
65
+ }
66
+ /**
67
+ * The node path to WRITE into a generated unit: a floating alias whose realpath
68
+ * is the same binary as `nodeBin`, when one exists; otherwise `nodeBin`
69
+ * unchanged. mise's major alias is preferred over Volta's when both match.
70
+ */
71
+ export function preferVersionManagerAlias(nodeBin, hooks = {}) {
72
+ const exists = hooks.exists ?? existsSync;
73
+ const realpath = hooks.realpath ?? ((p) => realpathSync(p));
74
+ let target;
75
+ try {
76
+ target = realpath(nodeBin);
77
+ }
78
+ catch {
79
+ return nodeBin; // the resolved binary is not readable — write it as given
80
+ }
81
+ for (const c of aliasCandidates(nodeBin, hooks)) {
82
+ try {
83
+ if (c.path === nodeBin)
84
+ continue;
85
+ if (!exists(c.path))
86
+ continue;
87
+ if (realpath(c.path) === target)
88
+ return c.path;
89
+ }
90
+ catch {
91
+ /* an unreadable candidate is not a match */
92
+ }
93
+ }
94
+ return nodeBin;
95
+ }
@@ -482,15 +482,59 @@ function runNpmViewJson(spec, field, registryUrl, timeoutMs) {
482
482
  const message = String(stderr || err.message || "npm view failed").trim();
483
483
  return resolve({ ok: false, message });
484
484
  }
485
- try {
486
- resolve({ ok: true, data: JSON.parse(String(stdout).trim()), message: "" });
487
- }
488
- catch {
489
- resolve({ ok: false, message: "npm view returned non-JSON output" });
490
- }
485
+ const parsed = parseNpmViewStdout(String(stdout));
486
+ resolve(parsed);
491
487
  });
492
488
  });
493
489
  }
490
+ /** Parse trimmed stdout as JSON; distinguish empty output from invalid JSON. */
491
+ export function parseNpmViewStdout(stdout) {
492
+ const text = stdout.trim();
493
+ if (text === "")
494
+ return { ok: false, message: "npm view returned empty output" };
495
+ try {
496
+ return { ok: true, data: JSON.parse(text), message: "" };
497
+ }
498
+ catch {
499
+ return { ok: false, message: "npm view returned malformed JSON" };
500
+ }
501
+ }
502
+ /** Remove characters in U+0000-U+001F and U+007F-U+009F. */
503
+ export function stripControlChars(value) {
504
+ return value.replace(/[\u0000-\u001F\u007F\u0080-\u009F]/g, "");
505
+ }
506
+ /** Accept a non-array object whose name and version equal the requested values. */
507
+ export function isExactVersionDocument(data, packageName, version) {
508
+ if (!data || typeof data !== "object" || Array.isArray(data))
509
+ return false;
510
+ const doc = data;
511
+ if (doc.version !== version)
512
+ return false;
513
+ if (doc.name !== packageName)
514
+ return false;
515
+ return true;
516
+ }
517
+ /**
518
+ * Empty-output errors and blank strings yield active; nonblank strings yield
519
+ * deprecated. Other errors and non-string values yield unavailable.
520
+ * Deprecation messages have control characters removed and a fallback if empty.
521
+ */
522
+ export function deprecationFromNpmView(parsed) {
523
+ if (!parsed.ok) {
524
+ if (parsed.message === "npm view returned empty output")
525
+ return { kind: "active" };
526
+ return { kind: "unavailable", message: parsed.message };
527
+ }
528
+ // Non-string JSON values yield unavailable, including null.
529
+ if (typeof parsed.data !== "string") {
530
+ return { kind: "unavailable", message: "npm view deprecated field was not a string" };
531
+ }
532
+ const raw = parsed.data;
533
+ const cleaned = stripControlChars(raw).trim();
534
+ if (!raw.trim())
535
+ return { kind: "active" };
536
+ return { kind: "deprecated", message: cleaned || "npm marked this version deprecated" };
537
+ }
494
538
  /** True when this registry should be queried through npm rather than fetch(). */
495
539
  async function useNpmTransport(registry, deps) {
496
540
  if (registry.url === DEFAULT_NPM_REGISTRY)
@@ -576,3 +620,72 @@ export async function fetchDeclaredDependencies(packageName, version, deps = {})
576
620
  : null;
577
621
  return { kind: "ok", dependencies, registry };
578
622
  }
623
+ /**
624
+ * Query deprecation for a strict semver version using the resolved registry.
625
+ * HTTP responses must pass isExactVersionDocument; npm output goes through
626
+ * deprecationFromNpmView. Absent HTTP fields and blank strings yield active;
627
+ * nonblank strings yield deprecated. Non-string fields yield unavailable.
628
+ * Registry resolution errors return refused; invalid versions return invalid.
629
+ * decideDeprecatedRollback refuses only a reported deprecated result.
630
+ */
631
+ export async function fetchVersionDeprecation(packageName, version, deps = {}) {
632
+ if (!isStrictSemver(version))
633
+ return { kind: "invalid", value: version };
634
+ let registry;
635
+ try {
636
+ registry = await resolveNpmRegistryDetailed(packageName, deps);
637
+ }
638
+ catch (err) {
639
+ if (err instanceof RegistryRefusalError)
640
+ return { kind: "refused", message: err.message };
641
+ return { kind: "refused", message: err instanceof Error ? err.message : String(err) };
642
+ }
643
+ deps.onRegistry?.(registry);
644
+ const timeoutMs = deps.timeoutMs ?? 5000;
645
+ if (await useNpmTransport(registry, deps)) {
646
+ const view = deps.npmViewJson ?? runNpmViewJson;
647
+ const out = await view(`${packageName}@${version}`, "deprecated", registry.url, timeoutMs);
648
+ const field = deprecationFromNpmView(out);
649
+ if (field.kind === "unavailable")
650
+ return { kind: "unavailable", message: field.message, registry };
651
+ if (field.kind === "deprecated")
652
+ return { kind: "deprecated", message: field.message, registry };
653
+ return { kind: "active", registry };
654
+ }
655
+ const out = await fetchRegistryJson(`${registry.url}/${packageName}/${version}`, timeoutMs, deps.fetchImpl);
656
+ if (!out.ok)
657
+ return { kind: "unavailable", message: out.message, registry };
658
+ if (!isExactVersionDocument(out.data, packageName, version)) {
659
+ return {
660
+ kind: "unavailable",
661
+ message: `registry response was not a version document for ${packageName}@${version}`,
662
+ registry,
663
+ };
664
+ }
665
+ const deprecated = out.data.deprecated;
666
+ if (!Object.prototype.hasOwnProperty.call(out.data, "deprecated")) {
667
+ return { kind: "active", registry };
668
+ }
669
+ if (typeof deprecated === "string" && !deprecated.trim())
670
+ return { kind: "active", registry };
671
+ if (deprecated === null) {
672
+ return {
673
+ kind: "unavailable",
674
+ message: `registry deprecated field for ${packageName}@${version} was null`,
675
+ registry,
676
+ };
677
+ }
678
+ if (typeof deprecated !== "string") {
679
+ return {
680
+ kind: "unavailable",
681
+ message: `registry deprecated field for ${packageName}@${version} was not a string`,
682
+ registry,
683
+ };
684
+ }
685
+ const cleaned = stripControlChars(deprecated).trim();
686
+ return {
687
+ kind: "deprecated",
688
+ message: cleaned || "npm marked this version deprecated",
689
+ registry,
690
+ };
691
+ }
@@ -16,11 +16,11 @@
16
16
  import { existsSync, lstatSync, readFileSync, statSync } from "node:fs";
17
17
  import { dirname, join } from "node:path";
18
18
  import { withHome } from "./home.js";
19
- import { ALL_CLIENTS, clientConfigPath, repinCodexPin, repinJsonMcpPin, } from "../install/clients.js";
20
- import { checkSessionStartHook, isFlairHookCommand, readClientMcpBlock, } from "../doctor-client.js";
19
+ import { ALL_CLIENTS, clientConfigPath, codexWiringPin, repinCodexPin, repinJsonMcpPin, } from "../install/clients.js";
20
+ import { checkSessionStartHook, isFlairHookCommand, SESSION_START_HOOK_INVOCATION_RE, readClientMcpBlock, } from "../doctor-client.js";
21
21
  import { decodeWiringSpec, decodeWiringSpecs, isComparableWiringPin, wiringPinString, } from "./wiring-spec.js";
22
22
  import { isUnsafeAdapterPin } from "./stale-client-pin.js";
23
- import { hookInstallHint, hookSettingsPath, repinSessionStartHook, SUPPORTED_HARNESSES, } from "../hook-install.js";
23
+ import { hookInstallHint, parseInstallerHookForm, hookSettingsPath, repinSessionStartHook, SUPPORTED_HARNESSES, } from "../hook-install.js";
24
24
  import { flairCliVersion, isResolvedVersion, FLAIR_MCP_PACKAGE } from "./mcp-spec.js";
25
25
  import { comparePinVersions, pinWriteWouldLowerOrIsUnknown } from "./upgrade-status.js";
26
26
  function displayHomePath(homeDir, path) {
@@ -87,7 +87,9 @@ export function readOwnedPin(target, homeDir) {
87
87
  entryExists: block.entryExists,
88
88
  // Read the pin whenever the ENTRY exists — an entry without an identity is
89
89
  // still a pin we own and may refresh (flair#1834 A1 item 1).
90
- pin: block.entryExists ? wiringPinString(decodeWiringSpec(text, FLAIR_MCP_PACKAGE)) : null,
90
+ pin: block.entryExists
91
+ ? wiringPinString(decodeWiringSpec(target.id === "codex" ? codexWiringPin(text) : text, FLAIR_MCP_PACKAGE))
92
+ : null,
91
93
  };
92
94
  }
93
95
  export function readOwnedPins(homeDir) {
@@ -280,8 +282,20 @@ export function repinSessionStartHookGuarded(homeDir, harness, target) {
280
282
  displayPath: hookSettingsPath(homeDir, harness),
281
283
  };
282
284
  const wouldWrite = flairCliVersion();
283
- const existing = readOwnedPin(resolved, homeDir).pin;
284
- if (pinWriteWouldLowerOrIsUnknown(existing, wouldWrite)) {
285
+ const command = checkSessionStartHook(homeDir, resolved.path).command;
286
+ const form = command ? parseInstallerHookForm(command) : null;
287
+ // A form supplies the exact span the writer replaces. For a rejected form,
288
+ // the status-only match may recover an unreadable pin for a HOLD; it cannot
289
+ // authorize a write. The writer still validates the full command in-lock.
290
+ const invocation = form ? undefined : command?.match(SESSION_START_HOOK_INVOCATION_RE)?.[0];
291
+ const spec = form?.pkgSpec
292
+ ?? invocation?.slice("npx -y -p ".length, -" flair-session-start".length);
293
+ const existing = spec ? wiringPinString(decodeWiringSpec(spec, FLAIR_MCP_PACKAGE)) : null;
294
+ // A comparable pin in a non-installer command is a shape refusal, not an
295
+ // unknown pin. Let the writer retain its "not one of the installer forms"
296
+ // classification. Unreadable pins retain their raw-value hold diagnostic.
297
+ if (pinWriteWouldLowerOrIsUnknown(existing, wouldWrite)
298
+ && (form !== null || comparePinVersions(existing, wouldWrite) === null)) {
285
299
  return {
286
300
  target: resolved,
287
301
  action: "hold",
@@ -43,6 +43,38 @@ function readPsLstart(pid) {
43
43
  return null;
44
44
  }
45
45
  }
46
+ /**
47
+ * The pid's start time truncated to a whole second, in epoch ms (flair#2056).
48
+ *
49
+ * macOS: the second `ps -o lstart=` reports. The zone correction is the
50
+ * `applyLstartZoneOffset` offset rounded to a whole minute: that offset is the
51
+ * parser's zone error (whole minutes) minus this process's sub-second start
52
+ * fraction, and the rounding drops the fraction. Linux: the `/proc` start time
53
+ * truncated to the second.
54
+ */
55
+ export function readProcessStartSecondMs(pid) {
56
+ if (!Number.isInteger(pid) || pid <= 0)
57
+ return null;
58
+ if (process.platform === "darwin") {
59
+ const targetRaw = readPsLstart(pid);
60
+ if (targetRaw === null)
61
+ return null;
62
+ const targetParsed = parsePsLstart(targetRaw);
63
+ if (targetParsed === null)
64
+ return null;
65
+ const ownRaw = pid === process.pid ? targetRaw : readPsLstart(process.pid);
66
+ if (ownRaw === null)
67
+ return null;
68
+ const ownParsed = parsePsLstart(ownRaw);
69
+ if (ownParsed === null)
70
+ return null;
71
+ const ownTrueStartMs = Date.now() - process.uptime() * 1000;
72
+ const zoneErrorMs = Math.round((ownParsed - ownTrueStartMs) / 60_000) * 60_000;
73
+ return targetParsed - zoneErrorMs;
74
+ }
75
+ const ms = readProcessStartTimeMs(pid);
76
+ return ms === null ? null : Math.floor(ms / 1000) * 1000;
77
+ }
46
78
  export function readProcessStartTimeMs(pid) {
47
79
  if (!Number.isInteger(pid) || pid <= 0)
48
80
  return null;
@@ -0,0 +1,267 @@
1
+ /**
2
+ * service-repoint-apply.ts — commit a re-point plan to an operator's unit file
3
+ * (flair#2034 §2).
4
+ *
5
+ * The planners in service-repoint.ts are pure. This module is where a plan
6
+ * meets the file and the service manager, and it holds three rules:
7
+ *
8
+ * 1. A plan is written only over the file it was PLANNED FROM: the file was
9
+ * read as a regular file (never through a symlink), and immediately before
10
+ * the rename it is re-checked — same file, same bytes — or nothing is
11
+ * written (atomic-write.ts, `expect`).
12
+ * 2. systemd: after the write, the manager is reloaded and asked what it now
13
+ * holds for the unit (the file it loaded, its drop-ins, its working
14
+ * directory). When the reload fails or the manager does not hold what was
15
+ * written, the previous bytes are put back, the manager is reloaded again
16
+ * and ASKED AGAIN. That query compares three fields — FragmentPath,
17
+ * drop-ins, WorkingDirectory — with the values captured before the write;
18
+ * when they are back, the result says exactly that, and still calls full
19
+ * agreement between the restored file and the manager unverified (three
20
+ * fields are not the whole unit). Anything short of that — a failed
21
+ * restore, a failed second reload, a different or missing answer — is
22
+ * reported with the manager's state as UNVERIFIED.
23
+ * 3. Linux: a unit with drop-ins — any the manager reports, from any
24
+ * location, or a `<unit>.d` directory beside the file — is refused, and
25
+ * so is one whose MainPID, asked again immediately before the write, is
26
+ * not the serving process the unit was proven to run.
27
+ * 4. `flair restart` on Linux (restartOnLinux): a proven user unit is
28
+ * restarted through systemd and its new main process verified; a process
29
+ * that is the main process of any other systemd unit is never stopped and
30
+ * respawned outside it.
31
+ *
32
+ * Every filesystem and service-manager call is injectable, so each branch is
33
+ * driven by a test with no real launchd, systemd or operator file.
34
+ */
35
+ import { snapshotRegularFile, writeFilesAtomically } from "./atomic-write.js";
36
+ import { planSystemdUnitRuntimeRepoint } from "./service-repoint.js";
37
+ import { planLinuxRestart, restartedUnitProblem, } from "./tree-divergence.js";
38
+ function msg(err) {
39
+ return err?.message ?? String(err);
40
+ }
41
+ /** Apply `plan`, which was computed from `planned` (see the module header). */
42
+ export function applyRepointPlan(plan, planned, opts = {}) {
43
+ const unitPath = planned.path;
44
+ switch (plan.kind) {
45
+ case "current":
46
+ case "pinned-node":
47
+ return { kind: plan.kind, unitPath, detail: plan.detail };
48
+ case "refuse":
49
+ return { kind: "refused", unitPath, detail: plan.detail };
50
+ case "repoint":
51
+ break;
52
+ }
53
+ if (opts.dryRun)
54
+ return { kind: "would-repoint", unitPath, detail: plan.detail.replace(/^re-pointed/, "would re-point") };
55
+ const handEdit = opts.handEdit ? ` ${opts.handEdit}` : "";
56
+ try {
57
+ writeFilesAtomically([{ path: unitPath, content: plan.text, mode: planned.mode, expect: planned }], opts.atomic);
58
+ }
59
+ catch (err) {
60
+ return {
61
+ kind: "refused",
62
+ unitPath,
63
+ detail: `${unitPath} was not re-pointed: ${msg(err)}. Re-run the command to plan again from the file as it is now.${handEdit}`,
64
+ };
65
+ }
66
+ if (!opts.reload)
67
+ return { kind: "repointed", unitPath, detail: plan.detail };
68
+ let failure = null;
69
+ try {
70
+ opts.reload();
71
+ failure = opts.verifyLoaded?.("planned") ?? null;
72
+ }
73
+ catch (err) {
74
+ failure = `the service manager could not reload it (${msg(err)})`;
75
+ }
76
+ if (failure === null)
77
+ return { kind: "repointed", unitPath, detail: plan.detail };
78
+ const unverified = "Run: systemctl --user daemon-reload, then check the unit with systemctl --user show.";
79
+ // Put the planned-from bytes back — only over the bytes flair itself wrote.
80
+ try {
81
+ const written = snapshotRegularFile(unitPath, { lstat: opts.atomic?.lstat, readBytes: opts.atomic?.readBytes });
82
+ if (written.content !== plan.text)
83
+ throw new Error(`${unitPath} was changed after flair wrote it`);
84
+ writeFilesAtomically([{ path: unitPath, content: planned.content, mode: planned.mode, expect: written }], opts.atomic);
85
+ }
86
+ catch (err) {
87
+ return {
88
+ kind: "refused",
89
+ unitPath,
90
+ detail: `${unitPath} was re-pointed on disk, but ${failure}, and restoring its previous content failed (${msg(err)}). ` +
91
+ "The file holds the RE-POINTED unit flair wrote (or, if it was changed after that write, the change); which " +
92
+ `unit the service manager holds is UNVERIFIED. Check the file by hand. ${unverified}`,
93
+ };
94
+ }
95
+ try {
96
+ opts.reload();
97
+ }
98
+ catch (err) {
99
+ return {
100
+ kind: "refused",
101
+ unitPath,
102
+ detail: `${unitPath} was not re-pointed: ${failure}. flair restored the file's previous content, but reloading the ` +
103
+ `service manager again failed (${msg(err)}): the file holds the previous unit; which unit the manager holds is ` +
104
+ `UNVERIFIED. ${unverified}`,
105
+ };
106
+ }
107
+ let back;
108
+ try {
109
+ back = opts.verifyLoaded ? opts.verifyLoaded("previous") : "flair cannot query this service manager";
110
+ }
111
+ catch (err) {
112
+ back = `the service manager could not be queried (${msg(err)})`;
113
+ }
114
+ if (back !== null) {
115
+ return {
116
+ kind: "refused",
117
+ unitPath,
118
+ detail: `${unitPath} was not re-pointed: ${failure}. flair restored the file's previous content and reloaded the ` +
119
+ "service manager, but the manager does not report the FragmentPath, drop-ins and WorkingDirectory captured " +
120
+ `before the write (${back}): the file holds the previous unit; which unit the manager holds is UNVERIFIED. ${unverified}`,
121
+ };
122
+ }
123
+ return {
124
+ kind: "refused",
125
+ unitPath,
126
+ detail: `${unitPath} was not re-pointed: ${failure}. flair restored the file's previous content and reloaded the service ` +
127
+ "manager; the manager's FragmentPath, drop-ins and WorkingDirectory are back at the values captured before the " +
128
+ "write. Only those three fields were checked, so full agreement between the restored file and what the manager " +
129
+ `loaded is unverified.${handEdit}`,
130
+ };
131
+ }
132
+ /**
133
+ * Re-point the systemd USER unit proven to own the serving process (Linux).
134
+ * Refuses drop-ins and anything that is not a regular unit file; plans from the
135
+ * snapshot; after the reload, requires the manager to report the same file, no
136
+ * drop-ins, and the new working directory — else restores (see applyRepointPlan).
137
+ */
138
+ export function repointSystemdUserUnit(serving, targets, deps, opts = {}) {
139
+ const unitPath = serving.unitPath;
140
+ const handEdit = `point its node, Harper entry${targets.launcher ? ", launcher (if it runs one)" : ""} and WorkingDirectory at ` +
141
+ `${targets.workingDirectory} by hand, then run: flair restart`;
142
+ if (serving.dropInPaths.length > 0) {
143
+ return {
144
+ kind: "refused",
145
+ unitPath,
146
+ detail: `systemd applies drop-ins to ${serving.unitName} (${serving.dropInPaths.join(", ")}), and a drop-in can set ` +
147
+ `ExecStart= or WorkingDirectory=, so flair does not re-point it. To move it, ${handEdit}`,
148
+ };
149
+ }
150
+ if (deps.exists(`${unitPath}.d`)) {
151
+ return {
152
+ kind: "refused",
153
+ unitPath,
154
+ detail: `${unitPath}.d exists and can hold drop-ins that set ExecStart= or WorkingDirectory=, so flair does not ` +
155
+ `re-point the unit. To move it, ${handEdit}`,
156
+ };
157
+ }
158
+ let planned;
159
+ try {
160
+ planned = snapshotRegularFile(unitPath, { lstat: deps.atomic?.lstat, readBytes: deps.atomic?.readBytes });
161
+ }
162
+ catch (err) {
163
+ return {
164
+ kind: "refused",
165
+ unitPath,
166
+ detail: `${unitPath} is not re-pointed: ${msg(err)}; flair rewrites only a regular unit file in place. To move it, ${handEdit}`,
167
+ };
168
+ }
169
+ const plan = planSystemdUnitRuntimeRepoint(planned.content, serving.unitTree ?? serving.dir, targets, deps.repoint, unitPath);
170
+ // Capture what the manager holds BEFORE writing: a restore is confirmed
171
+ // against it. When it cannot be read, a failed reload could never be
172
+ // verified, so nothing is written. The same answer must still name the
173
+ // serving process as the unit's MainPID.
174
+ let before = null;
175
+ if (plan.kind === "repoint" && !opts.dryRun) {
176
+ before = deps.unitState(serving.unitName);
177
+ if (!before || before.fragmentPath === null || !deps.repoint.samePath(before.fragmentPath, unitPath) || before.dropInPaths.length > 0) {
178
+ return {
179
+ kind: "refused",
180
+ unitPath,
181
+ detail: `${unitPath} is not re-pointed: systemd ${before ? `reports ${serving.unitName} from ${before.fragmentPath ?? "no file"} with drop-ins [${before.dropInPaths.join(", ")}]` : `did not report ${serving.unitName}`}, ` +
182
+ `so the state to restore to cannot be captured. To move it, ${handEdit}`,
183
+ };
184
+ }
185
+ // The write rests on the proof that this unit runs the serving process (its
186
+ // MainPID). A fresh answer naming another main process, or none, contradicts
187
+ // that proof, so nothing is written.
188
+ if (before.mainPid !== serving.pid) {
189
+ return {
190
+ kind: "refused",
191
+ unitPath,
192
+ detail: `${unitPath} is not re-pointed: systemd now reports ` +
193
+ `${before.mainPid === null ? "no main process" : `pid ${before.mainPid} as the main process`} ` +
194
+ `of ${serving.unitName}, ` +
195
+ `not the serving process (pid ${serving.pid}) it was proven to run, so the unit is not shown to run this ` +
196
+ `instance. Run \`flair status\` to see which process serves it, then re-run the command. To move it, ${handEdit}`,
197
+ };
198
+ }
199
+ }
200
+ const same = (a, b) => (a === null || b === null ? a === b : deps.repoint.samePath(a, b));
201
+ return applyRepointPlan(plan, planned, {
202
+ dryRun: opts.dryRun,
203
+ atomic: deps.atomic,
204
+ reload: deps.reload,
205
+ handEdit: `To move it, ${handEdit}`,
206
+ verifyLoaded: (want) => {
207
+ const st = deps.unitState(serving.unitName);
208
+ if (!st)
209
+ return `systemd did not report ${serving.unitName} after the reload`;
210
+ if (want === "previous") {
211
+ const was = before;
212
+ if (!same(st.fragmentPath, was.fragmentPath) ||
213
+ st.dropInPaths.join("\n") !== was.dropInPaths.join("\n") ||
214
+ !same(st.workingDirectory, was.workingDirectory)) {
215
+ return (`systemd reports ${serving.unitName} from ${st.fragmentPath ?? "no file"}, drop-ins [${st.dropInPaths.join(", ")}], ` +
216
+ `WorkingDirectory ${st.workingDirectory ?? "(none)"}; before the write it was ${was.fragmentPath}, drop-ins [], ` +
217
+ `WorkingDirectory ${was.workingDirectory ?? "(none)"}`);
218
+ }
219
+ return null;
220
+ }
221
+ if (st.fragmentPath === null || !deps.repoint.samePath(st.fragmentPath, unitPath)) {
222
+ return `after the reload systemd loads ${serving.unitName} from ${st.fragmentPath ?? "no file"}, not ${unitPath}`;
223
+ }
224
+ if (st.dropInPaths.length > 0) {
225
+ return `after the reload systemd applies drop-ins to ${serving.unitName} (${st.dropInPaths.join(", ")})`;
226
+ }
227
+ if (st.workingDirectory === null || !deps.repoint.samePath(st.workingDirectory, targets.workingDirectory)) {
228
+ return `after the reload systemd reports WorkingDirectory ${st.workingDirectory ?? "(none)"}, not ${targets.workingDirectory}`;
229
+ }
230
+ return null;
231
+ },
232
+ });
233
+ }
234
+ /**
235
+ * `flair restart` on Linux (see planLinuxRestart). A proven user unit is
236
+ * restarted THROUGH systemd and its new main process must run from the unit's
237
+ * WorkingDirectory; a process that is the main process (MainPID) of any other
238
+ * systemd unit is refused, never stopped and respawned outside its manager, and
239
+ * so is one whose cgroup or unit MainPID cannot be read. A process no unit
240
+ * supervises — none in its cgroup, or one whose MainPID is another process —
241
+ * takes the direct path.
242
+ */
243
+ export async function restartOnLinux(d) {
244
+ const plan = planLinuxRestart({
245
+ serving: d.serving,
246
+ pids: d.pids,
247
+ procCgroup: d.procCgroup,
248
+ uid: d.uid,
249
+ unitMainPid: d.unitMainPid,
250
+ });
251
+ if (plan.kind === "refuse")
252
+ throw new Error(plan.detail);
253
+ if (plan.kind === "direct") {
254
+ await d.direct();
255
+ return "direct";
256
+ }
257
+ const s = d.serving;
258
+ d.beforeRestart?.(s);
259
+ d.log?.(` (restarting through the systemd user unit that runs this instance: ${plan.unit})`);
260
+ d.systemctl(["--user", "daemon-reload"]);
261
+ d.systemctl(["--user", "restart", plan.unit]);
262
+ await d.waitHealthy();
263
+ const problem = restartedUnitProblem(plan.unit, s.pid, d.unitState(plan.unit), d.cwdOf, d.samePath);
264
+ if (problem)
265
+ throw new Error(`restarted ${plan.unit} through systemd, but ${problem}`);
266
+ return "systemd";
267
+ }