@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
@@ -8,6 +8,9 @@
8
8
  * - federation body signatures, key `f:<nonce>` — FederationPair and
9
9
  * FederationSync (Federation.ts, via verifyFederationRequestBody).
10
10
  *
11
+ * The XAA ID-JAG `jti` record (flair#2073) uses the same `recordOnce` on its
12
+ * own table; see `claimIdJagJti` below.
13
+ *
11
14
  * The record of truth is the local `ReplayNonce` table (schemas/replay.graphql:
12
15
  * `replicate: false`, `expiration: 120`). Every Harper thread of this instance
13
16
  * reads and writes the same rows. Per-thread memory holds only keys this thread
@@ -81,24 +84,25 @@ const STORE_METHODS = ["tryLock", "unlock", "getEntry"];
81
84
  * outlive twice `windowMs`.
82
85
  */
83
86
  export function replayStoreContractGap(deps, windowMs) {
87
+ const name = deps?.name ?? REPLAY_TABLE;
84
88
  const table = deps?.table;
85
89
  if (!table)
86
- return `table flair.${REPLAY_TABLE} is not defined`;
90
+ return `table flair.${name} is not defined`;
87
91
  const store = table.primaryStore;
88
92
  if (!store)
89
- return `flair.${REPLAY_TABLE} has no primaryStore`;
93
+ return `flair.${name} has no primaryStore`;
90
94
  for (const m of STORE_METHODS) {
91
95
  if (typeof store[m] !== "function")
92
- return `flair.${REPLAY_TABLE}.primaryStore.${m} is not a function`;
96
+ return `flair.${name}.primaryStore.${m} is not a function`;
93
97
  }
94
98
  if (typeof table.put !== "function")
95
- return `flair.${REPLAY_TABLE}.put is not a function`;
99
+ return `flair.${name}.put is not a function`;
96
100
  if (typeof deps.transaction !== "function")
97
101
  return "Harper's transaction() is not available";
98
102
  if (windowMs !== undefined) {
99
103
  const expirationMs = table.expirationMS;
100
104
  if (typeof expirationMs === "number" && expirationMs > 0 && expirationMs <= 2 * windowMs) {
101
- return `flair.${REPLAY_TABLE} keeps rows ${expirationMs} ms, not longer than twice the ${windowMs} ms window`;
105
+ return `flair.${name} keeps rows ${expirationMs} ms, not longer than twice the ${windowMs} ms window`;
102
106
  }
103
107
  }
104
108
  return null;
@@ -129,7 +133,7 @@ export async function recordOnce(key, seenAt, deps) {
129
133
  throw new ReplayStoreUnavailable(gap);
130
134
  const { table, transaction } = deps;
131
135
  const store = table.primaryStore;
132
- const lockKey = [REPLAY_LOCK_NAMESPACE, key];
136
+ const lockKey = [deps.lockNamespace ?? REPLAY_LOCK_NAMESPACE, key];
133
137
  if (!store.tryLock(lockKey))
134
138
  return "contended";
135
139
  try {
@@ -146,7 +150,12 @@ export async function recordOnce(key, seenAt, deps) {
146
150
  // ─── Refusal logging (bounded) ─────────────────────────────────────────────
147
151
  const LOG_INTERVAL_MS = 10_000;
148
152
  const lastLogged = new Map();
149
- function noteUnavailable(scope, err) {
153
+ const REFUSED = {
154
+ a: "TPS-Ed25519 signed request",
155
+ f: "federation signed request",
156
+ x: "XAA jwt-bearer grant whose assertion carries a jti",
157
+ };
158
+ function noteUnavailable(scope, err, table = REPLAY_TABLE) {
150
159
  const reason = err instanceof ReplayStoreUnavailable
151
160
  ? err.message
152
161
  : `ReplayStoreUnavailable: store error (${err?.constructor?.name ?? "Error"}: ${String(err?.message ?? err).slice(0, 200)})`;
@@ -157,8 +166,8 @@ function noteUnavailable(scope, err) {
157
166
  if (lastLogged.size > 64)
158
167
  lastLogged.clear();
159
168
  lastLogged.set(tag, now);
160
- console.error(`[flair-replay] ${reason}. Every ${scope === "a" ? "TPS-Ed25519" : "federation"} signed request is refused until the ` +
161
- `flair.${REPLAY_TABLE} store is usable (see resources/replay-store.ts).`);
169
+ console.error(`[flair-replay] ${reason}. Every ${REFUSED[scope]} is refused until the ` +
170
+ `flair.${table} store is usable (see resources/replay-store.ts).`);
162
171
  }
163
172
  export function createReplayGuard(opts) {
164
173
  const { scope, windowMs, windowSource } = opts;
@@ -262,6 +271,44 @@ export function verifyFederationRequestBody(body, publicKeyB64url) {
262
271
  replay: federationReplayGuard,
263
272
  });
264
273
  }
274
+ // ─── XAA ID-JAG jti (flair#2073) ───────────────────────────────────────────
275
+ /** Used ID-JAG `jti` values (schemas/oauth.graphql), one row per jti, keyed by the jti. */
276
+ export const ID_JAG_REPLAY_TABLE = "IdJagReplay";
277
+ /** First element of every jti lock key, so a jti never shares a lock key with a nonce. */
278
+ export const ID_JAG_LOCK_NAMESPACE = "flair-replay-id-jag";
279
+ function idJagReplayDeps() {
280
+ return {
281
+ table: databases?.flair?.[ID_JAG_REPLAY_TABLE],
282
+ transaction: globalThis.transaction,
283
+ name: ID_JAG_REPLAY_TABLE,
284
+ lockNamespace: ID_JAG_LOCK_NAMESPACE,
285
+ };
286
+ }
287
+ /**
288
+ * Claim an ID-JAG's `jti` once per instance, through `recordOnce`. Call it after
289
+ * the assertion has validated and before the grant has any effect; refuse on
290
+ * anything but "recorded". `minRetentionMs` is the longest an accepted
291
+ * assertion can stay acceptable after its jti is recorded: a table whose rows
292
+ * do not outlive it is unavailable.
293
+ */
294
+ export async function claimIdJagJti(jti, minRetentionMs, now = Date.now()) {
295
+ try {
296
+ const deps = idJagReplayDeps();
297
+ const gap = replayStoreContractGap(deps);
298
+ if (gap)
299
+ throw new ReplayStoreUnavailable(gap);
300
+ const expirationMs = deps.table.expirationMS;
301
+ if (typeof expirationMs === "number" && expirationMs > 0 && expirationMs <= minRetentionMs) {
302
+ throw new ReplayStoreUnavailable(`flair.${ID_JAG_REPLAY_TABLE} keeps rows ${expirationMs} ms, not longer than the ${minRetentionMs} ms an assertion can stay acceptable`);
303
+ }
304
+ // A lock miss ("contended") is refused like a stored row.
305
+ return (await recordOnce(jti, now, deps)) === "recorded" ? "recorded" : "replay";
306
+ }
307
+ catch (err) {
308
+ noteUnavailable("x", err, ID_JAG_REPLAY_TABLE);
309
+ return "unavailable";
310
+ }
311
+ }
265
312
  // ─── Boot report ───────────────────────────────────────────────────────────
266
313
  /** Every gap that would refuse requests on this thread, or an empty list. */
267
314
  export function replayStoreBootGaps(deps = harperReplayDeps()) {
@@ -0,0 +1,181 @@
1
+ /**
2
+ * skill-manifest.ts — the structured skills manifest in every successful
3
+ * bootstrap response (flair#2141 S1b, S1). No Harper imports.
4
+ *
5
+ * `resolveSkillManifest` turns an agent's `skill-assignment` Soul rows and the
6
+ * instance's org-scope assignments (OrgSkillAssignment) into two lists:
7
+ * - `skills`: the winners only — `{ name, skillId, scope, priority, source }`,
8
+ * where `skillId` is the skill-tagged Memory row to fetch with `skill_get`.
9
+ * - `diagnostics`: assignments refused (a non-durable source, an
10
+ * equal-priority tie or a non-boolean `optOut`) or superseded, and winners
11
+ * whose skill row does not resolve (unresolved or ambiguous).
12
+ * Candidates are the agent's own assignments (scope "own") plus the org
13
+ * assignments (scope "org") whose names the agent is not opted out of. The
14
+ * priority/tie rules (`resolveActiveSkills`, skill-provenance.ts) run on the
15
+ * candidates; then each winner's skill row is resolved: an own name to the
16
+ * agent's own skill row, an org assignment to its `skillRef`.
17
+ *
18
+ * The manifest strings (`name`, `source`) come from Soul `skill-assignment`
19
+ * rows, and an org entry's `name` from its OrgSkillAssignment row; they reach
20
+ * the agent's context without SkillScan. That is safe only because no agent
21
+ * key can write those rows; only operator credentials and Flair's own internal
22
+ * paths can (resources/soul-write-policy.ts, resources/OrgSkillAssignment.ts).
23
+ * Widening who may write them changes this render path.
24
+ */
25
+ import { formatBase, normalizePriority, parseSkillMetadata, resolveActiveSkills, skillSourceOf, } from "./skill-provenance.js";
26
+ import { isSkillWrite } from "./skill-write.js";
27
+ /** The Memory fields the bootstrap skill-row query selects. */
28
+ export const SKILL_ROW_SELECT = [
29
+ "id", "agentId", "visibility", "tags", "metadata", "archived", "validTo", "expiresAt",
30
+ ];
31
+ const NO_ORG = { assignments: [], rows: [], instanceId: null };
32
+ /**
33
+ * Whether a target receives org skills, from its Agent record: the record
34
+ * exists, `kind` is "agent" (absent counts as "agent") and `status` is
35
+ * "active" (absent counts as "active").
36
+ */
37
+ export function receivesOrgSkills(agent) {
38
+ if (!agent || typeof agent !== "object")
39
+ return false;
40
+ const { kind, status } = agent;
41
+ return (kind ?? "agent") === "agent" && (status ?? "active") === "active";
42
+ }
43
+ /** A skill row's name: `metadata.name` (skill_store folds it there). */
44
+ export function skillNameOf(row) {
45
+ const name = parseSkillMetadata(row.metadata).name;
46
+ return typeof name === "string" && name.length > 0 ? name : undefined;
47
+ }
48
+ function isPast(value, now) {
49
+ return typeof value === "string" && value.length > 0 && Date.parse(value) < now;
50
+ }
51
+ /**
52
+ * The rows passed to resolveSkillRef: skill-tagged, readable by the target agent
53
+ * (`isReadable`, the read-scope predicate `skill_get` applies), not archived,
54
+ * and not closed (`validTo`) or expired (`expiresAt`).
55
+ */
56
+ export function resolvableSkillRows(rows, isReadable, now = Date.now()) {
57
+ return rows.filter((row) => typeof row.id === "string"
58
+ && isSkillWrite(row)
59
+ && isReadable(row)
60
+ && row.archived !== true
61
+ && !isPast(row.expiresAt, now)
62
+ && !isPast(row.validTo, now));
63
+ }
64
+ /**
65
+ * flair#2141 S2 hook: the skill rows written by the reserved system writer
66
+ * (the operator seed), the only candidates besides the agent's own rows. None
67
+ * exist before S2, so this returns no rows.
68
+ */
69
+ export function seedSkillRows(_rows) {
70
+ return [];
71
+ }
72
+ /**
73
+ * Resolve a name-only assignment to one skill row: the target agent's own row
74
+ * with that name (then, from flair#2141 S2, a seed row; see seedSkillRows).
75
+ * More than one row at a step is ambiguous; no row is unresolved.
76
+ */
77
+ export function resolveSkillRef(name, rows, agentId) {
78
+ const named = rows.filter((row) => skillNameOf(row) === name);
79
+ const decide = (list, whose) => {
80
+ if (list.length === 1)
81
+ return { kind: "resolved", skillId: list[0].id };
82
+ if (list.length === 0)
83
+ return null;
84
+ return {
85
+ kind: "ambiguous",
86
+ reason: `${list.length} ${whose} skill rows have this name`,
87
+ candidates: list.map((row) => row.id).sort(),
88
+ };
89
+ };
90
+ return decide(named.filter((row) => row.agentId === agentId), "of the agent's own")
91
+ ?? decide(seedSkillRows(named), "seed")
92
+ ?? { kind: "unresolved", reason: "the agent has no live skill row with this name" };
93
+ }
94
+ /** An org assignment's `skillRef`, resolved against the rows it may name. */
95
+ function resolveOrgRef(skillRef, rows) {
96
+ if (typeof skillRef === "string" && rows.some((row) => row.id === skillRef)) {
97
+ return { kind: "resolved", skillId: skillRef };
98
+ }
99
+ return { kind: "unresolved", reason: "the skillRef is not a live skill row this agent can read" };
100
+ }
101
+ /** The "## Active Skills" prose line for a manifest entry. */
102
+ export function skillLine(entry) {
103
+ return formatBase(entry.name, entry.priority, entry.source ?? undefined);
104
+ }
105
+ function compareDiagnostics(a, b) {
106
+ return a.name.localeCompare(b.name)
107
+ || a.decision.localeCompare(b.decision)
108
+ || (a.source ?? "").localeCompare(b.source ?? "")
109
+ || a.priority.localeCompare(b.priority)
110
+ || a.reason.localeCompare(b.reason)
111
+ || a.scope.localeCompare(b.scope);
112
+ }
113
+ /**
114
+ * The manifest for one agent: `assignments` are its `skill-assignment` Soul
115
+ * rows, `rows` the skill rows its own names may resolve to (see
116
+ * resolvableSkillRows), `org` the org assignments it receives. A Soul row with
117
+ * `metadata.optOut: true` is an opt-out, never a candidate: it removes the org
118
+ * assignments with that name before the priority rules, when `org.instanceId`
119
+ * is a non-empty string and the row's `originatorInstanceId` equals it.
120
+ * `skills` is sorted by name; `diagnostics` by name, decision, source,
121
+ * priority, reason and scope.
122
+ */
123
+ export function resolveSkillManifest(assignments, rows, agentId, org = NO_ORG) {
124
+ const skills = [];
125
+ const diagnostics = [];
126
+ const candidates = [];
127
+ const optedOut = new Set();
128
+ for (const assignment of assignments) {
129
+ const optOut = parseSkillMetadata(assignment.metadata).optOut;
130
+ if (optOut === undefined || optOut === false) {
131
+ candidates.push({ input: assignment, scope: "own" });
132
+ continue;
133
+ }
134
+ if (typeof assignment.value !== "string" || assignment.value.length === 0)
135
+ continue;
136
+ if (optOut !== true) {
137
+ diagnostics.push({
138
+ name: assignment.value, scope: "own",
139
+ priority: normalizePriority(assignment.priority),
140
+ source: skillSourceOf(assignment) ?? null,
141
+ decision: "refused", reason: "metadata.optOut is not a boolean",
142
+ });
143
+ continue;
144
+ }
145
+ if (typeof org.instanceId === "string" && org.instanceId !== "" && assignment.originatorInstanceId === org.instanceId) {
146
+ optedOut.add(assignment.value);
147
+ }
148
+ }
149
+ for (const row of org.assignments) {
150
+ if (typeof row.skillName !== "string" || optedOut.has(row.skillName))
151
+ continue;
152
+ candidates.push({ input: { value: row.skillName, priority: row.priority }, scope: "org", skillRef: row.skillRef });
153
+ }
154
+ const byInput = new Map(candidates.map((candidate) => [candidate.input, candidate]));
155
+ for (const outcome of resolveActiveSkills(candidates.map((candidate) => candidate.input)).outcomes) {
156
+ const candidate = byInput.get(outcome.input);
157
+ const scope = candidate.scope;
158
+ const source = outcome.source ?? null;
159
+ if (!outcome.loaded) {
160
+ diagnostics.push({
161
+ name: outcome.name, scope, priority: outcome.priority, source,
162
+ decision: outcome.decision, reason: outcome.reason,
163
+ });
164
+ continue;
165
+ }
166
+ const ref = scope === "org"
167
+ ? resolveOrgRef(candidate.skillRef, org.rows)
168
+ : resolveSkillRef(outcome.name, rows, agentId);
169
+ if (ref.kind === "resolved") {
170
+ skills.push({ name: outcome.name, skillId: ref.skillId, scope, priority: outcome.priority, source });
171
+ continue;
172
+ }
173
+ diagnostics.push({
174
+ name: outcome.name, scope, priority: outcome.priority, source, decision: ref.kind, reason: ref.reason,
175
+ ...(ref.kind === "ambiguous" ? { candidates: ref.candidates } : {}),
176
+ });
177
+ }
178
+ skills.sort((a, b) => a.name.localeCompare(b.name));
179
+ diagnostics.sort(compareDiagnostics);
180
+ return { skills, diagnostics };
181
+ }
@@ -158,6 +158,11 @@ export function refuseSkillAssignmentWrite(content, existing) {
158
158
  if (assignmentKey(content, existing) !== SKILL_ASSIGNMENT_KEY)
159
159
  return null;
160
160
  const metadata = content?.metadata !== undefined ? content.metadata : existing?.metadata;
161
+ // flair#2141 S1: `metadata.optOut`, when present, is a boolean.
162
+ const parsed = parseSkillMetadata(metadata);
163
+ if (Object.hasOwn(parsed, "optOut") && typeof parsed.optOut !== "boolean") {
164
+ return new Response(JSON.stringify({ error: "skill_opt_out_not_boolean", message: "metadata.optOut must be true or false" }), { status: 400, headers: { "content-type": "application/json" } });
165
+ }
161
166
  const result = registerSkillAssignment({
162
167
  key: SKILL_ASSIGNMENT_KEY,
163
168
  value: content?.value ?? existing?.value,
@@ -172,7 +177,7 @@ export function refuseSkillAssignmentWrite(content, existing) {
172
177
  message: result.message,
173
178
  }), { status: 400, headers: { "content-type": "application/json" } });
174
179
  }
175
- function normalizePriority(p) {
180
+ export function normalizePriority(p) {
176
181
  if (typeof p === "string" && Object.hasOwn(PRIORITY_RANK, p))
177
182
  return p;
178
183
  return "standard";
@@ -180,7 +185,7 @@ function normalizePriority(p) {
180
185
  function priorityRank(p) {
181
186
  return PRIORITY_RANK[p] ?? PRIORITY_RANK.standard;
182
187
  }
183
- function formatBase(name, priority, source) {
188
+ export function formatBase(name, priority, source) {
184
189
  const src = source ? `, source: ${source}` : "";
185
190
  return `- ${name} (${priority} priority${src})`;
186
191
  }
@@ -196,7 +201,7 @@ function compareOutcomes(a, b) {
196
201
  return byPri;
197
202
  return a.reason.localeCompare(b.reason);
198
203
  }
199
- function outcomeOf(name, priority, source, decision, reason, loaded) {
204
+ function outcomeOf(input, name, priority, source, decision, reason, loaded) {
200
205
  let line = formatBase(name, priority, source);
201
206
  if (decision === "superseded") {
202
207
  line += ` [SKILL_CONFLICT superseded: ${reason}]`;
@@ -206,7 +211,7 @@ function outcomeOf(name, priority, source, decision, reason, loaded) {
206
211
  ? ` [refused: ${reason}]`
207
212
  : ` [SKILL_CONFLICT refused: ${reason}]`;
208
213
  }
209
- return { name, priority, source, decision, reason, loaded, line };
214
+ return { name, priority, source, decision, reason, loaded, line, input };
210
215
  }
211
216
  /**
212
217
  * Stated, deterministic Active Skills outcome.
@@ -231,10 +236,10 @@ export function resolveActiveSkills(assignments) {
231
236
  const priority = normalizePriority(raw.priority);
232
237
  const source = skillSourceOf(raw);
233
238
  if (source && !isDurableSkillSource(source)) {
234
- outcomes.push(outcomeOf(name, priority, source, "refused", `non-durable source ${source}`, false));
239
+ outcomes.push(outcomeOf(raw, name, priority, source, "refused", `non-durable source ${source}`, false));
235
240
  continue;
236
241
  }
237
- prepared.push({ name, priority, source });
242
+ prepared.push({ input: raw, name, priority, source });
238
243
  }
239
244
  const byName = new Map();
240
245
  for (const row of prepared) {
@@ -247,25 +252,25 @@ export function resolveActiveSkills(assignments) {
247
252
  for (const group of byName.values()) {
248
253
  if (group.length === 1) {
249
254
  const only = group[0];
250
- outcomes.push(outcomeOf(only.name, only.priority, only.source, "loaded", "sole", true));
255
+ outcomes.push(outcomeOf(only.input, only.name, only.priority, only.source, "loaded", "sole", true));
251
256
  continue;
252
257
  }
253
258
  const best = Math.min(...group.map((g) => priorityRank(g.priority)));
254
259
  const top = group.filter((g) => priorityRank(g.priority) === best);
255
260
  if (top.length === 1) {
256
261
  const winner = top[0];
257
- outcomes.push(outcomeOf(winner.name, winner.priority, winner.source, "loaded", `unique_priority ${winner.priority}`, true));
262
+ outcomes.push(outcomeOf(winner.input, winner.name, winner.priority, winner.source, "loaded", `unique_priority ${winner.priority}`, true));
258
263
  for (const loser of group) {
259
264
  if (loser === winner)
260
265
  continue;
261
- outcomes.push(outcomeOf(loser.name, loser.priority, loser.source, "superseded", `${winner.priority} priority is stated precedence over ${loser.priority}`, false));
266
+ outcomes.push(outcomeOf(loser.input, loser.name, loser.priority, loser.source, "superseded", `${winner.priority} priority is stated precedence over ${loser.priority}`, false));
262
267
  }
263
268
  continue;
264
269
  }
265
270
  const sources = [...new Set(top.map((t) => t.source ?? "(none)"))].sort((a, b) => a.localeCompare(b));
266
271
  const reason = `equal-priority tie at ${top[0].priority}; load refused (sources: ${sources.join(", ")})`;
267
272
  for (const member of group) {
268
- outcomes.push(outcomeOf(member.name, member.priority, member.source, "refused", reason, false));
273
+ outcomes.push(outcomeOf(member.input, member.name, member.priority, member.source, "refused", reason, false));
269
274
  }
270
275
  }
271
276
  outcomes.sort(compareOutcomes);
@@ -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
+ }