@spellkave/sdk 0.0.0-bootstrap → 0.0.0-stage

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/README.md +2 -155
  2. package/package.json +4 -63
  3. package/LICENSE +0 -89
  4. package/src/binding_rows.ts +0 -186
  5. package/src/connection.ts +0 -964
  6. package/src/core/actor.ts +0 -62
  7. package/src/core/actor_control.ts +0 -193
  8. package/src/core/actor_control_query_methods.ts +0 -101
  9. package/src/core/actor_control_reaction_methods.ts +0 -79
  10. package/src/core/actor_control_sense_methods.ts +0 -81
  11. package/src/core/actor_control_source.ts +0 -57
  12. package/src/core/actor_session_methods.ts +0 -226
  13. package/src/core/binding_drift.ts +0 -301
  14. package/src/core/credential.ts +0 -259
  15. package/src/core/driver_control.ts +0 -54
  16. package/src/core/effective_environment_state.ts +0 -71
  17. package/src/core/factored_manipulation_attempt.ts +0 -158
  18. package/src/core/ids.ts +0 -60
  19. package/src/core/interaction/canonical.ts +0 -15
  20. package/src/core/interaction/fingerprint.ts +0 -118
  21. package/src/core/interaction/index.ts +0 -31
  22. package/src/core/interaction/intent.ts +0 -284
  23. package/src/core/interaction/outcome.ts +0 -67
  24. package/src/core/interaction/rejection_ledger.ts +0 -108
  25. package/src/core/kernel_contract.generated.ts +0 -10
  26. package/src/core/log.ts +0 -23
  27. package/src/core/movement.ts +0 -111
  28. package/src/core/node-io.ts +0 -208
  29. package/src/core/paths.ts +0 -220
  30. package/src/core/profile.ts +0 -270
  31. package/src/core/profiles.ts +0 -9
  32. package/src/core/provenance_buffer.ts +0 -102
  33. package/src/core/readers/_helpers.ts +0 -273
  34. package/src/core/readers/action_description.ts +0 -17
  35. package/src/core/readers/action_economy_events.ts +0 -149
  36. package/src/core/readers/actor_body_swaps.ts +0 -62
  37. package/src/core/readers/actor_snapshot.ts +0 -197
  38. package/src/core/readers/actor_states.ts +0 -163
  39. package/src/core/readers/actors_and_bodies.ts +0 -179
  40. package/src/core/readers/affordance_cue.ts +0 -59
  41. package/src/core/readers/affordance_defaults.ts +0 -158
  42. package/src/core/readers/affordance_group_membership.ts +0 -67
  43. package/src/core/readers/affordance_input.ts +0 -129
  44. package/src/core/readers/affordance_reference.ts +0 -41
  45. package/src/core/readers/apply_consequences.ts +0 -54
  46. package/src/core/readers/audience_trace_presentation.ts +0 -62
  47. package/src/core/readers/bounded_collection.ts +0 -29
  48. package/src/core/readers/bundle_definitions.ts +0 -74
  49. package/src/core/readers/bundle_entities.ts +0 -62
  50. package/src/core/readers/co_location.ts +0 -71
  51. package/src/core/readers/combat_session.ts +0 -124
  52. package/src/core/readers/combat_session_active.ts +0 -44
  53. package/src/core/readers/combat_session_feedback.ts +0 -37
  54. package/src/core/readers/combat_session_grid.ts +0 -117
  55. package/src/core/readers/combat_session_roster.ts +0 -98
  56. package/src/core/readers/combat_session_types.ts +0 -51
  57. package/src/core/readers/condition_deltas.ts +0 -53
  58. package/src/core/readers/container_contents.ts +0 -92
  59. package/src/core/readers/dialogue_guide.ts +0 -99
  60. package/src/core/readers/dialogue_prompt_presentation.ts +0 -90
  61. package/src/core/readers/driver_control.ts +0 -64
  62. package/src/core/readers/entity_art.ts +0 -219
  63. package/src/core/readers/entity_containment.ts +0 -119
  64. package/src/core/readers/equipment.ts +0 -99
  65. package/src/core/readers/intervention_windows.ts +0 -136
  66. package/src/core/readers/inventory_query.ts +0 -145
  67. package/src/core/readers/item_detail.ts +0 -198
  68. package/src/core/readers/location_snapshot.ts +0 -216
  69. package/src/core/readers/manifest_apply_provenance.ts +0 -32
  70. package/src/core/readers/manifest_export.ts +0 -81
  71. package/src/core/readers/manipulation_context.ts +0 -475
  72. package/src/core/readers/map_layers.ts +0 -49
  73. package/src/core/readers/metadata_rows.ts +0 -56
  74. package/src/core/readers/object_state.ts +0 -124
  75. package/src/core/readers/observer_knowledge.ts +0 -41
  76. package/src/core/readers/observer_place_knowledge.ts +0 -37
  77. package/src/core/readers/observer_trace_knowledge.ts +0 -45
  78. package/src/core/readers/outcome_template.ts +0 -41
  79. package/src/core/readers/place_topology.ts +0 -109
  80. package/src/core/readers/reaction_options.ts +0 -156
  81. package/src/core/readers/resource_deltas.ts +0 -47
  82. package/src/core/readers/scene.ts +0 -275
  83. package/src/core/readers/seats.ts +0 -33
  84. package/src/core/readers/self.ts +0 -245
  85. package/src/core/readers/self_capabilities.ts +0 -159
  86. package/src/core/readers/self_economy.ts +0 -101
  87. package/src/core/readers/self_economy_budget.ts +0 -93
  88. package/src/core/readers/self_evaluations.ts +0 -128
  89. package/src/core/readers/self_identity.ts +0 -104
  90. package/src/core/readers/sense_context.ts +0 -112
  91. package/src/core/readers/session.ts +0 -207
  92. package/src/core/readers/session_detail.ts +0 -211
  93. package/src/core/readers/session_status.ts +0 -68
  94. package/src/core/readers/spatial_environment_state.ts +0 -74
  95. package/src/core/readers/spatial_niche_attachments.ts +0 -28
  96. package/src/core/readers/substrate_definitions.ts +0 -27
  97. package/src/core/readers/suggest_next_action.ts +0 -72
  98. package/src/core/readers/surface_membership.ts +0 -78
  99. package/src/core/readers/tag_reads.ts +0 -54
  100. package/src/core/readers/trace_query.ts +0 -120
  101. package/src/core/readers/trace_response.ts +0 -80
  102. package/src/core/readers/traces.ts +0 -124
  103. package/src/core/readers/travel_session.ts +0 -88
  104. package/src/core/readers/turn_state.ts +0 -34
  105. package/src/core/readers/world_events.ts +0 -43
  106. package/src/core/readers/world_status.ts +0 -63
  107. package/src/core/reducers/manipulation_args.ts +0 -239
  108. package/src/core/reducers/manipulation_receipt.ts +0 -66
  109. package/src/core/reducers/r_actor_wake_up.ts +0 -32
  110. package/src/core/reducers/r_inscribe_trace.ts +0 -109
  111. package/src/core/reducers/r_manipulate.ts +0 -163
  112. package/src/core/reducers/r_move.ts +0 -155
  113. package/src/core/reducers/r_react.ts +0 -143
  114. package/src/core/reducers/r_release_claim.ts +0 -81
  115. package/src/core/reducers/r_sense.ts +0 -84
  116. package/src/core/reducers/r_session_close.ts +0 -130
  117. package/src/core/reducers/r_session_move.ts +0 -116
  118. package/src/core/reducers/r_session_open.ts +0 -91
  119. package/src/core/reducers/session_lookup.ts +0 -64
  120. package/src/core/reducers/tick.ts +0 -65
  121. package/src/core/reducers/trace_lookup.ts +0 -29
  122. package/src/core/reducers/transport.ts +0 -84
  123. package/src/core/resolve.ts +0 -228
  124. package/src/core/shape_telemetry.ts +0 -146
  125. package/src/core/snapshot_rows.ts +0 -109
  126. package/src/core/tick_cadence.ts +0 -61
  127. package/src/core/types.ts +0 -501
  128. package/src/core/watch_provenance.ts +0 -113
  129. package/src/core/world-contract/classify.ts +0 -38
  130. package/src/core/world-contract/index.ts +0 -12
  131. package/src/core/world-contract/normalise.ts +0 -574
  132. package/src/core/world-contract/runtime.ts +0 -144
  133. package/src/core/world-contract/served.ts +0 -173
  134. package/src/core/world-contract/strict-reducers.ts +0 -14
  135. package/src/core/world-contract/typetext.ts +0 -94
  136. package/src/core/world_time.ts +0 -22
  137. package/src/index.ts +0 -262
  138. package/src/manifest-apply.ts +0 -497
  139. package/src/provenance.ts +0 -568
  140. package/src/reader-manifest.ts +0 -338
  141. package/src/readers.ts +0 -392
  142. package/src/replay.ts +0 -515
  143. package/src/watch-buffer.ts +0 -438
  144. package/src/world-events/builder.ts +0 -1042
package/src/core/paths.ts DELETED
@@ -1,220 +0,0 @@
1
- // XDG / SPELLKAVE_HOME path resolution for the Spellkave pi extension.
2
- //
3
- // Mirrors the Rust contract in `client/src/paths.rs`:
4
- // * SPELLKAVE_HOME override → <root>/{config,state,cache}
5
- // * otherwise XDG defaults on every platform (including macOS and Windows):
6
- // config: ${XDG_CONFIG_HOME:-$HOME/.config}/spellkave
7
- // state: ${XDG_STATE_HOME:-$HOME/.local/state}/spellkave
8
- // cache: ${XDG_CACHE_HOME:-$HOME/.cache}/spellkave
9
- // * profile names go through the same validation rules as the Rust CLI.
10
- //
11
- // The Rust CLI does NOT use `directories`/`ProjectDirs` — it uses XDG directly,
12
- // so we must not branch on `darwin`/`win32` to native app-data roots. Doing so
13
- // forks persona state from the CLI (BUG-001).
14
- //
15
- // This module is browser-reachable through the `@spellkave/sdk` barrel, so it
16
- // MUST NOT import Node builtins at the top level (see `node-io.ts`). Path
17
- // joining is pure string work (XDG forward-slash on every platform, matching
18
- // the Rust contract); the `home` default lives in the Node-only `node-io.ts`.
19
-
20
- export const ENV_OVERRIDE_ROOT = "SPELLKAVE_HOME";
21
- const APP_NAME = "spellkave";
22
-
23
- /**
24
- * Pure POSIX-style path join. The XDG contract above is forward-slash on every
25
- * platform (matching the Rust CLI), and profile names are `..`/separator-free
26
- * by `validateProfileName`, so a segment join + slash collapse is faithful to
27
- * `node:path`'s `join` for every path this module builds — without dragging
28
- * `node:path` into the browser bundle.
29
- */
30
- function joinPath(...segments: string[]): string {
31
- return segments
32
- .filter((s) => s.length > 0)
33
- .join("/")
34
- .replace(/\/{2,}/g, "/");
35
- }
36
-
37
- export interface CliPaths {
38
- config: string;
39
- state: string;
40
- cache: string;
41
- }
42
-
43
- export interface CliPathsEnv {
44
- /** Process env. Tests inject a synthetic record. */
45
- env?: NodeJS.ProcessEnv;
46
- /** Home dir override for tests. */
47
- home?: string;
48
- /**
49
- * Platform override for tests. Accepted but ignored — path resolution is
50
- * XDG on every platform. Kept so existing call sites compile.
51
- */
52
- platform?: NodeJS.Platform;
53
- }
54
-
55
- /**
56
- * Resolve XDG-style roots for the installed Spellkave CLI / extension.
57
- * Honors SPELLKAVE_HOME first, then falls back to platform conventions.
58
- */
59
- export function resolveCliPaths(opts: CliPathsEnv = {}): CliPaths {
60
- const env = opts.env ?? process.env;
61
-
62
- const override = env[ENV_OVERRIDE_ROOT];
63
- if (override && override.length > 0) {
64
- return {
65
- config: joinPath(override, "config"),
66
- state: joinPath(override, "state"),
67
- cache: joinPath(override, "cache"),
68
- };
69
- }
70
-
71
- // XDG fallback needs a home dir. This module is pure, so the Node-bound
72
- // `homedir()` default is injected by `@spellkave/sdk/node`'s wrapper.
73
- const home = opts.home;
74
- if (home === undefined) {
75
- throw new Error(
76
- "resolveCliPaths requires opts.home outside SPELLKAVE_HOME; use @spellkave/sdk/node for the Node-bound default",
77
- );
78
- }
79
-
80
- // XDG on every platform — must match the Rust CLI on macOS/Windows too.
81
- const configHome =
82
- env.XDG_CONFIG_HOME && env.XDG_CONFIG_HOME.length > 0
83
- ? env.XDG_CONFIG_HOME
84
- : joinPath(home, ".config");
85
- const stateHome =
86
- env.XDG_STATE_HOME && env.XDG_STATE_HOME.length > 0
87
- ? env.XDG_STATE_HOME
88
- : joinPath(home, ".local", "state");
89
- const cacheHome =
90
- env.XDG_CACHE_HOME && env.XDG_CACHE_HOME.length > 0
91
- ? env.XDG_CACHE_HOME
92
- : joinPath(home, ".cache");
93
- return {
94
- config: joinPath(configHome, APP_NAME),
95
- state: joinPath(stateHome, APP_NAME),
96
- cache: joinPath(cacheHome, APP_NAME),
97
- };
98
- }
99
-
100
- export const APP_CONFIG_FILENAME = "config.toml";
101
- /** Legacy app-global last-used file. Production reads ignore it (sk-sol / sk-1p83). */
102
- export const LAST_USED_PROFILE_FILENAME = "last_used_profile";
103
- /** One remembered profile per git worktree root — matches `client/src/state.rs`. */
104
- export const LAST_USED_PROFILES_DIR = "last_used_profiles/by_worktree";
105
- /**
106
- * One explicitly selected author context per git worktree root (change
107
- * `sk-config-contexts`). Same hash and shape as the last-used pointer, but
108
- * only `sk config use-context` and `sk dev up` write it.
109
- */
110
- export const CURRENT_CONTEXT_DIR = "current_context/by_worktree";
111
-
112
- export function appConfigFile(paths: CliPaths): string {
113
- return joinPath(paths.config, APP_CONFIG_FILENAME);
114
- }
115
-
116
- export function profilesDir(paths: CliPaths): string {
117
- return joinPath(paths.config, "profiles");
118
- }
119
-
120
- export function profileFile(paths: CliPaths, name: string): string {
121
- return joinPath(profilesDir(paths), `${name}.toml`);
122
- }
123
-
124
- export function checkedProfileFile(paths: CliPaths, name: string): string {
125
- validateProfileName(name);
126
- return profileFile(paths, name);
127
- }
128
-
129
- export function personaStateDir(paths: CliPaths, profile: string): string {
130
- return joinPath(paths.state, "personas", profile);
131
- }
132
-
133
- export function checkedPersonaStateDir(paths: CliPaths, profile: string): string {
134
- validateProfileName(profile);
135
- return personaStateDir(paths, profile);
136
- }
137
-
138
- export function lastUsedProfileFile(paths: CliPaths): string {
139
- return joinPath(paths.state, LAST_USED_PROFILE_FILENAME);
140
- }
141
-
142
- /**
143
- * FNV-1a 64-bit, matching `client/src/state.rs` `stable_scope_key` so the
144
- * TypeScript hosts and the Rust CLI remember the same per-worktree pointer.
145
- */
146
- export function worktreeScopeKey(worktreeRoot: string): string {
147
- let hash = 0xcbf29ce484222325n;
148
- const prime = 0x100000001b3n;
149
- const mask = 0xffffffffffffffffn;
150
- for (const byte of new TextEncoder().encode(worktreeRoot)) {
151
- hash ^= BigInt(byte);
152
- hash = (hash * prime) & mask;
153
- }
154
- return hash.toString(16).padStart(16, "0");
155
- }
156
-
157
- export function scopedLastUsedProfileFile(paths: CliPaths, worktreeRoot: string): string {
158
- return joinPath(paths.state, LAST_USED_PROFILES_DIR, worktreeScopeKey(worktreeRoot));
159
- }
160
-
161
- export function scopedCurrentContextFile(paths: CliPaths, worktreeRoot: string): string {
162
- return joinPath(paths.state, CURRENT_CONTEXT_DIR, worktreeScopeKey(worktreeRoot));
163
- }
164
-
165
- /**
166
- * Name of the local-node profile `sk dev up` owns for one worktree:
167
- * `local-<dir name>-<first 6 hex of worktreeScopeKey>`. Profiles are global,
168
- * so the hash keeps two clones with the same directory name apart.
169
- */
170
- export function localNodeProfileName(worktreeRoot: string): string {
171
- const trimmed = worktreeRoot.replace(/[/\\]+$/, "");
172
- const base = trimmed.slice(Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\")) + 1);
173
- const safe = base.replace(/[^A-Za-z0-9_-]+/g, "-").replace(/^[-.]+/, "") || "worktree";
174
- return `local-${safe}-${worktreeScopeKey(worktreeRoot).slice(0, 6)}`;
175
- }
176
-
177
- const LOCAL_NODE_PROFILE = /^local-.+-[0-9a-f]{6}$/;
178
- const LOOPBACK_HOSTS = new Set(["127.0.0.1", "::1", "[::1]", "localhost"]);
179
-
180
- /**
181
- * True for a profile `sk dev up` wrote: the `local-<worktree>-<6 hex>` name
182
- * pattern AND a loopback URL. Only such a profile may omit its credential and
183
- * fall back to the local SpacetimeDB client credential (sk-config-contexts D3).
184
- */
185
- export function isLocalNodeProfile(name: string, url: string): boolean {
186
- if (!LOCAL_NODE_PROFILE.test(name)) return false;
187
- try {
188
- return LOOPBACK_HOSTS.has(new URL(url).hostname);
189
- } catch {
190
- return false;
191
- }
192
- }
193
-
194
- /**
195
- * Reject profile names that could escape the `profiles/` directory or
196
- * abuse the filesystem. Mirrors the Rust `validate_profile_name` exactly:
197
- * * non-empty
198
- * * does not start with `.`
199
- * * no `..` substring
200
- * * no `/`, `\`, or NUL bytes
201
- *
202
- * Throws on rejection. Use this on every name reaching the filesystem from
203
- * user input (including the optional `/spellkave <profile-name>` argument).
204
- */
205
- export function validateProfileName(name: string): void {
206
- if (name.length === 0) {
207
- throw new Error("profile name must not be empty");
208
- }
209
- if (name.startsWith(".")) {
210
- throw new Error(`profile name must not start with '.' (rejects '..', hidden files): ${name}`);
211
- }
212
- if (name.includes("..")) {
213
- throw new Error(`profile name must not contain '..' (path traversal): ${name}`);
214
- }
215
- for (const c of name) {
216
- if (c === "/" || c === "\\" || c === "\0") {
217
- throw new Error(`profile name must not contain path separators or NUL: ${name}`);
218
- }
219
- }
220
- }
@@ -1,270 +0,0 @@
1
- // Persona-profile + app-config TOML model and loaders.
2
- //
3
- // Mirrors the Rust types in `client/src/config.rs` and `client/src/config_io.rs`:
4
- //
5
- // AppConfig {
6
- // default_profile: Option<String>,
7
- // }
8
- //
9
- // PersonaProfile {
10
- // connection: { url, db, env? }
11
- // identity: { role, in_world_self, credential? }
12
- // defaults: { mode? }
13
- // }
14
- //
15
- // The Rust code uses `serde(deny_unknown_fields)`. We mirror that here by
16
- // rejecting any top-level / table keys that are not in the schema. This
17
- // prevents host-private extensions to the profile shape from drifting away
18
- // from the Rust contract.
19
-
20
- import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
21
-
22
- import type { CredentialRef } from "./credential";
23
-
24
- export interface AppConfig {
25
- default_profile?: string;
26
- }
27
-
28
- export interface ConnectionConfig {
29
- url: string;
30
- db: string;
31
- env?: string;
32
- }
33
-
34
- export interface IdentityConfig {
35
- role: string;
36
- in_world_self: string;
37
- credential?: CredentialRef;
38
- }
39
-
40
- export interface PersonaDefaults {
41
- mode?: string;
42
- }
43
-
44
- export interface PersonaProfile {
45
- connection: ConnectionConfig;
46
- identity: IdentityConfig;
47
- defaults: PersonaDefaults;
48
- }
49
-
50
- const APP_CONFIG_KEYS = new Set(["default_profile"]);
51
- const PROFILE_TABLES = new Set(["connection", "identity", "defaults"]);
52
- const CONNECTION_KEYS = new Set(["url", "db", "env"]);
53
- const IDENTITY_KEYS = new Set(["role", "in_world_self", "credential"]);
54
- const DEFAULTS_KEYS = new Set(["mode"]);
55
-
56
- export function parseAppConfig(text: string): AppConfig {
57
- const raw = parseToml(text) as Record<string, unknown>;
58
- for (const k of Object.keys(raw)) {
59
- if (!APP_CONFIG_KEYS.has(k)) {
60
- throw new Error(`unknown field in config.toml: '${k}'`);
61
- }
62
- }
63
- const out: AppConfig = {};
64
- if (raw.default_profile !== undefined) {
65
- if (typeof raw.default_profile !== "string") {
66
- throw new Error("config.toml default_profile must be a string");
67
- }
68
- out.default_profile = raw.default_profile;
69
- }
70
- return out;
71
- }
72
-
73
- export function parsePersonaProfile(text: string): PersonaProfile {
74
- const raw = parseToml(text) as Record<string, unknown>;
75
- for (const k of Object.keys(raw)) {
76
- if (!PROFILE_TABLES.has(k)) {
77
- throw new Error(`unknown table in profile: '${k}'`);
78
- }
79
- }
80
- const connection = parseConnectionTable(raw.connection);
81
- const identity = parseIdentityTable(raw.identity);
82
- const defaults = parseDefaultsTable(raw.defaults);
83
- return { connection, identity, defaults };
84
- }
85
-
86
- function parseConnectionTable(raw: unknown): ConnectionConfig {
87
- if (raw === undefined) {
88
- throw new Error("profile missing required [connection] table");
89
- }
90
- if (typeof raw !== "object" || raw === null) {
91
- throw new Error("profile [connection] is not a table");
92
- }
93
- const obj = raw as Record<string, unknown>;
94
- for (const k of Object.keys(obj)) {
95
- if (!CONNECTION_KEYS.has(k)) {
96
- throw new Error(`unknown field in [connection]: '${k}'`);
97
- }
98
- }
99
- const url = requireString(obj, "connection.url");
100
- const db = requireString(obj, "connection.db");
101
- const env = optionalString(obj, "connection.env");
102
- return env === undefined ? { url, db } : { url, db, env };
103
- }
104
-
105
- function parseIdentityTable(raw: unknown): IdentityConfig {
106
- if (raw === undefined) {
107
- throw new Error("profile missing required [identity] table");
108
- }
109
- if (typeof raw !== "object" || raw === null) {
110
- throw new Error("profile [identity] is not a table");
111
- }
112
- const obj = raw as Record<string, unknown>;
113
- for (const k of Object.keys(obj)) {
114
- if (!IDENTITY_KEYS.has(k)) {
115
- throw new Error(`unknown field in [identity]: '${k}'`);
116
- }
117
- }
118
- const role = requireString(obj, "identity.role");
119
- const in_world_self = requireString(obj, "identity.in_world_self");
120
- const credential = parseCredentialRef(obj.credential);
121
- return credential === undefined ? { role, in_world_self } : { role, in_world_self, credential };
122
- }
123
-
124
- function parseDefaultsTable(raw: unknown): PersonaDefaults {
125
- if (raw === undefined) return {};
126
- if (typeof raw !== "object" || raw === null) {
127
- throw new Error("profile [defaults] is not a table");
128
- }
129
- const obj = raw as Record<string, unknown>;
130
- for (const k of Object.keys(obj)) {
131
- if (!DEFAULTS_KEYS.has(k)) {
132
- throw new Error(`unknown field in [defaults]: '${k}'`);
133
- }
134
- }
135
- const mode = optionalString(obj, "defaults.mode");
136
- return mode === undefined ? {} : { mode };
137
- }
138
-
139
- function parseCredentialRef(raw: unknown): CredentialRef | undefined {
140
- if (raw === undefined) return undefined;
141
- if (typeof raw !== "object" || raw === null) {
142
- throw new Error("identity.credential must be an inline table");
143
- }
144
- const obj = raw as Record<string, unknown>;
145
- const kind = obj.kind;
146
- if (typeof kind !== "string") {
147
- throw new Error("identity.credential.kind is required (env_var | file | inline)");
148
- }
149
- switch (kind) {
150
- case "env_var": {
151
- const name = requireString(obj, "identity.credential.name");
152
- const allowed = new Set(["kind", "name"]);
153
- checkOnlyKeys(obj, allowed, "identity.credential");
154
- return { kind: "env_var", name };
155
- }
156
- case "file": {
157
- const path = requireString(obj, "identity.credential.path");
158
- const allowed = new Set(["kind", "path"]);
159
- checkOnlyKeys(obj, allowed, "identity.credential");
160
- return { kind: "file", path };
161
- }
162
- case "inline": {
163
- const value = requireString(obj, "identity.credential.value");
164
- const allowed = new Set(["kind", "value"]);
165
- checkOnlyKeys(obj, allowed, "identity.credential");
166
- return { kind: "inline", value };
167
- }
168
- default:
169
- throw new Error(`identity.credential.kind '${kind}' is not one of env_var | file | inline`);
170
- }
171
- }
172
-
173
- function requireString(obj: Record<string, unknown>, label: string): string {
174
- const v = obj[label.split(".").pop() ?? label];
175
- if (typeof v !== "string") {
176
- throw new Error(`${label} is required and must be a string`);
177
- }
178
- return v;
179
- }
180
-
181
- function optionalString(obj: Record<string, unknown>, label: string): string | undefined {
182
- const key = label.split(".").pop() ?? label;
183
- const v = obj[key];
184
- if (v === undefined) return undefined;
185
- if (typeof v !== "string") {
186
- throw new Error(`${label} must be a string when present`);
187
- }
188
- return v;
189
- }
190
-
191
- function checkOnlyKeys(obj: Record<string, unknown>, allowed: Set<string>, label: string): void {
192
- for (const k of Object.keys(obj)) {
193
- if (!allowed.has(k)) {
194
- throw new Error(`unknown field in ${label}: '${k}'`);
195
- }
196
- }
197
- }
198
-
199
- /**
200
- * Cross-field validity for a parsed profile. Mirrors Rust
201
- * `validate_persona_contract`: connection/identity strings must not be empty.
202
- */
203
- export function validatePersonaContract(profile: PersonaProfile): void {
204
- const c = profile.connection;
205
- if (c.url.trim().length === 0) {
206
- throw new Error("profile connection.url must not be empty");
207
- }
208
- if (c.db.trim().length === 0) {
209
- throw new Error("profile connection.db must not be empty");
210
- }
211
- const id = profile.identity;
212
- if (id.role.trim().length === 0) {
213
- throw new Error("profile identity.role must not be empty");
214
- }
215
- if (id.in_world_self.trim().length === 0) {
216
- throw new Error("profile identity.in_world_self must not be empty");
217
- }
218
- }
219
-
220
- /**
221
- * Render a profile as TOML that `parsePersonaProfile` reads back unchanged.
222
- * `header` lines are written as leading `#` comments.
223
- */
224
- export function serializePersonaProfile(
225
- profile: PersonaProfile,
226
- header: readonly string[] = [],
227
- ): string {
228
- const body: Record<string, unknown> = {
229
- connection: { ...profile.connection },
230
- identity: { ...profile.identity },
231
- };
232
- if (Object.keys(profile.defaults).length > 0) body.defaults = { ...profile.defaults };
233
- const comments = header.map((line) => `# ${line}`.trimEnd()).join("\n");
234
- return `${comments.length > 0 ? `${comments}\n` : ""}${stringifyToml(body)}\n`;
235
- }
236
-
237
- export interface ProfileIo {
238
- readFileSync?: (path: string) => string;
239
- }
240
-
241
- export function loadAppConfigFromDisk(path: string, io: ProfileIo = {}): AppConfig {
242
- const text = read(path, io);
243
- if (text === undefined) return {};
244
- return parseAppConfig(text);
245
- }
246
-
247
- export function loadProfileFromDisk(path: string, io: ProfileIo = {}): PersonaProfile {
248
- const text = read(path, io);
249
- if (text === undefined) {
250
- throw new Error(`profile file not found: ${path}`);
251
- }
252
- const profile = parsePersonaProfile(text);
253
- validatePersonaContract(profile);
254
- return profile;
255
- }
256
-
257
- function read(path: string, io: ProfileIo): string | undefined {
258
- const reader = io.readFileSync;
259
- if (reader === undefined) {
260
- throw new Error(
261
- "profile loaders require io.readFileSync; use @spellkave/sdk/node for the Node-bound default",
262
- );
263
- }
264
- try {
265
- return reader(path);
266
- } catch (err: unknown) {
267
- if ((err as NodeJS.ErrnoException)?.code === "ENOENT") return undefined;
268
- throw err;
269
- }
270
- }
@@ -1,9 +0,0 @@
1
- // `@spellkave/sdk/profiles`: the persona-profile file contract without the
2
- // bindings or a connection (paths, profile TOML, pointer reads). For hosts that
3
- // only manage profiles, such as the `sk dev` plugin, and must not pull the
4
- // generated bindings into their type check.
5
-
6
- export * from "./credential";
7
- export * from "./paths";
8
- export * from "./profile";
9
- export { readCurrentContext, readLastUsedProfile } from "./resolve";
@@ -1,102 +0,0 @@
1
- // Per-subject FIFO ring buffer for evaluation_provenance rows.
2
- //
3
- // D-B note: EvaluationProvenanceRow has no correlationId field.
4
- // Secondary index uses bundleId as the correlation key.
5
- // This was verified against the generated binding at
6
- // packages/spellkave-bindings/src/module_bindings/visible_evaluation_provenance_table.ts.
7
-
8
- import type { ProvenanceRow, ProvenanceWatermark } from "../provenance";
9
-
10
- export interface ProvenanceBufferConfig {
11
- connectedCap: number;
12
- perSubjectCap: number;
13
- }
14
-
15
- const DEFAULT_CONFIG: ProvenanceBufferConfig = {
16
- connectedCap: 512,
17
- perSubjectCap: 200,
18
- };
19
-
20
- export class ProvenanceRingBuffer {
21
- private readonly config: ProvenanceBufferConfig;
22
- private readonly connectedActorId: string;
23
- // Primary index: subjectId → ordered ProvenanceRow[] (insertion order, oldest first)
24
- private readonly bySubject = new Map<string, ProvenanceRow[]>();
25
- // Secondary index: bundleId → ProvenanceRow[] (multiple rows can share a bundle)
26
- private readonly byBundle = new Map<string, ProvenanceRow[]>();
27
-
28
- constructor(connectedActorId: string, config: Partial<ProvenanceBufferConfig> = {}) {
29
- this.connectedActorId = connectedActorId;
30
- this.config = { ...DEFAULT_CONFIG, ...config };
31
- }
32
-
33
- insert(row: ProvenanceRow): void {
34
- const cap =
35
- row.subject_id === this.connectedActorId
36
- ? this.config.connectedCap
37
- : this.config.perSubjectCap;
38
-
39
- let bucket = this.bySubject.get(row.subject_id);
40
- if (!bucket) {
41
- bucket = [];
42
- this.bySubject.set(row.subject_id, bucket);
43
- }
44
-
45
- // Evict oldest if at capacity
46
- while (bucket.length >= cap) {
47
- const evicted = bucket.shift();
48
- if (evicted) this._removeFromBundleIndex(evicted);
49
- }
50
-
51
- bucket.push(row);
52
- this._addToBundleIndex(row);
53
- }
54
-
55
- forSubject(subjectId: string): ProvenanceRow[] {
56
- return this.bySubject.get(subjectId)?.slice() ?? [];
57
- }
58
-
59
- subjectIds(): readonly string[] {
60
- return [...this.bySubject.keys()];
61
- }
62
-
63
- byCorrelationId(bundleId: string): ProvenanceRow[] {
64
- return this.byBundle.get(bundleId)?.slice() ?? [];
65
- }
66
-
67
- latestWatermark(): ProvenanceWatermark | null {
68
- let max: ProvenanceWatermark | null = null;
69
- for (const bucket of this.bySubject.values()) {
70
- for (const row of bucket) {
71
- const wm: ProvenanceWatermark = { created_at_tick: row.created_at_tick, id: row.id };
72
- if (!max || compareWatermark(wm, max) > 0) max = wm;
73
- }
74
- }
75
- return max;
76
- }
77
-
78
- private _addToBundleIndex(row: ProvenanceRow): void {
79
- if (!row.bundle_id) return;
80
- let bucket = this.byBundle.get(row.bundle_id);
81
- if (!bucket) {
82
- bucket = [];
83
- this.byBundle.set(row.bundle_id, bucket);
84
- }
85
- bucket.push(row);
86
- }
87
-
88
- private _removeFromBundleIndex(row: ProvenanceRow): void {
89
- if (!row.bundle_id) return;
90
- const bucket = this.byBundle.get(row.bundle_id);
91
- if (!bucket) return;
92
- const idx = bucket.findIndex((r) => r.id === row.id);
93
- if (idx !== -1) bucket.splice(idx, 1);
94
- if (bucket.length === 0) this.byBundle.delete(row.bundle_id);
95
- }
96
- }
97
-
98
- function compareWatermark(a: ProvenanceWatermark, b: ProvenanceWatermark): number {
99
- if (a.created_at_tick < b.created_at_tick) return -1;
100
- if (a.created_at_tick > b.created_at_tick) return 1;
101
- return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
102
- }