@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
@@ -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;
@@ -1,6 +1,7 @@
1
1
  import { databases } from "harper";
2
2
  import { resolveAgentAuth, allowVerified, allowAdmin, invalidateAdminCache } from "./agent-auth.js";
3
3
  import { agentRecordIsAdmin, reconcileAdminFields } from "./agent-admin.js";
4
+ import { admitPrincipalWrite, statusWriteRefusal } from "./agent-status-guard.js";
4
5
  import { applyOriginatorInstanceId, resolveStoredRow, stampOriginatorOnCreate } from "./originator-instance.js";
5
6
  /**
6
7
  * Agent resource — serves as the Principal table in 1.0.
@@ -65,28 +66,47 @@ export class Agent extends databases.flair.Agent {
65
66
  * does not route through put() — so every rule written here was enforced on
66
67
  * one verb and not the other. Returns a Response to send, or null to proceed.
67
68
  *
68
- * Two rules:
69
+ * Three rules:
69
70
  * 1. Only an admin principal may modify a principal OTHER than itself.
70
71
  * 2. Only an admin principal may change a principal's ADMIN STATUS — on any
71
72
  * record, including the caller's own. Rule 1 alone never covered this:
72
73
  * an agent editing its own record is inside its rights for ordinary
73
74
  * fields (runtime, displayName, subjects) and must not be for the fields
74
75
  * that decide whether it is an administrator.
76
+ * 3. A non-admin caller may not write `status` — the principal's LIFECYCLE
77
+ * state — on any record, including its own (flair#2108). A body that
78
+ * includes `status` is refused whole, so the other fields in that
79
+ * request are not written either.
75
80
  *
76
81
  * `internal` (in-process maintenance, federation merge) and admin agents pass
77
82
  * through unchanged.
78
83
  */
79
84
  async authorizePrincipalWrite(content) {
80
85
  const auth = await resolveAgentAuth(this.getContext?.());
81
- // Anonymous denied (defense-in-depth alongside allowUpdate; the old check read
82
- // tpsAgent and treated a missing agent as trusted, so anonymous slipped through).
83
- if (auth.kind === "anonymous") {
84
- return new Response(JSON.stringify({ error: "authentication required" }), {
86
+ // A trusted internal call and an administrator are admitted here. Anonymous
87
+ // and any verdict kind the auth resolver does not define are refused before
88
+ // any mutation. A non-admin agent goes on to the rules below: a body with
89
+ // `status` is refused (rule 3); without it, rules 1 and 2 decide.
90
+ const admission = admitPrincipalWrite(auth);
91
+ if (admission === "internal" || admission === "admin")
92
+ return null;
93
+ if (admission === "deny") {
94
+ const anonymous = auth.kind === "anonymous";
95
+ return new Response(JSON.stringify({ error: anonymous ? "authentication required" : "unrecognized caller verdict; refused" }), { status: 401, headers: { "content-type": "application/json" } });
96
+ }
97
+ // admission === "non-admin" here. Narrow the type (and stay fail-closed if a
98
+ // future verdict shape ever slipped past admitPrincipalWrite).
99
+ if (auth.kind !== "agent") {
100
+ return new Response(JSON.stringify({ error: "unrecognized caller verdict; refused" }), {
85
101
  status: 401, headers: { "content-type": "application/json" },
86
102
  });
87
103
  }
88
- if (auth.kind !== "agent" || auth.isAdmin)
89
- return null;
104
+ // 3. A non-admin caller may not write `status`, on ANY row, including its
105
+ // own. Refused before the target-row update, so nothing in the request is
106
+ // applied.
107
+ const statusDenial = statusWriteRefusal(content, false);
108
+ if (statusDenial)
109
+ return statusDenial;
90
110
  const existing = await Promise.resolve(super.get()).catch(() => null);
91
111
  // 1. Only admin principals can modify OTHER principals.
92
112
  if (existing && existing.id !== auth.agentId) {
@@ -27,6 +27,7 @@ import { noteMemoryUpsert } from "./bm25-index-service.js";
27
27
  import { stripUndeclaredMemoryAttributes, stripServerStampedFields } from "./memory-declared-attributes.js";
28
28
  import { rejectSkillWritePath } from "./skill-write.js";
29
29
  import { stampOriginatorOnCreate } from "./originator-instance.js";
30
+ import { SKILL_ASSIGNMENT_KEY } from "./skill-provenance.js";
30
31
  const DEFAULT_SOUL_KEYS = (agentId, displayName, role, now) => ({
31
32
  name: displayName,
32
33
  role,
@@ -68,6 +69,14 @@ export class AgentSeed extends Resource {
68
69
  // Validate the entire caller-controlled template before creating any rows.
69
70
  const defaults = DEFAULT_SOUL_KEYS(agentId, name, role, now);
70
71
  const merged = { ...defaults, ...(soulTemplate || {}) };
72
+ // flair#2141 S1: a seeded Soul entry carries a value only, so a
73
+ // skill-assignment (and its optOut metadata) is written through Soul.
74
+ if (Object.hasOwn(merged, SKILL_ASSIGNMENT_KEY)) {
75
+ return new Response(JSON.stringify({
76
+ error: "skill_assignment_not_seedable",
77
+ message: "soulTemplate cannot carry a skill-assignment; write it through Soul",
78
+ }), { status: 400, headers: { "content-type": "application/json" } });
79
+ }
71
80
  for (const value of Object.values(merged)) {
72
81
  const refusal = await refuseSoulWriteContent({ agentId, value: String(value) });
73
82
  if (refusal)
@@ -13,8 +13,8 @@ import { stripInboundMemoryRow, stripServerStampedFields } from "./memory-declar
13
13
  import { noteWriteStamp } from "./embedding-space-guard.js";
14
14
  import { initFederationCleanup } from "./federation-cleanup.js";
15
15
  import { verifyFederationRequestBody } from "./replay-store.js";
16
- import { classifyRecord, reconstructRecordVerifyBody, checkPrincipalEntitlement, } from "./federation-classify.js";
17
- export { classifyRecord, reconstructRecordVerifyBody, checkPrincipalEntitlement, recordSignatureVersion, PRINCIPAL_OWNING_TABLES, FEDERATION_TABLE_POLICY, FEDERATION_SYNC_TABLES, } from "./federation-classify.js";
16
+ import { classifyRecord, reconstructRecordVerifyBody, checkPrincipalEntitlement, inboundChangesExistingPrincipalStatus, } from "./federation-classify.js";
17
+ export { classifyRecord, reconstructRecordVerifyBody, checkPrincipalEntitlement, inboundChangesExistingPrincipalStatus, recordSignatureVersion, PRINCIPAL_OWNING_TABLES, FEDERATION_TABLE_POLICY, FEDERATION_SYNC_TABLES, } from "./federation-classify.js";
18
18
  // Federation anti-replay: FederationPair and FederationSync both verify through
19
19
  // verifyFederationRequestBody (resources/replay-store.ts), which claims each
20
20
  // body nonce ONCE in the instance-wide `ReplayNonce` table after the signature
@@ -651,6 +651,18 @@ export class FederationSync extends Resource {
651
651
  recordSkip(principalSkip);
652
652
  continue;
653
653
  }
654
+ // ── flair#2108: skip an inbound Agent record whose `status` differs
655
+ // from an existing local principal's stored value, whether or not it
656
+ // would win the last-write-wins merge below. The federation path
657
+ // carries no verified administrator authority for that principal (the
658
+ // batch is signed, and a record signature may also be present; neither
659
+ // is an admin claim). The whole record is skipped rather than merged
660
+ // with a pinned status, so the merge stays atomic and the other fields
661
+ // in the record do not land either.
662
+ if (inboundChangesExistingPrincipalStatus(record, local)) {
663
+ recordSkip("agent_status_not_federated");
664
+ continue;
665
+ }
654
666
  const mergedData = mergeRecord(local, record);
655
667
  // ── flair#1940 A1'' item 8: the SAME declared-attribute whitelist the
656
668
  // writers apply. A dirty pushed row (a legacy direct-insert, or a raw
@@ -5,7 +5,7 @@ import { wrapUntrusted } from "./content-safety.js";
5
5
  import { isTeammate, formatTeamLine, isZeroRowNoOpEvent } from "./memory-bootstrap-lib.js";
6
6
  import { resolveReadScope } from "./memory-read-scope.js";
7
7
  import { isValidEntity } from "./entity-vocab.js";
8
- import { withDetachedTxn } from "./table-helpers.js";
8
+ import { withDetachedTxn, withDetachedTxnAsync } from "./table-helpers.js";
9
9
  import { getPresenceRoster } from "./presence-internal.js";
10
10
  import { buildCollisionEntries, buildEntityMatchCondition, freshPresenceByAgent, } from "./collision-lib.js";
11
11
  // The bounded HNSW candidate-pool retrieval for the task-relevant/teammate/
@@ -22,7 +22,10 @@ import { estimateTokens } from "./token-estimate.js";
22
22
  import { initialPosition, ORG_EVENT_STREAM } from "./agent-read-position-lib.js";
23
23
  import { defaultReadPositionTable, ensureReadPosition } from "./agent-read-position.js";
24
24
  import { catchupSeekTimestamp, isCatchupEligible } from "./org-event-catchup-lib.js";
25
- import { resolveActiveSkills } from "./skill-provenance.js";
25
+ import { SKILL_ASSIGNMENT_KEY } from "./skill-provenance.js";
26
+ import { SKILL_TAG } from "./skill-write.js";
27
+ import { SKILL_ROW_SELECT, receivesOrgSkills, resolvableSkillRows, resolveSkillManifest, skillLine, } from "./skill-manifest.js";
28
+ import { localInstanceId } from "./instance-identity.js";
26
29
  /**
27
30
  * POST /MemoryBootstrap
28
31
  *
@@ -82,13 +85,15 @@ import { resolveActiveSkills } from "./skill-provenance.js";
82
85
  * { context, sections, tokenEstimate, maxTokens, memoriesIncluded, memoriesAvailable,
83
86
  * memoriesTruncated, teammateFindingsIncluded, teammateFindingsTruncated,
84
87
  * teammateFindingsMatched, agentId, scope, soul, memories, predicted,
85
- * teammateFindings, events, soulTokens, memoryTokens, trustTokens,
86
- * eventsTokens, scaffoldTokens[, currentTaskHint][, taskRetrievalHint][, predictedHint] }
88
+ * teammateFindings, events, skills, skillDiagnostics, skillsTruncated,
89
+ * skillDiagnosticsTruncated, soulTokens, memoryTokens, trustTokens,
90
+ * eventsTokens, skillsTokens, skillDiagnosticsTokens, scaffoldTokens
91
+ * [, currentTaskHint][, taskRetrievalHint][, predictedHint] }
87
92
  *
88
93
  * TOKEN LEDGER (flair#1270): the counters decompose `tokenEstimate` from the
89
94
  * payload alone —
90
95
  * tokenEstimate ≈ scaffoldTokens + soulTokens + memoryTokens + trustTokens
91
- * + eventsTokens
96
+ * + eventsTokens + skillsTokens + skillDiagnosticsTokens
92
97
  * Each figure is measured from what SHIPS (never derived as a residual), so
93
98
  * a section that ships uncounted content breaks the identity visibly instead
94
99
  * of hiding in an unexplained gap. See the ledger block in the response tail
@@ -505,23 +510,28 @@ export class BootstrapMemories extends Resource {
505
510
  // Full workspace files — lowest priority (runtime already injects these)
506
511
  soul: 90, "workspace-rules": 91,
507
512
  };
513
+ // flair#2141 — `skill-assignment` rows are read whatever includeSoul says
514
+ // (the skills manifest in 1b is always present); the other soul entries
515
+ // only when includeSoul is on.
508
516
  const skillAssignments = [];
517
+ const soulEntries = [];
518
+ for await (const record of databases.flair.Soul.search()) {
519
+ if (record.agentId !== agentId)
520
+ continue;
521
+ if (record.key === SKILL_ASSIGNMENT_KEY) {
522
+ skillAssignments.push(record);
523
+ continue;
524
+ }
525
+ if (!includeSoul)
526
+ continue;
527
+ const line = `**${record.key}:** ${record.value}`;
528
+ const tokens = estimateTokens(line);
529
+ const priority = SOUL_KEY_PRIORITY[record.key] ?? 50;
530
+ soulEntries.push({ key: record.key, value: record.value, line, tokens, priority });
531
+ }
509
532
  const soulMaxTokens = Math.floor(maxTokens * 0.4); // 40% of budget for soul
510
533
  if (includeSoul) {
511
534
  let soulTokens = 0;
512
- const soulEntries = [];
513
- for await (const record of databases.flair.Soul.search()) {
514
- if (record.agentId !== agentId)
515
- continue;
516
- if (record.key === "skill-assignment") {
517
- skillAssignments.push(record);
518
- continue;
519
- }
520
- const line = `**${record.key}:** ${record.value}`;
521
- const tokens = estimateTokens(line);
522
- const priority = SOUL_KEY_PRIORITY[record.key] ?? 50;
523
- soulEntries.push({ key: record.key, value: record.value, line, tokens, priority });
524
- }
525
535
  // Sort by priority (lower = more important)
526
536
  soulEntries.sort((a, b) => a.priority - b.priority);
527
537
  // flair#1431 — collapse VERBATIM duplicates. The live payload shipped the
@@ -567,13 +577,78 @@ export class BootstrapMemories extends Resource {
567
577
  tokenBudget -= entry.tokens; // #1199 — soul draws from the shared budget
568
578
  }
569
579
  }
570
- // --- 1b. Skill assignments (durable source + stated conflict outcome) ---
571
- // flair#1433: do not report-and-load-both. resolveActiveSkills decides
572
- // (unique priority wins; equal-priority same-name tie refuses) and
573
- // states the decision on the line. Non-durable sources are refused.
574
- if (skillAssignments.length > 0) {
575
- const resolved = resolveActiveSkills(skillAssignments);
576
- sections.skills.push(...resolved.lines);
580
+ // The read scope (see the "Read-scope" block below), resolved here because
581
+ // the skills manifest (1b) re-checks its skill rows against it.
582
+ const scope = await resolveReadScope(agentId);
583
+ // --- 1b. Skills manifest (flair#2141 S1b and S1; conflict rules flair#1433) ---
584
+ // Present whatever includeSoul and includeContext say. resolveSkillManifest
585
+ // (resources/skill-manifest.ts) splits the agent's own and org-scope
586
+ // assignments into winners, each with the skill row `skill_get` reads,
587
+ // and diagnostics. Entries are
588
+ // admitted while they fit the shared budget, right after the soul, at
589
+ // their serialized size; an entry that does not fit is counted in
590
+ // skillsTruncated / skillDiagnosticsTruncated instead.
591
+ const includedSkills = [];
592
+ const includedSkillDiagnostics = [];
593
+ let skillsTruncated = 0;
594
+ let skillDiagnosticsTruncated = 0;
595
+ // flair#2141 S1 — when org rows exist, the target's Agent record is read on
596
+ // this call, and org assignments apply only when it says the target
597
+ // receives org skills.
598
+ const orgRows = [];
599
+ const orgQuery = withDetachedTxn(ctx, () => databases.flair.OrgSkillAssignment.search());
600
+ for await (const row of orgQuery)
601
+ orgRows.push(row);
602
+ const org = { assignments: [], rows: [], instanceId: null };
603
+ if (orgRows.length > 0
604
+ && receivesOrgSkills(await withDetachedTxnAsync(ctx, () => databases.flair.Agent.get(agentId)))) {
605
+ const refRows = [];
606
+ for (const ref of new Set(orgRows.map((row) => row.skillRef).filter((ref) => typeof ref === "string"))) {
607
+ const refQuery = withDetachedTxn(ctx, () => databases.flair.Memory.search({
608
+ conditions: [{ attribute: "id", comparator: "equals", value: ref }],
609
+ select: SKILL_ROW_SELECT,
610
+ }));
611
+ for await (const record of refQuery)
612
+ refRows.push(record);
613
+ }
614
+ org.assignments = orgRows;
615
+ org.rows = resolvableSkillRows(refRows, scope.isAllowed);
616
+ org.instanceId = await localInstanceId();
617
+ }
618
+ if (skillAssignments.length > 0 || org.assignments.length > 0) {
619
+ const skillRows = [];
620
+ if (skillAssignments.length > 0) {
621
+ const skillQuery = withDetachedTxn(ctx, () => databases.flair.Memory.search({
622
+ conditions: [
623
+ { attribute: "agentId", comparator: "equals", value: agentId },
624
+ { attribute: "tags", comparator: "equals", value: SKILL_TAG },
625
+ { attribute: "archived", comparator: "not_equal", value: true },
626
+ ],
627
+ select: SKILL_ROW_SELECT,
628
+ }));
629
+ for await (const record of skillQuery)
630
+ skillRows.push(record);
631
+ }
632
+ const manifest = resolveSkillManifest(skillAssignments, resolvableSkillRows(skillRows, scope.isAllowed), agentId, org);
633
+ for (const entry of manifest.skills) {
634
+ const cost = estimateTokens(JSON.stringify(entry));
635
+ if (cost > tokenBudget) {
636
+ skillsTruncated++;
637
+ continue;
638
+ }
639
+ includedSkills.push(entry);
640
+ sections.skills.push(skillLine(entry));
641
+ tokenBudget -= cost;
642
+ }
643
+ for (const diagnostic of manifest.diagnostics) {
644
+ const cost = estimateTokens(JSON.stringify(diagnostic));
645
+ if (cost > tokenBudget) {
646
+ skillDiagnosticsTruncated++;
647
+ continue;
648
+ }
649
+ includedSkillDiagnostics.push(diagnostic);
650
+ tokenBudget -= cost;
651
+ }
577
652
  }
578
653
  // --- 1c. Team roster + cross-agent search nudge ---
579
654
  // Soul is still caller-own-only (unaffected here). Memory loading below
@@ -634,8 +709,8 @@ export class BootstrapMemories extends Resource {
634
709
  // spans the org. Each bounded query still re-checks `scope.isAllowed()`
635
710
  // on every record even where it's provably a no-op (e.g. an
636
711
  // agentId==self-only query) — uniform defense-in-depth, never skipped
637
- // because "the filter already pushed down."
638
- const scope = await resolveReadScope(agentId);
712
+ // because "the filter already pushed down." (`scope` is resolved above,
713
+ // before the skills manifest.)
639
714
  // `memoriesAvailable`: dropped the org-wide exact count (computing it
640
715
  // exactly WAS the scan being removed — `visibility != private` isn't
641
716
  // index-seekable, so even a bare count would scan). Replaced with the
@@ -1454,7 +1529,9 @@ export class BootstrapMemories extends Resource {
1454
1529
  if (sections.soul.length > 0) {
1455
1530
  parts.push("## Identity\n" + sections.soul.join("\n"));
1456
1531
  }
1457
- if (sections.skills.length > 0) {
1532
+ // flair#2141 — rendered from the admitted `skills` entries, and only with
1533
+ // includeSoul.
1534
+ if (includeSoul && sections.skills.length > 0) {
1458
1535
  parts.push("## Active Skills\n" + sections.skills.join("\n"));
1459
1536
  }
1460
1537
  if (sections.team.length > 0) {
@@ -1513,7 +1590,8 @@ export class BootstrapMemories extends Resource {
1513
1590
  // counter doesn't prevent silent regression, per Kern's #1270 ruling):
1514
1591
  //
1515
1592
  // tokenEstimate ≈ scaffoldTokens + soulTokens + memoryTokens
1516
- // + trustTokens + eventsTokens
1593
+ // + trustTokens + eventsTokens + skillsTokens
1594
+ // + skillDiagnosticsTokens
1517
1595
  //
1518
1596
  // Every token-charged content class has a named counter, so a consumer can
1519
1597
  // decompose `tokenEstimate` FROM THE PAYLOAD ALONE and any future section
@@ -1553,6 +1631,10 @@ export class BootstrapMemories extends Resource {
1553
1631
  // events admission loop charged (#1199). Same reporting hole-class as
1554
1632
  // trust: charged content with no counter would be invisible in the ledger.
1555
1633
  const eventsTokens = includedEvents.reduce((sum, evt) => sum + estimateTokens(JSON.stringify(evt)), 0);
1634
+ // flair#2141 — the skills manifest and its diagnostics: Σ estimateTokens
1635
+ // (JSON) over the shipped entries, the same per-entry cost 1b charged.
1636
+ const skillsTokens = includedSkills.reduce((sum, entry) => sum + estimateTokens(JSON.stringify(entry)), 0);
1637
+ const skillDiagnosticsTokens = includedSkillDiagnostics.reduce((sum, entry) => sum + estimateTokens(JSON.stringify(entry)), 0);
1556
1638
  // flair#744 slice 1 — opt-in per-memory trust block. Bootstrap renders
1557
1639
  // memories as text lines rather than result objects, so the block is
1558
1640
  // surfaced as a `trust` array of self-contained entries (each carries its
@@ -1659,6 +1741,12 @@ export class BootstrapMemories extends Resource {
1659
1741
  ...(taskRetrievalHint ? { taskRetrievalHint } : {}),
1660
1742
  scope: scopeInfo,
1661
1743
  soul: soulMap,
1744
+ // flair#2141 S1b — always present (`[]` when none), whatever includeSoul
1745
+ // and includeContext say; see 1b.
1746
+ skills: includedSkills,
1747
+ skillDiagnostics: includedSkillDiagnostics,
1748
+ skillsTruncated,
1749
+ skillDiagnosticsTruncated,
1662
1750
  memories: includedOwnMemories,
1663
1751
  predicted: includedPredicted,
1664
1752
  // flair#1199 — cross-agent teammate findings as a structured container
@@ -1704,6 +1792,8 @@ export class BootstrapMemories extends Resource {
1704
1792
  // token-charged content class is decomposable from the payload alone.
1705
1793
  trustTokens,
1706
1794
  eventsTokens,
1795
+ skillsTokens,
1796
+ skillDiagnosticsTokens,
1707
1797
  // flair#1199 — the content-selection budget this response was built
1708
1798
  // against (echoed so a connector can relate tokenEstimate to the budget it
1709
1799
  // asked for — and so the conformance tokenEstimate<=maxTokens invariant is
@@ -1769,6 +1859,8 @@ export class BootstrapMemories extends Resource {
1769
1859
  ...responseBody,
1770
1860
  context: "",
1771
1861
  soul: {},
1862
+ skills: [],
1863
+ skillDiagnostics: [],
1772
1864
  memories: [],
1773
1865
  predicted: [],
1774
1866
  teammateFindings: [],
@@ -0,0 +1,209 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { databases } from "harper";
3
+ import { resolveAgentAuth } from "./agent-auth.js";
4
+ import { resolveStoredRow } from "./originator-instance.js";
5
+ import { FORBIDDEN, NOT_FOUND, UNAUTH, makeAuthGate } from "./record-type-kit.js";
6
+ import { withKeyLock } from "./key-lock.js";
7
+ import { withOwnedTransaction, withSharedWriteTransaction } from "./request-transaction.js";
8
+ import { PRIORITY_RANK } from "./skill-provenance.js";
9
+ import { soulWriteSource } from "./soul-write-policy.js";
10
+ /**
11
+ * OrgSkillAssignment — org-scope skill assignments (flair#2141 S1).
12
+ *
13
+ * A row assigns `skillRef` under `skillName` and `priority`;
14
+ * bootstrap's skills manifest resolves it for an agent that receives org
15
+ * skills (resources/skill-manifest.ts).
16
+ *
17
+ * Writes: post, put, patch and delete each require the operator source
18
+ * (`soulWriteSource`: verified Basic admin auth, or the deliberate internal
19
+ * marker). Agent keys, admin agent keys included, are refused. `writer`,
20
+ * `sourceClass`, `createdAt` and `updatedAt` are server-stamped; other body
21
+ * fields are not stored. Reads: any verified agent.
22
+ *
23
+ * History: each accepted write appends an OrgSkillAssignmentHistory row
24
+ * (actor, source class, a hash of the stored row before the write) in the
25
+ * write's transaction. put, patch and delete hold a per-assignment lock shared
26
+ * by the threads of this Harper process (`withAssignmentLock`) while they read
27
+ * the stored row and commit. Writes on other replicated nodes are not covered
28
+ * by that lock.
29
+ */
30
+ const TABLE = "OrgSkillAssignment";
31
+ /** The stored fields, in the order `previousHash` covers them. */
32
+ const HASHED_FIELDS = ["id", "skillName", "skillRef", "priority", "createdAt", "updatedAt", "writer", "sourceClass"];
33
+ /** sha256 over a stored row's fields (HASHED_FIELDS), for `previousHash`. */
34
+ export function assignmentHash(row) {
35
+ const canonical = JSON.stringify(HASHED_FIELDS.map((field) => [field, row[field] ?? null]));
36
+ return createHash("sha256").update(canonical).digest("hex");
37
+ }
38
+ function badRequest(error, message) {
39
+ return new Response(JSON.stringify({ error, message }), {
40
+ status: 400, headers: { "Content-Type": "application/json" },
41
+ });
42
+ }
43
+ async function authorizeOperator(self) {
44
+ const context = self.getContext?.();
45
+ const auth = await resolveAgentAuth(context);
46
+ if (auth.kind === "anonymous")
47
+ return UNAUTH();
48
+ const sourceClass = soulWriteSource(context, auth);
49
+ if (!sourceClass)
50
+ return FORBIDDEN("org_skill_assignment_requires_operator: use operator credentials");
51
+ return { writer: auth.kind === "agent" ? auth.agentId : null, sourceClass };
52
+ }
53
+ /** The URL-bound row id, or null on a collection address. */
54
+ function boundId(self) {
55
+ try {
56
+ const id = self.getId?.();
57
+ if (typeof id === "string" && id.length > 0)
58
+ return id;
59
+ if (typeof id === "number")
60
+ return String(id);
61
+ }
62
+ catch {
63
+ /* no bound id */
64
+ }
65
+ return null;
66
+ }
67
+ function isRecord(value) {
68
+ return !!value && typeof value === "object" && !Array.isArray(value);
69
+ }
70
+ function validFields(body) {
71
+ const { skillName, skillRef, priority = "standard" } = body;
72
+ if (typeof skillName !== "string" || skillName.trim() === "") {
73
+ return badRequest("skill_name_required", "skillName must be a non-empty string");
74
+ }
75
+ if (typeof skillRef !== "string" || skillRef.trim() === "") {
76
+ return badRequest("skill_ref_required", "skillRef must be a non-empty string");
77
+ }
78
+ if (typeof priority !== "string" || !Object.hasOwn(PRIORITY_RANK, priority)) {
79
+ return badRequest("invalid_priority", `priority must be one of ${Object.keys(PRIORITY_RANK).join(", ")}`);
80
+ }
81
+ return { skillName, skillRef, priority };
82
+ }
83
+ async function appendHistory(context, assignmentId, op, previous, who, at) {
84
+ await databases.flair.OrgSkillAssignmentHistory.put({
85
+ id: randomUUID(),
86
+ assignmentId,
87
+ op,
88
+ actor: who.writer,
89
+ sourceClass: who.sourceClass,
90
+ previousHash: previous ? assignmentHash(previous) : null,
91
+ at,
92
+ }, context);
93
+ }
94
+ const LOCK_NAMESPACE = "flair-org-skill-assignment";
95
+ /** The wait for another write to the same assignment: at most LOCK_ATTEMPTS × LOCK_WAIT_MS. */
96
+ const LOCK_ATTEMPTS = 200;
97
+ const LOCK_WAIT_MS = 10;
98
+ /**
99
+ * Run `fn` holding this process's lock on assignment `id` (resources/key-lock.ts).
100
+ * `fn` must commit before it returns. 409 when the lock stays held
101
+ * past the wait; 503 when the store has no lock.
102
+ */
103
+ async function withAssignmentLock(id, fn) {
104
+ const store = databases.flair.OrgSkillAssignment?.primaryStore;
105
+ const outcome = await withKeyLock(store, [LOCK_NAMESPACE, id], fn, LOCK_ATTEMPTS, LOCK_WAIT_MS);
106
+ if (outcome.kind === "done")
107
+ return outcome.value;
108
+ if (outcome.kind === "busy") {
109
+ return new Response(JSON.stringify({
110
+ error: "org_skill_assignment_busy",
111
+ message: "another write to this assignment is still in progress; retry",
112
+ }), { status: 409, headers: { "Content-Type": "application/json" } });
113
+ }
114
+ return new Response(JSON.stringify({
115
+ error: "org_skill_assignment_lock_unavailable",
116
+ message: "the OrgSkillAssignment store has no per-key lock, so the write was refused",
117
+ }), { status: 503, headers: { "Content-Type": "application/json" } });
118
+ }
119
+ const authGate = makeAuthGate();
120
+ export class OrgSkillAssignment extends databases.flair.OrgSkillAssignment {
121
+ allowRead() { return authGate.call(this); }
122
+ async post(content, context) {
123
+ const who = await authorizeOperator(this);
124
+ if (who instanceof Response)
125
+ return who;
126
+ if (boundId(this))
127
+ return badRequest("org_skill_assignment_post_to_collection", "create an assignment with POST /OrgSkillAssignment/");
128
+ if (!isRecord(content))
129
+ return badRequest("org_skill_assignment_requires_one_record", "send one assignment object");
130
+ const fields = validFields(content);
131
+ if (fields instanceof Response)
132
+ return fields;
133
+ const at = new Date().toISOString();
134
+ const record = { id: randomUUID(), ...fields, createdAt: at, updatedAt: at, writer: who.writer, sourceClass: who.sourceClass };
135
+ return withSharedWriteTransaction(this.getContext?.(), async (shared) => {
136
+ await appendHistory(shared, record.id, "create", null, who, at);
137
+ return super.post(record, context);
138
+ });
139
+ }
140
+ async put(content, context) {
141
+ const who = await authorizeOperator(this);
142
+ if (who instanceof Response)
143
+ return who;
144
+ const id = boundId(this);
145
+ if (!id)
146
+ return badRequest("org_skill_assignment_id_required", "address one assignment: PUT /OrgSkillAssignment/<id>");
147
+ if (!isRecord(content))
148
+ return badRequest("org_skill_assignment_requires_one_record", "send one assignment object");
149
+ const fields = validFields(content);
150
+ if (fields instanceof Response)
151
+ return fields;
152
+ return withAssignmentLock(id, () => withOwnedTransaction(this.getContext?.(), async (shared) => {
153
+ const stored = await resolveStoredRow(this, TABLE, content, () => super.get());
154
+ if (stored.denial)
155
+ return stored.denial;
156
+ const at = new Date().toISOString();
157
+ const createdAt = typeof stored.row?.createdAt === "string" ? stored.row.createdAt : at;
158
+ const record = { id, ...fields, createdAt, updatedAt: at, writer: who.writer, sourceClass: who.sourceClass };
159
+ await appendHistory(shared, id, stored.row ? "update" : "create", stored.row, who, at);
160
+ return super.put(record, context);
161
+ }));
162
+ }
163
+ async patch(content, query) {
164
+ const who = await authorizeOperator(this);
165
+ if (who instanceof Response)
166
+ return who;
167
+ const id = boundId(this);
168
+ if (!id)
169
+ return badRequest("org_skill_assignment_id_required", "address one assignment: PATCH /OrgSkillAssignment/<id>");
170
+ if (!isRecord(content))
171
+ return badRequest("org_skill_assignment_requires_one_record", "send one assignment object");
172
+ return withAssignmentLock(id, () => withOwnedTransaction(this.getContext?.(), async (shared) => {
173
+ const stored = await resolveStoredRow(this, TABLE, content, () => super.get());
174
+ if (stored.denial)
175
+ return stored.denial;
176
+ if (!stored.row)
177
+ return NOT_FOUND();
178
+ const merged = {};
179
+ for (const field of ["skillName", "skillRef", "priority"]) {
180
+ merged[field] = Object.hasOwn(content, field) ? content[field] : stored.row[field];
181
+ }
182
+ const fields = validFields(merged);
183
+ if (fields instanceof Response)
184
+ return fields;
185
+ const at = new Date().toISOString();
186
+ const changes = { ...fields, updatedAt: at, writer: who.writer, sourceClass: who.sourceClass };
187
+ await appendHistory(shared, id, "update", stored.row, who, at);
188
+ return super.patch(changes, query);
189
+ }));
190
+ }
191
+ async delete(target) {
192
+ const who = await authorizeOperator(this);
193
+ if (who instanceof Response)
194
+ return who;
195
+ const id = boundId(this);
196
+ if (!id)
197
+ return badRequest("org_skill_assignment_id_required", "address one assignment: DELETE /OrgSkillAssignment/<id>");
198
+ return withAssignmentLock(id, () => withOwnedTransaction(this.getContext?.(), async (shared) => {
199
+ const stored = await resolveStoredRow(this, TABLE, undefined, () => super.get());
200
+ if (stored.denial)
201
+ return stored.denial;
202
+ if (!stored.row)
203
+ return NOT_FOUND();
204
+ const at = new Date().toISOString();
205
+ await appendHistory(shared, id, "delete", stored.row, who, at);
206
+ return super.delete(target);
207
+ }));
208
+ }
209
+ }