@mago-foundation/mago-ski 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +30 -3
  2. package/dist/hosts/github/run.d.ts +3 -1
  3. package/dist/hosts/github/run.js +29 -9
  4. package/dist/hosts/pi/index.js +48 -5
  5. package/dist/src/admin.d.ts +136 -1
  6. package/dist/src/admin.js +221 -84
  7. package/dist/src/cli.js +335 -10
  8. package/dist/src/fs-safe.d.ts +15 -2
  9. package/dist/src/fs-safe.js +32 -3
  10. package/dist/src/gate/adapters/claude-code-hook.d.ts +1 -0
  11. package/dist/src/gate/adapters/claude-code-hook.js +4 -0
  12. package/dist/src/gate/adapters/claude-code-settings.d.ts +13 -0
  13. package/dist/src/gate/adapters/claude-code-settings.js +49 -0
  14. package/dist/src/gate/adapters/claude-code.d.ts +33 -0
  15. package/dist/src/gate/adapters/claude-code.js +193 -0
  16. package/dist/src/gate/adapters/client.d.ts +13 -0
  17. package/dist/src/gate/adapters/client.js +57 -0
  18. package/dist/src/gate/adapters/codex-hook.d.ts +1 -0
  19. package/dist/src/gate/adapters/codex-hook.js +5 -0
  20. package/dist/src/gate/adapters/codex-requirements.d.ts +19 -0
  21. package/dist/src/gate/adapters/codex-requirements.js +56 -0
  22. package/dist/src/gate/adapters/codex.d.ts +16 -0
  23. package/dist/src/gate/adapters/codex.js +574 -0
  24. package/dist/src/gate/adapters/hook-main.d.ts +7 -0
  25. package/dist/src/gate/adapters/hook-main.js +35 -0
  26. package/dist/src/gate/adapters/host-pid.d.ts +1 -0
  27. package/dist/src/gate/adapters/host-pid.js +20 -0
  28. package/dist/src/gate/admission.d.ts +54 -0
  29. package/dist/src/gate/admission.js +490 -0
  30. package/dist/src/gate/contract.d.ts +51 -0
  31. package/dist/src/gate/contract.js +94 -0
  32. package/dist/src/gate/decision-log.d.ts +38 -0
  33. package/dist/src/gate/decision-log.js +251 -0
  34. package/dist/src/gate/generations.d.ts +67 -0
  35. package/dist/src/gate/generations.js +518 -0
  36. package/dist/src/gate/proc.d.ts +31 -0
  37. package/dist/src/gate/proc.js +79 -0
  38. package/dist/src/gate/refresh.d.ts +11 -0
  39. package/dist/src/gate/refresh.js +30 -0
  40. package/dist/src/gate/run-verifier.d.ts +23 -0
  41. package/dist/src/gate/run-verifier.js +89 -0
  42. package/dist/src/gate/service.d.ts +80 -0
  43. package/dist/src/gate/service.js +722 -0
  44. package/dist/src/gate/strict-json.d.ts +11 -0
  45. package/dist/src/gate/strict-json.js +190 -0
  46. package/dist/src/gate/trust-store.d.ts +36 -0
  47. package/dist/src/gate/trust-store.js +251 -0
  48. package/dist/src/gate/verifier-worker.d.ts +8 -0
  49. package/dist/src/gate/verifier-worker.js +66 -0
  50. package/dist/src/index.d.ts +2 -0
  51. package/dist/src/index.js +2 -0
  52. package/dist/src/keys.d.ts +4 -0
  53. package/dist/src/keys.js +23 -14
  54. package/dist/src/policy.d.ts +145 -0
  55. package/dist/src/policy.js +554 -35
  56. package/dist/src/recovery-admin.d.ts +173 -0
  57. package/dist/src/recovery-admin.js +400 -0
  58. package/dist/src/root-events.d.ts +107 -0
  59. package/dist/src/root-events.js +376 -0
  60. package/dist/src/timestamp.d.ts +61 -0
  61. package/dist/src/timestamp.js +107 -0
  62. package/dist/src/tree-digest.d.ts +1 -0
  63. package/dist/src/tree-digest.js +1 -1
  64. package/dist/src/verify.d.ts +33 -0
  65. package/dist/src/verify.js +4 -2
  66. package/docs/hosts/adapter-interface.md +8 -2
  67. package/docs/hosts/github-action.md +1 -1
  68. package/docs/hosts/pi.md +2 -0
  69. package/docs/spec/gui-admin-rack-v1.md +289 -0
  70. package/docs/spec/root-recovery-v1.md +33 -12
  71. package/docs/spec/trust-documents-v1.md +8 -2
  72. package/docs/spec/verification.md +9 -2
  73. package/docs/threat-model.md +4 -2
  74. package/package.json +3 -1
@@ -0,0 +1,54 @@
1
+ import { type Verdict } from '../verify.ts';
2
+ import type { GateErrorCode } from './contract.ts';
3
+ export declare const MAX_SESSIONS = 1024;
4
+ export declare const MAX_LOG = 4096;
5
+ export declare const MAX_SET = 64;
6
+ /** Ended/expired refs remembered per boot; open sessions + tombstones never exceed this (fail closed when full). */
7
+ export declare const MAX_TOMBSTONES: number;
8
+ /** Oldest host start time admission accepts; compaction never folds log entries newer than this. */
9
+ export declare const MAX_STARTUP_AGE_MS: number;
10
+ /** Fixed margin between two CLOCK_BOOTTIME readings (no wall-clock skew exists); the admission point is this much earlier than the host start. */
11
+ export declare const START_MARGIN_MS = 1000;
12
+ /** `no-session-record` and `internal` come from contract.ts; the others are local to admission. */
13
+ export type AssessError = Extract<GateErrorCode, 'no-session-record' | 'internal'> | 'not-installed' | 'state-corrupt' | 'bound-exceeded' | 'io-busy';
14
+ export type AssessResult = {
15
+ kind: 'verdict';
16
+ verdict: Verdict;
17
+ digests: string[];
18
+ } | {
19
+ kind: 'error';
20
+ reason: AssessError;
21
+ };
22
+ export type MutationResult = {
23
+ ok: true;
24
+ } | {
25
+ ok: false;
26
+ reason: 'state-corrupt' | 'io-busy' | 'session-exists' | 'session-ended' | 'invalid-start' | 'session-limit' | 'log-full' | 'write-failed' | 'clock-moved-backwards';
27
+ };
28
+ export interface AdmissionStore {
29
+ publish(name: string, digest: string, bootMs: number): Promise<MutationResult>;
30
+ uninstall(name: string, bootMs: number): Promise<MutationResult>;
31
+ admitSession(sessionRef: string, bootMs: number, options: {
32
+ startedBootMs: number;
33
+ }): Promise<MutationResult>;
34
+ endSession(sessionRef: string): Promise<MutationResult>;
35
+ reapSessions(isLive: (ref: string) => boolean | Promise<boolean>): Promise<MutationResult & {
36
+ reaped?: number;
37
+ }>;
38
+ expireSessions(maxAgeMs: number, bootMs: number): Promise<MutationResult & {
39
+ expired?: number;
40
+ }>;
41
+ assess(sessionRef: string, name: string, check: (name: string, digest: string) => Promise<Verdict>): Promise<AssessResult>;
42
+ /** Current generation of every installed Skill (read-only). */
43
+ installed(): Promise<{
44
+ name: string;
45
+ digest: string;
46
+ }[]>;
47
+ /** 'unloaded' = a transient error at open, retried on every call; an unloaded or corrupt store is not ready. */
48
+ health(): Promise<'ready' | 'corrupt' | 'unloaded'>;
49
+ }
50
+ /** `fault` is a test-only hook: it may return an errno code to make the next read or write fail with that error. */
51
+ export declare function openAdmissionStore(dir: string, options: {
52
+ bootId: string;
53
+ fault?: (op: 'read' | 'write') => string | undefined;
54
+ }): Promise<AdmissionStore>;
@@ -0,0 +1,490 @@
1
+ // Session admission and the generation-set rule.
2
+ // A session's set for Skill N = the generation of N current at the session's admission sequence (if any)
3
+ // + every digest published for N after it. It is derived from one append-only publication log; sessions store
4
+ // only their admission sequence. The gate allows N in S only if EVERY digest in that set is still VERIFIED.
5
+ // Single writer process per directory (as trust-store.ts); the directory must be root-only.
6
+ // Same-seq tampering (rewriting a log entry in place) needs write access to that root-only directory; the file has
7
+ // no MAC, so the directory permission is the control.
8
+ // Session refs MUST be minted by the service and bound to the host process by the service (packet 6), never an
9
+ // employee-supplied id; only authenticated host lifecycle events may call admitSession/endSession. Ended or expired
10
+ // refs are tombstoned until the boot id changes, so a ref cannot be re-admitted to shed its history.
11
+ // REAPING. reapSessions(isLive) removes open sessions the caller says are dead WITHOUT tombstoning them, then compacts.
12
+ // Liveness is evaluated outside the store lock (snapshot, evaluate, then remove only refs still present and unchanged).
13
+ // Only valid for refs that cannot recur within a boot (the service's kernel-derived `pid:starttime` refs); a reaped ref
14
+ // admitted again is a brand-new session with a fresh (shorter) history. NEVER call it with employee-supplied refs.
15
+ // An isLive that throws keeps the session (fail safe).
16
+ // TRANSIENT I/O. A read/write error of EMFILE, ENFILE, EAGAIN, EINTR or ENOMEM fails only that operation (`io-busy`,
17
+ // a deny for that request) and neither latches `corrupt` nor changes the in-memory state. Every other I/O error
18
+ // (EIO included) and every integrity failure (parse, rollback, inconsistent content, symlink) latches corrupt. If a
19
+ // directory fsync is what failed after the rename, the next operation adopts the (newer) file as usual. It runs inside the store lock, so keep it quick.
20
+ // TIME. Every time here is boot-relative milliseconds (`bootMs`, a non-negative safe integer), never wall-clock time.
21
+ // The caller MUST pass CLOCK_BOOTTIME-based values: its own "now" from /proc/uptime, and a host process start from
22
+ // /proc/<pid>/stat field 22 / CLK_TCK. Those are immune to wall-clock steps; sessions are per boot already (bootId).
23
+ // CALLER CONTRACT: (1) read the bootMs passed to publish() AFTER the new generation is installed and visible to hosts
24
+ // (a stamp earlier than visibility by more than START_MARGIN_MS lets a host that started in between hold the old
25
+ // generation unrecorded); (2) bootId must be /proc/sys/kernel/random/boot_id, which changes on every boot.
26
+ // Each log entry stores `at_boot_ms`. The store persists `high_boot_ms` (largest bootMs seen) and refuses any operation
27
+ // below it (`clock-moved-backwards`), except uninstall, which still succeeds and is stamped max(bootMs, high). So stored
28
+ // times never decrease, and a later publish can never look earlier than an earlier one.
29
+ // A session's admission point is the last entry with at_boot_ms <= startedBootMs - START_MARGIN_MS (conservatively
30
+ // earlier than the host start), so a Skill version the host snapshotted before the SessionStart hook reached us still counts.
31
+ // Compaction folds only entries older than MAX_STARTUP_AGE_MS (vs high_boot_ms) and than every open session's point.
32
+ // `folded_at_boot_ms` is the at_boot_ms of the newest folded entry (0 = none); an admission whose point is at or before
33
+ // it is refused (`invalid-start`), because `base` cannot reconstruct what was current before the fold.
34
+ // A boot id change folds the whole log into `base` (boot-relative times of the old boot are meaningless), clears
35
+ // sessions and tombstones, resets high_boot_ms and folded_at_boot_ms to 0, and keeps current installs.
36
+ // `assess` runs `check` outside the lock. That is safe because the service publishes only VERIFIED generations and
37
+ // a revocation is a trust-state change that every later `check` sees; a stale answer can only be one decision old.
38
+ // Compaction folds log entries up to the oldest open session's sequence into `base` (current per Skill at that
39
+ // point), so no history an open session depends on is lost. Bounds fail closed (refuse / deny), never drop history.
40
+ import { constants as fsConstants } from 'node:fs';
41
+ import { lstat, mkdir, open, readdir } from 'node:fs/promises';
42
+ import path from 'node:path';
43
+ import { canonicalBytes, exactKeys, MAX_CANONICAL_JSON_BYTES, parseCanonicalJsonBytes, requireArray, requireString } from "../canonical-json.js";
44
+ import { readRegularFile, writeFileAtomic } from "../fs-safe.js";
45
+ import { VERDICT_RANK } from "../verify.js";
46
+ export const MAX_SESSIONS = 1024;
47
+ export const MAX_LOG = 4096;
48
+ export const MAX_SET = 64;
49
+ /** Ended/expired refs remembered per boot; open sessions + tombstones never exceed this (fail closed when full). */
50
+ export const MAX_TOMBSTONES = 4 * MAX_SESSIONS;
51
+ /** Oldest host start time admission accepts; compaction never folds log entries newer than this. */
52
+ export const MAX_STARTUP_AGE_MS = 24 * 60 * 60 * 1000;
53
+ /** Fixed margin between two CLOCK_BOOTTIME readings (no wall-clock skew exists); the admission point is this much earlier than the host start. */
54
+ export const START_MARGIN_MS = 1000;
55
+ /** Uninstalls are exempt from MAX_LOG (revoke must always be able to uninstall); the parse bound allows for them. */
56
+ const MAX_LOG_PARSE = 2 * MAX_LOG;
57
+ const FILE = 'admission.json';
58
+ const TYPE = 'mago.gate-admission/v1';
59
+ const toBytes = (s) => canonicalBytes({
60
+ type: TYPE, boot_id: s.bootId, seq: s.seq, high_boot_ms: s.high, folded_at_boot_ms: s.folded,
61
+ log: s.log.map((e) => ({ seq: e.seq, name: e.name, digest: e.digest, at_boot_ms: e.at })),
62
+ base: [...s.base].map(([name, digest]) => ({ name, digest })),
63
+ sessions: [...s.sessions].map(([ref, v]) => ({ ref, seq: v.seq, at_boot_ms: v.at })),
64
+ ended: [...s.ended],
65
+ });
66
+ function seqOf(v) {
67
+ if (typeof v !== 'number' || !Number.isSafeInteger(v) || v < 0)
68
+ throw new Error('invalid sequence');
69
+ return v;
70
+ }
71
+ function parse(bytes) {
72
+ const o = exactKeys(parseCanonicalJsonBytes(bytes, 'admission state'), ['type', 'boot_id', 'seq', 'high_boot_ms', 'folded_at_boot_ms', 'log', 'base', 'sessions', 'ended'], 'admission state');
73
+ if (o.type !== TYPE)
74
+ throw new Error('unsupported type');
75
+ const seq = seqOf(o.seq);
76
+ const high = seqOf(o.high_boot_ms);
77
+ const folded = seqOf(o.folded_at_boot_ms);
78
+ const log = requireArray(o.log, 'log', MAX_LOG_PARSE).map((v) => {
79
+ const e = exactKeys(v, ['seq', 'name', 'digest', 'at_boot_ms'], 'log entry');
80
+ return { seq: seqOf(e.seq), name: requireString(e.name, 'name', 128), digest: e.digest === null ? null : requireString(e.digest, 'digest', 128), at: seqOf(e.at_boot_ms) };
81
+ });
82
+ log.forEach((e, i) => { if (e.seq > seq || (i > 0 && e.seq <= log[i - 1].seq))
83
+ throw new Error('log is not ordered'); });
84
+ log.forEach((e, i) => { if ((i > 0 && e.at < log[i - 1].at) || e.at > high || e.at < folded)
85
+ throw new Error('log times are not monotonic'); });
86
+ if (folded > high)
87
+ throw new Error('fold watermark is ahead of the clock');
88
+ const baseRows = requireArray(o.base, 'base', MAX_CANONICAL_JSON_BYTES).map((v) => {
89
+ const e = exactKeys(v, ['name', 'digest'], 'base entry');
90
+ return [requireString(e.name, 'name', 128), requireString(e.digest, 'digest', 128)];
91
+ });
92
+ const base = new Map(baseRows);
93
+ if (base.size !== baseRows.length)
94
+ throw new Error('duplicate base name');
95
+ const sessionRows = requireArray(o.sessions, 'sessions', MAX_SESSIONS).map((v) => {
96
+ const e = exactKeys(v, ['ref', 'seq', 'at_boot_ms'], 'session');
97
+ const s = seqOf(e.seq);
98
+ if (s > seq)
99
+ throw new Error('session is ahead of the log');
100
+ return [requireString(e.ref, 'ref', 256), { seq: s, at: seqOf(e.at_boot_ms) }];
101
+ // (session time is bounded by high below)
102
+ });
103
+ const sessions = new Map(sessionRows);
104
+ if (sessions.size !== sessionRows.length)
105
+ throw new Error('duplicate session ref');
106
+ const endedRows = requireArray(o.ended, 'ended', MAX_TOMBSTONES).map((v) => requireString(v, 'ended ref', 256));
107
+ const ended = new Set(endedRows);
108
+ for (const r of sessions.keys())
109
+ if (ended.has(r))
110
+ throw new Error('ref is both open and ended');
111
+ for (const v of sessions.values())
112
+ if (v.at > high)
113
+ throw new Error('session is ahead of the clock');
114
+ if (ended.size !== endedRows.length)
115
+ throw new Error('duplicate ended ref');
116
+ if (ended.size + sessions.size > MAX_TOMBSTONES)
117
+ throw new Error('too many session refs');
118
+ return { bootId: requireString(o.boot_id, 'boot_id', 128), seq, high, folded, log, base, sessions, ended };
119
+ }
120
+ const clone = (s) => ({ ...s, log: [...s.log], base: new Map(s.base), sessions: new Map(s.sessions), ended: new Set(s.ended) });
121
+ function currentAt(s, name, at) {
122
+ for (let i = s.log.length - 1; i >= 0; i--) {
123
+ const e = s.log[i];
124
+ if (e.name === name && e.seq <= at)
125
+ return e.digest;
126
+ }
127
+ return s.base.get(name) ?? null;
128
+ }
129
+ function setFor(s, name, at) {
130
+ const out = [];
131
+ const first = currentAt(s, name, at);
132
+ if (first !== null)
133
+ out.push(first);
134
+ for (const e of s.log)
135
+ if (e.name === name && e.seq > at && e.digest !== null && !out.includes(e.digest))
136
+ out.push(e.digest);
137
+ return out;
138
+ }
139
+ /** Fold entries no open session or admission can still need: older than every open session's point and than the startup window. */
140
+ function compact(s, nowMs) {
141
+ const windowStart = nowMs - MAX_STARTUP_AGE_MS;
142
+ let windowSeq = 0; // last seq of the maximal log prefix older than the window
143
+ for (const e of s.log) {
144
+ if (e.at >= windowStart)
145
+ break;
146
+ windowSeq = e.seq;
147
+ }
148
+ const fold = Math.min(windowSeq, ...[...s.sessions.values()].map((v) => v.seq));
149
+ const keep = [];
150
+ for (const e of s.log) {
151
+ if (e.seq > fold) {
152
+ keep.push(e);
153
+ continue;
154
+ }
155
+ if (e.digest === null)
156
+ s.base.delete(e.name); // not installed == absent from base
157
+ else
158
+ s.base.set(e.name, e.digest);
159
+ s.folded = Math.max(s.folded, e.at);
160
+ }
161
+ s.log = keep;
162
+ }
163
+ function requireBootMs(v, label) {
164
+ if (typeof v !== 'number' || !Number.isSafeInteger(v) || v < 0)
165
+ throw new Error(`${label} must be a non-negative integer (boot ms)`);
166
+ return v;
167
+ }
168
+ const BACKWARDS = { ok: false, reason: 'clock-moved-backwards' };
169
+ const TRANSIENT = new Set(['EMFILE', 'ENFILE', 'EAGAIN', 'EINTR', 'ENOMEM']);
170
+ const isTransient = (e) => TRANSIENT.has(e?.code ?? '');
171
+ const BUSY = { ok: false, reason: 'io-busy' };
172
+ /** `fault` is a test-only hook: it may return an errno code to make the next read or write fail with that error. */
173
+ export async function openAdmissionStore(dir, options) {
174
+ const bootId = requireString(options.bootId, 'bootId', 128);
175
+ dir = path.resolve(dir);
176
+ await mkdir(dir, { mode: 0o700 }).catch((e) => { if (e?.code !== 'EEXIST')
177
+ throw e; });
178
+ const info = await lstat(dir);
179
+ if (info.isSymbolicLink() || !info.isDirectory())
180
+ throw new Error('admission directory must be a real directory, not a symlink');
181
+ if ((info.mode & 0o022) !== 0)
182
+ throw new Error('admission directory must not be group- or world-writable');
183
+ const file = path.join(dir, FILE);
184
+ let corrupt = false;
185
+ let held = null;
186
+ let state = null;
187
+ const inject = (op) => {
188
+ const code = options.fault?.(op);
189
+ if (code)
190
+ throw Object.assign(new Error(`injected ${code}`), { code });
191
+ };
192
+ async function read() {
193
+ try {
194
+ inject('read');
195
+ return await readRegularFile(file, 'admission state', MAX_CANONICAL_JSON_BYTES);
196
+ }
197
+ catch (e) {
198
+ if (e?.code !== 'ENOENT')
199
+ throw e;
200
+ // A missing state file is a fresh store only if the directory is otherwise empty.
201
+ if ((await readdir(dir)).some((n) => !/^\..*\.tmp$/u.test(n)))
202
+ throw new Error('state file is missing but the directory is not empty');
203
+ return null;
204
+ }
205
+ }
206
+ /** 'busy': a transient error, nothing changed in memory and nothing is latched. */
207
+ async function persist(next) {
208
+ const bytes = toBytes(next);
209
+ try {
210
+ inject('write');
211
+ await writeFileAtomic(file, bytes, 0o600);
212
+ const h = await open(dir, fsConstants.O_RDONLY | (fsConstants.O_DIRECTORY ?? 0));
213
+ try {
214
+ await h.sync();
215
+ }
216
+ finally {
217
+ await h.close();
218
+ }
219
+ }
220
+ catch (e) {
221
+ if (isTransient(e))
222
+ return 'busy';
223
+ corrupt = true;
224
+ return 'failed'; // on-disk state now unknown: stop rather than guess
225
+ }
226
+ held = bytes;
227
+ state = next;
228
+ return 'ok';
229
+ }
230
+ /** Loads (or creates) the state. Throws a transient error to be retried on the next operation; anything else latches corrupt. */
231
+ async function load() {
232
+ const disk = await read();
233
+ const loaded = disk ? parse(disk) : null;
234
+ if (loaded && loaded.bootId === bootId) {
235
+ held = disk;
236
+ state = loaded;
237
+ return;
238
+ }
239
+ // A different boot (or no file): no recorded session can still be running. Tombstones are per boot and
240
+ // boot-relative times are meaningless across boots, so fold the whole log into base.
241
+ const old = loaded ?? { bootId, seq: 0, high: 0, folded: 0, log: [], base: new Map(), sessions: new Map(), ended: new Set() };
242
+ const base = new Map(old.base);
243
+ for (const e of old.log) {
244
+ if (e.digest === null)
245
+ base.delete(e.name);
246
+ else
247
+ base.set(e.name, e.digest);
248
+ }
249
+ const p = await persist({ ...old, bootId, high: 0, folded: 0, log: [], base, sessions: new Map(), ended: new Set() });
250
+ if (p === 'busy')
251
+ throw Object.assign(new Error('busy'), { code: 'EAGAIN' });
252
+ if (p !== 'ok')
253
+ throw new Error('cannot persist');
254
+ }
255
+ // A transient error at open leaves the store "not loaded yet" (retried inside the lock by the next operation).
256
+ try {
257
+ await load();
258
+ }
259
+ catch (e) {
260
+ if (!isTransient(e))
261
+ corrupt = true;
262
+ }
263
+ /** Inside the lock: reload if the file changed under us; never accept older state. */
264
+ async function refresh() {
265
+ if (corrupt)
266
+ return true;
267
+ if (!state) {
268
+ try {
269
+ await load();
270
+ }
271
+ catch (e) {
272
+ if (isTransient(e))
273
+ return false;
274
+ corrupt = true;
275
+ }
276
+ return true;
277
+ }
278
+ try {
279
+ const disk = await read();
280
+ if (disk !== null && held !== null && disk.equals(held))
281
+ return true;
282
+ const next = disk ? parse(disk) : null;
283
+ if (!next || next.bootId !== state.bootId || next.seq < state.seq) {
284
+ corrupt = true;
285
+ return true;
286
+ }
287
+ state = next;
288
+ held = disk;
289
+ }
290
+ catch (e) {
291
+ if (isTransient(e))
292
+ return false;
293
+ corrupt = true;
294
+ }
295
+ return true;
296
+ }
297
+ let tail = Promise.resolve();
298
+ const locked = (fn, busy) => {
299
+ const run = tail.then(async () => (await refresh()) ? fn() : busy);
300
+ tail = run.catch(() => { });
301
+ return run;
302
+ };
303
+ const mutate = (fn) => locked(async () => {
304
+ if (corrupt || !state)
305
+ return { ok: false, reason: 'state-corrupt' };
306
+ const next = clone(state);
307
+ const refused = fn(next);
308
+ if (refused)
309
+ return refused;
310
+ const p = await persist(next);
311
+ return p === 'ok' ? { ok: true } : p === 'busy' ? BUSY : { ok: false, reason: 'write-failed' };
312
+ }, BUSY);
313
+ const event = (name, digest, bootMs) => {
314
+ requireString(name, 'name', 128);
315
+ if (digest !== null)
316
+ requireString(digest, 'digest', 128);
317
+ requireBootMs(bootMs, 'bootMs');
318
+ return mutate((s) => {
319
+ let stamp = bootMs;
320
+ if (bootMs < s.high) {
321
+ if (digest !== null)
322
+ return BACKWARDS;
323
+ stamp = s.high; // an uninstall (revoke) must still succeed
324
+ }
325
+ s.high = stamp;
326
+ compact(s, stamp);
327
+ if (digest === null) {
328
+ if (currentAt(s, name, s.seq) === null)
329
+ return; // nothing installed: no entry, so uninstalls stay bounded
330
+ }
331
+ else if (s.log.length >= MAX_LOG)
332
+ return { ok: false, reason: 'log-full' };
333
+ s.log.push({ seq: ++s.seq, name, digest, at: stamp });
334
+ });
335
+ };
336
+ return {
337
+ publish: (name, digest, bootMs) => event(name, digest, bootMs),
338
+ uninstall: (name, bootMs) => event(name, null, bootMs),
339
+ admitSession(ref, bootMs, { startedBootMs }) {
340
+ requireString(ref, 'sessionRef', 256);
341
+ requireBootMs(bootMs, 'bootMs');
342
+ requireBootMs(startedBootMs, 'startedBootMs');
343
+ const cutoff = startedBootMs - START_MARGIN_MS; // conservatively earlier than the host start
344
+ if (startedBootMs > bootMs || cutoff < bootMs - MAX_STARTUP_AGE_MS)
345
+ return Promise.resolve({ ok: false, reason: 'invalid-start' });
346
+ return mutate((s) => {
347
+ if (bootMs < s.high)
348
+ return BACKWARDS;
349
+ if (s.ended.has(ref))
350
+ return { ok: false, reason: 'session-ended' };
351
+ if (s.sessions.has(ref))
352
+ return { ok: false, reason: 'session-exists' };
353
+ if (s.sessions.size >= MAX_SESSIONS || s.sessions.size + s.ended.size >= MAX_TOMBSTONES)
354
+ return { ok: false, reason: 'session-limit' }; // fail closed
355
+ s.high = bootMs;
356
+ compact(s, bootMs);
357
+ if (s.folded > 0 && cutoff <= s.folded)
358
+ return { ok: false, reason: 'invalid-start' }; // base cannot reconstruct pre-fold history
359
+ let seq = 0; // base alone is "before the log"; stop at the first entry newer than the cutoff
360
+ for (const e of s.log) {
361
+ if (e.at > cutoff)
362
+ break;
363
+ seq = e.seq;
364
+ }
365
+ s.sessions.set(ref, { seq, at: bootMs });
366
+ });
367
+ },
368
+ // An unknown ref is tombstoned too, so it can never be admitted later in this boot (fail closed when full).
369
+ endSession: (ref) => mutate((s) => {
370
+ if (s.sessions.delete(ref)) {
371
+ s.ended.add(ref);
372
+ return;
373
+ }
374
+ if (s.ended.has(ref))
375
+ return;
376
+ if (s.sessions.size + s.ended.size >= MAX_TOMBSTONES)
377
+ return { ok: false, reason: 'session-limit' };
378
+ s.ended.add(ref);
379
+ }), // compaction waits for the next event (needs a time)
380
+ async expireSessions(maxAgeMs, bootMs) {
381
+ requireBootMs(bootMs, 'bootMs');
382
+ if (typeof maxAgeMs !== 'number' || !Number.isFinite(maxAgeMs) || maxAgeMs < 0)
383
+ throw new Error('maxAgeMs must be a finite non-negative number');
384
+ let expired = 0;
385
+ const r = await mutate((s) => {
386
+ if (bootMs < s.high)
387
+ return BACKWARDS;
388
+ s.high = bootMs;
389
+ for (const [ref, v] of s.sessions)
390
+ if (bootMs - v.at > maxAgeMs) {
391
+ s.sessions.delete(ref);
392
+ s.ended.add(ref);
393
+ expired++;
394
+ }
395
+ compact(s, bootMs);
396
+ });
397
+ return r.ok ? { ...r, expired } : r;
398
+ },
399
+ // Two phases: liveness is evaluated OUTSIDE the lock (the caller reads /proc), so a slow sweep never blocks assess or
400
+ // admissions. Only refs that are still present with the same admission point are removed; a session admitted after the snapshot is untouched.
401
+ async reapSessions(isLive) {
402
+ const snap = await locked(async () => (corrupt || !state ? 'corrupt' : new Map(state.sessions)), 'busy');
403
+ if (snap === 'busy')
404
+ return BUSY;
405
+ if (snap === 'corrupt')
406
+ return { ok: false, reason: 'state-corrupt' };
407
+ const dead = [];
408
+ for (const ref of snap.keys()) {
409
+ let live = true;
410
+ try {
411
+ live = await isLive(ref);
412
+ }
413
+ catch { /* keep */ }
414
+ if (!live)
415
+ dead.push(ref);
416
+ }
417
+ if (dead.length === 0)
418
+ return { ok: true, reaped: 0 };
419
+ return locked(async () => {
420
+ if (corrupt || !state)
421
+ return { ok: false, reason: 'state-corrupt' };
422
+ const next = clone(state);
423
+ let reaped = 0;
424
+ for (const ref of dead) {
425
+ const was = snap.get(ref), cur = next.sessions.get(ref);
426
+ if (cur && cur.seq === was.seq && cur.at === was.at) {
427
+ next.sessions.delete(ref);
428
+ reaped++;
429
+ }
430
+ }
431
+ if (reaped === 0)
432
+ return { ok: true, reaped: 0 };
433
+ compact(next, next.high);
434
+ const p = await persist(next);
435
+ return p === 'ok' ? { ok: true, reaped } : p === 'busy' ? BUSY : { ok: false, reason: 'write-failed' };
436
+ }, BUSY);
437
+ },
438
+ installed: () => locked(async () => {
439
+ if (corrupt || !state)
440
+ return [];
441
+ const s = state;
442
+ const out = [];
443
+ for (const name of new Set([...s.base.keys(), ...s.log.map((e) => e.name)])) {
444
+ const digest = currentAt(s, name, s.seq);
445
+ if (digest !== null)
446
+ out.push({ name, digest });
447
+ }
448
+ return out;
449
+ }, []),
450
+ health: () => locked(async () => (corrupt ? 'corrupt' : state ? 'ready' : 'unloaded'), 'unloaded'),
451
+ async assess(ref, name, check) {
452
+ // Snapshot under the lock; the (slow) checks run outside it so they never block publishing.
453
+ const snap = await locked(async () => {
454
+ if (corrupt || !state)
455
+ return { error: 'state-corrupt', digests: undefined };
456
+ const sess = state.sessions.get(ref);
457
+ if (!sess)
458
+ return { error: 'no-session-record', digests: undefined };
459
+ if (currentAt(state, name, state.seq) === null)
460
+ return { error: 'not-installed', digests: undefined };
461
+ const digests = setFor(state, name, sess.seq);
462
+ return digests.length > MAX_SET ? { error: 'bound-exceeded', digests: undefined } : { error: undefined, digests };
463
+ }, { error: 'io-busy', digests: undefined });
464
+ if (!snap.digests)
465
+ return { kind: 'error', reason: snap.error };
466
+ let worst = 'VERIFIED';
467
+ try {
468
+ for (const d of snap.digests) {
469
+ const v = await check(name, d);
470
+ if (typeof v !== 'string' || !Object.hasOwn(VERDICT_RANK, v))
471
+ return { kind: 'error', reason: 'internal' };
472
+ if (severity(v) > severity(worst))
473
+ worst = v;
474
+ }
475
+ }
476
+ catch {
477
+ return { kind: 'error', reason: 'internal' };
478
+ }
479
+ return { kind: 'verdict', verdict: worst, digests: snap.digests };
480
+ },
481
+ };
482
+ }
483
+ // Most severe failing verdict across generations. The engine's VERDICT_RANK lists failure precedence with the
484
+ // highest-priority reason first (REVOKED, UNAPPROVED_CHANGE, EXPIRED, ...), so the lowest non-zero rank is reported.
485
+ function severity(v) {
486
+ const rank = VERDICT_RANK[v];
487
+ if (!Number.isFinite(rank))
488
+ throw new Error('non-finite verdict rank');
489
+ return v === 'VERIFIED' ? -1 : 100 - rank;
490
+ }
@@ -0,0 +1,51 @@
1
+ import type { Mode } from '../policy.ts';
2
+ import { type Verdict } from '../verify.ts';
3
+ export declare const GATE_EVENTS: readonly ["skill-invoke", "prompt-expansion", "session-start"];
4
+ export type GateEvent = (typeof GATE_EVENTS)[number];
5
+ export declare const GATE_ERROR_CODES: readonly ["bad-request", "verifier-failed", "verifier-timeout", "no-session-record", "trust-unavailable", "internal"];
6
+ export type GateErrorCode = (typeof GATE_ERROR_CODES)[number];
7
+ export declare const MODES: readonly Mode[];
8
+ export interface GateRequest {
9
+ v: 1;
10
+ request_id: string;
11
+ event: GateEvent;
12
+ skill?: string;
13
+ session: string;
14
+ }
15
+ export type GateResult = {
16
+ v: 1;
17
+ request_id: string;
18
+ kind: 'verdict';
19
+ verdict: Verdict;
20
+ mode: Mode;
21
+ } | {
22
+ v: 1;
23
+ request_id: string;
24
+ kind: 'gate-error';
25
+ code: GateErrorCode;
26
+ mode: Mode;
27
+ }
28
+ /** Reply to session-start only. It carries no verdict and is never permission (decideAction denies/observes it). */
29
+ | {
30
+ v: 1;
31
+ request_id: string;
32
+ kind: 'ack';
33
+ mode: Mode;
34
+ };
35
+ /** Any failure to obtain a valid GateResult (transport error, timeout, parse error). */
36
+ export interface ParseFailure {
37
+ kind: 'parse-failure';
38
+ }
39
+ export type GateAction = 'allow' | 'deny' | 'observe';
40
+ export declare function parseGateRequest(bytes: Uint8Array): GateRequest;
41
+ export declare function parseGateResult(bytes: Uint8Array, expectedRequestId: string): GateResult;
42
+ /**
43
+ * Only a VERIFIED verdict allows (an ack never does). Anything else denies when enforce applies and is observed
44
+ * (would-deny, never blocked) when it does not. Enforce applies if the local configuration says
45
+ * enforce (or holds anything other than exactly 'shadow') or the service's result says enforce,
46
+ * so nothing in a result can downgrade local enforce. A parse failure carries no mode and
47
+ * follows the local configuration.
48
+ */
49
+ export declare function decideAction(result: GateResult | ParseFailure, configuredMode: Mode): GateAction;
50
+ export declare function serializeGateRequest(request: GateRequest): string;
51
+ export declare function serializeGateResult(result: GateResult): string;