@tpsdev-ai/flair 0.56.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 (153) hide show
  1. package/README.md +19 -20
  2. package/SECURITY.md +4 -1
  3. package/dist/build-info.json +3 -3
  4. package/dist/cli.js +1800 -293
  5. package/dist/commands/agent.js +22 -15
  6. package/dist/commands/bridge.js +40 -3
  7. package/dist/commands/doctor.js +214 -4
  8. package/dist/commands/federation.js +265 -38
  9. package/dist/commands/hook.js +10 -2
  10. package/dist/commands/init.js +179 -48
  11. package/dist/commands/memory.js +24 -2
  12. package/dist/commands/quality.js +26 -18
  13. package/dist/commands/service.js +137 -22
  14. package/dist/commands/status.js +114 -3
  15. package/dist/commands/upgrade.js +204 -84
  16. package/dist/doctor-client.js +50 -4
  17. package/dist/federation/scheduler.js +253 -4
  18. package/dist/install/clients.js +89 -23
  19. package/dist/install/global-bin-path.js +26 -6
  20. package/dist/lib/atomic-write.js +256 -0
  21. package/dist/lib/auth-resolve.js +46 -0
  22. package/dist/lib/daemon-liveness.js +61 -0
  23. package/dist/lib/doctor-run.js +5 -0
  24. package/dist/lib/embed-gpu-doctor.js +49 -26
  25. package/dist/lib/federation-memory-attributes.js +15 -0
  26. package/dist/lib/init-admin-pass.js +4 -2
  27. package/dist/lib/init-listener-environ.js +38 -0
  28. package/dist/lib/init-occupied-listener.js +165 -0
  29. package/dist/lib/instance-identity-row.js +580 -0
  30. package/dist/lib/launchd-domain-preflight.js +448 -0
  31. package/dist/lib/launchd-management.js +176 -6
  32. package/dist/lib/launchd-repair.js +95 -0
  33. package/dist/lib/memory-attributes.js +77 -0
  34. package/dist/lib/node-alias-path.js +95 -0
  35. package/dist/lib/npm-registry.js +119 -6
  36. package/dist/lib/owned-pins.js +20 -6
  37. package/dist/lib/redact-token-id.js +197 -0
  38. package/dist/lib/service-repoint-apply.js +267 -0
  39. package/dist/lib/service-repoint.js +575 -0
  40. package/dist/lib/toml-string-array.js +104 -0
  41. package/dist/lib/tree-divergence.js +716 -0
  42. package/dist/lib/upgrade-plain-tree.js +18 -8
  43. package/dist/lib/upgrade-prior-liveness.js +69 -0
  44. package/dist/lib/upgrade-rollback.js +116 -0
  45. package/dist/rem/runner.js +11 -0
  46. package/dist/resources/Agent.js +27 -14
  47. package/dist/resources/AgentSeed.js +39 -2
  48. package/dist/resources/Asset.js +3 -11
  49. package/dist/resources/Credential.js +4 -10
  50. package/dist/resources/Federation.js +299 -127
  51. package/dist/resources/Integration.js +8 -32
  52. package/dist/resources/Memory.js +623 -86
  53. package/dist/resources/MemoryArchive.js +9 -0
  54. package/dist/resources/MemoryBootstrap.js +23 -12
  55. package/dist/resources/MemoryCandidate.js +3 -11
  56. package/dist/resources/MemoryDedupStats.js +1 -1
  57. package/dist/resources/MemoryFeed.js +214 -5
  58. package/dist/resources/MemoryGrant.js +19 -40
  59. package/dist/resources/MemoryHostSource.js +90 -0
  60. package/dist/resources/MemoryMaintenance.js +121 -32
  61. package/dist/resources/MemoryReflect.js +4 -1
  62. package/dist/resources/MemoryReindex.js +7 -4
  63. package/dist/resources/MemoryUsage.js +55 -18
  64. package/dist/resources/Presence.js +18 -10
  65. package/dist/resources/RecordUsage.js +30 -40
  66. package/dist/resources/Relationship.js +170 -89
  67. package/dist/resources/SemanticSearch.js +44 -19
  68. package/dist/resources/Soul.js +31 -19
  69. package/dist/resources/XAA.js +7 -3
  70. package/dist/resources/agent-auth.js +16 -10
  71. package/dist/resources/auth-middleware.js +164 -50
  72. package/dist/resources/auto-promote-lib.js +4 -4
  73. package/dist/resources/bm25-index-service.js +246 -32
  74. package/dist/resources/bm25-status.js +132 -0
  75. package/dist/resources/bm25.js +13 -14
  76. package/dist/resources/ed25519-auth.js +11 -54
  77. package/dist/resources/embed-gpu.js +262 -47
  78. package/dist/resources/embeddings-boot.js +52 -17
  79. package/dist/resources/federation-classify.js +12 -0
  80. package/dist/resources/federation-cleanup.js +289 -51
  81. package/dist/resources/federation-crypto.js +65 -19
  82. package/dist/resources/health.js +105 -22
  83. package/dist/resources/host-pointer/registry.js +35 -0
  84. package/dist/resources/host-pointer-adapter.js +15 -0
  85. package/dist/resources/host-source-visibility.js +167 -0
  86. package/dist/resources/host-source.js +151 -0
  87. package/dist/resources/in-process-api.js +2 -1
  88. package/dist/resources/instance-create-lock.js +363 -0
  89. package/dist/resources/instance-identity-rows.js +43 -0
  90. package/dist/resources/instance-identity.js +97 -12
  91. package/dist/resources/mcp-handler.js +155 -51
  92. package/dist/resources/mcp-tool-arguments.js +83 -0
  93. package/dist/resources/mcp-tools.js +28 -25
  94. package/dist/resources/memory-consolidate-lib.js +3 -1
  95. package/dist/resources/memory-declared-attributes.js +103 -0
  96. package/dist/resources/memory-feed-lib.js +5 -1
  97. package/dist/resources/memory-host-source.js +163 -0
  98. package/dist/resources/memory-visibility.js +10 -7
  99. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  100. package/dist/resources/migrations/visibility-backfill.js +4 -1
  101. package/dist/resources/originator-instance.js +235 -0
  102. package/dist/resources/promotion-stamp.js +2 -0
  103. package/dist/resources/provenance.js +111 -11
  104. package/dist/resources/rate-limit.js +6 -4
  105. package/dist/resources/record-owner-guard.js +19 -0
  106. package/dist/resources/record-type-kit.js +44 -23
  107. package/dist/resources/record-types.js +6 -6
  108. package/dist/resources/relay-ops.js +28 -3
  109. package/dist/resources/replay-store.js +289 -0
  110. package/dist/resources/request-transaction.js +78 -0
  111. package/dist/resources/search-readiness.js +26 -22
  112. package/dist/resources/semantic-retrieval-core.js +103 -4
  113. package/dist/resources/table-helpers.js +33 -0
  114. package/dist/resources/table-patch-policy.js +109 -0
  115. package/dist/resources/table-patches.js +17 -0
  116. package/dist/resources/table-post-policy.js +138 -0
  117. package/dist/resources/table-posts.js +22 -0
  118. package/dist/resources/table-subscription-policy.js +135 -0
  119. package/dist/resources/table-subscriptions.js +19 -0
  120. package/dist/resources/tool-descriptors/index.js +15 -15
  121. package/dist/resources/trust-block.js +10 -3
  122. package/dist/resources/usage-recording.js +169 -41
  123. package/dist/src/lib/instance-identity-row.js +580 -0
  124. package/dist/src/lib/memory-attributes.js +77 -0
  125. package/dist/src/lib/redact-token-id.js +197 -0
  126. package/docs/api-reference.md +80 -16
  127. package/docs/auth.md +5 -5
  128. package/docs/claude-code.md +137 -6
  129. package/docs/deploying-on-fabric.md +6 -3
  130. package/docs/deployment.md +1 -1
  131. package/docs/embedding-in-a-harper-app.md +3 -3
  132. package/docs/federation.md +17 -10
  133. package/docs/hosted-on-fabric.md +4 -3
  134. package/docs/integrations.md +28 -19
  135. package/docs/mcp-clients.md +26 -32
  136. package/docs/n8n.md +8 -8
  137. package/docs/notes/mcp-oauth-model2.md +27 -18
  138. package/docs/openclaw.md +29 -28
  139. package/docs/quickstart.md +5 -0
  140. package/docs/releasing.md +134 -2
  141. package/docs/spoke-bringup.md +14 -11
  142. package/docs/standalone-local.md +2 -2
  143. package/docs/supply-chain-policy.md +28 -10
  144. package/docs/system-requirements.md +1 -1
  145. package/docs/troubleshooting.md +11 -0
  146. package/docs/upgrade.md +189 -63
  147. package/package.json +9 -5
  148. package/schemas/agent.graphql +9 -6
  149. package/schemas/federation.graphql +2 -11
  150. package/schemas/memory.graphql +106 -17
  151. package/schemas/replay.graphql +18 -0
  152. package/templates/launchd/start-flair-with-admin-pass.sh +22 -0
  153. package/dist/resources/federation-nonce-store.js +0 -195
@@ -610,6 +610,16 @@ export function restartSystemdUnits(units, exec = execFileSync) {
610
610
  });
611
611
  }
612
612
  }
613
+ /** Stop the unit itself so Restart= cannot respawn a writer during restore. */
614
+ export function stopSystemdUnits(units, exec = execFileSync) {
615
+ for (const unit of units) {
616
+ exec("systemctl", unit.scope === "user" ? ["--user", "stop", unit.name] : ["stop", unit.name], {
617
+ encoding: "utf-8",
618
+ timeout: 120_000,
619
+ stdio: ["ignore", "pipe", "pipe"],
620
+ });
621
+ }
622
+ }
613
623
  function copyPreserved(fromTree, toTree, names) {
614
624
  for (const name of names) {
615
625
  const src = join(fromTree, name);
@@ -719,25 +729,25 @@ export async function applyPlainTreeUpgrade(plan, hooks = {}) {
719
729
  }
720
730
  }
721
731
  /**
722
- * Put `.upgrade-prev` back at the live tree path. Used by upgrade rollback
723
- * when restart or verify fails after a swap.
724
- *
725
- * Returns whether a previous tree was restored. `false` means there was
726
- * nothing to restore (swap never completed) — the caller must say so.
732
+ * Return restored: false when previousDir is absent. Otherwise attempt to
733
+ * move the live path to .upgrade-failed when it exists, then move previousDir
734
+ * to the live path. A restored: true result also reports whether the live path moved.
727
735
  */
728
736
  export function restorePlainTreePrevious(plan) {
729
737
  const treeDir = canonicalPath(plan.treeDir);
730
738
  const previousDir = plan.previousDir;
731
739
  if (!existsSync(previousDir))
732
- return false;
740
+ return { restored: false };
733
741
  const failedDir = treeSibling(treeDir, UPGRADE_FAILED_SUFFIX);
742
+ let liveTreeSetAside = false;
734
743
  if (existsSync(treeDir)) {
735
744
  if (existsSync(failedDir))
736
745
  rmSync(failedDir, { recursive: true, force: true });
737
746
  renameSync(treeDir, failedDir);
747
+ liveTreeSetAside = true;
738
748
  }
739
749
  renameSync(previousDir, treeDir);
740
- return true;
750
+ return { restored: true, liveTreeSetAside };
741
751
  }
742
752
  /** Drop the displaced previous tree after a successful verify (saves a second copy). */
743
753
  export function discardPlainTreePrevious(previousDir) {
@@ -798,6 +808,6 @@ export function decidePlainTreeRollback(previousDirExists) {
798
808
  return { kind: "restore" };
799
809
  return {
800
810
  kind: "skip",
801
- reason: "no previous tree to restore (the live tree was not swapped)",
811
+ reason: "no previous tree to restore",
802
812
  };
803
813
  }
@@ -0,0 +1,69 @@
1
+ /** Classify the pre-install /Health attempt for the restart-failure decision. */
2
+ const DEFAULT_TIMEOUT_MS = 3000;
3
+ const REFUSED_TOKENS = ["ECONNREFUSED", "ConnectionRefused"];
4
+ function namesRefusal(text) {
5
+ return REFUSED_TOKENS.some((token) => text.includes(token));
6
+ }
7
+ /**
8
+ * Walk cause and array-valued errors, skipping cycles. Every string code must
9
+ * be ECONNREFUSED or ConnectionRefused. Every uncoded failure without nested
10
+ * failures must contain one of them in its text; an uncoded wrapper defers to
11
+ * its nested failures. Any other code or leaf text does not match.
12
+ */
13
+ export function isConnectionRefused(err) {
14
+ let matched = false;
15
+ const seen = new Set();
16
+ const stack = [err];
17
+ while (stack.length > 0) {
18
+ const cur = stack.pop();
19
+ const isObject = !!cur && typeof cur === "object";
20
+ if (isObject) {
21
+ if (seen.has(cur))
22
+ continue;
23
+ seen.add(cur);
24
+ }
25
+ const e = (isObject ? cur : {});
26
+ const nested = [
27
+ ...(e.cause !== undefined ? [e.cause] : []),
28
+ ...(Array.isArray(e.errors) ? e.errors : []),
29
+ ];
30
+ if (typeof e.code === "string") {
31
+ if (!REFUSED_TOKENS.includes(e.code))
32
+ return false;
33
+ matched = true;
34
+ }
35
+ else if (nested.length === 0) {
36
+ if (!namesRefusal(cur instanceof Error ? cur.message : String(cur ?? "")))
37
+ return false;
38
+ matched = true;
39
+ }
40
+ stack.push(...nested);
41
+ }
42
+ return matched;
43
+ }
44
+ function errorText(err) {
45
+ if (err instanceof Error && err.message)
46
+ return err.message;
47
+ return String(err ?? "health probe failed");
48
+ }
49
+ /**
50
+ * Fetch /Health once with a timeout signal. An ok response yields running;
51
+ * a caught error matching isConnectionRefused yields stopped. Other responses
52
+ * and caught errors yield indeterminate.
53
+ */
54
+ export async function classifyUpgradePriorLiveness(baseUrl, opts = {}) {
55
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
56
+ const fetchImpl = opts.fetchImpl ?? fetch;
57
+ const url = `${baseUrl.replace(/\/+$/, "")}/Health`;
58
+ try {
59
+ const res = await fetchImpl(url, { signal: AbortSignal.timeout(timeoutMs) });
60
+ if (res.ok)
61
+ return { kind: "running" };
62
+ return { kind: "indeterminate", reason: `HTTP ${res.status}` };
63
+ }
64
+ catch (err) {
65
+ if (isConnectionRefused(err))
66
+ return { kind: "stopped" };
67
+ return { kind: "indeterminate", reason: errorText(err) };
68
+ }
69
+ }
@@ -0,0 +1,116 @@
1
+ /** Pure decisions and diagnostic formatting for upgrade rollback. */
2
+ const FLAIR_PKG = "@tpsdev-ai/flair";
3
+ /**
4
+ * No swap yields no-target. Otherwise stopped yields keep, regardless of the
5
+ * previous version. Running/indeterminate yields rollback for a nonempty
6
+ * previous version, or no-target without one.
7
+ */
8
+ export function decideAfterRestartFailure(input) {
9
+ if (!input.flairWasSwapped)
10
+ return { kind: "no-target" };
11
+ if (input.priorLiveness === "stopped") {
12
+ return {
13
+ kind: "keep",
14
+ lines: formatNotRunningRestartFailure({
15
+ installedVersion: input.installedVersion,
16
+ startError: input.startError,
17
+ }),
18
+ };
19
+ }
20
+ if (!input.previousVersion)
21
+ return { kind: "no-target" };
22
+ const priorNote = input.priorLiveness === "indeterminate"
23
+ ? " (prior /Health was indeterminate, not confirmed stopped)"
24
+ : "";
25
+ return {
26
+ kind: "rollback",
27
+ toVersion: input.previousVersion,
28
+ reason: `restart failed: ${input.startError}${priorNote}`,
29
+ };
30
+ }
31
+ /** Format the installed-version label, refused-connection note, error and start command. */
32
+ export function formatNotRunningRestartFailure(input) {
33
+ const installed = input.installedVersion
34
+ ? `${FLAIR_PKG}@${input.installedVersion}`
35
+ : FLAIR_PKG;
36
+ return [
37
+ ` ${installed} is installed.`,
38
+ ` Before this upgrade, /Health refused the connection: no listener accepted it. That does not show that no process was running. This start failure is not evidence against the new version — nothing was rolled back.`,
39
+ ` Start error: ${input.startError}`,
40
+ ` Next: flair start`,
41
+ ];
42
+ }
43
+ /** Remove characters in U+0000-U+001F and U+007F-U+009F. */
44
+ export function stripControlChars(value) {
45
+ return value.replace(/[\u0000-\u001F\u007F\u0080-\u009F]/g, "");
46
+ }
47
+ /**
48
+ * Return refuse only for lookup.kind === "deprecated"; otherwise proceed.
49
+ * Remove control characters from the deprecation message before formatting it.
50
+ */
51
+ export function decideDeprecatedRollback(input) {
52
+ if (input.lookup.kind !== "deprecated")
53
+ return { kind: "proceed" };
54
+ const cleaned = stripControlChars(input.lookup.message).trim();
55
+ const message = cleaned || "npm marked this version deprecated";
56
+ const installed = input.installedVersion
57
+ ? `${FLAIR_PKG}@${input.installedVersion}`
58
+ : "the upgraded version";
59
+ return {
60
+ kind: "refuse",
61
+ lines: [
62
+ `❌ Not rolling back to ${FLAIR_PKG}@${input.toVersion}: npm marks that version deprecated.`,
63
+ ` Deprecation: ${message}`,
64
+ ` ${installed} stays installed (not rolled back).`,
65
+ ` Original failure: ${input.reason}`,
66
+ ` Do not reinstall ${FLAIR_PKG}@${input.toVersion}.`,
67
+ ` Check the instance: flair status`,
68
+ ` If you need a different release, check a candidate (\`npm view ${FLAIR_PKG} version\` — not guaranteed non-deprecated) instead of returning to ${input.toVersion}.`,
69
+ ],
70
+ };
71
+ }
72
+ /**
73
+ * Plain-tree with restored: false gets a neutral restart-failure headline;
74
+ * other lanes get KNOWN-BROKEN for this attempt. Recovery text uses the lane,
75
+ * liveTreeSetAside and recoveryVersion. Snapshot text uses snapshotRestored.
76
+ */
77
+ export function formatKnownBrokenRollbackRestart(input) {
78
+ const installed = `${FLAIR_PKG}@${input.toVersion}`;
79
+ const lines = [];
80
+ if (input.lane.kind === "plain-tree" && !input.lane.restored) {
81
+ lines.push(`❌ Restart failed. No previous tree was restored: ${input.error}`, ` The previous tree was not restored (nothing at ${input.lane.previousDir}), so ${installed} is not what this rollback installed.`, ` Check the live-tree path ${input.lane.treeDir}; this rollback did not move it to ${input.lane.failedDir}.`, ` Do not run \`flair start\` expecting ${installed}; that version was not restored.`, ` Recovery (plain-tree): do not npm install -g. There is no previous tree to move back onto ${input.lane.treeDir}.`, ` Inspect the tree at ${input.lane.treeDir}, then run \`flair doctor\`.`);
82
+ }
83
+ else {
84
+ lines.push(`❌❌ KNOWN-BROKEN: rollback restart failed: ${input.error}`, ` ${installed} is installed and known-broken — it did not start on this attempt.`, ` Do not run \`flair start\` on ${installed}; it did not start on this attempt.`);
85
+ if (input.lane.kind === "plain-tree") {
86
+ lines.push(` Recovery (plain-tree): the previous tree was restored to ${input.lane.treeDir}. Do not npm install -g.`);
87
+ if (input.lane.liveTreeSetAside) {
88
+ lines.push(` The live tree was set aside at ${input.lane.failedDir}.`);
89
+ if (input.recoveryVersion && input.recoveryVersion !== input.toVersion) {
90
+ lines.push(` Move ${input.lane.failedDir} back onto ${input.lane.treeDir} to return to ${FLAIR_PKG}@${input.recoveryVersion}.`);
91
+ }
92
+ else {
93
+ lines.push(` Move ${input.lane.failedDir} back onto ${input.lane.treeDir} to return to the version this upgrade had reached.`);
94
+ }
95
+ }
96
+ else {
97
+ lines.push(` No live tree was moved to ${input.lane.failedDir}. Nothing was at ${input.lane.treeDir} to move.`);
98
+ }
99
+ }
100
+ else if (input.recoveryVersion && input.recoveryVersion !== input.toVersion) {
101
+ lines.push(` Recovery (npm-global): ${FLAIR_PKG}@${input.recoveryVersion} already failed restart or verification in this run. Reinstalling it may repeat that failure:`, ` npm install -g ${FLAIR_PKG}@${input.recoveryVersion}`, ` Or choose a different, non-deprecated release: npm view ${FLAIR_PKG} versions`, ` Check its status with npm view ${FLAIR_PKG}@<version> deprecated, then install it: npm install -g ${FLAIR_PKG}@<version>`, ` After either install, check the instance: flair doctor`);
102
+ }
103
+ else {
104
+ lines.push(` Recovery (npm-global): install another release (this installed version did not start on this attempt):`, ` npm view ${FLAIR_PKG} version`, ` Check that candidate (not guaranteed non-deprecated), then: npm install -g ${FLAIR_PKG}@<that-version>`);
105
+ }
106
+ }
107
+ if (input.snapshotRestored) {
108
+ lines.push(` A pre-upgrade data snapshot was restored before this restart failed.`);
109
+ if (input.snapshotPath)
110
+ lines.push(` Snapshot: ${input.snapshotPath}`);
111
+ }
112
+ else {
113
+ lines.push(` No pre-upgrade data snapshot was restored by this rollback.`);
114
+ }
115
+ return lines;
116
+ }
@@ -433,6 +433,17 @@ export function deriveSettledContinuityTags(memories, params) {
433
433
  * Pure orchestration; all I/O goes through injected dependencies.
434
434
  */
435
435
  export async function runNightlyCycle(opts) {
436
+ // Validate stage response envelopes before their existing error handlers.
437
+ const apiCall = opts.apiCall;
438
+ opts = { ...opts, apiCall: async (method, path, body) => {
439
+ const raw = await apiCall(method, path, body);
440
+ const stage = ["/MemoryMaintenance", "/ReflectMemories", "/AutoPromoteCandidates", "/MemoryDedupStats"];
441
+ if (method === "POST" && stage.includes(path) &&
442
+ (!raw || typeof raw !== "object" || Array.isArray(raw))) {
443
+ throw new Error("unexpected " + path + " response shape: expected an object");
444
+ }
445
+ return raw;
446
+ } };
436
447
  const startedAt = opts.nowOverride ?? new Date();
437
448
  const startedMs = startedAt.getTime();
438
449
  const logPath = opts.logPath ?? REM_NIGHTLY_LOG;
@@ -1,7 +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 { localInstanceId } from "./instance-identity.js";
4
+ import { applyOriginatorInstanceId, resolveStoredRow, stampOriginatorOnCreate } from "./originator-instance.js";
5
5
  /**
6
6
  * Agent resource — serves as the Principal table in 1.0.
7
7
  *
@@ -50,14 +50,12 @@ export class Agent extends databases.flair.Agent {
50
50
  }
51
51
  content.createdAt = now;
52
52
  content.updatedAt = now;
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
  /**
@@ -126,11 +124,15 @@ export class Agent extends databases.flair.Agent {
126
124
  // authorizePrincipalWrite), so this normalises an authorized intent; it
127
125
  // never manufactures one.
128
126
  reconcileAdminFields(content);
129
- // Write-time originatorInstanceId stamp — see post() above / Memory.ts's
130
- // stampOriginatorInstanceId doc. No-op if already set.
131
- if (content.originatorInstanceId == null) {
132
- content.originatorInstanceId = await localInstanceId();
133
- }
127
+ // Write-time originatorInstanceId — see post() above /
128
+ // resources/originator-instance.ts. A CREATE stamps the local id; an
129
+ // UPDATE keeps the stored value (a body value never replaces or clears it).
130
+ // The row is resolved by the URL-BOUND target id, never a body `id` (Harper
131
+ // writes to the URL target); a mismatch or a failed read refuses the write.
132
+ const resolvedOriginRow = await resolveStoredRow(this, "Agent", content, () => super.get());
133
+ if (resolvedOriginRow.denial)
134
+ return resolvedOriginRow.denial;
135
+ await applyOriginatorInstanceId(content, resolvedOriginRow.row);
134
136
  const result = await super.put(content);
135
137
  invalidateAdminCache();
136
138
  return result;
@@ -168,6 +170,17 @@ export class Agent extends databases.flair.Agent {
168
170
  // Immutable fields, matching put().
169
171
  delete content.createdAt;
170
172
  delete content.publicKey;
173
+ // flair#1965 r2: an EXISTING row keeps its stored originatorInstanceId
174
+ // (a body value is dropped); a PATCH whose URL target has no stored row is
175
+ // a CREATE when it reaches the table and must stamp the local id (Harper's
176
+ // patch path does not require an existing row; only an administrator's or
177
+ // a trusted internal PATCH gets that far — resources/table-patch-policy.ts
178
+ // refuses the rest). The row is resolved by the URL-BOUND target id, never
179
+ // a body `id`. See resources/originator-instance.ts.
180
+ const resolvedOriginRow = await resolveStoredRow(this, "Agent", content, () => super.get());
181
+ if (resolvedOriginRow.denial)
182
+ return resolvedOriginRow.denial;
183
+ await applyOriginatorInstanceId(content, resolvedOriginRow.row);
171
184
  content.updatedAt = new Date().toISOString();
172
185
  }
173
186
  const result = await super.patch(content, query);
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  /**
2
3
  * POST /AgentSeed
3
4
  *
@@ -23,7 +24,9 @@ import { allowAdmin, invalidateAdminCache } from "./agent-auth.js";
23
24
  import { authorizeSoulWrite, refuseSoulWriteContent, soulProvenance } from "./soul-write-policy.js";
24
25
  import { reconcileAdminFields } from "./agent-admin.js";
25
26
  import { noteMemoryUpsert } from "./bm25-index-service.js";
27
+ import { stripUndeclaredMemoryAttributes, stripServerStampedFields } from "./memory-declared-attributes.js";
26
28
  import { rejectSkillWritePath } from "./skill-write.js";
29
+ import { stampOriginatorOnCreate } from "./originator-instance.js";
27
30
  const DEFAULT_SOUL_KEYS = (agentId, displayName, role, now) => ({
28
31
  name: displayName,
29
32
  role,
@@ -71,7 +74,25 @@ export class AgentSeed extends Resource {
71
74
  return refusal;
72
75
  }
73
76
  // ── Agent record ──────────────────────────────────────────────────────────
74
- const existingAgent = await databases.flair.Agent.get(agentId).catch(() => null);
77
+ // flair#1965 r3: a FAILED existing-Agent lookup must refuse the whole seed.
78
+ // The previous `.catch(() => null)` turned a read ERROR into "no agent", so
79
+ // the raw Agent.put below would take the CREATE branch and overwrite an
80
+ // existing row (with a fresh local originator stamp). A read error is never
81
+ // "no row". See resources/originator-instance.ts for the same rule on the
82
+ // resource write paths.
83
+ let existingAgent;
84
+ try {
85
+ existingAgent = await databases.flair.Agent.get(agentId);
86
+ }
87
+ catch (err) {
88
+ // Constant format string + a structured data object (semgrep
89
+ // javascript.lang.security.audit.unsafe-formatstring).
90
+ console.error("AgentSeed: the existing-agent lookup failed, so the seed was refused rather than overwriting the row as a create", { agentId, err });
91
+ return new Response(JSON.stringify({
92
+ error: "agent_lookup_failed",
93
+ message: "the existing agent record could not be read, so the seed was refused",
94
+ }), { status: 500, headers: { "content-type": "application/json" } });
95
+ }
75
96
  let agent = existingAgent;
76
97
  if (!existingAgent) {
77
98
  // flair#941 — this writes the RAW table, so resources/Agent.ts's post()
@@ -81,6 +102,11 @@ export class AgentSeed extends Resource {
81
102
  // ordinary agent. Admin-only path (allowCreate + the isAdmin re-check
82
103
  // above), so this normalises an authorized intent.
83
104
  agent = reconcileAdminFields({ id: agentId, name, role, publicKey: "pending", createdAt: now, updatedAt: now });
105
+ // flair#1965 r2: this creates an Agent row through the RAW table, so the
106
+ // Agent resource's post() stamp never runs. Stamp the local instance id
107
+ // here (every create path carries it). See
108
+ // resources/originator-instance.ts.
109
+ await stampOriginatorOnCreate(agent);
84
110
  await databases.flair.Agent.put(agent);
85
111
  invalidateAdminCache();
86
112
  }
@@ -94,6 +120,8 @@ export class AgentSeed extends Resource {
94
120
  continue;
95
121
  }
96
122
  const entry = { id, agentId, key, value: String(value), provenance: soulProvenance(auth, source, now), durability: "permanent", createdAt: now, updatedAt: now };
123
+ // flair#1965 r2: raw Soul create — stamp the local instance id.
124
+ await stampOriginatorOnCreate(entry);
97
125
  await databases.flair.Soul.put(entry);
98
126
  soulEntries.push(entry);
99
127
  }
@@ -128,7 +156,9 @@ export class AgentSeed extends Resource {
128
156
  const skillDenial = rejectSkillWritePath(def);
129
157
  if (skillDenial)
130
158
  return skillDenial;
131
- const id = `seed-${agentId}-${i}-${Date.now()}`;
159
+ // A full random UUID in the id: this raw-table write is meant to create,
160
+ // never to replace an existing record.
161
+ const id = `seed-${agentId}-${i}-${Date.now()}-${randomUUID()}`;
132
162
  const record = {
133
163
  id,
134
164
  agentId,
@@ -140,6 +170,13 @@ export class AgentSeed extends Resource {
140
170
  updatedAt: now,
141
171
  archived: false,
142
172
  };
173
+ stripUndeclaredMemoryAttributes(record);
174
+ // A1-iv items 1/3: the seed is a create path — strip server-stamped
175
+ // fields and stamp a fresh incarnation token.
176
+ stripServerStampedFields(record);
177
+ record.instanceToken = randomUUID();
178
+ // flair#1965 r2: raw Memory create — stamp the local instance id.
179
+ await stampOriginatorOnCreate(record);
143
180
  await databases.flair.Memory.put(record);
144
181
  noteMemoryUpsert(record);
145
182
  memories.push(record);
@@ -1,11 +1,12 @@
1
1
  import { createBlob, databases } from "harper";
2
2
  import { resolveAgentAuth } from "./agent-auth.js";
3
3
  import { guardOwnerFieldImmutable } from "./owner-field-guard.js";
4
- import { FORBIDDEN, UNAUTH, makeAuthGate, makeByIdReadGate, makeReadScope, resolveAuthGate, stampAttribution, } from "./record-type-kit.js";
4
+ import { FORBIDDEN, UNAUTH, makeAuthGate, makeByIdReadGate, makeReadScope, makeScopedSearch, resolveAuthGate, stampAttribution, } from "./record-type-kit.js";
5
5
  import { RECORD_TYPES } from "./record-types.js";
6
6
  // Kit parameters read FROM RECORD_TYPES.Asset (single source of truth), same
7
7
  // composition MemoryCandidate.ts uses.
8
8
  const assetReadScope = makeReadScope(RECORD_TYPES.Asset.readScope, RECORD_TYPES.Asset.ownerField);
9
+ const assetScopedSearch = makeScopedSearch(assetReadScope);
9
10
  const assetByIdReadGate = makeByIdReadGate(assetReadScope);
10
11
  const assetAuthGate = makeAuthGate();
11
12
  /**
@@ -58,16 +59,7 @@ export class Asset extends databases.flair.Asset {
58
59
  return gate.response;
59
60
  if (gate.kind === "unfiltered")
60
61
  return super.search(query);
61
- const scope = await assetReadScope(gate.agentId);
62
- const agentCondition = scope.condition;
63
- if (!query?.conditions) {
64
- return super.search({ conditions: [agentCondition], ...(query || {}) });
65
- }
66
- return super.search({
67
- ...query,
68
- conditions: [agentCondition, { conditions: query.conditions, operator: query.operator || "and" }],
69
- operator: "and",
70
- });
62
+ return assetScopedSearch(gate.agentId, query, (q) => super.search(q));
71
63
  }
72
64
  async post(content) {
73
65
  const ctx = this.getContext?.();
@@ -2,7 +2,9 @@ import { databases } from "harper";
2
2
  import { resolveAgentAuth, allowVerified } from "./agent-auth.js";
3
3
  import { guardOwnerFieldImmutable } from "./owner-field-guard.js";
4
4
  import { checkRateLimit, rateLimitResponse } from "./rate-limiter.js";
5
- import { stampAttribution, UNAUTH } from "./record-type-kit.js";
5
+ import { makeReadScope, makeScopedSearch, stampAttribution, UNAUTH } from "./record-type-kit.js";
6
+ const credentialReadScope = makeReadScope("owner-only", "principalId");
7
+ const credentialScopedSearch = makeScopedSearch(credentialReadScope);
6
8
  /**
7
9
  * Credential resource — authentication surfaces for Principals.
8
10
  *
@@ -84,15 +86,7 @@ export class Credential extends databases.flair.Credential {
84
86
  return super.search(query);
85
87
  }
86
88
  // Non-admin agent: scope to own credentials.
87
- const condition = { attribute: "principalId", comparator: "equals", value: auth.agentId };
88
- if (!query?.conditions) {
89
- return super.search({ conditions: [condition], ...(query || {}) });
90
- }
91
- return super.search({
92
- ...query,
93
- conditions: [condition, { conditions: query.conditions, operator: query.operator || "and" }],
94
- operator: "and",
95
- });
89
+ return credentialScopedSearch(auth.agentId, query, (q) => super.search(q));
96
90
  }
97
91
  async get() {
98
92
  const result = await super.get();