@tpsdev-ai/flair 0.57.0 → 0.58.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 (122) hide show
  1. package/README.md +4 -4
  2. package/SECURITY.md +4 -1
  3. package/dist/build-info.json +3 -3
  4. package/dist/cli.js +1685 -279
  5. package/dist/commands/doctor.js +162 -4
  6. package/dist/commands/federation.js +2 -1
  7. package/dist/commands/hook.js +10 -2
  8. package/dist/commands/init.js +150 -44
  9. package/dist/commands/memory.js +24 -2
  10. package/dist/commands/quality.js +26 -18
  11. package/dist/commands/service.js +137 -22
  12. package/dist/commands/status.js +114 -3
  13. package/dist/commands/upgrade.js +204 -84
  14. package/dist/doctor-client.js +50 -4
  15. package/dist/federation/scheduler.js +253 -4
  16. package/dist/install/clients.js +89 -23
  17. package/dist/install/global-bin-path.js +26 -6
  18. package/dist/lib/atomic-write.js +256 -0
  19. package/dist/lib/daemon-liveness.js +61 -0
  20. package/dist/lib/doctor-run.js +5 -0
  21. package/dist/lib/embed-gpu-doctor.js +49 -26
  22. package/dist/lib/federation-memory-attributes.js +15 -0
  23. package/dist/lib/init-admin-pass.js +4 -2
  24. package/dist/lib/init-listener-environ.js +38 -0
  25. package/dist/lib/init-occupied-listener.js +165 -0
  26. package/dist/lib/launchd-domain-preflight.js +448 -0
  27. package/dist/lib/launchd-management.js +176 -6
  28. package/dist/lib/launchd-repair.js +95 -0
  29. package/dist/lib/memory-attributes.js +77 -0
  30. package/dist/lib/node-alias-path.js +95 -0
  31. package/dist/lib/npm-registry.js +119 -6
  32. package/dist/lib/owned-pins.js +20 -6
  33. package/dist/lib/service-repoint-apply.js +267 -0
  34. package/dist/lib/service-repoint.js +575 -0
  35. package/dist/lib/toml-string-array.js +104 -0
  36. package/dist/lib/tree-divergence.js +716 -0
  37. package/dist/lib/upgrade-plain-tree.js +18 -8
  38. package/dist/lib/upgrade-prior-liveness.js +69 -0
  39. package/dist/lib/upgrade-rollback.js +116 -0
  40. package/dist/rem/runner.js +11 -0
  41. package/dist/resources/Agent.js +27 -14
  42. package/dist/resources/AgentSeed.js +35 -1
  43. package/dist/resources/Federation.js +70 -52
  44. package/dist/resources/Memory.js +567 -72
  45. package/dist/resources/MemoryArchive.js +9 -0
  46. package/dist/resources/MemoryBootstrap.js +4 -0
  47. package/dist/resources/MemoryFeed.js +204 -3
  48. package/dist/resources/MemoryHostSource.js +90 -0
  49. package/dist/resources/MemoryMaintenance.js +121 -32
  50. package/dist/resources/MemoryReflect.js +4 -1
  51. package/dist/resources/MemoryReindex.js +7 -4
  52. package/dist/resources/MemoryUsage.js +53 -3
  53. package/dist/resources/Presence.js +18 -10
  54. package/dist/resources/RecordUsage.js +30 -40
  55. package/dist/resources/Relationship.js +167 -78
  56. package/dist/resources/SemanticSearch.js +19 -6
  57. package/dist/resources/Soul.js +31 -19
  58. package/dist/resources/XAA.js +7 -3
  59. package/dist/resources/agent-auth.js +16 -10
  60. package/dist/resources/auth-middleware.js +135 -48
  61. package/dist/resources/auto-promote-lib.js +4 -4
  62. package/dist/resources/bm25-index-service.js +246 -32
  63. package/dist/resources/bm25-status.js +132 -0
  64. package/dist/resources/ed25519-auth.js +11 -54
  65. package/dist/resources/embed-gpu.js +262 -47
  66. package/dist/resources/embeddings-boot.js +52 -17
  67. package/dist/resources/federation-classify.js +12 -0
  68. package/dist/resources/federation-crypto.js +65 -19
  69. package/dist/resources/health.js +57 -14
  70. package/dist/resources/host-pointer/registry.js +35 -0
  71. package/dist/resources/host-pointer-adapter.js +15 -0
  72. package/dist/resources/host-source-visibility.js +167 -0
  73. package/dist/resources/host-source.js +151 -0
  74. package/dist/resources/instance-identity.js +3 -2
  75. package/dist/resources/mcp-handler.js +147 -51
  76. package/dist/resources/mcp-tools.js +25 -21
  77. package/dist/resources/memory-consolidate-lib.js +3 -1
  78. package/dist/resources/memory-declared-attributes.js +103 -0
  79. package/dist/resources/memory-feed-lib.js +5 -1
  80. package/dist/resources/memory-host-source.js +163 -0
  81. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  82. package/dist/resources/migrations/visibility-backfill.js +4 -1
  83. package/dist/resources/originator-instance.js +235 -0
  84. package/dist/resources/promotion-stamp.js +2 -0
  85. package/dist/resources/provenance.js +111 -11
  86. package/dist/resources/record-owner-guard.js +19 -0
  87. package/dist/resources/record-type-kit.js +9 -12
  88. package/dist/resources/record-types.js +6 -6
  89. package/dist/resources/relay-ops.js +28 -3
  90. package/dist/resources/replay-store.js +289 -0
  91. package/dist/resources/request-transaction.js +78 -0
  92. package/dist/resources/search-readiness.js +19 -21
  93. package/dist/resources/semantic-retrieval-core.js +5 -1
  94. package/dist/resources/table-patch-policy.js +109 -0
  95. package/dist/resources/table-patches.js +17 -0
  96. package/dist/resources/table-post-policy.js +138 -0
  97. package/dist/resources/table-posts.js +22 -0
  98. package/dist/resources/table-subscription-policy.js +135 -0
  99. package/dist/resources/table-subscriptions.js +19 -0
  100. package/dist/resources/tool-descriptors/index.js +15 -15
  101. package/dist/resources/trust-block.js +10 -3
  102. package/dist/resources/usage-recording.js +169 -41
  103. package/dist/src/lib/memory-attributes.js +77 -0
  104. package/docs/api-reference.md +79 -15
  105. package/docs/claude-code.md +132 -0
  106. package/docs/deployment.md +1 -1
  107. package/docs/federation.md +1 -1
  108. package/docs/integrations.md +5 -5
  109. package/docs/mcp-clients.md +11 -21
  110. package/docs/notes/mcp-oauth-model2.md +15 -1
  111. package/docs/quickstart.md +5 -0
  112. package/docs/releasing.md +134 -2
  113. package/docs/supply-chain-policy.md +10 -5
  114. package/docs/troubleshooting.md +11 -0
  115. package/docs/upgrade.md +187 -61
  116. package/package.json +9 -5
  117. package/schemas/agent.graphql +9 -6
  118. package/schemas/federation.graphql +2 -11
  119. package/schemas/memory.graphql +106 -17
  120. package/schemas/replay.graphql +18 -0
  121. package/templates/launchd/start-flair-with-admin-pass.sh +22 -0
  122. package/dist/resources/federation-nonce-store.js +0 -195
@@ -1,6 +1,6 @@
1
1
  import { databases } from "harper";
2
2
  import { guardOwnerFieldImmutable } from "./owner-field-guard.js";
3
- import { localInstanceId } from "./instance-identity.js";
3
+ import { applyOriginatorInstanceId, dropClientOriginator, resolveStoredRow, stampOriginatorOnCreate } from "./originator-instance.js";
4
4
  import { makeAuthGate, stampAttribution } from "./record-type-kit.js";
5
5
  import { RECORD_TYPES } from "./record-types.js";
6
6
  import { authorizeSoulWrite, refuseSoulWriteContent, soulProvenance } from "./soul-write-policy.js";
@@ -50,14 +50,12 @@ export class Soul extends databases.flair.Soul {
50
50
  content.durability ||= "permanent";
51
51
  content.createdAt = new Date().toISOString();
52
52
  content.updatedAt = content.createdAt;
53
- // Write-time originatorInstanceId stamp (federation-edge-hardening slice
54
- // 1) — see resources/Memory.ts's stampOriginatorInstanceId doc for the
55
- // full contract. No-op if already set (never fires for a genuine local
56
- // write; a federation-synced record never reaches this method — the
57
- // merge path writes via the raw table object, bypassing this class).
58
- if (content.originatorInstanceId == null) {
59
- content.originatorInstanceId = await localInstanceId();
60
- }
53
+ // Write-time originatorInstanceId (federation-edge-hardening slice 1): a
54
+ // post() is a CREATE — stamp this instance's own id, ignoring any
55
+ // request-body value. See resources/originator-instance.ts for the full
56
+ // contract (create/update rule; the federation merge path is the raw
57
+ // table writer and never consults a body).
58
+ await stampOriginatorOnCreate(content);
61
59
  return super.post(content, context);
62
60
  }
63
61
  // PATCH must validate the merged value and retained legacy tags, rather
@@ -69,11 +67,17 @@ export class Soul extends databases.flair.Soul {
69
67
  const denial = await guardOwnerFieldImmutable(this, () => super.get(), content, "agentId");
70
68
  if (denial)
71
69
  return denial;
72
- // Fail-closed, same as Memory's stored-state read: a throw aborts the
73
- // write; missing/unreadable stored state cannot authorize a PATCH that
74
- // typically omits agentId (that used to skip the content-provenance match).
75
- const existing = await super.get();
76
- if (!existing || typeof existing !== "object" || existing instanceof Response) {
70
+ // Fail-closed, same class as Memory's stored-state read: the stored row is
71
+ // resolved by the URL-BOUND target id, refusing a body id that disagrees
72
+ // with the address and refusing a lookup that FAILS (a failed read is never
73
+ // "no stored row"). A PATCH that typically omits agentId cannot be
74
+ // authorized without the stored state, so an absent row is refused too. See
75
+ // resources/originator-instance.ts's resolveStoredRow.
76
+ const resolvedStored = await resolveStoredRow(this, "Soul", content, () => super.get());
77
+ if (resolvedStored.denial)
78
+ return resolvedStored.denial;
79
+ const existing = resolvedStored.row;
80
+ if (!existing) {
77
81
  return new Response(JSON.stringify({ error: "soul_stored_state_unavailable" }), {
78
82
  status: 403,
79
83
  headers: { "Content-Type": "application/json" },
@@ -82,6 +86,10 @@ export class Soul extends databases.flair.Soul {
82
86
  const learnedDenied = await refuseSoulWriteContent({ ...existing, ...content });
83
87
  if (learnedDenied)
84
88
  return learnedDenied;
89
+ // flair#1965: originatorInstanceId is server-stamped — a PATCH body value is
90
+ // dropped so the stored value stands (a patch merges; see
91
+ // resources/originator-instance.ts).
92
+ dropClientOriginator(content);
85
93
  const skillSourceDenied = refuseSkillAssignmentWrite(content, existing);
86
94
  if (skillSourceDenied)
87
95
  return skillSourceDenied;
@@ -105,11 +113,15 @@ export class Soul extends databases.flair.Soul {
105
113
  if (ownerDenial)
106
114
  return ownerDenial;
107
115
  content.updatedAt = new Date().toISOString();
108
- // Write-time originatorInstanceId stamp — see post() above / Memory.ts's
109
- // stampOriginatorInstanceId doc. No-op if already set.
110
- if (content.originatorInstanceId == null) {
111
- content.originatorInstanceId = await localInstanceId();
112
- }
116
+ // Write-time originatorInstanceId — see post() above /
117
+ // resources/originator-instance.ts. A CREATE stamps the local id; an
118
+ // UPDATE keeps the stored value (a body value never replaces or clears it).
119
+ // The row is resolved by the URL-BOUND target id, never a body `id` (Harper
120
+ // writes to the URL target); a mismatch or a failed read refuses the write.
121
+ const resolvedOriginRow = await resolveStoredRow(this, "Soul", content, () => super.get());
122
+ if (resolvedOriginRow.denial)
123
+ return resolvedOriginRow.denial;
124
+ await applyOriginatorInstanceId(content, resolvedOriginRow.row);
113
125
  return super.put(content, context);
114
126
  }
115
127
  async delete(id) {
@@ -4,6 +4,7 @@ import { harperPortValue } from "../src/lib/harper-port-value.js";
4
4
  import { DEFAULT_HTTP_PORT } from "./a2a-url.js";
5
5
  import { createHash, randomBytes } from "node:crypto";
6
6
  import { createRemoteJWKSet, jwtVerify } from "jose";
7
+ import { stampOriginatorOnCreate } from "./originator-instance.js";
7
8
  /**
8
9
  * XAA (Enterprise-Managed Authorization) — ID-JAG validation for Flair.
9
10
  *
@@ -148,8 +149,9 @@ async function resolveOrCreatePrincipal(payload, idpConfig) {
148
149
  }
149
150
  const principalId = `usr_${idpSubject.replace(/[^a-zA-Z0-9]/g, "_").slice(0, 20)}_${randomBytes(4).toString("hex")}`;
150
151
  const now = nowISO();
151
- // Create principal (via Agent table)
152
- await databases.flair.Agent.put({
152
+ // Create principal (via Agent table). flair#1965 r2: a raw Agent create —
153
+ // stamp the local instance id (the Agent resource's post() does not run here).
154
+ const principalRow = {
153
155
  id: principalId,
154
156
  name: displayName,
155
157
  displayName,
@@ -161,7 +163,9 @@ async function resolveOrCreatePrincipal(payload, idpConfig) {
161
163
  admin: false,
162
164
  createdAt: now,
163
165
  updatedAt: now,
164
- });
166
+ };
167
+ await stampOriginatorOnCreate(principalRow);
168
+ await databases.flair.Agent.put(principalRow);
165
169
  // Create IdP credential
166
170
  await databases.flair.Credential.put({
167
171
  id: `cred_idp_${randomBytes(8).toString("hex")}`,
@@ -13,10 +13,12 @@
13
13
  * Auth model: an agent presents `Authorization: TPS-Ed25519 <id>:<ts>:<nonce>:<sig>`.
14
14
  * The signature covers `<id>:<ts>:<nonce>:<METHOD>:<pathname><search>` and is
15
15
  * verified against the agent's stored Ed25519 public key. Replay is bounded by a
16
- * 30s timestamp window + a per-(agent,nonce) seen-set pruned to that window.
16
+ * 30s timestamp window + an instance-wide record of each (agent, nonce)
17
+ * (resources/replay-store.ts).
17
18
  */
18
19
  import { databases } from "harper";
19
- import { WINDOW_MS, isNonceReplay, recordNonce, importEd25519Key, b64ToArrayBuffer, parseTpsEd25519Header } from "./ed25519-auth.js";
20
+ import { WINDOW_MS, importEd25519Key, b64ToArrayBuffer, parseTpsEd25519Header } from "./ed25519-auth.js";
21
+ import { isKnownAgentReplay, claimAgentNonce } from "./replay-store.js";
20
22
  import { ADMIN_ROLE, agentRecordIsAdmin } from "./agent-admin.js";
21
23
  /**
22
24
  * Shared Harper user that verified Ed25519 agents resolve to (least-privilege
@@ -53,11 +55,11 @@ export function isPrincipalDeactivated(agent) {
53
55
  return agent.status !== "active";
54
56
  }
55
57
  // ─── Crypto + replay-guard helpers ────────────────────────────────────────────
56
- // WINDOW_MS, isNonceReplay/recordNonce (the ONE shared nonce store), and
57
- // importEd25519Key all live in ./ed25519-auth.ts — the single
58
- // shared implementation imported by auth-middleware.ts, agent-auth.ts, and
59
- // Presence.ts so a nonce recorded via any one of the three call sites is
60
- // visible to the other two, and the crypto/decoder logic can't drift.
58
+ // WINDOW_MS and importEd25519Key live in ./ed25519-auth.ts, and the replay
59
+ // guard (isKnownAgentReplay / claimAgentNonce) in ./replay-store.ts — shared by
60
+ // auth-middleware.ts, agent-auth.ts and Presence.ts, so a nonce recorded via
61
+ // any one of the three call sites, on any worker thread, is refused by all of
62
+ // them, and the crypto/decoder logic can't drift.
61
63
  // ─── Admin resolution ─────────────────────────────────────────────────────────
62
64
  // Admin agents come from FLAIR_ADMIN_AGENTS (comma-separated) OR Agent records
63
65
  // whose `role` is the admin sentinel. OR-combined, cached 60s. Distinct from
@@ -124,8 +126,9 @@ async function doVerify(request) {
124
126
  const now = Date.now();
125
127
  if (!Number.isFinite(ts) || Math.abs(now - ts) > WINDOW_MS)
126
128
  return null;
127
- // Reject replays within the window (isNonceReplay prunes expired entries first).
128
- if (isNonceReplay(agentId, nonce, now))
129
+ // A nonce this thread already saw recorded is refused before any lookup. A
130
+ // miss here proves nothing: claimAgentNonce below is the authoritative check.
131
+ if (isKnownAgentReplay(agentId, nonce, now))
129
132
  return null;
130
133
  const agent = await databases.flair.Agent.get(agentId).catch(() => null);
131
134
  if (!agent?.publicKey)
@@ -147,7 +150,10 @@ async function doVerify(request) {
147
150
  catch {
148
151
  return null;
149
152
  }
150
- recordNonce(agentId, nonce, ts);
153
+ // Record the nonce instance-wide now that the signature has verified, and
154
+ // before the request has any effect. A replay or an unusable store refuses.
155
+ if (!(await claimAgentNonce(agentId, nonce)).ok)
156
+ return null;
151
157
  return { agentId, isAdmin: await isAdmin(agentId) };
152
158
  }
153
159
  /**
@@ -2,11 +2,107 @@ import { patchRecord } from "./table-helpers.js";
2
2
  import { server, databases } from "harper";
3
3
  import { getEmbedding } from "./embeddings-provider.js";
4
4
  import { isAdmin, isPrincipalDeactivated, FLAIR_AGENT_USERNAME } from "./agent-auth.js";
5
- import { WINDOW_MS, isNonceReplay, recordNonce, importEd25519Key, b64ToArrayBuffer, parseTpsEd25519Header } from "./ed25519-auth.js";
6
- import { resolveReadScope } from "./memory-read-scope.js";
7
- import { NOT_FOUND } from "./record-type-kit.js";
8
- import { isForbiddenOwnerMutation, resolveGuardedRecord } from "./record-owner-guard.js";
5
+ import { WINDOW_MS, importEd25519Key, b64ToArrayBuffer, parseTpsEd25519Header } from "./ed25519-auth.js";
6
+ import { isKnownAgentReplay, claimAgentNonce } from "./replay-store.js";
7
+ import { isForbiddenOwnerMutation, ownerMutationRefusal, resolveGuardedRecord } from "./record-owner-guard.js";
9
8
  import { checkHttpRateLimit } from "./rate-limit.js";
9
+ import { stripUndeclaredMemoryAttributes, DECLARED_MEMORY_ATTRIBUTES } from "./memory-declared-attributes.js";
10
+ // --- Non-admin Memory read: ignore the caller's selection --------------------
11
+ //
12
+ // flair#1940 round 17. A non-admin HTTP Memory read returns the authorized,
13
+ // pointer-projected row; a caller `select(...)` or `property` is dropped from the
14
+ // request URL before Harper parses it, while conditions, operator, sort, limit
15
+ // and offset are left exactly as sent. These helpers are the whole of that
16
+ // normalization.
17
+ const DECLARED_MEMORY_ATTRIBUTE_SET = new Set(DECLARED_MEMORY_ATTRIBUTES);
18
+ function isMemoryReadPath(pathname) {
19
+ return pathname === "/Memory" || pathname === "/Memory/" || pathname.startsWith("/Memory/");
20
+ }
21
+ // Drop a caller's `select(...)` and `property` from a Memory read URL, keeping
22
+ // conditions, operator, sort, limit and offset. Returns the input unchanged when
23
+ // the URL carries no selection.
24
+ function stripMemorySelection(rawUrl) {
25
+ const q = rawUrl.indexOf("?");
26
+ let pathPart = q === -1 ? rawUrl : rawUrl.slice(0, q);
27
+ let query = q === -1 ? "" : rawUrl.slice(q + 1);
28
+ // Path form: Harper reads a trailing `.<declared>` on the id as `property`.
29
+ // Harper decides on the DECODED path — RequestTarget decodes the path
30
+ // (`this.id = decodeURIComponent(path)`) and Resource.parsePath then splits at
31
+ // the first dot — so the middleware must decide on the decoded segment too, or
32
+ // it misses a percent-encoded dot: `%2E` (and `%2e`) IS a dot to Harper. Drop
33
+ // that suffix so the id addresses the full row; a suffix that is not a
34
+ // declared Memory attribute stays part of the id, exactly as Harper's own rule
35
+ // leaves it (a content-type extension such as `json` is not a declared
36
+ // attribute, so it is left for Harper to read as a content type).
37
+ const slash = pathPart.lastIndexOf("/");
38
+ const seg = pathPart.slice(slash + 1);
39
+ const decodedSeg = decodePathSegment(seg);
40
+ const dot = decodedSeg.indexOf(".");
41
+ if (dot > -1 && DECLARED_MEMORY_ATTRIBUTE_SET.has(decodedSeg.slice(dot + 1))) {
42
+ // Rebuild the id from its decoded form. Harper decodes the path it is handed,
43
+ // so this re-encoded segment addresses the SAME id, without the property.
44
+ pathPart = `${pathPart.slice(0, slash + 1)}${encodeURIComponent(decodedSeg.slice(0, dot))}`;
45
+ }
46
+ // Query form: drop every `select(...)` token and every `property` parameter.
47
+ for (const [start, end] of selectSpans(query).reverse()) {
48
+ query = query.slice(0, start) + query.slice(end);
49
+ }
50
+ query = query
51
+ .split("&")
52
+ .filter((p) => p !== "" && p !== "property" && !p.startsWith("property="))
53
+ .join("&");
54
+ // A run of separators left by removing `select(...)` tokens carries nothing.
55
+ if (/^[,;]*$/.test(query))
56
+ query = "";
57
+ if (q === -1)
58
+ return pathPart;
59
+ return query === "" ? pathPart : `${pathPart}?${query}`;
60
+ }
61
+ /** Decode a path segment the way Harper does before its property parse; fall
62
+ * back to the raw segment when it is not valid percent-encoding (Harper rejects
63
+ * the malformed request; the middleware must not crash on it). */
64
+ function decodePathSegment(raw) {
65
+ try {
66
+ return decodeURIComponent(raw);
67
+ }
68
+ catch {
69
+ return raw;
70
+ }
71
+ }
72
+ // [start, end) ranges of every `select(...)` call in a query string, accounting
73
+ // for Harper's nested-list form `select((a,b))`.
74
+ function selectSpans(query) {
75
+ const spans = [];
76
+ const marker = "select(";
77
+ let from = 0;
78
+ for (;;) {
79
+ const idx = query.indexOf(marker, from);
80
+ if (idx < 0)
81
+ break;
82
+ const before = idx > 0 ? query[idx - 1] : "";
83
+ if (before && /[A-Za-z0-9_$-]/.test(before)) {
84
+ from = idx + marker.length;
85
+ continue;
86
+ }
87
+ let depth = 1;
88
+ let i = idx + marker.length;
89
+ for (; i < query.length; i++) {
90
+ const ch = query[i];
91
+ if (ch === "(")
92
+ depth++;
93
+ else if (ch === ")") {
94
+ depth--;
95
+ if (depth === 0)
96
+ break;
97
+ }
98
+ }
99
+ if (i >= query.length)
100
+ break;
101
+ spans.push([idx, i + 1]);
102
+ from = i + 1;
103
+ }
104
+ return spans;
105
+ }
10
106
  // --- Admin credentials ---
11
107
  // Admin auth is sourced exclusively from Harper's own environment variables
12
108
  // (HDB_ADMIN_PASSWORD / FLAIR_ADMIN_PASSWORD). No filesystem token file.
@@ -40,11 +136,11 @@ function getAdminPass() {
40
136
  // auth reshape this gate and the per-resource allow* helpers must agree on who's
41
137
  // an admin — one implementation guarantees they can't diverge.
42
138
  // ─── Crypto + replay-guard helpers ────────────────────────────────────────────
43
- // WINDOW_MS, isNonceReplay/recordNonce (the ONE shared nonce store), and
44
- // importEd25519Key all live in ./ed25519-auth.ts — the single
45
- // shared implementation imported by auth-middleware.ts, agent-auth.ts, and
46
- // Presence.ts so a nonce recorded via any one of the three call sites is
47
- // visible to the other two, and the crypto/decoder logic can't drift.
139
+ // WINDOW_MS and importEd25519Key live in ./ed25519-auth.ts, and the replay
140
+ // guard (isKnownAgentReplay / claimAgentNonce) in ./replay-store.ts — shared by
141
+ // auth-middleware.ts, agent-auth.ts and Presence.ts, so a nonce recorded via
142
+ // any one of the three call sites, on any worker thread, is refused by all of
143
+ // them, and the crypto/decoder logic can't drift.
48
144
  async function backfillEmbedding(memoryId) {
49
145
  try {
50
146
  const record = await databases.flair.Memory.get(memoryId);
@@ -57,7 +153,9 @@ async function backfillEmbedding(memoryId) {
57
153
  const embedding = await getEmbedding(record.content, "document");
58
154
  if (!embedding)
59
155
  return;
60
- await patchRecord(databases.flair.Memory, memoryId, { embedding });
156
+ const embedPatch = { embedding };
157
+ stripUndeclaredMemoryAttributes(embedPatch);
158
+ await patchRecord(databases.flair.Memory, memoryId, embedPatch);
61
159
  console.log(`[auto-embed] ${memoryId}: ${embedding.length}d`);
62
160
  }
63
161
  catch (err) {
@@ -343,7 +441,9 @@ server.http(async (request, nextLayer) => {
343
441
  const now = Date.now();
344
442
  if (!Number.isFinite(ts) || Math.abs(now - ts) > WINDOW_MS)
345
443
  return new Response(JSON.stringify({ error: "timestamp_out_of_window" }), { status: 401 });
346
- if (isNonceReplay(agentId, nonce, now))
444
+ // A nonce this thread already saw recorded is refused before any lookup. A
445
+ // miss here proves nothing: claimAgentNonce below is the authoritative check.
446
+ if (isKnownAgentReplay(agentId, nonce, now))
347
447
  return new Response(JSON.stringify({ error: "nonce_replay_detected" }), { status: 401 });
348
448
  const agent = await databases.flair.Agent.get(agentId);
349
449
  if (!agent)
@@ -365,7 +465,12 @@ server.http(async (request, nextLayer) => {
365
465
  catch (e) {
366
466
  return new Response(JSON.stringify({ error: "signature_verification_failed", detail: e?.message }), { status: 401 });
367
467
  }
368
- recordNonce(agentId, nonce, ts);
468
+ // Record the nonce instance-wide now that the signature has verified, and
469
+ // before the request reaches anything else. A replay (401) or an unusable
470
+ // replay store (503, named in the server log) refuses.
471
+ const claim = await claimAgentNonce(agentId, nonce);
472
+ if (!claim.ok)
473
+ return new Response(JSON.stringify({ error: claim.error }), { status: claim.status });
369
474
  request.tpsAgent = agentId;
370
475
  request._tpsAuthVerified = true;
371
476
  request.tpsAgentIsAdmin = await isAdmin(agentId);
@@ -456,9 +561,7 @@ server.http(async (request, nextLayer) => {
456
561
  try {
457
562
  const record = await databases.flair[guarded.table]?.get(guarded.id);
458
563
  if (isForbiddenOwnerMutation(record, guarded.ownerField, agentId)) {
459
- return new Response(JSON.stringify({
460
- error: `forbidden: cannot modify ${guarded.table} owned by another principal`,
461
- }), { status: 403, headers: { "Content-Type": "application/json" } });
564
+ return ownerMutationRefusal(guarded.table);
462
565
  }
463
566
  }
464
567
  catch { /* unreadable row → fall through to the resource's own rules */ }
@@ -624,39 +727,23 @@ server.http(async (request, nextLayer) => {
624
727
  // Instead, the resource-level check (e.g. BootstrapMemories line 58) handles
625
728
  // body-level enforcement since it receives the parsed data from Harper's REST
626
729
  // layer. The middleware's job is identity verification (done above).
627
- // ── Memory GET: non-admin can only read own memories (by ID) ────────────────
628
- if (!request.tpsAgentIsAdmin && method === "GET") {
629
- if (url.pathname.startsWith("/Memory/")) {
630
- try {
631
- const pathParts = url.pathname.split("/").filter(Boolean);
632
- const memId = pathParts[1] ? decodeURIComponent(pathParts[1]) : null;
633
- if (memId) {
634
- const record = await databases.flair.Memory.get(memId);
635
- if (record && record.agentId && record.agentId !== agentId) {
636
- // Centralized read-scope (Layer 1): the owner's records at any
637
- // visibility plus every other agent's non-private records; grants
638
- // are not consulted on reads (resolveReadScope()). This
639
- // used to be a `visibility === "office"` bypass (any authenticated
640
- // agent, no grant needed) — that's gone; the private-exclusion is
641
- // now enforced the same way every other read path enforces it.
642
- //
643
- // Denial is the SAME 404 the resource layer returns (flair#1264):
644
- // Memory.get() deliberately answers NOT_FOUND for a cross-agent
645
- // private id so a denied caller can't distinguish "doesn't exist"
646
- // from "exists but not yours" — a 403 here, worse yet one naming
647
- // the owning agent, confirmed the id exists AND disclosed its
648
- // owner, defeating that anti-enumeration contract one layer up.
649
- // Reuses record-type-kit's NOT_FOUND so the two layers cannot
650
- // drift apart in shape.
651
- const scope = await resolveReadScope(agentId);
652
- if (!scope.isAllowed(record)) {
653
- return NOT_FOUND();
654
- }
655
- }
656
- }
657
- }
658
- catch { /* record not found or table error — let resource handle */ }
659
- }
730
+ // ── Memory read: a non-admin read ignores the caller's selection ─────────────
731
+ // flair#1940 round 17 (design ruling): a non-admin HTTP Memory read does NOT
732
+ // honour a caller `select(...)` or `property`. As soon as authentication has
733
+ // established that the caller is not an admin — and BEFORE anything reads a
734
+ // Memory row or hands the request to the next layer — the request URL is
735
+ // normalized to drop the caller's selection, keeping conditions, operator,
736
+ // sort, limit and offset exactly as sent. Harper builds its REST target from
737
+ // this URL AFTER this middleware, so the original selection cannot be
738
+ // reapplied. An admin read and a trusted internal read are unchanged, while a
739
+ // direct contextual non-admin read now ignores the selection too (the same
740
+ // contract, applied in `Memory.get`/`Memory.search`). The by-id
741
+ // read-scope denial is enforced by the resource layer (memoryByIdReadGate),
742
+ // which returns the same 404 this middleware used to return.
743
+ if (!request.tpsAgentIsAdmin && method === "GET" && isMemoryReadPath(url.pathname)) {
744
+ const stripped = stripMemorySelection(request.url);
745
+ if (stripped !== request.url)
746
+ request.url = stripped;
660
747
  }
661
748
  // ── Embedding backfill ─────────────────────────────────────────────────────
662
749
  const isMemoryWrite = isMutation && (url.pathname === "/Memory" || url.pathname.startsWith("/Memory/"));
@@ -107,10 +107,10 @@ export const DEFAULT_MAX_AUTO_PROMOTE_PER_CYCLE = 200;
107
107
  // describe it otherwise anywhere (comment, changelog, skip reason) — we amended
108
108
  // the 0.55.0 Metal entry for exactly this overclaim shape.
109
109
  //
110
- // The detection is ASCII-ONLY. It recognizes the ASCII backtick and the ASCII
111
- // pairs ( ) [ ] { }. Non-ASCII pairs — full-width ()/[]/{} and CJK lenticular
112
- // 【】/〔〕/〖〗 — are NOT covered, so a truncated claim written in those scripts
113
- // is judged balanced and is NOT refused. Do not assume Unicode coverage.
110
+ // Bracket coverage is the enumerated table in src/rem/promote-policy.ts,
111
+ // including its full-width/CJK pairs; unlisted bracket pairs are not checked.
112
+ // Backticks use parity, not Markdown span matching, so valid escape spans
113
+ // can be refused. This signal does not establish semantic completeness.
114
114
  //
115
115
  // The check counts delimiters WITHOUT interpreting context, so it is deliberately
116
116
  // over-broad: a COMPLETE claim that merely discusses an unmatched delimiter (an