@tpsdev-ai/flair 0.58.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 (46) hide show
  1. package/README.md +3 -2
  2. package/config.yaml +3 -0
  3. package/dist/build-info.json +3 -3
  4. package/dist/cli.js +42 -98
  5. package/dist/commands/agent.js +160 -2
  6. package/dist/commands/doctor.js +15 -23
  7. package/dist/commands/mcp.js +53 -22
  8. package/dist/lib/daemon-liveness.js +42 -0
  9. package/dist/lib/doctor-run.js +67 -0
  10. package/dist/lib/flair-agent-role.js +116 -0
  11. package/dist/lib/launchd-management.js +3 -2
  12. package/dist/lib/mcp-enable.js +667 -72
  13. package/dist/lib/process-start-time.js +32 -0
  14. package/dist/resources/Agent.js +27 -7
  15. package/dist/resources/AgentSeed.js +9 -0
  16. package/dist/resources/Federation.js +14 -2
  17. package/dist/resources/MemoryBootstrap.js +121 -29
  18. package/dist/resources/OrgSkillAssignment.js +209 -0
  19. package/dist/resources/XAA.js +40 -11
  20. package/dist/resources/agent-status-guard.js +63 -0
  21. package/dist/resources/auth-middleware.js +2 -1
  22. package/dist/resources/federation-classify.js +22 -0
  23. package/dist/resources/flair-agent-role-boot.js +26 -0
  24. package/dist/resources/health.js +10 -2
  25. package/dist/resources/key-lock.js +31 -0
  26. package/dist/resources/mcp-oauth.js +3 -6
  27. package/dist/resources/mcp-tools.js +22 -4
  28. package/dist/resources/multi-worker-guard.js +121 -0
  29. package/dist/resources/oauth-discovery.js +1 -0
  30. package/dist/resources/oauth-wellknown.js +8 -4
  31. package/dist/resources/record-types.js +16 -0
  32. package/dist/resources/replay-store.js +56 -9
  33. package/dist/resources/skill-manifest.js +181 -0
  34. package/dist/resources/skill-provenance.js +15 -10
  35. package/dist/src/lib/flair-agent-role.js +116 -0
  36. package/docs/access-control.md +667 -0
  37. package/docs/api-reference.md +6 -2
  38. package/docs/auth.md +4 -0
  39. package/docs/deepseek-harness.md +1 -1
  40. package/docs/integrations.md +1 -1
  41. package/docs/mcp-clients.md +5 -3
  42. package/docs/releasing.md +24 -24
  43. package/package.json +4 -3
  44. package/schemas/memory.graphql +31 -0
  45. package/schemas/oauth.graphql +8 -4
  46. package/templates/launchd/start-flair-with-admin-pass.sh +89 -16
@@ -4,7 +4,7 @@ import nacl from "tweetnacl";
4
4
  import * as render from "../render.js";
5
5
  import { defaultKeysDir, resolveAdminUser, resolveLocalAdminPass } from "../lib/auth-resolve.js";
6
6
  import { resolveAgentKeyPath, loadEd25519PrivateKeyFromFile, signClientAssertion, buildTokenRequestForm, getMcpAccessToken, McpTokenRequestError, defaultMcpClientId, defaultMcpTokenEndpoint, defaultMcpResource, defaultMcpIssuer, MAX_ASSERTION_LIFETIME_SECONDS, } from "../mcp-client-assertion.js";
7
- import { enableMcp, disableMcp, mcpStatus, checkLocalOriginRefusal, selfVerifyMcpMetadata, } from "../lib/mcp-enable.js";
7
+ import { enableMcp, disableMcp, mcpStatus, checkLocalOriginRefusal, selfVerifyMcpMetadata, cimdAllowedHostsFromFlag, claudeAiExcludedNote, } from "../lib/mcp-enable.js";
8
8
  import { resolveHome } from "../lib/home.js";
9
9
  let cli;
10
10
  /** Bind shared CLI helpers. cli.ts calls this immediately before register(program). */
@@ -285,6 +285,25 @@ async function promptText(question) {
285
285
  const answer = await new Promise((res) => rl.question(question, (a) => { rl.close(); res(a); }));
286
286
  return answer.trim();
287
287
  }
288
+ /**
289
+ * flair#2113 review: the closing lines of a successful `flair mcp enable`.
290
+ * They claim only what the run checked: the self-verify step's OAuth metadata
291
+ * check (the /mcp route itself is not probed), and, when this run confirmed a
292
+ * --cimd-allowed-hosts list (ensured it in config.yaml, writing the list only
293
+ * if the file did not already hold that exact list, and read it back), whether
294
+ * that list includes claude.ai. With no flag the command does not inspect
295
+ * allowedHosts, so it says nothing about claude.ai.
296
+ */
297
+ export function enableSuccessLines(result) {
298
+ const lines = [
299
+ `${render.icons.ok} ${render.wrap(render.c.bold, "The OAuth metadata check passed.")} The /mcp route itself was not probed.`,
300
+ ];
301
+ const claudeAiNote = claudeAiExcludedNote(result.cimdAllowedHosts);
302
+ if (claudeAiNote)
303
+ lines.push(`${render.icons.info} ${claudeAiNote}`);
304
+ lines.push("", result.pasteBlock ?? "", "");
305
+ return lines;
306
+ }
288
307
  function printEnableSteps(result) {
289
308
  console.log(`\n${render.wrap(render.c.bold, "flair mcp enable")}${result.dryRun ? render.wrap(render.c.dim, " (dry run)") : ""}\n`);
290
309
  for (const s of result.steps) {
@@ -536,12 +555,18 @@ export function register(program) {
536
555
  .option("--principal-kind <human|agent>", "Kind for a newly-created principal", "human")
537
556
  .option("--secrets-mechanism <fabric-env-secrets|env-file>", "Override the shape-aware secrets mechanism (else auto-detected from --instance)")
538
557
  .option("--secrets-path <path>", "Override the secrets staging file path")
539
- .option("--cimd-allowed-hosts <hosts>", "Comma-separated clientIdMetadataDocuments.allowedHosts override (else claude.ai,claude.com)")
558
+ .option("--cimd-allowed-hosts <hosts>", "Comma-separated lowercase hostnames to ensure as mcp.clientIdMetadataDocuments.allowedHosts in the config.yaml " +
559
+ "this command edits on this machine (./config.yaml, else ~/.flair/config.yaml), written unless that file already holds " +
560
+ "that exact list, then read back, before the restart. " +
561
+ "Without --dry-run, refused unless a preflight match links the host and pid the target reports, a readable " +
562
+ "process on this machine, and that file (by realpath); --dry-run skips the match and writes nothing. " +
563
+ "Always refused for a *.harperfabric.com instance. " +
564
+ "Without it the list is not changed (shipped: claude.ai,claude.com)")
540
565
  .option("--signing-key-file <path>", "RS256 signing key PEM file (else ~/.flair/mcp-signing-key.pem)")
541
566
  .option("--admin-pass <pass>", "Admin password for the TARGET instance. Required explicitly for a remote target — FLAIR_ADMIN_PASS and ~/.flair/admin-pass are this machine's local credentials and are never sent to a remote instance")
542
567
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
543
568
  .option("--confirm-secrets-applied", "Confirm the staged secrets are already live on the target instance's environment (skips the interactive confirm)")
544
- .option("--dry-run", "Generate keys/tokens/config and validate inputs; skip every remote call")
569
+ .option("--dry-run", "Validate inputs and report the signing key a real run would reuse or generate; write no file and make no remote call")
545
570
  .option("--json", "Print machine-readable JSON instead of a human summary")
546
571
  .action(async (opts) => {
547
572
  const instance = opts.instance ?? process.env.FLAIR_URL;
@@ -557,6 +582,14 @@ export function register(program) {
557
582
  console.error(`${render.icons.error} ${localCheck.message}`);
558
583
  process.exit(1);
559
584
  }
585
+ // flair#2113: an invalid --cimd-allowed-hosts, or one for a Fabric
586
+ // instance, is refused here, before anything is asked for. An explicit empty
587
+ // value is refused too: it used to be dropped as if the flag were absent.
588
+ const cimdFlag = cimdAllowedHostsFromFlag(opts.cimdAllowedHosts, instance);
589
+ if (cimdFlag.error) {
590
+ console.error(`${render.icons.error} ${cimdFlag.error}`);
591
+ process.exit(1);
592
+ }
560
593
  const dryRun = Boolean(opts.dryRun);
561
594
  // --instance is ALWAYS remote for this command (local is refused above)
562
595
  // — isRemoteTarget=true so a missing --admin-pass/FLAIR_ADMIN_PASS never
@@ -564,8 +597,8 @@ export function register(program) {
564
597
  // against someone else's instance (see resolveLocalAdminPass's doc comment).
565
598
  const adminPass = dryRun ? (opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? "") : resolveLocalAdminPass(opts.adminPass, /* isRemoteTarget */ true);
566
599
  if (!dryRun && !adminPass) {
567
- console.error("Error: --admin-pass <pass> or --admin-pass-file <path> is required for a REMOTE target " +
568
- "(the operations API on the target instance needs it for identity mapping + restart).\n" +
600
+ console.error("Error: --admin-pass <pass> is required for a REMOTE target " +
601
+ "(the command authenticates to the target instance's operations API with it).\n" +
569
602
  " FLAIR_ADMIN_PASS and ~/.flair/admin-pass are deliberately NOT used here: they are THIS machine's " +
570
603
  "local admin credentials, and sending them to another instance is how a local secret ends up on someone " +
571
604
  "else's Harper. Pass the target's own admin password explicitly.");
@@ -587,9 +620,6 @@ export function register(program) {
587
620
  console.error(`Error: --secrets-mechanism must be "fabric-env-secrets" or "env-file", got "${secretsMechanism}"`);
588
621
  process.exit(1);
589
622
  }
590
- const cimdAllowedHosts = opts.cimdAllowedHosts
591
- ? String(opts.cimdAllowedHosts).split(",").map((h) => h.trim()).filter(Boolean)
592
- : undefined;
593
623
  const result = await enableMcp({
594
624
  instance,
595
625
  issuer: opts.issuer,
@@ -604,7 +634,7 @@ export function register(program) {
604
634
  signingKeyFilePath: opts.signingKeyFile,
605
635
  secretsMechanism,
606
636
  secretsStagingPath: opts.secretsPath,
607
- cimdAllowedHosts,
637
+ cimdAllowedHosts: cimdFlag.hosts,
608
638
  dryRun,
609
639
  confirmSecretsApplied: Boolean(opts.confirmSecretsApplied),
610
640
  }, { confirmPrompt: dryRun ? undefined : confirmYesNo });
@@ -620,15 +650,17 @@ export function register(program) {
620
650
  }
621
651
  if (!result.ok) {
622
652
  if (result.failedStep === "fabric-operator-deploy") {
623
- // flair#1136: Fabric deployments require the operator to deploy the
624
- // config change — we can't write to harperdb-config.yaml (Fabric
625
- // regenerates it on every container restart).
653
+ // flair#1136/#1152: on Fabric, `enable` never restarts the instance and
654
+ // needs no config edit (config.yaml ships mcp.enabled as an env
655
+ // reference). The operator addresses the cause the step reports (applying
656
+ // the environment and restarting when it says so); a re-run then passes
657
+ // this step once self-verify does (flair#2116).
658
+ // The step's own detail above carries the specifics.
626
659
  console.error(`\n${render.icons.info} ${render.wrap(render.c.bold, "Fabric deployment detected.")}`);
627
- console.error(` The @harperfast/oauth block ships in your component config.yaml with mcp.enabled: false.`);
628
- console.error(` To activate: set mcp.enabled: true (literal boolean) in your deployed component`);
629
- console.error(` config.yaml, ensure the staged secrets are live in the instance's process`);
630
- console.error(` environment, and redeploy. Then re-run \`flair mcp enable\` — earlier steps`);
631
- console.error(` are idempotent and will be reused.\n`);
660
+ console.error(` The /mcp OAuth surface did not pass self-verify on the public origin yet; the step above says why`);
661
+ console.error(` and what to do. Address that cause (restart the instance if its environment changed), then re-run`);
662
+ console.error(` \`flair mcp enable\` with the same options plus --confirm-secrets-applied: that step checks again`);
663
+ console.error(` and passes once self-verify does.\n`);
632
664
  }
633
665
  else {
634
666
  console.error(`${render.icons.error} enable failed at step "${result.failedStep}" — see detail above for the exact fix, then re-run \`flair mcp enable\` (earlier steps are idempotent and will be reused).`);
@@ -639,15 +671,14 @@ export function register(program) {
639
671
  console.log(`${render.icons.info} ${render.wrap(render.c.dim, "dry-run: no remote calls were made.")}`);
640
672
  return;
641
673
  }
642
- console.log(`${render.icons.ok} ${render.wrap(render.c.bold, "claude.ai can now connect.")}\n`);
643
- console.log(result.pasteBlock ?? "");
644
- console.log("");
674
+ for (const line of enableSuccessLines(result))
675
+ console.log(line);
645
676
  });
646
677
  mcp
647
678
  .command("disable")
648
679
  .description("Flag off + restart = byte-identical boot (Model-2 contract) — removes the /mcp OAuth surface.")
649
680
  .option("--instance <url>", "Remote flair instance to disable against (else FLAIR_URL)")
650
- .option("--admin-pass <pass>", "Admin password for the target instance (or FLAIR_ADMIN_PASS)")
681
+ .option("--admin-pass <pass>", "Admin password for the remote target instance; pass it explicitly with --admin-pass")
651
682
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
652
683
  .option("--confirm-flag-off", "Confirm FLAIR_MCP_OAUTH is already unset on the target instance's environment (skips the interactive confirm)")
653
684
  .option("--json", "Print machine-readable JSON instead of a human summary")
@@ -661,7 +692,7 @@ export function register(program) {
661
692
  // comment in `mcp enable` above.
662
693
  const adminPass = resolveLocalAdminPass(opts.adminPass, /* isRemoteTarget */ true);
663
694
  if (!adminPass) {
664
- console.error("Error: --admin-pass or FLAIR_ADMIN_PASS required.");
695
+ console.error("Error: --admin-pass <pass> is required for a REMOTE target. Pass the target instance's admin password explicitly.");
665
696
  process.exit(1);
666
697
  }
667
698
  const result = await disableMcp({ instance, adminUser: resolveAdminUser(opts.adminUser), adminPass, confirmFlagOff: Boolean(opts.confirmFlagOff) }, { confirmPrompt: confirmYesNo });
@@ -171,6 +171,48 @@ export function verifyIdentity(input) {
171
171
  export function isStartTimeMatch(actualMs, recordedMs, toleranceMs = 2000) {
172
172
  return Math.abs(actualMs - recordedMs) <= toleranceMs;
173
173
  }
174
+ /**
175
+ * Does a flair#1454 sidecar's `startTimeMs` agree with a process's start
176
+ * second (flair#2056)? `startSecondMs` is the start time truncated to a whole
177
+ * second, in epoch ms (the second `ps -o lstart=` reports). They agree when
178
+ * they are within 2000 ms of each other, compared in milliseconds: a start
179
+ * second of 12 s against a sidecar of 14.5 s is 2500 ms and does not agree.
180
+ */
181
+ export function sidecarStartAgrees(startSecondMs, sidecarStartMs) {
182
+ return Math.abs(sidecarStartMs - startSecondMs) <= 2000;
183
+ }
184
+ /** A Harper entry path under an install tree: `…/node_modules/[@<scope>/]harper/dist/bin/harper.js`. */
185
+ const HARPER_ENTRY_PATH = /(^|\/)node_modules\/(@[^/]+\/)?harper\/dist\/bin\/harper\.js$/;
186
+ /** The relative entry Harper's own restart forks, from its package directory (LAUNCH_SERVICE_SCRIPTS.MAIN). */
187
+ const HARPER_RESTART_ENTRY = "dist/bin/harper.js";
188
+ /**
189
+ * Is this a Harper-shaped command line (flair#2056)? It shows what the process
190
+ * was started with, not that it serves anything.
191
+ *
192
+ * The first argument's basename is `node` or `bun`, and the second is a Harper
193
+ * entry path: `…/node_modules/harper/dist/bin/harper.js` or
194
+ * `…/node_modules/@<scope>/harper/dist/bin/harper.js` (what `flair start`, the
195
+ * launchd launcher and a systemd unit pass), or `dist/bin/harper.js` (what
196
+ * Harper's own restart forks). A second argument starting with `-`, or a Harper
197
+ * path in a later argument, does not match.
198
+ *
199
+ * `cmdline` is `/proc/<pid>/cmdline` (NUL-separated: the arguments exactly) or
200
+ * the line `ps -o command=` reports (arguments joined by spaces; split here on
201
+ * whitespace). From the `ps` line this does not establish which argument is the
202
+ * script: an argument containing a space can produce a matching line.
203
+ */
204
+ export function isHarperProcessCommandLine(cmdline) {
205
+ const args = cmdline.includes("\u0000") ? cmdline.split("\u0000") : cmdline.trim().split(/\s+/);
206
+ if (args.length < 2)
207
+ return false;
208
+ const exe = args[0].split("/").pop();
209
+ if (exe !== "node" && exe !== "bun")
210
+ return false;
211
+ const second = args[1];
212
+ if (second.startsWith("-"))
213
+ return false;
214
+ return second === HARPER_RESTART_ENTRY || HARPER_ENTRY_PATH.test(second);
215
+ }
174
216
  /**
175
217
  * Parse `/proc/<pid>/stat` field 22 (starttime, in clock ticks).
176
218
  *
@@ -45,6 +45,7 @@ export const DOCTOR_CHECK_IDS = [
45
45
  "verified-read",
46
46
  "keys-prune",
47
47
  "launchd-management",
48
+ "worker-threads",
48
49
  ];
49
50
  const MCP_CLIENT_IDS = ["claude-code", "codex", "gemini", "cursor", "antigravity"];
50
51
  function result(id, label, status, extra = {}) {
@@ -331,6 +332,71 @@ function runKeysPrune(ctx) {
331
332
  detail: `classified ${agentKeyIds.length} agent / ${nodeKeyIds.length} node key(s)`,
332
333
  });
333
334
  }
335
+ export function readWorkerThreadsObservation(raw) {
336
+ if (raw === undefined)
337
+ return { kind: "serving" };
338
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw))
339
+ return { kind: "unknown" };
340
+ const rec = raw;
341
+ if (rec.state !== "refused" && rec.state !== "unsafe-opt-in")
342
+ return { kind: "unknown" };
343
+ const workerCount = rec.workerCount;
344
+ return {
345
+ kind: "refused",
346
+ state: rec.state,
347
+ workerCount: typeof workerCount === "number" && Number.isFinite(workerCount) ? workerCount : null,
348
+ };
349
+ }
350
+ export function interpretFlairHealth(status, body) {
351
+ const observation = readWorkerThreadsObservation(body?.multiWorker);
352
+ if (status >= 200 && status < 300)
353
+ return { reaching: true, observation };
354
+ if (status === 503 && observation.kind === "refused")
355
+ return { reaching: true, observation };
356
+ return { reaching: false, observation: null };
357
+ }
358
+ export async function probeFlairHealth(url, fetchImpl = fetch, timeoutMs = 3000) {
359
+ try {
360
+ const res = await fetchImpl(url, { signal: AbortSignal.timeout(timeoutMs) });
361
+ let body = null;
362
+ try {
363
+ body = await res.json();
364
+ }
365
+ catch {
366
+ body = null;
367
+ }
368
+ const verdict = interpretFlairHealth(res.status, body);
369
+ return { ...verdict, status: res.status, body };
370
+ }
371
+ catch {
372
+ return { reaching: false, status: 0, body: null, observation: null };
373
+ }
374
+ }
375
+ function runWorkerThreads(ctx) {
376
+ const id = "worker-threads";
377
+ const label = "worker threads";
378
+ const observed = ctx.workerThreads;
379
+ if (!observed) {
380
+ return result(id, label, "skip", { detail: "no /Health response observed at the configured URL" });
381
+ }
382
+ if (observed.kind === "unknown") {
383
+ return result(id, label, "fail", {
384
+ detail: "the /Health response carried a worker-thread state this doctor does not recognize",
385
+ remedy: "Inspect /Health and re-run doctor",
386
+ });
387
+ }
388
+ if (observed.kind === "serving") {
389
+ return result(id, label, "pass", { detail: "the configured /Health response has no multi-worker refusal field" });
390
+ }
391
+ const count = observed.workerCount === null ? "an unreadable worker count" : `${observed.workerCount} Harper worker threads`;
392
+ const detail = observed.state === "refused"
393
+ ? `the configured /Health response reports refusal with ${count}; multi-worker is unsupported until the readiness work lands`
394
+ : `the configured /Health response reports ${count} and an explicit unsafe opt-in`;
395
+ return result(id, label, "fail", {
396
+ detail,
397
+ remedy: "Set THREADS_COUNT=1 and restart flair",
398
+ });
399
+ }
334
400
  function runLaunchdManagement(ctx) {
335
401
  const id = "launchd-management";
336
402
  const label = "launchd management";
@@ -388,6 +454,7 @@ export const DOCTOR_CHECKS = [
388
454
  { id: "verified-read", label: "per-agent verified-read", run: runVerifiedRead },
389
455
  { id: "keys-prune", label: "keys prune classification", run: runKeysPrune },
390
456
  { id: "launchd-management", label: "launchd management", run: runLaunchdManagement },
457
+ { id: "worker-threads", label: "worker threads", run: runWorkerThreads },
391
458
  ];
392
459
  /**
393
460
  * Run every catalog id. Missing implementations and thrown runners become
@@ -0,0 +1,116 @@
1
+ /**
2
+ * flair-agent-role.ts — the `flair_agent` Harper role's grant spec, shared by
3
+ * the CLI (`ensureFlairAgentRole`, src/cli.ts) and the server's startup check
4
+ * (resources/flair-agent-role-boot.ts). No Harper imports.
5
+ */
6
+ // ─── flair_agent role ────────────────────────────────────────────────────────
7
+ //
8
+ // The auth reshape replaces the global gate's "verified agent borrows admin
9
+ // super_user" elevation with a real, least-privilege Harper role. After an
10
+ // agent's Ed25519 signature verifies, resources resolve the request to the
11
+ // shared `flair_agent`-roled user instead of admin. Critically: with no
12
+ // `super_user` and no operations grants, /sql and /graphql become NATIVELY 403
13
+ // for agents (the raw-query block the gate hand-rolled is now enforced by
14
+ // Harper itself).
15
+ // Harper 5.0.21 add_role requires an `attribute_permissions` array on EVERY table
16
+ // grant (empty = no attribute-level restriction, so the table-level CRUD applies);
17
+ // omitting it makes add_role reject the whole spec ("Missing 'attribute_permissions'
18
+ // array"). Validated live against a spawned Harper. This helper guarantees the
19
+ // array is never forgotten. Also: `cluster_user` is NOT a valid top-level key —
20
+ // Harper reads unrecognized top-level keys as database names ("database
21
+ // 'cluster_user' does not exist"); only super_user / structure_user are recognized.
22
+ const grant = (read, insert, update, del) => ({ read, insert, update, delete: del, attribute_permissions: [] });
23
+ /** Canonical permission spec for flair_agent (least-privilege; real @table names). */
24
+ export const FLAIR_AGENT_PERMISSION = {
25
+ super_user: false,
26
+ structure_user: false,
27
+ flair: {
28
+ tables: {
29
+ // Core agent-owned data — CRUD envelope.
30
+ Memory: grant(true, true, true, true),
31
+ MemoryCandidate: grant(true, true, true, true),
32
+ MemoryGrant: grant(true, true, true, true),
33
+ // Asset (images-in-Flair slice 1). Harper authorizes BEFORE Asset.post
34
+ // runs, so a de-elevated flair_agent needs the table grant or signed
35
+ // POST /Asset 403s as AccessViolation (Kern P0). CRUD envelope;
36
+ // owner-only + write-time size/MIME gates live in resources/Asset.ts.
37
+ Asset: grant(true, true, true, true),
38
+ Soul: grant(true, true, true, false),
39
+ OrgEvent: grant(true, true, true, true),
40
+ WorkspaceState: grant(true, true, true, true),
41
+ Relationship: grant(true, true, true, true),
42
+ // Flair Relay S1 (flair#1521). Harper authorizes BEFORE the resource
43
+ // methods run, so a de-elevated flair_agent needs the table grant OR it
44
+ // 403s on POST /Message before relaySend is reached (Kern P0-2). read =
45
+ // the party-scoped collection (Message.search); insert = send via post().
46
+ // update = FALSE (least privilege, Kern P0 blocker): the ack's write goes
47
+ // through the IN-PROCESS static accessor (relayConsume → deps.messages.put),
48
+ // which bypasses role gates entirely — the same raw-put seam Federation.ts
49
+ // relies on — so update:true is NOT needed for any legitimate path. Leaving
50
+ // it granted let PATCH /Message/<id> reach Table's update verb, whose
51
+ // authorize step consults update:true and PASSES for any de-elevated agent,
52
+ // bypassing Message.put()'s FORBIDDEN guard AND relayConsume's recipient-only
53
+ // check (Message has no patch() at the platform level → TableResource.patch
54
+ // runs update()+save() directly). delete = false: direct deletes are
55
+ // admin/internal only. Message.patch() also guards the verb in-resource.
56
+ Message: grant(true, true, false, false),
57
+ Integration: grant(true, true, true, true),
58
+ Credential: grant(true, true, true, true),
59
+ Presence: grant(true, true, true, false),
60
+ // MemoryUsage (flair#683): the usage-feedback dedup ledger. Read (own
61
+ // contributions, scoped in resources/MemoryUsage.ts) + insert (a fresh
62
+ // contribution row) only — NO update/delete. This is load-bearing, not
63
+ // just least-privilege tidiness: the dedup rule ("(agent, memory)
64
+ // contributes ≤ 1") is enforced by requiring a NEW ledger row before
65
+ // any usageCount bump; if an agent could delete its own row, it could
66
+ // re-trigger the /RecordUsage endpoint for the same memory indefinitely
67
+ // (create → count → delete → count again → repeat), defeating the cap
68
+ // entirely. See resources/MemoryUsage.ts's module doc.
69
+ MemoryUsage: grant(true, true, false, false),
70
+ // MemoryHitStat (flair#1528): internal search-hit ledger. No agent REST
71
+ // surface (@table without @export). Counts overlay onto Memory reads.
72
+ MemoryHitStat: grant(false, false, false, false),
73
+ // Agent: read for discovery, update own card; creation/removal is admin.
74
+ Agent: grant(true, false, true, false),
75
+ // Read-only reference data.
76
+ Instance: grant(true, false, false, false),
77
+ // flair#2141 S1: org-scope skill assignments. Agents read them; every
78
+ // write is operator/internal only (resources/OrgSkillAssignment.ts), so
79
+ // no write grant. The history table has no direct REST route.
80
+ OrgSkillAssignment: grant(true, false, false, false),
81
+ OrgSkillAssignmentHistory: grant(false, false, false, false),
82
+ // Federation / OAuth / IdP / internal — system + admin only; agents get none.
83
+ Peer: grant(false, false, false, false),
84
+ PairingToken: grant(false, false, false, false),
85
+ SyncLog: grant(false, false, false, false),
86
+ OAuthClient: grant(false, false, false, false),
87
+ OAuthToken: grant(false, false, false, false),
88
+ OAuthAuthCode: grant(false, false, false, false),
89
+ IdpConfig: grant(false, false, false, false),
90
+ IdJagReplay: grant(false, false, false, false),
91
+ },
92
+ },
93
+ };
94
+ export const FLAIR_AGENT_ROLE_NAME = "flair_agent";
95
+ /**
96
+ * Brings an existing `flair_agent` role to FLAIR_AGENT_PERMISSION (flair#2141
97
+ * S1): "updated" after an `alter_role`, "unchanged" when it already matches,
98
+ * "absent" when the instance has no such role (this never creates it). Throws
99
+ * when the role list cannot be read; nothing is written then.
100
+ */
101
+ export async function alignFlairAgentRole(op) {
102
+ const roles = await op({ operation: "list_roles" });
103
+ if (!Array.isArray(roles))
104
+ throw new Error("list_roles did not return a list of roles");
105
+ const existing = roles.find((r) => r?.role === FLAIR_AGENT_ROLE_NAME || r?.name === FLAIR_AGENT_ROLE_NAME);
106
+ if (!existing)
107
+ return "absent";
108
+ const permission = existing.permission ?? existing.role?.permission;
109
+ if (JSON.stringify(permission) === JSON.stringify(FLAIR_AGENT_PERMISSION))
110
+ return "unchanged";
111
+ // Harper's alter_role addresses the role by its `id`.
112
+ if (typeof existing.id !== "string" || existing.id.length === 0)
113
+ throw new Error("the flair_agent role has no id");
114
+ await op({ operation: "alter_role", id: existing.id, role: FLAIR_AGENT_ROLE_NAME, permission: FLAIR_AGENT_PERMISSION });
115
+ return "updated";
116
+ }
@@ -332,9 +332,10 @@ export function readLaunchctlJobState(label, list) {
332
332
  * PID is no evidence, so it is discarded and the port listener answers instead.
333
333
  */
334
334
  export function pickInstancePid(input) {
335
- const { pidFilePid, isAlive, listeningPids } = input;
336
- if (pidFilePid !== null && isAlive(pidFilePid))
335
+ const { pidFilePid, isAlive, listeningPids, isPidFileEvidence } = input;
336
+ if (pidFilePid !== null && isAlive(pidFilePid) && (isPidFileEvidence === undefined || isPidFileEvidence(pidFilePid))) {
337
337
  return pidFilePid;
338
+ }
338
339
  return listeningPids.length > 0 ? listeningPids[0] : null;
339
340
  }
340
341
  /** True when the instance is running outside the service manager that is registered to own it. */