@tpsdev-ai/flair 0.58.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 +7 -6
- package/SECURITY.md +36 -0
- package/config.yaml +15 -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 +1030 -343
- package/dist/commands/agent.js +384 -45
- 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 +601 -163
- 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 +146 -53
- 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 +81 -8
- package/dist/lib/doctor-run.js +140 -35
- package/dist/lib/durability-copy.js +10 -0
- package/dist/lib/embedding-space-doctor.js +75 -0
- package/dist/lib/flair-agent-role.js +120 -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 +27 -2
- 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 +1775 -338
- 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 +103 -7
- 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 +348 -8
- package/dist/resources/AgentKeyRegister.js +214 -0
- package/dist/resources/AgentKeyRegistration.js +28 -0
- package/dist/resources/AgentSeed.js +19 -4
- package/dist/resources/AutoPromoteCandidates.js +7 -1
- package/dist/resources/Credential.js +177 -2
- package/dist/resources/Federation.js +752 -132
- 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 +227 -64
- 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/OrgSkillAssignment.js +209 -0
- 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 +212 -65
- package/dist/resources/agent-auth.js +40 -15
- package/dist/resources/agent-status-guard.js +63 -0
- package/dist/resources/auth-middleware.js +402 -162
- 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 +94 -0
- package/dist/resources/federation-crypto.js +5 -5
- package/dist/resources/federation-retry-lib.js +135 -0
- package/dist/resources/flair-agent-role-boot.js +26 -0
- package/dist/resources/grant-visibility.js +135 -0
- package/dist/resources/harper-routing.js +83 -0
- package/dist/resources/health.js +130 -20
- 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 +31 -0
- package/dist/resources/mcp-handler.js +36 -8
- package/dist/resources/mcp-oauth-env-guard.js +36 -0
- package/dist/resources/mcp-oauth.js +26 -12
- package/dist/resources/mcp-tool-arguments.js +4 -6
- package/dist/resources/mcp-tools.js +150 -23
- 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/multi-worker-guard.js +121 -0
- package/dist/resources/oauth-discovery.js +1 -0
- package/dist/resources/oauth-wellknown.js +8 -4
- 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 +17 -1
- package/dist/resources/relay-ops.js +78 -6
- package/dist/resources/replay-store.js +145 -21
- 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 +190 -0
- package/dist/resources/skill-provenance.js +15 -10
- 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 +120 -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 +768 -0
- package/docs/api-reference.md +52 -13
- package/docs/auth.md +10 -12
- package/docs/bridges.md +11 -0
- package/docs/claude-code.md +34 -4
- package/docs/deepseek-harness.md +1 -1
- 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 +6 -6
- package/docs/mcp-clients.md +10 -5
- 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 +34 -28
- 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 +12 -6
- package/schemas/agent-key-registration.graphql +22 -0
- package/schemas/agent.graphql +3 -0
- package/schemas/federation.graphql +38 -1
- package/schemas/memory.graphql +115 -5
- package/schemas/oauth.graphql +27 -4
- package/schemas/schema.graphql +2 -0
- package/templates/launchd/start-flair-with-admin-pass.sh +89 -16
|
@@ -16,8 +16,8 @@
|
|
|
16
16
|
*
|
|
17
17
|
* `recordUsageContribution()` is the one (agentId, memoryId) ledger write —
|
|
18
18
|
* see its doc below for the read-scope gate it applies, the ledger-then-count
|
|
19
|
-
* ordering, the
|
|
20
|
-
*
|
|
19
|
+
* ordering, and the owned read-modify-write that confirms the stored row before
|
|
20
|
+
* the count bump.
|
|
21
21
|
*
|
|
22
22
|
* `recordCitations()` is the NEW batch helper citation-on-write uses: the
|
|
23
23
|
* same agent-required / cap / dedup / per-id failure-isolation shape as
|
|
@@ -54,8 +54,11 @@
|
|
|
54
54
|
* unfiltered.
|
|
55
55
|
*/
|
|
56
56
|
import { databases } from "harper";
|
|
57
|
-
import {
|
|
57
|
+
import { withKeyLock } from "./key-lock.js";
|
|
58
58
|
import { withDetachedTxn } from "./table-helpers.js";
|
|
59
|
+
import { withOwnedTransaction } from "./request-transaction.js";
|
|
60
|
+
import { WriteBackConflictError, writeBackCommittedRow } from "./write-back.js";
|
|
61
|
+
import { txnPausePoint } from "./txn-pause-point.js";
|
|
59
62
|
import { resolveReadScope } from "./memory-read-scope.js";
|
|
60
63
|
/**
|
|
61
64
|
* Per-call cap on ids credited in one batch — shared by RecordUsage.post()'s
|
|
@@ -64,6 +67,22 @@ import { resolveReadScope } from "./memory-read-scope.js";
|
|
|
64
67
|
* see that function's doc for why the two differ here).
|
|
65
68
|
*/
|
|
66
69
|
export const MAX_USAGE_IDS_PER_CALL = 20;
|
|
70
|
+
/**
|
|
71
|
+
* The named refusal of a contribution whose ledger READ failed. The read is the
|
|
72
|
+
* decision "does this (agent, memory) pair already have a row?" — an error is
|
|
73
|
+
* NOT evidence there is none. Treating it as "no row" would upsert over whatever
|
|
74
|
+
* row is stored and bump the count a second time, so this contribution is
|
|
75
|
+
* aborted instead (no ledger write, no count change) and the batch logs the
|
|
76
|
+
* failure; the other ids in the batch are unaffected.
|
|
77
|
+
*/
|
|
78
|
+
export class UsageLedgerReadError extends Error {
|
|
79
|
+
ledgerId;
|
|
80
|
+
constructor(ledgerId, cause) {
|
|
81
|
+
super(`usage ledger row read failed for ${ledgerId}: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
82
|
+
this.name = "UsageLedgerReadError";
|
|
83
|
+
this.ledgerId = ledgerId;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
67
86
|
/**
|
|
68
87
|
* One (agentId, memoryId) contribution — the shared ledger-write core.
|
|
69
88
|
*
|
|
@@ -79,75 +98,135 @@ export const MAX_USAGE_IDS_PER_CALL = 20;
|
|
|
79
98
|
* Ledger-row-create FIRST, THEN the Memory.usageCount bump — so a crash
|
|
80
99
|
* between the two leaves the SAFE failure state (ledger row exists, count
|
|
81
100
|
* not yet bumped: a later retry just re-checks and no-ops) rather than the
|
|
82
|
-
* reverse (count bumped, no ledger row → a retry would double-count).
|
|
101
|
+
* reverse (count bumped, no ledger row → a retry would double-count). The
|
|
102
|
+
* ledger READ that decides all this FAILS CLOSED: an error is not "no row", so
|
|
103
|
+
* that contribution aborts (named UsageLedgerReadError, no ledger write, no
|
|
104
|
+
* count change) rather than upsert over the stored row and bump again.
|
|
83
105
|
*
|
|
84
|
-
*
|
|
85
|
-
*
|
|
86
|
-
* that reads/writes MULTIPLE tables (or the same table twice) in sequence
|
|
87
|
-
* can otherwise inherit a closed transaction from a prior call's drained
|
|
88
|
-
* chain (table-helpers.ts's withDetachedTxn doc); resources/Memory.ts's
|
|
89
|
-
* closeSupersededRecord documents exactly why a single wrap around a
|
|
90
|
-
* multi-await async function does NOT protect a later call inside it —
|
|
91
|
-
* this mirrors that function's literal shape (get wrapped, then a
|
|
92
|
-
* SEPARATE put wrapped) rather than delegating to the generic
|
|
93
|
-
* patchRecord() helper, which would combine both into one un-safe wrap.
|
|
106
|
+
* The ledger read and any create share an owned transaction. The count bump
|
|
107
|
+
* uses a separate owned transaction through writeBackCommittedRow.
|
|
94
108
|
*
|
|
95
|
-
* The
|
|
96
|
-
* read
|
|
97
|
-
*
|
|
98
|
-
*
|
|
99
|
-
*
|
|
100
|
-
*
|
|
101
|
-
*
|
|
102
|
-
*
|
|
103
|
-
*
|
|
104
|
-
*
|
|
109
|
+
* The count bump is the shared write-back helper (write-back.ts): the row is
|
|
110
|
+
* read inside a transaction this call OWNS, the bump is built from THAT read,
|
|
111
|
+
* and the committed row is re-read before commit. The plan skips an absent
|
|
112
|
+
* row or one outside the agent's read scope before any identity comparison.
|
|
113
|
+
* For a row the plan does not skip, an identity change the in-transaction read
|
|
114
|
+
* already sees throws WriteBackConflictError at once (no retry). Only a change to the committed
|
|
115
|
+
* row found by the re-read after the bump is staged retries, from a fresh
|
|
116
|
+
* read, at most WRITE_BACK_ATTEMPTS attempts in all (then
|
|
117
|
+
* WriteBackConflictError). recordUsageBatch / recordCitations log either
|
|
118
|
+
* refusal with the reason `stored_row_changed`. The earlier read only decides
|
|
119
|
+
* the read-scope gate above; it never authorizes the count write on its own.
|
|
105
120
|
*
|
|
106
121
|
* Called by recordUsageBatch() (POST /RecordUsage, explicit usage feedback)
|
|
107
122
|
* and by recordCitations() below (citation-on-write) — identical ledger
|
|
108
123
|
* semantics regardless of which surface triggered the contribution.
|
|
109
124
|
*/
|
|
110
125
|
export async function recordUsageContribution(ctx, agentId, memoryId, attribution, now, canRead) {
|
|
126
|
+
// Within one Harper process, the per-(agentId, memoryId) lock serializes
|
|
127
|
+
// contributions across the ledger check, any create and any count bump.
|
|
128
|
+
const store = databases?.flair?.MemoryUsage?.primaryStore;
|
|
129
|
+
const outcome = await withKeyLock(store, [USAGE_LEDGER_LOCK_NAMESPACE, agentId, memoryId], () => recordUsageContributionLocked(ctx, agentId, memoryId, attribution, now, canRead), USAGE_LOCK_ATTEMPTS, USAGE_LOCK_WAIT_MS);
|
|
130
|
+
// The lock could not be acquired (or the store has none): this contribution
|
|
131
|
+
// writes no ledger row and makes no count change; the caller still gets its
|
|
132
|
+
// recorded response. Other ids in the same batch may already have been credited.
|
|
133
|
+
if (outcome.kind !== "done")
|
|
134
|
+
return;
|
|
135
|
+
// Test-only: pause after the ledger lock releases and the owned transaction
|
|
136
|
+
// commits, before this request's transaction commits (flair#2333).
|
|
137
|
+
const committed = txnPausePoint("usage-ledger-lock-released");
|
|
138
|
+
if (committed)
|
|
139
|
+
await committed;
|
|
140
|
+
}
|
|
141
|
+
/** The per-(agentId, memoryId) lock namespace and wait (resources/key-lock.ts). */
|
|
142
|
+
const USAGE_LEDGER_LOCK_NAMESPACE = "flair-usage-ledger";
|
|
143
|
+
const USAGE_LOCK_ATTEMPTS = 200;
|
|
144
|
+
const USAGE_LOCK_WAIT_MS = 10;
|
|
145
|
+
/**
|
|
146
|
+
* The ledger check, the ledger create and the count bump, run while holding the
|
|
147
|
+
* (agentId, memoryId) lock: see `recordUsageContribution` for the whole contract.
|
|
148
|
+
* Split out so the whole check-and-write runs under the lock; it is never called
|
|
149
|
+
* outside it.
|
|
150
|
+
*/
|
|
151
|
+
async function recordUsageContributionLocked(ctx, agentId, memoryId, attribution, now, canRead) {
|
|
111
152
|
const ledgerId = `${agentId}:${memoryId}`;
|
|
112
|
-
//
|
|
113
|
-
//
|
|
114
|
-
//
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
153
|
+
// Within one Harper process, the ledger check and any create share an owned
|
|
154
|
+
// transaction that commits before the contribution lock releases. The count
|
|
155
|
+
// bump uses a separate owned transaction.
|
|
156
|
+
const prepared = await withOwnedTransaction(ctx, async (owned) => {
|
|
157
|
+
// Bypasses resources/MemoryUsage.ts's own auth wrapper by design — this
|
|
158
|
+
// IS the trusted internal caller that resource's module doc describes
|
|
159
|
+
// (same "raw table object" pattern resources/Memory.ts uses for
|
|
160
|
+
// MemoryGrant). The read DECIDES whether a row is already there, so a
|
|
161
|
+
// failed read is not "no row": abort this contribution (fail closed,
|
|
162
|
+
// named) rather than upsert over the stored row and bump the count again.
|
|
163
|
+
let existingContribution;
|
|
164
|
+
try {
|
|
165
|
+
existingContribution = await databases.flair.MemoryUsage.get(ledgerId, owned);
|
|
166
|
+
}
|
|
167
|
+
catch (err) {
|
|
168
|
+
throw new UsageLedgerReadError(ledgerId, err);
|
|
169
|
+
}
|
|
170
|
+
if (existingContribution)
|
|
171
|
+
return null; // already counted by this agent — silent no-op
|
|
172
|
+
// Test-only: pause after finding no ledger row. Creation and the count bump
|
|
173
|
+
// still require their read-scope gates and successful writes.
|
|
174
|
+
const pause = txnPausePoint("usage-contribution-claim");
|
|
175
|
+
if (pause)
|
|
176
|
+
await pause;
|
|
177
|
+
// Absent, unreadable, or a failed read: ONE silent no-op branch (no
|
|
178
|
+
// enumeration). A read failure is never evidence the memory is readable.
|
|
179
|
+
const memory = await databases.flair.Memory.get(memoryId, owned).catch(() => null);
|
|
180
|
+
if (!memory || !canRead(memory))
|
|
181
|
+
return null;
|
|
182
|
+
const ledgerRecord = { id: ledgerId, agentId, memoryId, createdAt: now };
|
|
183
|
+
if (attribution)
|
|
184
|
+
ledgerRecord.attribution = attribution;
|
|
185
|
+
// .put(), not .post(): Harper's raw TableResource has no default post()
|
|
186
|
+
// implementation for a static-style (non-`isCollection`-instantiated)
|
|
187
|
+
// call — confirmed live ("The MemoryUsage does not have a post method
|
|
188
|
+
// implemented", statusCode 405) — the SAME class of gotcha
|
|
189
|
+
// resources/Memory.ts documents for HTTP POST, but here it bites even
|
|
190
|
+
// this in-process call. Irrelevant anyway: ledgerId is already a
|
|
191
|
+
// deterministic composite key, so this is a create-with-explicit-id —
|
|
192
|
+
// exactly what PUT (upsert) is for, not an auto-generated-id insert.
|
|
193
|
+
await databases.flair.MemoryUsage.put(ledgerRecord, owned);
|
|
194
|
+
return memory;
|
|
195
|
+
});
|
|
196
|
+
if (!prepared)
|
|
123
197
|
return;
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
//
|
|
128
|
-
// implementation for a static-style (non-`isCollection`-instantiated)
|
|
129
|
-
// call — confirmed live ("The MemoryUsage does not have a post method
|
|
130
|
-
// implemented", statusCode 405) — the SAME class of gotcha
|
|
131
|
-
// resources/Memory.ts documents for HTTP POST, but here it bites even
|
|
132
|
-
// this in-process call. Irrelevant anyway: ledgerId is already a
|
|
133
|
-
// deterministic composite key, so this is a create-with-explicit-id —
|
|
134
|
-
// exactly what PUT (upsert) is for, not an auto-generated-id insert.
|
|
135
|
-
await withDetachedTxn(ctx, () => databases.flair.MemoryUsage.put(ledgerRecord));
|
|
136
|
-
// Targeted usageCount-ONLY bump: read-full-record, merge just this one
|
|
137
|
-
// field, write — against the RAW Memory table, NEVER Memory.put() (the
|
|
138
|
-
// resource class): that would 403 this cross-agent write via its
|
|
139
|
-
// ownership check, and bypassing that check directly would risk letting
|
|
198
|
+
// Targeted usageCount-ONLY bump: an INCREMENTAL update of exactly this one
|
|
199
|
+
// field through the shared helper, against the RAW Memory table, NEVER
|
|
200
|
+
// Memory.put() (the resource class): that would 403 this cross-agent write via
|
|
201
|
+
// its ownership check, and bypassing that check directly would risk letting
|
|
140
202
|
// this write path smuggle OTHER field changes through instead of just the
|
|
141
|
-
// count (RecordUsage.ts module doc's "WHY THIS IS ITS OWN ENDPOINT").
|
|
142
|
-
|
|
143
|
-
//
|
|
144
|
-
//
|
|
145
|
-
//
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
203
|
+
// count (RecordUsage.ts module doc's "WHY THIS IS ITS OWN ENDPOINT"). The helper
|
|
204
|
+
// confirms, inside its own transaction, that the stored row is still the one
|
|
205
|
+
// this contribution was checked against (flair#2441): a row deleted or purged
|
|
206
|
+
// before the in-transaction read is skipped by the plan (absent row), as is a
|
|
207
|
+
// row outside the agent's read scope; for any other row an identity mismatch
|
|
208
|
+
// seen by the check is refused. An error from the transactional read is not
|
|
209
|
+
// caught here: it propagates to the caller.
|
|
210
|
+
await writeBackCommittedRow(databases.flair.Memory, memoryId, (row) => {
|
|
211
|
+
// Deleted, or moved out of the agent's read scope, between the check
|
|
212
|
+
// above and this read — the count is not bumped (the ledger row written
|
|
213
|
+
// above stays). The count is only ever bumped on a row in the agent's
|
|
214
|
+
// read scope.
|
|
215
|
+
if (!row || !canRead(row))
|
|
216
|
+
return { skip: true };
|
|
217
|
+
// Only `usageCount`: an incremental update, never a
|
|
218
|
+
// full-row put of the row read above (flair#2470).
|
|
219
|
+
return { update: { usageCount: (row.usageCount ?? 0) + 1 } };
|
|
220
|
+
}, {
|
|
221
|
+
ctx,
|
|
222
|
+
label: "usage-recording",
|
|
223
|
+
// The row the contribution was checked against is the basis: the helper
|
|
224
|
+
// refuses when the stored row is no longer it (a delete, a purge, or a
|
|
225
|
+
// same-id replace with a new token).
|
|
226
|
+
expectedRow: prepared,
|
|
227
|
+
pausePre: () => txnPausePoint("usage-count-pre"),
|
|
228
|
+
pausePoint: () => txnPausePoint("usage-count"),
|
|
229
|
+
});
|
|
151
230
|
}
|
|
152
231
|
/**
|
|
153
232
|
* Default record fetch for the read-scope gates in this module
|
|
@@ -245,7 +324,22 @@ export async function recordCitations(ctx, auth, usedMemoryIds, now, recordFn =
|
|
|
245
324
|
catch (err) {
|
|
246
325
|
// Never let one bad id stop the batch — same no-op-on-error discipline
|
|
247
326
|
// as RecordUsage.post()'s loop, log server-side only.
|
|
248
|
-
|
|
327
|
+
if (err instanceof WriteBackConflictError) {
|
|
328
|
+
// flair#2441: the stored row is no longer the one read (a same-id
|
|
329
|
+
// replace, or a change found on every attempt); the count bump was
|
|
330
|
+
// refused. The ledger row was already written and committed before the
|
|
331
|
+
// bump, so it stays, and the count is not bumped.
|
|
332
|
+
console.error("recordCitations: not credited, stored_row_changed (no-op)", { memoryId: id, reason: "stored_row_changed", err });
|
|
333
|
+
}
|
|
334
|
+
else if (err instanceof UsageLedgerReadError) {
|
|
335
|
+
// flair#2333: the ledger read that decides whether this pair already
|
|
336
|
+
// has a row failed — not "no row". This contribution is aborted (no
|
|
337
|
+
// ledger write, no count bump); the other ids stand.
|
|
338
|
+
console.error("recordCitations: not credited, ledger read failed (no-op)", { memoryId: id, ledgerId: err.ledgerId, reason: "ledger_read_failed", err });
|
|
339
|
+
}
|
|
340
|
+
else {
|
|
341
|
+
console.error("recordCitations: failed to credit (no-op)", { memoryId: id, err });
|
|
342
|
+
}
|
|
249
343
|
}
|
|
250
344
|
}
|
|
251
345
|
}
|
|
@@ -288,7 +382,21 @@ export async function recordUsageBatch(ctx, agentId, memoryIds, attribution, now
|
|
|
288
382
|
// error leak existence information either — log server-side, collapse
|
|
289
383
|
// to the same no-op the response already returns for every other
|
|
290
384
|
// outcome.
|
|
291
|
-
|
|
385
|
+
if (err instanceof WriteBackConflictError) {
|
|
386
|
+
// flair#2441: the stored row is no longer the one read (a same-id
|
|
387
|
+
// replace, or a change found on every attempt); the count bump was
|
|
388
|
+
// refused. The ledger row was already written and committed before the
|
|
389
|
+
// bump, so it stays, and the count is not bumped.
|
|
390
|
+
console.error("RecordUsage.post: not recorded, stored_row_changed (treated as no-op)", { memoryId, reason: "stored_row_changed", err });
|
|
391
|
+
}
|
|
392
|
+
else if (err instanceof UsageLedgerReadError) {
|
|
393
|
+
// flair#2333: the ledger read failed — not "no row". This contribution
|
|
394
|
+
// is aborted (no ledger write, no count bump); the other ids stand.
|
|
395
|
+
console.error("RecordUsage.post: not recorded, ledger read failed (treated as no-op)", { memoryId, ledgerId: err.ledgerId, reason: "ledger_read_failed", err });
|
|
396
|
+
}
|
|
397
|
+
else {
|
|
398
|
+
console.error("RecordUsage.post: failed to record usage (treated as no-op)", { memoryId, err });
|
|
399
|
+
}
|
|
292
400
|
}
|
|
293
401
|
}
|
|
294
402
|
}
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from "node:util";
|
|
2
|
+
import { withOwnedTransaction } from "./request-transaction.js";
|
|
3
|
+
/** The fields of `expectedRow` (or of the helper's own first read) it compares
|
|
4
|
+
* with the row read inside its transaction, besides `matchFields`. */
|
|
5
|
+
export const WRITE_BACK_IDENTITY_FIELDS = ["id", "agentId", "instanceToken", "contentHash", "createdAt"];
|
|
6
|
+
/**
|
|
7
|
+
* Is `row` still the stored row `basis` describes? Compares the fields in
|
|
8
|
+
* {@link WRITE_BACK_IDENTITY_FIELDS} — the row's id and agent, and the
|
|
9
|
+
* server-stamped incarnation token, content hash and creation time. A `basis`
|
|
10
|
+
* of `null` requires `row` to still be absent.
|
|
11
|
+
*
|
|
12
|
+
* This is the identity check the write-back helper applies, exposed so a
|
|
13
|
+
* writer that cannot hand its write to the helper (one that joins a
|
|
14
|
+
* request-owned transaction, e.g. Memory.put) confirms the SAME facts: before
|
|
15
|
+
* it stages its write, and against the committed row after (through
|
|
16
|
+
* {@link confirmCommittedRow}).
|
|
17
|
+
*/
|
|
18
|
+
export function sameStoredRow(row, basis) {
|
|
19
|
+
return row == null ? basis == null : basis != null &&
|
|
20
|
+
String(row.id) === String(basis.id) && row.agentId === basis.agentId &&
|
|
21
|
+
row.instanceToken === basis.instanceToken && row.contentHash === basis.contentHash && row.createdAt === basis.createdAt;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* The named 409 for a write refused because the row it read is no longer the
|
|
25
|
+
* stored one: the row is gone (a delete or a purge committed) or its identity
|
|
26
|
+
* changed (a same-id replace committed: a field {@link sameStoredRow} compares,
|
|
27
|
+
* such as the incarnation token, differs). Nothing was written.
|
|
28
|
+
*/
|
|
29
|
+
export function storedRowChangedRefusal(tableName) {
|
|
30
|
+
return new Response(JSON.stringify({
|
|
31
|
+
error: "stored_row_changed",
|
|
32
|
+
message: `${tableName} row changed since it was read; not written`,
|
|
33
|
+
}), { status: 409, headers: { "content-type": "application/json" } });
|
|
34
|
+
}
|
|
35
|
+
/** Only the identity fields of `row`: an `expectedRow` for a caller that
|
|
36
|
+
* selects many rows before writing each back, so it need not hold them whole. */
|
|
37
|
+
export function writeBackIdentity(row) {
|
|
38
|
+
const identity = {};
|
|
39
|
+
for (const field of WRITE_BACK_IDENTITY_FIELDS)
|
|
40
|
+
identity[field] = row[field];
|
|
41
|
+
return identity;
|
|
42
|
+
}
|
|
43
|
+
/** Attempts of a write-back before it gives up on a row that keeps changing. */
|
|
44
|
+
export const WRITE_BACK_ATTEMPTS = 3;
|
|
45
|
+
/**
|
|
46
|
+
* The helper's named refusal: the row changed and nothing was written. Both
|
|
47
|
+
* checks that lead to it (the in-transaction comparison, and the committed-row
|
|
48
|
+
* confirmation after the write is staged) run inside the owned transaction
|
|
49
|
+
* before any commit is submitted, and their throw aborts that transaction, so
|
|
50
|
+
* its staged write is discarded. Whichever check fails, the outcome is known:
|
|
51
|
+
* not written.
|
|
52
|
+
*/
|
|
53
|
+
export class WriteBackConflictError extends Error {
|
|
54
|
+
id;
|
|
55
|
+
constructor(label, id, attempts) {
|
|
56
|
+
super(`${label}: row ${id} changed; write not applied (${attempts} attempts)`);
|
|
57
|
+
this.name = "WriteBackConflictError";
|
|
58
|
+
this.id = id;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/** Aborts the write's transaction: the COMMITTED row, re-read after the write
|
|
62
|
+
* was staged, is no longer the one the write is over. Inside the helper it
|
|
63
|
+
* never escapes (it is retried, then named by {@link WriteBackConflictError});
|
|
64
|
+
* a writer that runs {@link confirmCommittedRow} itself (Memory.put) catches it
|
|
65
|
+
* outside its transaction and answers with {@link storedRowChangedRefusal}. */
|
|
66
|
+
export class CommittedRowChanged extends Error {
|
|
67
|
+
constructor() {
|
|
68
|
+
super("committed row changed after the write was staged");
|
|
69
|
+
this.name = "CommittedRowChanged";
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* The committed-row confirmation the write-back helper runs once its write is
|
|
74
|
+
* staged and before its transaction commits: re-read the COMMITTED row and
|
|
75
|
+
* throw {@link CommittedRowChanged} unless `same(committed)` holds. The
|
|
76
|
+
* transaction must then abort so the staged write is discarded: an owned
|
|
77
|
+
* transaction aborts when the throw leaves its callback; a caller that joined
|
|
78
|
+
* a request-owned transaction aborts it itself (Memory.put does).
|
|
79
|
+
*
|
|
80
|
+
* The read is an EXPLICIT fresh context, never contextless: a contextless read
|
|
81
|
+
* joins the caller's transaction and sees its old snapshot or its staged write.
|
|
82
|
+
* Harper has no compare-and-set on a table write, so a change committed after
|
|
83
|
+
* this read and before the commit is not seen by it.
|
|
84
|
+
*
|
|
85
|
+
* Exported so a writer that cannot hand its write to the helper (Memory.put,
|
|
86
|
+
* which joins a request-owned transaction) runs the same re-read, with its own
|
|
87
|
+
* predicate (the helper compares the whole row; Memory.put, sameStoredRow).
|
|
88
|
+
*/
|
|
89
|
+
export async function confirmCommittedRow(table, id, same) {
|
|
90
|
+
const committed = await table.get(id, {});
|
|
91
|
+
if (!same(committed))
|
|
92
|
+
throw new CommittedRowChanged();
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* The name for a close whose authorizing "write" grant is gone at the
|
|
96
|
+
* committed-state re-check (flair#2333 H10 / flair#2511). The two closes share
|
|
97
|
+
* the re-check ({@link writeGrantHeld}) and this name, but only the
|
|
98
|
+
* skill-version close answers its caller with it. The skill-version close
|
|
99
|
+
* (skill-version-write.ts) returns {@link grantedCloseRevokedRefusal}, a 409
|
|
100
|
+
* carrying this code. The non-skill close (Memory.ts closeSupersededRecord) runs
|
|
101
|
+
* after its successor is written and throws {@link GrantedCloseRevoked}, which
|
|
102
|
+
* its caller logs: the predecessor stays open, the successor stays written, and
|
|
103
|
+
* the caller's response is a success.
|
|
104
|
+
*/
|
|
105
|
+
export const GRANTED_CLOSE_REVOKED = "granted_close_revoked";
|
|
106
|
+
/** The skill-version close's named 409 for a close whose authorizing "write"
|
|
107
|
+
* grant is gone at the committed-state re-check. Returned from inside the
|
|
108
|
+
* version transaction, which then rolls back: nothing is written. */
|
|
109
|
+
export function grantedCloseRevokedRefusal() {
|
|
110
|
+
return new Response(JSON.stringify({
|
|
111
|
+
error: GRANTED_CLOSE_REVOKED,
|
|
112
|
+
message: "the write grant authorizing this close was revoked; not written",
|
|
113
|
+
}), { status: 409, headers: { "content-type": "application/json" } });
|
|
114
|
+
}
|
|
115
|
+
/** Aborts the non-skill close's owned transaction (Memory.ts
|
|
116
|
+
* closeSupersededRecord): the "write" grant that authorized a cross-agent close
|
|
117
|
+
* is gone on committed state (flair#2333 H10). The predecessor is not closed;
|
|
118
|
+
* the caller logs this after its successor is already written. */
|
|
119
|
+
export class GrantedCloseRevoked extends Error {
|
|
120
|
+
constructor() {
|
|
121
|
+
super(`${GRANTED_CLOSE_REVOKED}: the write grant authorizing the close was revoked`);
|
|
122
|
+
this.name = "GrantedCloseRevoked";
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Does `table` hold a "write" grant from `ownerId` to `granteeId`? A caller that
|
|
127
|
+
* re-checks on committed state passes an explicit fresh context (`{}`) rather
|
|
128
|
+
* than its own transaction — the same discipline {@link confirmCommittedRow}
|
|
129
|
+
* applies to a row. Fail-closed: a search that rejects reads as no grant, so an
|
|
130
|
+
* unreadable grant does not close the owner's row.
|
|
131
|
+
*
|
|
132
|
+
* The committed-state grant re-check both closes run after staging a
|
|
133
|
+
* grant-authorized cross-agent close: the non-skill close (Memory.ts
|
|
134
|
+
* closeSupersededRecord, flair#2333 H10) and the shared skill-version writer
|
|
135
|
+
* (skill-version-write.ts, flair#2511), whose every caller passes the grant a
|
|
136
|
+
* cross-agent close stands on.
|
|
137
|
+
*/
|
|
138
|
+
export async function writeGrantHeld(table, granteeId, ownerId, ctx) {
|
|
139
|
+
try {
|
|
140
|
+
for await (const grant of table.search({
|
|
141
|
+
conditions: [
|
|
142
|
+
{ attribute: "granteeId", comparator: "equals", value: granteeId },
|
|
143
|
+
{ attribute: "ownerId", comparator: "equals", value: ownerId },
|
|
144
|
+
],
|
|
145
|
+
}, ctx)) {
|
|
146
|
+
if (grant?.scope === "write")
|
|
147
|
+
return true;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
return false;
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Write an incremental update of exactly `patch`'s fields, in the caller's
|
|
157
|
+
* transaction. Refuses by name when the table cannot write incrementally
|
|
158
|
+
* (a fake or a stub without `update`): falling back to a full-row `put` here
|
|
159
|
+
* would reintroduce the very full-row write this helper's `update` plan exists
|
|
160
|
+
* to avoid.
|
|
161
|
+
*/
|
|
162
|
+
async function applyFieldUpdate(table, id, patch, ctx) {
|
|
163
|
+
if (typeof table.update !== "function") {
|
|
164
|
+
throw new Error("write-back: the table has no incremental update; refusing to fall back to a full-row put");
|
|
165
|
+
}
|
|
166
|
+
await table.update(id, patch, ctx);
|
|
167
|
+
}
|
|
168
|
+
export async function writeBackCommittedRow(table, id, plan, opts) {
|
|
169
|
+
const attempts = opts.attempts ?? WRITE_BACK_ATTEMPTS;
|
|
170
|
+
const selected = "expectedRow" in opts ? opts.expectedRow : await table.get(id, {});
|
|
171
|
+
const basis = selected == null ? selected : { ...selected };
|
|
172
|
+
const sameTarget = (row) => {
|
|
173
|
+
if (row == null)
|
|
174
|
+
return basis == null;
|
|
175
|
+
if (basis == null)
|
|
176
|
+
return false;
|
|
177
|
+
return sameStoredRow(row, basis) &&
|
|
178
|
+
(!opts.wholeRow || isDeepStrictEqual({ ...row }, basis)) &&
|
|
179
|
+
(opts.matchFields ?? []).every((field) => isDeepStrictEqual(row[field], basis[field]));
|
|
180
|
+
};
|
|
181
|
+
if (opts.pausePre) {
|
|
182
|
+
const pre = opts.pausePre();
|
|
183
|
+
if (pre)
|
|
184
|
+
await pre;
|
|
185
|
+
}
|
|
186
|
+
for (let attempt = 1;; attempt++) {
|
|
187
|
+
try {
|
|
188
|
+
return await withOwnedTransaction(opts.ctx, async (c) => {
|
|
189
|
+
const row = await table.get(id, c);
|
|
190
|
+
if (opts.matches && !opts.matches(row))
|
|
191
|
+
return { skip: true };
|
|
192
|
+
const decision = await plan(row);
|
|
193
|
+
if ("skip" in decision)
|
|
194
|
+
return decision;
|
|
195
|
+
if (!sameTarget(row))
|
|
196
|
+
throw new WriteBackConflictError(opts.label, id, attempt);
|
|
197
|
+
// Test-only: inert unless the fault-injection opt-in is armed.
|
|
198
|
+
if (opts.pausePoint) {
|
|
199
|
+
const pause = opts.pausePoint();
|
|
200
|
+
if (pause)
|
|
201
|
+
await pause;
|
|
202
|
+
}
|
|
203
|
+
if ("update" in decision)
|
|
204
|
+
await applyFieldUpdate(table, id, decision.update, c);
|
|
205
|
+
else
|
|
206
|
+
await table.put(decision.write, c);
|
|
207
|
+
await confirmCommittedRow(table, id, (committed) => isDeepStrictEqual(committed, row));
|
|
208
|
+
return decision;
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
catch (err) {
|
|
212
|
+
if (!(err instanceof CommittedRowChanged))
|
|
213
|
+
throw err;
|
|
214
|
+
if (attempt >= attempts)
|
|
215
|
+
throw new WriteBackConflictError(opts.label, id, attempts);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const ENGINE_VERSION_STAMP = "engine-version.txt";
|
package/dist/src/keystore.js
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
12
12
|
import { join } from "node:path";
|
|
13
13
|
import { resolveHome } from "./lib/home.js";
|
|
14
|
+
import { writeFilesAtomically } from "./lib/atomic-write.js";
|
|
14
15
|
import { randomBytes, createCipheriv, createDecipheriv, hkdfSync, } from "node:crypto";
|
|
15
16
|
// ─── Helpers ────────────────────────────────────────────────────────────────
|
|
16
17
|
/**
|
|
@@ -120,5 +121,76 @@ class FileKeyStore {
|
|
|
120
121
|
}
|
|
121
122
|
/** Singleton keystore instance. */
|
|
122
123
|
export const keystore = new FileKeyStore();
|
|
124
|
+
// ─── Seed ownership sidecars (flair#2200) ───────────────────────────────────
|
|
125
|
+
/** File name suffix of a seed's ownership sidecar, appended to the seed path. */
|
|
126
|
+
export const SEED_OWNER_SUFFIX = ".owner.json";
|
|
127
|
+
/** The sidecar's schema version. */
|
|
128
|
+
export const SEED_OWNER_VERSION = 1;
|
|
129
|
+
/** The sidecar path for `instanceId` — the seed path plus the owner suffix. */
|
|
130
|
+
export function seedOwnerPath(instanceId) {
|
|
131
|
+
return `${keyPath(instanceId)}${SEED_OWNER_SUFFIX}`;
|
|
132
|
+
}
|
|
133
|
+
/** Serialize an ownership record to the exact bytes the sidecar holds. */
|
|
134
|
+
export function serializeSeedOwner(record) {
|
|
135
|
+
return `${JSON.stringify(record)}\n`;
|
|
136
|
+
}
|
|
137
|
+
/** Parse sidecar bytes into a read result. Pure — no filesystem access. */
|
|
138
|
+
export function parseSeedOwner(raw) {
|
|
139
|
+
let value;
|
|
140
|
+
try {
|
|
141
|
+
value = JSON.parse(raw);
|
|
142
|
+
}
|
|
143
|
+
catch (err) {
|
|
144
|
+
return { state: "malformed", reason: `not valid JSON (${err instanceof Error ? err.message : String(err)})` };
|
|
145
|
+
}
|
|
146
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
147
|
+
return { state: "malformed", reason: "not a JSON object" };
|
|
148
|
+
}
|
|
149
|
+
const rec = value;
|
|
150
|
+
if (rec.v !== SEED_OWNER_VERSION) {
|
|
151
|
+
return { state: "malformed", reason: `unsupported owner-record version ${JSON.stringify(rec.v)}` };
|
|
152
|
+
}
|
|
153
|
+
if (typeof rec.instanceId !== "string" || rec.instanceId.trim() === "") {
|
|
154
|
+
return { state: "malformed", reason: "no instance id" };
|
|
155
|
+
}
|
|
156
|
+
if (typeof rec.dataDir !== "string" || rec.dataDir.trim() === "") {
|
|
157
|
+
return { state: "malformed", reason: "no data directory" };
|
|
158
|
+
}
|
|
159
|
+
return { state: "ok", instanceId: rec.instanceId, dataDir: rec.dataDir };
|
|
160
|
+
}
|
|
161
|
+
/** Read a sidecar from its path, distinguishing absent / unreadable / malformed. */
|
|
162
|
+
export function readSeedOwnerAt(ownerPath) {
|
|
163
|
+
if (!existsSync(ownerPath))
|
|
164
|
+
return { state: "absent" };
|
|
165
|
+
let raw;
|
|
166
|
+
try {
|
|
167
|
+
raw = readFileSync(ownerPath, "utf-8");
|
|
168
|
+
}
|
|
169
|
+
catch (err) {
|
|
170
|
+
return { state: "unreadable", reason: err instanceof Error ? err.message : String(err) };
|
|
171
|
+
}
|
|
172
|
+
return parseSeedOwner(raw);
|
|
173
|
+
}
|
|
174
|
+
/** Read the ownership sidecar for `instanceId`, if any. */
|
|
175
|
+
export function readSeedOwner(instanceId) {
|
|
176
|
+
return readSeedOwnerAt(seedOwnerPath(instanceId));
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Record an instance seed's owner: write the sidecar atomically (owner-only,
|
|
180
|
+
* mode 0600) beside the seed. The writer is the mint; a reader never invents
|
|
181
|
+
* one. Throws on a write failure — the caller decides whether that is fatal.
|
|
182
|
+
*/
|
|
183
|
+
export function recordSeedOwner(instanceId, dataDir) {
|
|
184
|
+
const dir = keysDir();
|
|
185
|
+
if (!existsSync(dir))
|
|
186
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
187
|
+
writeFilesAtomically([
|
|
188
|
+
{
|
|
189
|
+
path: seedOwnerPath(instanceId),
|
|
190
|
+
content: serializeSeedOwner({ v: SEED_OWNER_VERSION, instanceId, dataDir }),
|
|
191
|
+
mode: 0o600,
|
|
192
|
+
},
|
|
193
|
+
]);
|
|
194
|
+
}
|
|
123
195
|
// Export helpers for testing
|
|
124
196
|
export { encryptSeed, decryptSeed, deriveKey, keyPath, keysDir };
|