@tpsdev-ai/flair 0.59.0 → 0.62.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 +36 -0
- package/config.yaml +12 -1
- package/dist/bridges/builtins/mem0.js +63 -28
- package/dist/bridges/runtime/import-runner.js +12 -0
- package/dist/bridges/runtime/load-plugin.js +42 -13
- package/dist/bridges/runtime/yaml-loader.js +4 -2
- package/dist/build-info.json +3 -3
- package/dist/cli.js +991 -248
- package/dist/commands/agent.js +224 -43
- package/dist/commands/attention.js +4 -3
- package/dist/commands/backup.js +202 -34
- package/dist/commands/bridge.js +172 -119
- package/dist/commands/deploy.js +37 -4
- package/dist/commands/doctor.js +592 -146
- package/dist/commands/export.js +54 -19
- package/dist/commands/federation.js +141 -21
- package/dist/commands/hook.js +155 -2
- package/dist/commands/idp.js +14 -1
- package/dist/commands/import.js +7 -3
- package/dist/commands/init.js +462 -193
- package/dist/commands/integrity.js +388 -0
- package/dist/commands/keys.js +247 -58
- package/dist/commands/mcp.js +97 -35
- package/dist/commands/memory.js +171 -21
- package/dist/commands/migrate-harness-memory.js +3 -2
- package/dist/commands/orgevent.js +46 -37
- package/dist/commands/presence.js +4 -3
- package/dist/commands/principal.js +426 -48
- package/dist/commands/quality.js +10 -1
- package/dist/commands/reembed.js +141 -17
- package/dist/commands/relationship.js +2 -1
- package/dist/commands/rem.js +56 -18
- package/dist/commands/restore.js +101 -61
- package/dist/commands/search.js +6 -4
- package/dist/commands/service.js +151 -38
- package/dist/commands/soul.js +4 -3
- package/dist/commands/status.js +43 -5
- package/dist/commands/test.js +3 -2
- package/dist/commands/upgrade.js +24 -1
- package/dist/commands/workspace.js +6 -3
- package/dist/component-env.js +31 -41
- package/dist/deploy.js +77 -1
- package/dist/doctor-client.js +529 -92
- package/dist/engine-version-contract.js +1 -0
- package/dist/engine-version.js +23 -3
- package/dist/federation-verify.js +4 -3
- package/dist/hook-install.js +670 -6
- package/dist/keystore.js +72 -0
- package/dist/lib/action-recall-runtime.js +328 -0
- package/dist/lib/agent-home-fields.js +132 -0
- package/dist/lib/agent-home.js +427 -0
- package/dist/lib/agent-id-rule.js +46 -0
- package/dist/lib/agent-roster.js +33 -0
- package/dist/lib/auth-resolve.js +49 -16
- package/dist/lib/capture-runtime.js +124 -0
- package/dist/lib/credential-status-rule.js +78 -0
- package/dist/lib/daemon-liveness.js +41 -10
- package/dist/lib/doctor-run.js +75 -37
- package/dist/lib/durability-copy.js +10 -0
- package/dist/lib/embedding-space-doctor.js +75 -0
- package/dist/lib/flair-agent-role.js +4 -0
- package/dist/lib/hub-url.js +12 -0
- package/dist/lib/init-admin-pass.js +88 -12
- package/dist/lib/init-listener-environ.js +1 -2
- package/dist/lib/init-occupied-listener.js +15 -111
- package/dist/lib/init-spawn-attribution.js +73 -0
- package/dist/lib/init-tcp-probe.js +33 -0
- package/dist/lib/instance-identity-row.js +20 -0
- package/dist/lib/launchd-management.js +24 -0
- package/dist/lib/listener-table.js +268 -0
- package/dist/lib/local-delete-instance.js +27 -0
- package/dist/lib/local-instance-pair.js +256 -0
- package/dist/lib/mcp-enable.js +1168 -326
- package/dist/lib/mcp-oauth-env-core.js +133 -0
- package/dist/lib/mcp-oauth-env.js +125 -0
- package/dist/lib/mcp-spec.js +17 -1
- package/dist/lib/memory-attributes.js +2 -0
- package/dist/lib/memory-id-policy.js +46 -0
- package/dist/lib/memory-integrity.js +309 -0
- package/dist/lib/memory-purge-response.js +20 -0
- package/dist/lib/ops-table-count.js +25 -0
- package/dist/lib/owned-pins.js +67 -10
- package/dist/lib/peer-status.js +27 -0
- package/dist/lib/principal-status.js +29 -0
- package/dist/lib/process-start-time.js +76 -12
- package/dist/lib/proto-safe-record.js +42 -0
- package/dist/lib/record-id-path.js +25 -0
- package/dist/lib/reembed-server-support.js +66 -0
- package/dist/lib/restore-verify.js +104 -0
- package/dist/lib/scheduler-platform.js +10 -6
- package/dist/lib/secret-keys.js +25 -0
- package/dist/lib/secrets-push.js +50 -22
- package/dist/lib/skill-seed-pending.js +24 -0
- package/dist/lib/skill-seed.js +365 -0
- package/dist/lib/stop-start-recovery.js +54 -0
- package/dist/lib/using-flair-skill.js +87 -0
- package/dist/mcp-client-assertion.js +112 -4
- package/dist/memory-id-checkpoint.js +326 -0
- package/dist/memory-node-compare.js +207 -0
- package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
- package/dist/rem/restore.js +6 -5
- package/dist/rem/runner.js +103 -44
- package/dist/resources/Agent.js +321 -1
- package/dist/resources/AgentKeyRegister.js +214 -0
- package/dist/resources/AgentKeyRegistration.js +28 -0
- package/dist/resources/AgentSeed.js +10 -4
- package/dist/resources/AutoPromoteCandidates.js +7 -1
- package/dist/resources/Credential.js +177 -2
- package/dist/resources/Federation.js +751 -143
- package/dist/resources/FederationRetry.js +140 -0
- package/dist/resources/InstructionVersion.js +220 -0
- package/dist/resources/Integration.js +300 -25
- package/dist/resources/Memory.js +2113 -604
- package/dist/resources/MemoryArchive.js +75 -42
- package/dist/resources/MemoryBootstrap.js +110 -39
- package/dist/resources/MemoryCandidate.js +21 -1
- package/dist/resources/MemoryDedupStats.js +30 -1
- package/dist/resources/MemoryFeed.js +327 -45
- package/dist/resources/MemoryGrant.js +21 -1
- package/dist/resources/MemoryMaintenance.js +129 -25
- package/dist/resources/MemoryPurge.js +232 -0
- package/dist/resources/MemoryReflect.js +7 -2
- package/dist/resources/MemoryReindex.js +24 -8
- package/dist/resources/Message.js +5 -3
- package/dist/resources/OAuth.js +186 -9
- package/dist/resources/OrgEvent.js +126 -3
- package/dist/resources/Presence.js +144 -49
- package/dist/resources/PromoteMemoryCandidate.js +18 -7
- package/dist/resources/Relationship.js +23 -0
- package/dist/resources/SemanticSearch.js +63 -32
- package/dist/resources/Soul.js +189 -76
- package/dist/resources/TeamDirectory.js +35 -0
- package/dist/resources/WorkspaceState.js +21 -1
- package/dist/resources/XAA.js +181 -63
- package/dist/resources/agent-auth.js +40 -15
- package/dist/resources/auth-middleware.js +400 -161
- package/dist/resources/ed25519-auth.js +1 -1
- package/dist/resources/embedding-space-guard.js +366 -72
- package/dist/resources/engine-version-stamp-boot.js +53 -0
- package/dist/resources/federation-classify.js +72 -0
- package/dist/resources/federation-crypto.js +5 -5
- package/dist/resources/federation-retry-lib.js +135 -0
- package/dist/resources/grant-visibility.js +135 -0
- package/dist/resources/harper-routing.js +83 -0
- package/dist/resources/health.js +120 -18
- package/dist/resources/host-source-citation.js +49 -0
- package/dist/resources/host-source-visibility.js +7 -6
- package/dist/resources/instance-create-lock.js +17 -0
- package/dist/resources/instance-identity.js +23 -0
- package/dist/resources/instruction-version-record.js +343 -0
- package/dist/resources/key-lock.js +3 -3
- package/dist/resources/mcp-handler.js +36 -8
- package/dist/resources/mcp-oauth-env-guard.js +36 -0
- package/dist/resources/mcp-oauth.js +23 -6
- package/dist/resources/mcp-tool-arguments.js +4 -6
- package/dist/resources/mcp-tools.js +128 -19
- package/dist/resources/memory-bootstrap-lib.js +5 -15
- package/dist/resources/memory-declared-attributes.js +3 -1
- package/dist/resources/memory-deletion-history.js +55 -0
- package/dist/resources/memory-durability.js +54 -0
- package/dist/resources/memory-embed-hash.js +88 -0
- package/dist/resources/memory-embedding-value.js +8 -0
- package/dist/resources/memory-host-source.js +27 -5
- package/dist/resources/memory-id-guard.js +75 -0
- package/dist/resources/memory-redaction.js +236 -0
- package/dist/resources/memory-supplied-vector.js +72 -0
- package/dist/resources/memory-write-lock.js +310 -0
- package/dist/resources/memory-write-response.js +139 -0
- package/dist/resources/migrations/data-dir.js +74 -16
- package/dist/resources/migrations/dir-safety.js +1 -1
- package/dist/resources/migrations/embedding-stamp.js +193 -79
- package/dist/resources/migrations/export.js +1 -0
- package/dist/resources/migrations/graph-heal.js +18 -25
- package/dist/resources/migrations/lock.js +7 -1
- package/dist/resources/migrations/snapshot.js +1 -0
- package/dist/resources/migrations/source-fields.js +5 -5
- package/dist/resources/migrations/synthetic-test-migration.js +14 -11
- package/dist/resources/migrations/visibility-backfill.js +29 -29
- package/dist/resources/object-body-guard.js +33 -0
- package/dist/resources/org-event-created-at.js +133 -0
- package/dist/resources/originator-instance.js +39 -7
- package/dist/resources/owner-delete-recheck.js +78 -0
- package/dist/resources/owner-field-guard.js +39 -5
- package/dist/resources/owner-scoped-write-policy.js +212 -0
- package/dist/resources/owner-scoped-writes.js +58 -0
- package/dist/resources/presence-receipt.js +236 -0
- package/dist/resources/promotion-stamp.js +47 -12
- package/dist/resources/record-owner-guard.js +74 -26
- package/dist/resources/record-types.js +1 -1
- package/dist/resources/relay-ops.js +78 -6
- package/dist/resources/replay-store.js +96 -19
- package/dist/resources/request-target.js +136 -0
- package/dist/resources/request-transaction.js +35 -0
- package/dist/resources/search-readiness.js +4 -1
- package/dist/resources/seed-ids.js +9 -0
- package/dist/resources/seed-reservation.js +117 -0
- package/dist/resources/semantic-retrieval-core.js +20 -9
- package/dist/resources/skill-manifest.js +20 -11
- package/dist/resources/skill-subject.js +53 -0
- package/dist/resources/skill-version-write.js +432 -0
- package/dist/resources/skill-write-fault.js +17 -0
- package/dist/resources/skill-write-policy.js +67 -0
- package/dist/resources/skill-write.js +67 -7
- package/dist/resources/table-helpers.js +10 -7
- package/dist/resources/team-directory.js +248 -0
- package/dist/resources/tool-descriptors/index.js +69 -8
- package/dist/resources/txn-pause-point.js +118 -0
- package/dist/resources/usage-recording.js +171 -63
- package/dist/resources/write-back.js +218 -0
- package/dist/src/engine-version-contract.js +1 -0
- package/dist/src/keystore.js +72 -0
- package/dist/src/lib/agent-home-fields.js +132 -0
- package/dist/src/lib/agent-id-rule.js +46 -0
- package/dist/src/lib/agent-key-register.js +80 -0
- package/dist/src/lib/atomic-write.js +256 -0
- package/dist/src/lib/credential-status-rule.js +78 -0
- package/dist/src/lib/expired-by-agent.js +37 -0
- package/dist/src/lib/flair-agent-role.js +4 -0
- package/dist/src/lib/idp-mapping-rule.js +81 -0
- package/dist/src/lib/instance-identity-row.js +20 -0
- package/dist/src/lib/mcp-oauth-env-core.js +133 -0
- package/dist/src/lib/memory-attributes.js +2 -0
- package/dist/src/lib/memory-id-policy.js +46 -0
- package/dist/src/lib/principal-status.js +29 -0
- package/dist/src/lib/proto-safe-record.js +42 -0
- package/dist/src/lib/reembed-server-support.js +66 -0
- package/dist/src/lib/scheduler-platform.js +10 -6
- package/dist/src/lib/systemd-agent-id.js +38 -0
- package/docs/access-control.md +146 -45
- package/docs/api-reference.md +46 -11
- package/docs/auth.md +6 -12
- package/docs/bridges.md +11 -0
- package/docs/claude-code.md +34 -4
- package/docs/deploying-on-fabric.md +70 -0
- package/docs/deployment.md +2 -0
- package/docs/embedding-in-a-harper-app.md +1 -1
- package/docs/federation.md +33 -2
- package/docs/hosted-on-fabric.md +43 -36
- package/docs/integrations.md +5 -5
- package/docs/mcp-clients.md +5 -2
- package/docs/n8n.md +17 -11
- package/docs/notes/mcp-agent-auth-consumer.md +12 -4
- package/docs/notes/mcp-oauth-model2.md +34 -5
- package/docs/quickstart-fabric.md +2 -2
- package/docs/quickstart.md +9 -1
- package/docs/releasing.md +12 -6
- package/docs/rem.md +8 -0
- package/docs/secrets-and-keys.md +19 -2
- package/docs/standalone-local.md +1 -0
- package/docs/supply-chain-policy.md +13 -3
- package/docs/upgrade.md +32 -6
- package/package.json +10 -5
- package/schemas/agent-key-registration.graphql +22 -0
- package/schemas/agent.graphql +3 -0
- package/schemas/federation.graphql +38 -1
- package/schemas/memory.graphql +84 -5
- package/schemas/oauth.graphql +19 -0
- package/schemas/schema.graphql +2 -0
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Guards permission-marked writes on owner-scoped tables.
|
|
3
|
+
*
|
|
4
|
+
* ── The rule ────────────────────────────────────────────────────────────────
|
|
5
|
+
* For a verified non-admin agent, an HTTP write to a table listed in
|
|
6
|
+
* resources/record-owner-guard.ts's OWNER_FIELDS, through a resource class that
|
|
7
|
+
* extends that table:
|
|
8
|
+
* - addressed to one record (POST/PUT/PATCH/DELETE to `/<Table>/<id>`) is
|
|
9
|
+
* checked for a differing string or number body `id` on POST/PUT/PATCH
|
|
10
|
+
* (`writeIdNotAddressedRefusal`, 403), then for a stored owner other than
|
|
11
|
+
* the caller (`ownerMutationRefusal`, 403), if reached. The middleware can
|
|
12
|
+
* return the owner refusal first on a plain addressed URL;
|
|
13
|
+
* - addressed to no single record (the table's collection, with or without a
|
|
14
|
+
* query): if reached, the table guard returns `collectionWriteRefusal` (403)
|
|
15
|
+
* on PUT, PATCH and DELETE; existing DELETE middleware may refuse earlier.
|
|
16
|
+
* A POST to a collection is NOT decided here: it is delegated to the
|
|
17
|
+
* resource's own POST handling (its create and attribution rules;
|
|
18
|
+
* OrgEvent's post() can also update a caller-owned record its body names).
|
|
19
|
+
* A write refused by this guard leaves its target row unchanged
|
|
20
|
+
* (authentication has already recorded the request's replay nonce), and one
|
|
21
|
+
* such refusal fails the whole request. When the guard's own stored-record
|
|
22
|
+
* read for an addressed owner check fails, the request is refused with
|
|
23
|
+
* `owner_check_unavailable`.
|
|
24
|
+
*
|
|
25
|
+
* This guard exempts administrators, trusted internal calls and anonymous
|
|
26
|
+
* callers. Write targets with a non-null, non-false `checkPermission` take
|
|
27
|
+
* the asynchronous guard path, including permission-marked internal calls.
|
|
28
|
+
*
|
|
29
|
+
* ── The seam ────────────────────────────────────────────────────────────────
|
|
30
|
+
* For an addressed REST call, Harper supplies the target resolved to a record
|
|
31
|
+
* id and the request as context to static `getResource(target, context, options)`.
|
|
32
|
+
* A collection target addresses no single record and carries `isCollection: true`.
|
|
33
|
+
* Internal or MQTT calls supply a context, not an HTTP request.
|
|
34
|
+
* `guardOwnerScopedWrites` gives every owner-scoped table class its own static
|
|
35
|
+
* `getResource` that applies the rule there and then delegates to the inherited
|
|
36
|
+
* one. A resource class that extends the flair table inherits it; a custom
|
|
37
|
+
* resource that extends `Resource` rather than the table (for example
|
|
38
|
+
* AgentReadPosition) is not on this path and enforces its own rule. The table
|
|
39
|
+
* list is OWNER_FIELDS; test/unit/record-owner-guard-coverage.test.ts fails
|
|
40
|
+
* when a table declares an owner-shaped column and is neither added to that map
|
|
41
|
+
* nor exempted with a stated reason, so a new owner-scoped table has to be
|
|
42
|
+
* enrolled there. resources/owner-scoped-writes.ts installs the guard at load
|
|
43
|
+
* and logs any OWNER_FIELDS table it could not guard.
|
|
44
|
+
*
|
|
45
|
+
* This module imports only helpers from resources/record-owner-guard.ts, which
|
|
46
|
+
* has no Harper or authentication-module dependency, so it is unit-tested
|
|
47
|
+
* directly (test/unit/owner-scoped-write-policy.test.ts);
|
|
48
|
+
* the dependencies it needs are passed in by resources/owner-scoped-writes.ts.
|
|
49
|
+
* test/integration/owner-scoped-writes.test.ts checks the rule on a real Harper.
|
|
50
|
+
*
|
|
51
|
+
*/
|
|
52
|
+
import { collectionWriteRefusal, isForbiddenOwnerMutation, ownerMutationRefusal } from "./record-owner-guard.js";
|
|
53
|
+
/** Marks a table class whose writes have been guarded. */
|
|
54
|
+
export const OWNER_SCOPED_WRITE_GUARD = Symbol.for("flair.ownerScopedWriteGuard");
|
|
55
|
+
/** The Harper resource methods an HTTP request reaches to write a record. */
|
|
56
|
+
export const GUARDED_WRITE_METHODS = Object.freeze(["put", "patch", "delete", "post"]);
|
|
57
|
+
/** Methods refused on a collection target, where the request does not resolve to one addressed row. */
|
|
58
|
+
const STORED_RECORD_METHODS = new Set(["put", "patch", "delete"]);
|
|
59
|
+
/** Methods whose string or number body `id` must name the addressed record. */
|
|
60
|
+
const BODY_ID_METHODS = new Set(["put", "patch", "post"]);
|
|
61
|
+
/**
|
|
62
|
+
* Whether `target` carries a non-null, non-false permission marker.
|
|
63
|
+
*/
|
|
64
|
+
export function isRequestEntryTarget(target) {
|
|
65
|
+
if (target == null || typeof target !== "object")
|
|
66
|
+
return false;
|
|
67
|
+
const permission = target.checkPermission;
|
|
68
|
+
return permission != null && permission !== false;
|
|
69
|
+
}
|
|
70
|
+
/** Whether a resolved target addresses no single record: a collection, or no id at all. */
|
|
71
|
+
export function addressesNoSingleRecord(target) {
|
|
72
|
+
return target.isCollection === true || target.id == null;
|
|
73
|
+
}
|
|
74
|
+
/** The refusal when the caller of a guarded write cannot be resolved. */
|
|
75
|
+
export function unverifiedWriteCallerRefusal(table) {
|
|
76
|
+
return Object.assign(new Error(`the caller of this ${table} write could not be verified, so it was refused; retry`), { statusCode: 500 });
|
|
77
|
+
}
|
|
78
|
+
/** A non-admin addressed write whose body could not be read: refused, never admitted. */
|
|
79
|
+
export function writeBodyUnreadableRefusal(table) {
|
|
80
|
+
return new Response(JSON.stringify({
|
|
81
|
+
error: "write_body_unreadable",
|
|
82
|
+
message: `the ${table} write's body could not be read, so the record it names could not be checked`,
|
|
83
|
+
}), { status: 400, headers: { "Content-Type": "application/json" } });
|
|
84
|
+
}
|
|
85
|
+
/** The named refusal for an addressed write whose string or number body `id` names a record other than the one it addresses. */
|
|
86
|
+
export function writeIdNotAddressedRefusal() {
|
|
87
|
+
return new Response(JSON.stringify({
|
|
88
|
+
error: "write_id_not_addressed",
|
|
89
|
+
message: "a write may name only the record it addresses",
|
|
90
|
+
}), { status: 403, headers: { "Content-Type": "application/json" } });
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Whether a parsed request `body` carries a string or number body `id` that
|
|
94
|
+
* names a record other than `targetId` (the addressed record).
|
|
95
|
+
*/
|
|
96
|
+
export function bodyNamesDifferentRecord(targetId, body) {
|
|
97
|
+
if (targetId == null)
|
|
98
|
+
return false;
|
|
99
|
+
if (body == null || typeof body !== "object" || Array.isArray(body))
|
|
100
|
+
return false;
|
|
101
|
+
const bodyId = body.id;
|
|
102
|
+
if (bodyId == null)
|
|
103
|
+
return false;
|
|
104
|
+
if (typeof bodyId !== "string" && typeof bodyId !== "number")
|
|
105
|
+
return false;
|
|
106
|
+
return String(bodyId) !== String(targetId);
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Decide one entry write. Resolves when the write may proceed; rejects with the
|
|
110
|
+
* refusal (a Response, which Harper's REST layer returns as is, or a named
|
|
111
|
+
* error) when it may not.
|
|
112
|
+
*
|
|
113
|
+
* In order: resolve the caller (an unresolvable one is refused); leave an
|
|
114
|
+
* administrator, a trusted internal call and an anonymous caller to their
|
|
115
|
+
* existing handling; refuse a collection PUT/PATCH/DELETE; refuse an addressed
|
|
116
|
+
* POST/PUT/PATCH whose string or number body `id` names a record other than the
|
|
117
|
+
* addressed one; then refuse a write to a stored record owned by another
|
|
118
|
+
* principal. Each refusal by this guard leaves the target row unchanged.
|
|
119
|
+
*/
|
|
120
|
+
export async function admitOwnerScopedWrite(table, ownerField, method, target, context, deps) {
|
|
121
|
+
let caller;
|
|
122
|
+
try {
|
|
123
|
+
caller = await deps.resolveAuth(context);
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
throw unverifiedWriteCallerRefusal(table);
|
|
127
|
+
}
|
|
128
|
+
if (caller.kind !== "agent" || caller.isAdmin === true)
|
|
129
|
+
return;
|
|
130
|
+
if (addressesNoSingleRecord(target)) {
|
|
131
|
+
if (STORED_RECORD_METHODS.has(method))
|
|
132
|
+
throw collectionWriteRefusal(table);
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
// Addressed write: a string or number body `id` must name the addressed record.
|
|
136
|
+
if (BODY_ID_METHODS.has(method)) {
|
|
137
|
+
let body;
|
|
138
|
+
try {
|
|
139
|
+
body = await deps.readBody(context);
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
// A body that cannot be read cannot be checked: refuse rather than admit.
|
|
143
|
+
throw writeBodyUnreadableRefusal(table);
|
|
144
|
+
}
|
|
145
|
+
if (bodyNamesDifferentRecord(target.id, body))
|
|
146
|
+
throw writeIdNotAddressedRefusal();
|
|
147
|
+
}
|
|
148
|
+
let stored;
|
|
149
|
+
try {
|
|
150
|
+
stored = await deps.readStored(table, target.id);
|
|
151
|
+
}
|
|
152
|
+
catch (err) {
|
|
153
|
+
throw deps.unreadable(err);
|
|
154
|
+
}
|
|
155
|
+
if (isForbiddenOwnerMutation(stored, ownerField, caller.agentId)) {
|
|
156
|
+
throw ownerMutationRefusal(table);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Give every table class named in `ownerFields` and present in `tables` its own
|
|
161
|
+
* static `getResource` that admits a permission-marked write through
|
|
162
|
+
* `admitOwnerScopedWrite` before delegating to the inherited `getResource`.
|
|
163
|
+
* Reads and writes without that marker delegate synchronously. Idempotent.
|
|
164
|
+
* Returns the names of the guarded tables.
|
|
165
|
+
*/
|
|
166
|
+
export function guardOwnerScopedWrites(tables, ownerFields, deps) {
|
|
167
|
+
const guarded = [];
|
|
168
|
+
for (const [name, ownerField] of Object.entries(ownerFields)) {
|
|
169
|
+
const table = tables?.[name];
|
|
170
|
+
if (typeof table !== "function")
|
|
171
|
+
continue;
|
|
172
|
+
if (Object.prototype.hasOwnProperty.call(table, OWNER_SCOPED_WRITE_GUARD)) {
|
|
173
|
+
guarded.push(name);
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
const inherited = table.getResource;
|
|
177
|
+
if (typeof inherited !== "function")
|
|
178
|
+
continue;
|
|
179
|
+
Object.defineProperty(table, "getResource", {
|
|
180
|
+
configurable: true,
|
|
181
|
+
writable: true,
|
|
182
|
+
enumerable: false,
|
|
183
|
+
value: function getResource(target, context, options) {
|
|
184
|
+
const method = options?.method;
|
|
185
|
+
if (typeof method !== "string" || !GUARDED_WRITE_METHODS.includes(method) || !isRequestEntryTarget(target)) {
|
|
186
|
+
return inherited.call(this, target, context, options);
|
|
187
|
+
}
|
|
188
|
+
return admitOwnerScopedWrite(name, ownerField, method, target, context, deps)
|
|
189
|
+
.then(() => inherited.call(this, target, context, options));
|
|
190
|
+
},
|
|
191
|
+
});
|
|
192
|
+
Object.defineProperty(table, OWNER_SCOPED_WRITE_GUARD, { value: true });
|
|
193
|
+
guarded.push(name);
|
|
194
|
+
}
|
|
195
|
+
return guarded;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* What an installation left unguarded, given the registry, the owner-scoped
|
|
199
|
+
* tables and the names `guardOwnerScopedWrites` returned. An empty or missing
|
|
200
|
+
* registry yields one generic gap. Otherwise the result names every table in
|
|
201
|
+
* `ownerFields` that was not guarded, including one absent from the registry
|
|
202
|
+
* (it has no table class to guard), so a renamed table cannot drop out
|
|
203
|
+
* silently; it is empty only when every table in `ownerFields` was guarded.
|
|
204
|
+
*/
|
|
205
|
+
export function ownerScopedWriteGuardGaps(tables, ownerFields, guarded) {
|
|
206
|
+
if (Object.keys(tables ?? {}).length === 0)
|
|
207
|
+
return ["the flair table registry is missing or empty"];
|
|
208
|
+
const done = new Set(guarded);
|
|
209
|
+
return Object.keys(ownerFields)
|
|
210
|
+
.filter((name) => !done.has(name))
|
|
211
|
+
.map((name) => `${name} is not a table class with a getResource() to guard`);
|
|
212
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Installs the owner-scoped write guard (resources/owner-scoped-write-policy.ts)
|
|
3
|
+
* on every table class named in resources/record-owner-guard.ts's OWNER_FIELDS
|
|
4
|
+
* when the component loads. For a non-admin HTTP request to a resource class
|
|
5
|
+
* that extends one of those tables: an addressed write (POST/PUT/PATCH/DELETE
|
|
6
|
+
* to `/<Table>/<id>`) checks a string or number body `id` on POST/PUT/PATCH before the
|
|
7
|
+
* stored owner, if reached; middleware can return the owner refusal first.
|
|
8
|
+
* For collection PUT/PATCH/DELETE, if reached, the table guard returns the
|
|
9
|
+
* collection refusal; existing DELETE middleware may refuse earlier. A POST to a collection is delegated
|
|
10
|
+
* to each resource's own POST handling. An incomplete installation (a missing or empty
|
|
11
|
+
* registry, or an owner-scoped table that could not be guarded) is logged as an
|
|
12
|
+
* error at load.
|
|
13
|
+
*
|
|
14
|
+
* The stored record is read with its own empty context, so the read runs in a
|
|
15
|
+
* fresh transaction as a trusted internal read of committed state, the same
|
|
16
|
+
* read resources/auth-middleware.ts's single-record owner check makes.
|
|
17
|
+
* `readBody` reads `data` from the entry call's context.
|
|
18
|
+
*
|
|
19
|
+
* This module deliberately exports nothing: Harper registers exported values of
|
|
20
|
+
* a resource module as routes.
|
|
21
|
+
*
|
|
22
|
+
* ─── No static auth import; agent-auth.js loads on the first guarded write ──
|
|
23
|
+
* Harper links a component's resource modules concurrently while it starts.
|
|
24
|
+
* This module's static imports are `harper` and two modules with no
|
|
25
|
+
* authentication-module dependency (record-owner-guard.ts, which also supplies
|
|
26
|
+
* the `owner_check_unavailable` refusal, and owner-scoped-write-policy.ts), so
|
|
27
|
+
* loading it adds no link of the authentication module graph to that startup
|
|
28
|
+
* phase; a static import of agent-auth.js from here stopped Harper from
|
|
29
|
+
* starting under Bun (test/integration/init-persisted-admin-harper5.test.ts).
|
|
30
|
+
*
|
|
31
|
+
* agent-auth.js is imported once, when the first guarded write needs its
|
|
32
|
+
* caller resolved, by which time the component has finished loading. The guard
|
|
33
|
+
* itself is installed synchronously here either way. If that import fails, the
|
|
34
|
+
* guard refuses the write as a caller that could not be verified (its named
|
|
35
|
+
* 500 refusal), and the cached import is cleared so the next write retries.
|
|
36
|
+
*/
|
|
37
|
+
import { databases } from "harper";
|
|
38
|
+
import { OWNER_FIELDS, ownerCheckUnavailable } from "./record-owner-guard.js";
|
|
39
|
+
import { guardOwnerScopedWrites, ownerScopedWriteGuardGaps } from "./owner-scoped-write-policy.js";
|
|
40
|
+
let agentAuthModule;
|
|
41
|
+
function agentAuth() {
|
|
42
|
+
agentAuthModule ??= import("./agent-auth.js").catch((err) => {
|
|
43
|
+
agentAuthModule = undefined;
|
|
44
|
+
throw err;
|
|
45
|
+
});
|
|
46
|
+
return agentAuthModule;
|
|
47
|
+
}
|
|
48
|
+
const registry = databases.flair;
|
|
49
|
+
const guarded = guardOwnerScopedWrites(registry, OWNER_FIELDS, {
|
|
50
|
+
resolveAuth: async (context) => (await agentAuth()).resolveAgentAuth(context),
|
|
51
|
+
readStored: (table, id) => registry[table].get(id, {}),
|
|
52
|
+
unreadable: ownerCheckUnavailable,
|
|
53
|
+
readBody: (context) => context?.data,
|
|
54
|
+
});
|
|
55
|
+
const gaps = ownerScopedWriteGuardGaps(registry, OWNER_FIELDS, guarded);
|
|
56
|
+
if (gaps.length > 0) {
|
|
57
|
+
console.error(`[flair] the owner-scoped write guard is incomplete: ${gaps.join("; ")}`);
|
|
58
|
+
}
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* presence-receipt.ts — the federation receive-side rules for Presence, and the
|
|
3
|
+
* local-write home guard (flair#2578 slice 1: office-wide Presence).
|
|
4
|
+
*
|
|
5
|
+
* PURE: no Harper import, so every rule here is unit-testable without a live
|
|
6
|
+
* Harper. The callers read the local Agent row and the stored Presence row and
|
|
7
|
+
* pass them in; resources/Federation.ts runs the receive path, and
|
|
8
|
+
* resources/Presence.ts runs the local write paths (POST, PUT, PATCH).
|
|
9
|
+
*
|
|
10
|
+
* This module also owns the Presence activity vocabulary and the currentTask
|
|
11
|
+
* cap, because the receipt validator accepts the same activity vocabulary and
|
|
12
|
+
* currentTask cap a POST heartbeat applies — one definition, so the two cannot
|
|
13
|
+
* drift.
|
|
14
|
+
*
|
|
15
|
+
* Receive-side support for planned spoke-to-hub Presence replication; the sender
|
|
16
|
+
* follows in a later slice. It ships
|
|
17
|
+
* behind ONE default-off receive flag; with the flag off a Presence record that
|
|
18
|
+
* reaches the receive branch is skipped by its own name
|
|
19
|
+
* (`presence_receive_disabled`), not `unknown_table`.
|
|
20
|
+
*
|
|
21
|
+
* The sender contract (a later slice): a Presence record's wire `id` and its
|
|
22
|
+
* `data.id` will be the row's `agentId` (this table's primary key),
|
|
23
|
+
* `data.agentId` will carry that same value, the record's
|
|
24
|
+
* `originatorInstanceId` will be the sending instance, and only rows whose
|
|
25
|
+
* `originatorInstanceId` is the sender will be sent.
|
|
26
|
+
*/
|
|
27
|
+
// ─── Flag ────────────────────────────────────────────────────────────────────
|
|
28
|
+
/** The receive flag (default OFF). */
|
|
29
|
+
export const PRESENCE_RECEIVE_FLAG_ENV = "FLAIR_FEDERATION_PRESENCE_RECEIVE";
|
|
30
|
+
/** Truthy: `1` / `true` / `yes` / `on`. Anything else — unset, empty, `false`,
|
|
31
|
+
* `0`, garbage — is OFF, so the default is no Presence replication. */
|
|
32
|
+
export function presenceReceiveEnabled(env = process.env) {
|
|
33
|
+
const raw = (env[PRESENCE_RECEIVE_FLAG_ENV] ?? "").trim().toLowerCase();
|
|
34
|
+
return raw === "1" || raw === "true" || raw === "yes" || raw === "on";
|
|
35
|
+
}
|
|
36
|
+
// ─── Vocabulary + caps (shared with resources/Presence.ts) ────────────────────
|
|
37
|
+
/** The local activity vocabulary; a replicated row's `activity` must be a
|
|
38
|
+
* member. Same set a POST heartbeat accepts (resources/Presence.ts). */
|
|
39
|
+
export const PRESENCE_ACTIVITIES = new Set([
|
|
40
|
+
"coding",
|
|
41
|
+
"reviewing",
|
|
42
|
+
"planning",
|
|
43
|
+
"debugging",
|
|
44
|
+
"idle",
|
|
45
|
+
]);
|
|
46
|
+
/** The currentTask cap; a replicated `currentTask` goes through the same cap as
|
|
47
|
+
* a POST heartbeat. */
|
|
48
|
+
export const PRESENCE_CURRENT_TASK_MAX_LENGTH = 200;
|
|
49
|
+
/** Trim + cap a currentTask, or null for absent/empty — the POST heartbeat's
|
|
50
|
+
* rule, applied to a replicated row. */
|
|
51
|
+
export function sanitizePresenceCurrentTask(task) {
|
|
52
|
+
if (typeof task !== "string")
|
|
53
|
+
return null;
|
|
54
|
+
const trimmed = task.trim();
|
|
55
|
+
if (trimmed.length === 0)
|
|
56
|
+
return null;
|
|
57
|
+
return trimmed.slice(0, PRESENCE_CURRENT_TASK_MAX_LENGTH);
|
|
58
|
+
}
|
|
59
|
+
// ─── Bounds ──────────────────────────────────────────────────────────────────
|
|
60
|
+
/** The allowance the receiver grants an inbound heartbeat stamp ahead of its
|
|
61
|
+
* own clock — the same 5 minutes classifyRecord applies to a wire `updatedAt`. */
|
|
62
|
+
export const PRESENCE_FUTURE_ALLOWANCE_MS = 5 * 60 * 1000;
|
|
63
|
+
/** The cap on `flairVersion` / `harperVersion`; a longer value is dropped. */
|
|
64
|
+
export const PRESENCE_VERSION_MAX_LENGTH = 64;
|
|
65
|
+
function finiteNumber(value) {
|
|
66
|
+
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
67
|
+
}
|
|
68
|
+
/** A stored Presence stamp read back from Harper: the schema column is BigInt,
|
|
69
|
+
* so a row read from the table may hand back a bigint (or a numeric string),
|
|
70
|
+
* not a JS number. Normalize it to a finite number, or null. NOT used on
|
|
71
|
+
* inbound wire data — that is a JSON number and is checked strictly. */
|
|
72
|
+
function presenceMs(value) {
|
|
73
|
+
if (typeof value === "number")
|
|
74
|
+
return Number.isFinite(value) ? value : null;
|
|
75
|
+
if (typeof value === "bigint") {
|
|
76
|
+
const n = Number(value);
|
|
77
|
+
return Number.isFinite(n) ? n : null;
|
|
78
|
+
}
|
|
79
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
80
|
+
const n = Number(value);
|
|
81
|
+
return Number.isFinite(n) ? n : null;
|
|
82
|
+
}
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
function presenceVersion(value) {
|
|
86
|
+
return typeof value === "string" && value.length <= PRESENCE_VERSION_MAX_LENGTH ? value : null;
|
|
87
|
+
}
|
|
88
|
+
// ─── P1: home binding on receipt ─────────────────────────────────────────────
|
|
89
|
+
/**
|
|
90
|
+
* Is the local Agent row for a replicated Presence record homed on the
|
|
91
|
+
* batch-verified SENDER? The sender is the only home authority — never the wire
|
|
92
|
+
* `originatorInstanceId` (which a sender self-asserts).
|
|
93
|
+
*
|
|
94
|
+
* - the Agent row is absent locally → `presence_agent_not_replicated`
|
|
95
|
+
* (retryable: it may replicate later);
|
|
96
|
+
* - the Agent row's home is another instance, or null →
|
|
97
|
+
* `presence_agent_homed_elsewhere` (non-retryable);
|
|
98
|
+
* - the home is the sender → null (accept).
|
|
99
|
+
*/
|
|
100
|
+
export function presenceHomeBindingReason(agentRow, senderInstanceId) {
|
|
101
|
+
if (agentRow == null)
|
|
102
|
+
return "presence_agent_not_replicated";
|
|
103
|
+
const home = agentRow.originatorInstanceId;
|
|
104
|
+
if (typeof home !== "string" || home.length === 0 || home !== senderInstanceId) {
|
|
105
|
+
return "presence_agent_homed_elsewhere";
|
|
106
|
+
}
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
// ─── P5: receipt validation ──────────────────────────────────────────────────
|
|
110
|
+
/**
|
|
111
|
+
* Strip an inbound Presence row to the declared Presence fields and validate
|
|
112
|
+
* it. Returns the stripped row, or a named skip reason. A row that fails is
|
|
113
|
+
* never stored, so one bad peer row cannot reach a reader.
|
|
114
|
+
*
|
|
115
|
+
* `recordId` is the wire record's id, which for this table IS the primary key
|
|
116
|
+
* (`agentId`); the inbound `data.agentId` must agree with it, so the row that
|
|
117
|
+
* is validated is the row that is written. The stored `originatorInstanceId` is
|
|
118
|
+
* `senderInstanceId`, whatever the record carries.
|
|
119
|
+
*/
|
|
120
|
+
export function validatePresenceReceipt(recordId, data, receivedAt, senderInstanceId) {
|
|
121
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) {
|
|
122
|
+
return { ok: false, reason: "presence_invalid_shape" };
|
|
123
|
+
}
|
|
124
|
+
const d = data;
|
|
125
|
+
const agentId = typeof d.agentId === "string" ? d.agentId : null;
|
|
126
|
+
if (!agentId || agentId !== recordId)
|
|
127
|
+
return { ok: false, reason: "presence_invalid_shape" };
|
|
128
|
+
const lastHeartbeatAt = finiteNumber(d.lastHeartbeatAt);
|
|
129
|
+
if (lastHeartbeatAt == null)
|
|
130
|
+
return { ok: false, reason: "presence_invalid_shape" };
|
|
131
|
+
if (lastHeartbeatAt > receivedAt + PRESENCE_FUTURE_ALLOWANCE_MS) {
|
|
132
|
+
return { ok: false, reason: "presence_future_timestamp" };
|
|
133
|
+
}
|
|
134
|
+
if (d.activity !== undefined && d.activity !== null &&
|
|
135
|
+
(typeof d.activity !== "string" || !PRESENCE_ACTIVITIES.has(d.activity))) {
|
|
136
|
+
return { ok: false, reason: "presence_invalid_shape" };
|
|
137
|
+
}
|
|
138
|
+
let activityUpdatedAt = null;
|
|
139
|
+
if (d.activityUpdatedAt !== undefined && d.activityUpdatedAt !== null) {
|
|
140
|
+
activityUpdatedAt = finiteNumber(d.activityUpdatedAt);
|
|
141
|
+
if (activityUpdatedAt == null)
|
|
142
|
+
return { ok: false, reason: "presence_invalid_shape" };
|
|
143
|
+
if (activityUpdatedAt > receivedAt + PRESENCE_FUTURE_ALLOWANCE_MS) {
|
|
144
|
+
return { ok: false, reason: "presence_future_timestamp" };
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
const row = {
|
|
148
|
+
agentId,
|
|
149
|
+
lastHeartbeatAt,
|
|
150
|
+
currentTask: sanitizePresenceCurrentTask(d.currentTask),
|
|
151
|
+
activityUpdatedAt,
|
|
152
|
+
flairVersion: presenceVersion(d.flairVersion),
|
|
153
|
+
harperVersion: presenceVersion(d.harperVersion),
|
|
154
|
+
originatorInstanceId: senderInstanceId,
|
|
155
|
+
receivedAt,
|
|
156
|
+
};
|
|
157
|
+
// An absent activity is left off so the merge can fall back to the stored
|
|
158
|
+
// label instead of overwriting it with a hole.
|
|
159
|
+
if (typeof d.activity === "string")
|
|
160
|
+
row.activity = d.activity;
|
|
161
|
+
return { ok: true, row };
|
|
162
|
+
}
|
|
163
|
+
// ─── P4: Presence-specific merge ─────────────────────────────────────────────
|
|
164
|
+
/**
|
|
165
|
+
* An older `lastHeartbeatAt`, or a tie with both `activityUpdatedAt` stamps
|
|
166
|
+
* present and the incoming stamp older, skips as `presence_stale_heartbeat`.
|
|
167
|
+
* On a heartbeat tie, an equal or absent incoming activity stamp merges while
|
|
168
|
+
* keeping the stored activity fields. An accepted record never lowers the
|
|
169
|
+
* stored `activityUpdatedAt`.
|
|
170
|
+
*/
|
|
171
|
+
export function mergePresenceReceipt(local, incoming, receivedAt) {
|
|
172
|
+
const incHb = incoming.lastHeartbeatAt;
|
|
173
|
+
const incAut = presenceMs(incoming.activityUpdatedAt);
|
|
174
|
+
const localHb = local ? presenceMs(local.lastHeartbeatAt) : null;
|
|
175
|
+
const localAut = local ? presenceMs(local.activityUpdatedAt) : null;
|
|
176
|
+
if (localHb != null) {
|
|
177
|
+
if (incHb < localHb)
|
|
178
|
+
return { action: "skip", reason: "presence_stale_heartbeat" };
|
|
179
|
+
// A tie whose activity ordering is OLDER (both stamps present) is stale.
|
|
180
|
+
// A tie with an absent incoming stamp merges, keeping stored activity fields.
|
|
181
|
+
if (incHb === localHb && localAut != null && incAut != null && incAut < localAut) {
|
|
182
|
+
return { action: "skip", reason: "presence_stale_heartbeat" };
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
// On a heartbeat tie, the incoming activity fields replace the stored ones
|
|
186
|
+
// only when the incoming stamp is STRICTLY newer. An equal or absent stamp
|
|
187
|
+
// merges while keeping the stored activity/task/stamp.
|
|
188
|
+
const tied = localHb != null && incHb === localHb;
|
|
189
|
+
const incomingStrictlyNewer = incAut != null && (localAut == null || incAut > localAut);
|
|
190
|
+
const keepStoredActivity = tied && !incomingStrictlyNewer;
|
|
191
|
+
const activityUpdatedAt = keepStoredActivity
|
|
192
|
+
? localAut
|
|
193
|
+
: incAut == null ? localAut : localAut == null ? incAut : Math.max(incAut, localAut);
|
|
194
|
+
const activity = keepStoredActivity
|
|
195
|
+
? (typeof local?.activity === "string" ? local.activity : (incoming.activity ?? "idle"))
|
|
196
|
+
: (incoming.activity
|
|
197
|
+
?? (typeof local?.activity === "string" ? local.activity : undefined)
|
|
198
|
+
?? "idle");
|
|
199
|
+
const currentTask = keepStoredActivity ? (local?.currentTask ?? null) : (incoming.currentTask ?? null);
|
|
200
|
+
return {
|
|
201
|
+
action: "merge",
|
|
202
|
+
row: {
|
|
203
|
+
agentId: incoming.agentId,
|
|
204
|
+
lastHeartbeatAt: incHb,
|
|
205
|
+
currentTask,
|
|
206
|
+
activity,
|
|
207
|
+
activityUpdatedAt: activityUpdatedAt ?? null,
|
|
208
|
+
flairVersion: incoming.flairVersion ?? null,
|
|
209
|
+
harperVersion: incoming.harperVersion ?? null,
|
|
210
|
+
originatorInstanceId: incoming.originatorInstanceId ?? null,
|
|
211
|
+
receivedAt,
|
|
212
|
+
},
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
// ─── P2: local-write home refusal ────────────────────────────────────────────
|
|
216
|
+
/**
|
|
217
|
+
* A local write for an agent HOMED ON ANOTHER INSTANCE is refused; a null home
|
|
218
|
+
* is treated as LOCAL (so a legacy Agent row created before the originator
|
|
219
|
+
* contract keeps heartbeating). `localInstanceId` is this instance's canonical
|
|
220
|
+
* id as the caller read it at write time; with no single canonical `Instance`
|
|
221
|
+
* row it is null, and such an instance is the home of no agent that has a
|
|
222
|
+
* non-null home.
|
|
223
|
+
*
|
|
224
|
+
* Returns a named refusal, or null to allow the write.
|
|
225
|
+
*/
|
|
226
|
+
export function presenceWriteHomeRefusal(agentRow, localInstanceId) {
|
|
227
|
+
const home = agentRow?.originatorInstanceId;
|
|
228
|
+
if (typeof home !== "string" || home.length === 0)
|
|
229
|
+
return null;
|
|
230
|
+
if (localInstanceId != null && home === localInstanceId)
|
|
231
|
+
return null;
|
|
232
|
+
return {
|
|
233
|
+
error: "presence_agent_homed_elsewhere",
|
|
234
|
+
message: "this agent's presence is homed on another instance; write it there",
|
|
235
|
+
};
|
|
236
|
+
}
|
|
@@ -1,27 +1,62 @@
|
|
|
1
|
-
import { withDetachedTxn } from "./table-helpers.js";
|
|
2
1
|
import { databases } from "harper";
|
|
3
2
|
import { stripUndeclaredMemoryAttributes } from "./memory-declared-attributes.js";
|
|
4
3
|
import { noteMemoryUpsert } from "./bm25-index-service.js";
|
|
4
|
+
import { writeBackCommittedRow } from "./write-back.js";
|
|
5
|
+
import { txnPausePoint } from "./txn-pause-point.js";
|
|
6
|
+
import { isJoinableTransaction } from "./request-transaction.js";
|
|
7
|
+
/** The stamp's first read is not the row the promotion wrote: nothing stamped. */
|
|
8
|
+
export class PromotedRowChangedError extends Error {
|
|
9
|
+
constructor(id) {
|
|
10
|
+
super(`promotion-stamp: row ${id} is not the row this promotion wrote; no stamp written`);
|
|
11
|
+
this.name = "PromotedRowChangedError";
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
function isWrittenRow(row, written) {
|
|
15
|
+
return written != null && typeof written.instanceToken === "string" && written.instanceToken.length > 0 &&
|
|
16
|
+
row.agentId === written.agentId && row.content === written.content && row.instanceToken === written.instanceToken;
|
|
17
|
+
}
|
|
5
18
|
// Called only after the promotion workflow has authorized and written a Memory
|
|
6
19
|
// through its resource (safety, embedding, ownership and provenance still run).
|
|
7
20
|
// Auto-promotion supplies its enumeration context: its Memory write used a
|
|
8
21
|
// separate agentContext, so that enumeration snapshot cannot see the new row.
|
|
9
|
-
//
|
|
10
|
-
|
|
22
|
+
// It also supplies the identity of the row it wrote; the stamp's first read
|
|
23
|
+
// must be that row. Manual promotion passes the context of the open
|
|
24
|
+
// transaction its Memory write used, and the stamp joins it.
|
|
25
|
+
export async function stampMemoryPromotion(id, reviewerId, decidedAt, enumerationContext, stagedContext, written) {
|
|
11
26
|
const table = databases.flair.Memory;
|
|
12
|
-
const
|
|
13
|
-
|
|
27
|
+
const stamp = (stored) => {
|
|
28
|
+
if (!stored)
|
|
29
|
+
throw new Error(`Promotion memory ${id} was not written`);
|
|
30
|
+
const row = { ...stored, promotionStatus: "approved", promotedBy: reviewerId, promotedAt: decidedAt };
|
|
31
|
+
stripUndeclaredMemoryAttributes(row);
|
|
32
|
+
return row;
|
|
33
|
+
};
|
|
34
|
+
if (isJoinableTransaction(stagedContext)) {
|
|
35
|
+
const row = stamp(await table.get(id, stagedContext));
|
|
36
|
+
await table.put(row, stagedContext);
|
|
37
|
+
noteMemoryUpsert(row);
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
// Test-only: inert unless the fault-injection opt-in is armed.
|
|
41
|
+
const beforeFirstRead = txnPausePoint("promotion-stamp-select");
|
|
42
|
+
if (beforeFirstRead)
|
|
43
|
+
await beforeFirstRead;
|
|
44
|
+
const selected = await table.get(id, {});
|
|
45
|
+
if (!selected)
|
|
14
46
|
throw new Error(`Promotion memory ${id} was not written`);
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
await
|
|
18
|
-
|
|
47
|
+
if (!isWrittenRow(selected, written))
|
|
48
|
+
throw new PromotedRowChangedError(id);
|
|
49
|
+
const outcome = await writeBackCommittedRow(table, id, (stored) => ({ write: stamp(stored) }), { ctx: enumerationContext, label: "promotion-stamp", pausePre: () => txnPausePoint("promotion-stamp-pre"), pausePoint: () => txnPausePoint("promotion-stamp"), matchFields: ["content"], expectedRow: selected });
|
|
50
|
+
if ("write" in outcome)
|
|
51
|
+
noteMemoryUpsert(outcome.write);
|
|
19
52
|
}
|
|
20
53
|
/** Stamp after a successful Memory write. Failures must not abort a sweep or
|
|
21
|
-
* leave a candidate pending (that re-writes the same claim next cycle).
|
|
22
|
-
|
|
54
|
+
* leave a candidate pending (that re-writes the same claim next cycle).
|
|
55
|
+
* Auto-promotion uses this non-fatal wrapper; manual promotion calls
|
|
56
|
+
* stampMemoryPromotion directly, so a stamp failure fails that request. */
|
|
57
|
+
export async function stampMemoryPromotionIsolated(id, reviewerId, decidedAt, enumerationContext, written) {
|
|
23
58
|
try {
|
|
24
|
-
await stampMemoryPromotion(id, reviewerId, decidedAt, enumerationContext);
|
|
59
|
+
await stampMemoryPromotion(id, reviewerId, decidedAt, enumerationContext, undefined, written);
|
|
25
60
|
return true;
|
|
26
61
|
}
|
|
27
62
|
catch (err) {
|