@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.
- package/README.md +4 -4
- package/SECURITY.md +4 -1
- package/dist/build-info.json +3 -3
- package/dist/cli.js +1685 -279
- package/dist/commands/doctor.js +162 -4
- package/dist/commands/federation.js +2 -1
- package/dist/commands/hook.js +10 -2
- package/dist/commands/init.js +150 -44
- package/dist/commands/memory.js +24 -2
- package/dist/commands/quality.js +26 -18
- package/dist/commands/service.js +137 -22
- package/dist/commands/status.js +114 -3
- package/dist/commands/upgrade.js +204 -84
- package/dist/doctor-client.js +50 -4
- package/dist/federation/scheduler.js +253 -4
- package/dist/install/clients.js +89 -23
- package/dist/install/global-bin-path.js +26 -6
- package/dist/lib/atomic-write.js +256 -0
- package/dist/lib/daemon-liveness.js +61 -0
- package/dist/lib/doctor-run.js +5 -0
- package/dist/lib/embed-gpu-doctor.js +49 -26
- package/dist/lib/federation-memory-attributes.js +15 -0
- package/dist/lib/init-admin-pass.js +4 -2
- package/dist/lib/init-listener-environ.js +38 -0
- package/dist/lib/init-occupied-listener.js +165 -0
- package/dist/lib/launchd-domain-preflight.js +448 -0
- package/dist/lib/launchd-management.js +176 -6
- package/dist/lib/launchd-repair.js +95 -0
- package/dist/lib/memory-attributes.js +77 -0
- package/dist/lib/node-alias-path.js +95 -0
- package/dist/lib/npm-registry.js +119 -6
- package/dist/lib/owned-pins.js +20 -6
- package/dist/lib/service-repoint-apply.js +267 -0
- package/dist/lib/service-repoint.js +575 -0
- package/dist/lib/toml-string-array.js +104 -0
- package/dist/lib/tree-divergence.js +716 -0
- package/dist/lib/upgrade-plain-tree.js +18 -8
- package/dist/lib/upgrade-prior-liveness.js +69 -0
- package/dist/lib/upgrade-rollback.js +116 -0
- package/dist/rem/runner.js +11 -0
- package/dist/resources/Agent.js +27 -14
- package/dist/resources/AgentSeed.js +35 -1
- package/dist/resources/Federation.js +70 -52
- package/dist/resources/Memory.js +567 -72
- package/dist/resources/MemoryArchive.js +9 -0
- package/dist/resources/MemoryBootstrap.js +4 -0
- package/dist/resources/MemoryFeed.js +204 -3
- package/dist/resources/MemoryHostSource.js +90 -0
- package/dist/resources/MemoryMaintenance.js +121 -32
- package/dist/resources/MemoryReflect.js +4 -1
- package/dist/resources/MemoryReindex.js +7 -4
- package/dist/resources/MemoryUsage.js +53 -3
- package/dist/resources/Presence.js +18 -10
- package/dist/resources/RecordUsage.js +30 -40
- package/dist/resources/Relationship.js +167 -78
- package/dist/resources/SemanticSearch.js +19 -6
- package/dist/resources/Soul.js +31 -19
- package/dist/resources/XAA.js +7 -3
- package/dist/resources/agent-auth.js +16 -10
- package/dist/resources/auth-middleware.js +135 -48
- package/dist/resources/auto-promote-lib.js +4 -4
- package/dist/resources/bm25-index-service.js +246 -32
- package/dist/resources/bm25-status.js +132 -0
- package/dist/resources/ed25519-auth.js +11 -54
- package/dist/resources/embed-gpu.js +262 -47
- package/dist/resources/embeddings-boot.js +52 -17
- package/dist/resources/federation-classify.js +12 -0
- package/dist/resources/federation-crypto.js +65 -19
- package/dist/resources/health.js +57 -14
- package/dist/resources/host-pointer/registry.js +35 -0
- package/dist/resources/host-pointer-adapter.js +15 -0
- package/dist/resources/host-source-visibility.js +167 -0
- package/dist/resources/host-source.js +151 -0
- package/dist/resources/instance-identity.js +3 -2
- package/dist/resources/mcp-handler.js +147 -51
- package/dist/resources/mcp-tools.js +25 -21
- package/dist/resources/memory-consolidate-lib.js +3 -1
- package/dist/resources/memory-declared-attributes.js +103 -0
- package/dist/resources/memory-feed-lib.js +5 -1
- package/dist/resources/memory-host-source.js +163 -0
- package/dist/resources/migrations/synthetic-test-migration.js +4 -1
- package/dist/resources/migrations/visibility-backfill.js +4 -1
- package/dist/resources/originator-instance.js +235 -0
- package/dist/resources/promotion-stamp.js +2 -0
- package/dist/resources/provenance.js +111 -11
- package/dist/resources/record-owner-guard.js +19 -0
- package/dist/resources/record-type-kit.js +9 -12
- package/dist/resources/record-types.js +6 -6
- package/dist/resources/relay-ops.js +28 -3
- package/dist/resources/replay-store.js +289 -0
- package/dist/resources/request-transaction.js +78 -0
- package/dist/resources/search-readiness.js +19 -21
- package/dist/resources/semantic-retrieval-core.js +5 -1
- package/dist/resources/table-patch-policy.js +109 -0
- package/dist/resources/table-patches.js +17 -0
- package/dist/resources/table-post-policy.js +138 -0
- package/dist/resources/table-posts.js +22 -0
- package/dist/resources/table-subscription-policy.js +135 -0
- package/dist/resources/table-subscriptions.js +19 -0
- package/dist/resources/tool-descriptors/index.js +15 -15
- package/dist/resources/trust-block.js +10 -3
- package/dist/resources/usage-recording.js +169 -41
- package/dist/src/lib/memory-attributes.js +77 -0
- package/docs/api-reference.md +79 -15
- package/docs/claude-code.md +132 -0
- package/docs/deployment.md +1 -1
- package/docs/federation.md +1 -1
- package/docs/integrations.md +5 -5
- package/docs/mcp-clients.md +11 -21
- package/docs/notes/mcp-oauth-model2.md +15 -1
- package/docs/quickstart.md +5 -0
- package/docs/releasing.md +134 -2
- package/docs/supply-chain-policy.md +10 -5
- package/docs/troubleshooting.md +11 -0
- package/docs/upgrade.md +187 -61
- package/package.json +9 -5
- package/schemas/agent.graphql +9 -6
- package/schemas/federation.graphql +2 -11
- package/schemas/memory.graphql +106 -17
- package/schemas/replay.graphql +18 -0
- package/templates/launchd/start-flair-with-admin-pass.sh +22 -0
- 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
|
-
*
|
|
723
|
-
*
|
|
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
|
|
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
|
+
}
|
package/dist/rem/runner.js
CHANGED
|
@@ -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;
|
package/dist/resources/Agent.js
CHANGED
|
@@ -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 {
|
|
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
|
|
54
|
-
//
|
|
55
|
-
//
|
|
56
|
-
//
|
|
57
|
-
//
|
|
58
|
-
|
|
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
|
|
130
|
-
//
|
|
131
|
-
|
|
132
|
-
|
|
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);
|
|
@@ -24,7 +24,9 @@ import { allowAdmin, invalidateAdminCache } from "./agent-auth.js";
|
|
|
24
24
|
import { authorizeSoulWrite, refuseSoulWriteContent, soulProvenance } from "./soul-write-policy.js";
|
|
25
25
|
import { reconcileAdminFields } from "./agent-admin.js";
|
|
26
26
|
import { noteMemoryUpsert } from "./bm25-index-service.js";
|
|
27
|
+
import { stripUndeclaredMemoryAttributes, stripServerStampedFields } from "./memory-declared-attributes.js";
|
|
27
28
|
import { rejectSkillWritePath } from "./skill-write.js";
|
|
29
|
+
import { stampOriginatorOnCreate } from "./originator-instance.js";
|
|
28
30
|
const DEFAULT_SOUL_KEYS = (agentId, displayName, role, now) => ({
|
|
29
31
|
name: displayName,
|
|
30
32
|
role,
|
|
@@ -72,7 +74,25 @@ export class AgentSeed extends Resource {
|
|
|
72
74
|
return refusal;
|
|
73
75
|
}
|
|
74
76
|
// ── Agent record ──────────────────────────────────────────────────────────
|
|
75
|
-
|
|
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
|
+
}
|
|
76
96
|
let agent = existingAgent;
|
|
77
97
|
if (!existingAgent) {
|
|
78
98
|
// flair#941 — this writes the RAW table, so resources/Agent.ts's post()
|
|
@@ -82,6 +102,11 @@ export class AgentSeed extends Resource {
|
|
|
82
102
|
// ordinary agent. Admin-only path (allowCreate + the isAdmin re-check
|
|
83
103
|
// above), so this normalises an authorized intent.
|
|
84
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);
|
|
85
110
|
await databases.flair.Agent.put(agent);
|
|
86
111
|
invalidateAdminCache();
|
|
87
112
|
}
|
|
@@ -95,6 +120,8 @@ export class AgentSeed extends Resource {
|
|
|
95
120
|
continue;
|
|
96
121
|
}
|
|
97
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);
|
|
98
125
|
await databases.flair.Soul.put(entry);
|
|
99
126
|
soulEntries.push(entry);
|
|
100
127
|
}
|
|
@@ -143,6 +170,13 @@ export class AgentSeed extends Resource {
|
|
|
143
170
|
updatedAt: now,
|
|
144
171
|
archived: false,
|
|
145
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);
|
|
146
180
|
await databases.flair.Memory.put(record);
|
|
147
181
|
noteMemoryUpsert(record);
|
|
148
182
|
memories.push(record);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Resource, databases, server } from "harper";
|
|
2
|
-
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
3
3
|
import nacl from "tweetnacl";
|
|
4
4
|
import { allowAdmin } from "./agent-auth.js";
|
|
5
5
|
import { canonicalize, signBody, verifyBodySignature, signBodyFresh, verifyBodySignatureFresh, generateNonce, } from "./federation-crypto.js";
|
|
@@ -9,21 +9,29 @@ import { readAllInstanceRows } from "./instance-identity-rows.js";
|
|
|
9
9
|
import { findOrCreateInstance } from "./instance-create-lock.js";
|
|
10
10
|
import { withDetachedTxnAsync } from "./table-helpers.js";
|
|
11
11
|
import { isSkillWrite } from "./skill-write.js";
|
|
12
|
+
import { stripInboundMemoryRow, stripServerStampedFields } from "./memory-declared-attributes.js";
|
|
12
13
|
import { noteWriteStamp } from "./embedding-space-guard.js";
|
|
13
14
|
import { initFederationCleanup } from "./federation-cleanup.js";
|
|
14
|
-
import {
|
|
15
|
+
import { verifyFederationRequestBody } from "./replay-store.js";
|
|
15
16
|
import { classifyRecord, reconstructRecordVerifyBody, checkPrincipalEntitlement, } from "./federation-classify.js";
|
|
16
17
|
export { classifyRecord, reconstructRecordVerifyBody, checkPrincipalEntitlement, recordSignatureVersion, PRINCIPAL_OWNING_TABLES, FEDERATION_TABLE_POLICY, FEDERATION_SYNC_TABLES, } from "./federation-classify.js";
|
|
17
|
-
//
|
|
18
|
-
//
|
|
19
|
-
//
|
|
20
|
-
//
|
|
21
|
-
//
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
18
|
+
// Federation anti-replay: FederationPair and FederationSync both verify through
|
|
19
|
+
// verifyFederationRequestBody (resources/replay-store.ts), which claims each
|
|
20
|
+
// body nonce ONCE in the instance-wide `ReplayNonce` table after the signature
|
|
21
|
+
// has verified (flair#2061). Nonces are globally unique (signBodyFresh generates
|
|
22
|
+
// a 128-bit random nonce per request), so the nonce alone is the key.
|
|
23
|
+
/** The response for a body whose signature, freshness or nonce check refused. */
|
|
24
|
+
function federationVerifyRefusal(reason) {
|
|
25
|
+
if (reason === "replay_store_unavailable") {
|
|
26
|
+
return new Response(JSON.stringify({
|
|
27
|
+
error: "replay_store_unavailable",
|
|
28
|
+
detail: "This instance cannot record request nonces right now, so it refuses signed federation requests. The server log names the cause.",
|
|
29
|
+
}), { status: 503, headers: { "content-type": "application/json" } });
|
|
30
|
+
}
|
|
31
|
+
return new Response(JSON.stringify({ error: `invalid signature — ${reason}` }), {
|
|
32
|
+
status: 401, headers: { "content-type": "application/json" },
|
|
33
|
+
});
|
|
34
|
+
}
|
|
27
35
|
// Re-export for consumers that import from Federation.ts
|
|
28
36
|
export { canonicalize, signBody, verifyBodySignature, signBodyFresh, verifyBodySignatureFresh, generateNonce };
|
|
29
37
|
// ─── Per-record signature enforcement mode (federation-edge-hardening slice 3b) ──
|
|
@@ -64,8 +72,8 @@ export function payloadIdMismatch(record) {
|
|
|
64
72
|
return !record.data || record.data.id !== record.id;
|
|
65
73
|
}
|
|
66
74
|
/**
|
|
67
|
-
*
|
|
68
|
-
*
|
|
75
|
+
* Record-level Last-Write-Wins merge.
|
|
76
|
+
* Incoming fields are applied when the remote record's updatedAt is later.
|
|
69
77
|
* Records with no local counterpart are accepted directly.
|
|
70
78
|
*/
|
|
71
79
|
export function mergeRecord(local, remote) {
|
|
@@ -344,22 +352,16 @@ export class FederationPair extends Resource {
|
|
|
344
352
|
status: 401, headers: { "content-type": "application/json" },
|
|
345
353
|
});
|
|
346
354
|
}
|
|
347
|
-
const verifyResult =
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
});
|
|
351
|
-
if (!verifyResult.ok) {
|
|
352
|
-
return new Response(JSON.stringify({ error: `invalid signature — ${verifyResult.reason}` }), {
|
|
353
|
-
status: 401, headers: { "content-type": "application/json" },
|
|
354
|
-
});
|
|
355
|
-
}
|
|
355
|
+
const verifyResult = await verifyFederationRequestBody(data, publicKey);
|
|
356
|
+
if (!verifyResult.ok)
|
|
357
|
+
return federationVerifyRefusal(verifyResult.reason);
|
|
356
358
|
// ── The identity this response hands the peer, decided BEFORE the pairing
|
|
357
359
|
// token is consumed, BEFORE the peer is read and before ANY peer is written
|
|
358
360
|
// (flair#1883 round 3). ──────────────────────────────────────────────────
|
|
359
361
|
//
|
|
360
362
|
// NOT "before anything": the signature check above has already run and
|
|
361
|
-
// RECORDED ITS NONCE (
|
|
362
|
-
//
|
|
363
|
+
// RECORDED ITS NONCE (verifyFederationRequestBody → the ReplayNonce table,
|
|
364
|
+
// see replay-store.ts). That is deliberate anti-replay state, not a
|
|
363
365
|
// pairing effect — but it is written, and the refusal is precise about what
|
|
364
366
|
// it precedes.
|
|
365
367
|
//
|
|
@@ -508,7 +510,7 @@ export class FederationPair extends Resource {
|
|
|
508
510
|
*/
|
|
509
511
|
export class FederationSync extends Resource {
|
|
510
512
|
// Public endpoint by design: spokes have no Harper credentials. Body signature
|
|
511
|
-
// (with timestamp + nonce, via
|
|
513
|
+
// (with timestamp + nonce, via verifyFederationRequestBody) is the auth boundary.
|
|
512
514
|
// Same pattern as FederationPair.
|
|
513
515
|
allowCreate(_user, _record, _context) {
|
|
514
516
|
return true;
|
|
@@ -535,15 +537,9 @@ export class FederationSync extends Resource {
|
|
|
535
537
|
status: 401, headers: { "content-type": "application/json" },
|
|
536
538
|
});
|
|
537
539
|
}
|
|
538
|
-
const verifyResult =
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
});
|
|
542
|
-
if (!verifyResult.ok) {
|
|
543
|
-
return new Response(JSON.stringify({ error: `invalid signature — ${verifyResult.reason}` }), {
|
|
544
|
-
status: 401, headers: { "content-type": "application/json" },
|
|
545
|
-
});
|
|
546
|
-
}
|
|
540
|
+
const verifyResult = await verifyFederationRequestBody(data, peer.publicKey);
|
|
541
|
+
if (!verifyResult.ok)
|
|
542
|
+
return federationVerifyRefusal(verifyResult.reason);
|
|
547
543
|
const startTime = Date.now();
|
|
548
544
|
let merged = 0;
|
|
549
545
|
let skipped = 0;
|
|
@@ -598,7 +594,7 @@ export class FederationSync extends Resource {
|
|
|
598
594
|
// classifyRecord's "merge" verdict above only proves the record is
|
|
599
595
|
// STRUCTURALLY eligible (known table, self-originated OR the sender
|
|
600
596
|
// is a hub, not stale, not a no-op) — that hub bypass trusts the
|
|
601
|
-
// BATCH-level signature (
|
|
597
|
+
// BATCH-level signature (verifyFederationRequestBody above, verified
|
|
602
598
|
// against the SENDER's pinned key). It does NOT prove the record's
|
|
603
599
|
// *claimed* originator actually produced it — a hub relaying on
|
|
604
600
|
// behalf of many spokes could otherwise forge a record under any
|
|
@@ -656,6 +652,15 @@ export class FederationSync extends Resource {
|
|
|
656
652
|
continue;
|
|
657
653
|
}
|
|
658
654
|
const mergedData = mergeRecord(local, record);
|
|
655
|
+
// ── flair#1940 A1'' item 8: the SAME declared-attribute whitelist the
|
|
656
|
+
// writers apply. A dirty pushed row (a legacy direct-insert, or a raw
|
|
657
|
+
// writer that slipped a pointer field past the writers) must not carry
|
|
658
|
+
// a pointer attribute onto the merged Memory row here either. The named
|
|
659
|
+
// federation bookkeeping fields (_originatorInstanceId, _syncedFrom,
|
|
660
|
+
// _syncedAt, meta, kind) are on the whitelist and survive.
|
|
661
|
+
if (record.table === "Memory") {
|
|
662
|
+
stripInboundMemoryRow(mergedData);
|
|
663
|
+
}
|
|
659
664
|
// ── flair#1542: skills are not federated ──
|
|
660
665
|
// A skill-tagged Memory is a local, gated artifact (SkillScan + forced
|
|
661
666
|
// durability on the write path). Merging a pushed skill-tagged row RAW
|
|
@@ -692,6 +697,33 @@ export class FederationSync extends Resource {
|
|
|
692
697
|
mergedData._originatorInstanceId = decision.originator;
|
|
693
698
|
mergedData._syncedFrom = instanceId;
|
|
694
699
|
mergedData._syncedAt = new Date().toISOString();
|
|
700
|
+
// Re-assert the whitelist AFTER stamping the bookkeeping fields, so a
|
|
701
|
+
// dirty inbound row cannot smuggle a pointer field through this merge
|
|
702
|
+
// even if it also carried one of the allowed keys.
|
|
703
|
+
if (record.table === "Memory") {
|
|
704
|
+
stripInboundMemoryRow(mergedData);
|
|
705
|
+
// A1-iv items 1/3: a federated receive is a LOCAL incarnation — the
|
|
706
|
+
// token is OURS, never the peer's. Drop a peer-supplied server-stamped
|
|
707
|
+
// field, then PRESERVE the local row's token on a merge (a new row
|
|
708
|
+
// gets a locally-generated one).
|
|
709
|
+
//
|
|
710
|
+
// Round 22: `provenance` is NOT a local incarnation stamp — it is the
|
|
711
|
+
// ORIGINATOR's signed stamp and must survive the merge. Capture the
|
|
712
|
+
// value mergeRecord SELECTED (the inbound data for a new row; the
|
|
713
|
+
// merge's LWW choice for an update — NOT always local.provenance)
|
|
714
|
+
// before stripping, then restore it in the same per-record apply.
|
|
715
|
+
// Pinned by test/unit-isolated/federation-merge-provenance.test.ts —
|
|
716
|
+
// RED if this capture/restore is removed.
|
|
717
|
+
const mergedProvenance = mergedData.provenance;
|
|
718
|
+
stripServerStampedFields(mergedData);
|
|
719
|
+
if (typeof mergedProvenance === "string") {
|
|
720
|
+
mergedData.provenance = mergedProvenance;
|
|
721
|
+
}
|
|
722
|
+
mergedData.instanceToken =
|
|
723
|
+
local && typeof local.instanceToken === "string" && local.instanceToken.length > 0
|
|
724
|
+
? local.instanceToken
|
|
725
|
+
: randomUUID();
|
|
726
|
+
}
|
|
695
727
|
await table.put(mergedData);
|
|
696
728
|
// embedding-space-guard slice 1: a federation-merged Memory can carry a
|
|
697
729
|
// FOREIGN embeddingModel (LWW remote-win) — trip the guard's latch so
|
|
@@ -814,21 +846,7 @@ if (typeof setTimeout !== "undefined") {
|
|
|
814
846
|
// Swallow — in test/resource-env the Harper databases may not be bound.
|
|
815
847
|
// In production, initFederationCleanup handles its own error paths.
|
|
816
848
|
});
|
|
817
|
-
// Nonce
|
|
818
|
-
//
|
|
819
|
-
// Runs on the same deferred tick as the cleanup sweep above; there is a
|
|
820
|
-
// narrow window between process start and hydration completing during
|
|
821
|
-
// which a pre-restart nonce isn't yet visible — an accepted tradeoff
|
|
822
|
-
// consistent with this file's existing deferred-init pattern (see the
|
|
823
|
-
// cleanup sweep comment above).
|
|
824
|
-
federationNonceStore.hydrate().catch((err) => {
|
|
825
|
-
// Swallow — in test/resource-env the Harper databases may not be bound.
|
|
826
|
-
});
|
|
827
|
-
// Nonce table eviction sweep — runs on every instance (both hub and
|
|
828
|
-
// spoke can be the receiving/verifying side of a signed federation
|
|
829
|
-
// request), unlike PairingToken cleanup which is hub-only.
|
|
830
|
-
initNonceStoreCleanup().catch((err) => {
|
|
831
|
-
// Swallow — in test/resource-env the Harper databases may not be bound.
|
|
832
|
-
});
|
|
849
|
+
// Nonce eviction is the ReplayNonce table's own expiration (one scan per
|
|
850
|
+
// instance, on Harper's last worker) — no sweep is started here.
|
|
833
851
|
}, 0);
|
|
834
852
|
}
|