@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,94 @@
1
+ // Harness-neutral, versioned, closed contracts between hook adapters and the
2
+ // gate service. No transport, no file system. Parsing is strict: unknown or
3
+ // missing fields, wrong types and a mismatched request_id are errors, and there
4
+ // is no status field or any other fallback.
5
+ import { isRecord } from "../canonical-json.js";
6
+ import { validateSkillName } from "../names.js";
7
+ import { VERDICTS } from "../verify.js";
8
+ import { parseStrictJson } from "./strict-json.js";
9
+ export const GATE_EVENTS = ['skill-invoke', 'prompt-expansion', 'session-start'];
10
+ export const GATE_ERROR_CODES = [
11
+ 'bad-request', 'verifier-failed', 'verifier-timeout',
12
+ 'no-session-record', 'trust-unavailable', 'internal',
13
+ ];
14
+ export const MODES = ['shadow', 'enforce'];
15
+ const TOKEN_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/u;
16
+ function token(value, label) {
17
+ if (typeof value !== 'string' || !TOKEN_PATTERN.test(value))
18
+ throw new Error(`${label} must be 1-128 ASCII letters, digits, dot, underscore, colon or hyphen`);
19
+ return value;
20
+ }
21
+ function closed(value, allowed, label) {
22
+ if (typeof value !== 'string' || !allowed.includes(value))
23
+ throw new Error(`${label} is not an allowed value`);
24
+ return value;
25
+ }
26
+ function record(value, keys, label) {
27
+ if (!isRecord(value))
28
+ throw new Error(`${label} must be an object`);
29
+ const extra = Object.keys(value).filter((key) => !keys.includes(key));
30
+ if (extra.length > 0)
31
+ throw new Error(`${label} has unknown fields`);
32
+ if (value['v'] !== 1)
33
+ throw new Error(`${label} version must be 1`);
34
+ return value;
35
+ }
36
+ export function parseGateRequest(bytes) {
37
+ const raw = record(parseStrictJson(bytes), ['v', 'request_id', 'event', 'skill', 'session'], 'request');
38
+ const event = closed(raw['event'], GATE_EVENTS, 'event');
39
+ const hasSkill = Object.hasOwn(raw, 'skill');
40
+ if (event === 'session-start' ? hasSkill : !hasSkill)
41
+ throw new Error('skill must be present except for session-start, where it must be absent');
42
+ const request = {
43
+ v: 1,
44
+ request_id: token(raw['request_id'], 'request_id'),
45
+ event,
46
+ session: token(raw['session'], 'session'),
47
+ };
48
+ if (hasSkill)
49
+ request.skill = validateSkillName(raw['skill']);
50
+ return request;
51
+ }
52
+ export function parseGateResult(bytes, expectedRequestId) {
53
+ const parsed = parseStrictJson(bytes);
54
+ if (!isRecord(parsed))
55
+ throw new Error('result must be an object');
56
+ const kind = parsed['kind'];
57
+ const raw = record(parsed, kind === 'verdict'
58
+ ? ['v', 'request_id', 'kind', 'verdict', 'mode']
59
+ : kind === 'ack' ? ['v', 'request_id', 'kind', 'mode']
60
+ : ['v', 'request_id', 'kind', 'code', 'mode'], 'result');
61
+ const requestId = token(raw['request_id'], 'request_id');
62
+ if (requestId !== expectedRequestId)
63
+ throw new Error('result request_id does not match the request');
64
+ const mode = closed(raw['mode'], MODES, 'mode');
65
+ if (kind === 'verdict')
66
+ return { v: 1, request_id: requestId, kind, verdict: closed(raw['verdict'], VERDICTS, 'verdict'), mode };
67
+ if (kind === 'ack')
68
+ return { v: 1, request_id: requestId, kind, mode };
69
+ if (kind === 'gate-error')
70
+ return { v: 1, request_id: requestId, kind, code: closed(raw['code'], GATE_ERROR_CODES, 'code'), mode };
71
+ throw new Error('result kind is not an allowed value');
72
+ }
73
+ /**
74
+ * Only a VERIFIED verdict allows (an ack never does). Anything else denies when enforce applies and is observed
75
+ * (would-deny, never blocked) when it does not. Enforce applies if the local configuration says
76
+ * enforce (or holds anything other than exactly 'shadow') or the service's result says enforce,
77
+ * so nothing in a result can downgrade local enforce. A parse failure carries no mode and
78
+ * follows the local configuration.
79
+ */
80
+ export function decideAction(result, configuredMode) {
81
+ const ok = result.kind === 'verdict' && result.verdict === 'VERIFIED';
82
+ if (ok)
83
+ return 'allow';
84
+ // Enforce wins if either side says so: a result can never downgrade local enforce.
85
+ // Any configured value other than exactly 'shadow' fails closed to enforce.
86
+ const enforce = configuredMode !== 'shadow' || (result.kind !== 'parse-failure' && result.mode === 'enforce');
87
+ return enforce ? 'deny' : 'observe';
88
+ }
89
+ export function serializeGateRequest(request) {
90
+ return JSON.stringify(request);
91
+ }
92
+ export function serializeGateResult(result) {
93
+ return JSON.stringify(result);
94
+ }
@@ -0,0 +1,38 @@
1
+ export interface LogInput {
2
+ bootMs: number;
3
+ mode: string;
4
+ action: 'allow' | 'deny' | 'observe' | 'ack';
5
+ event: string;
6
+ /** Pseudonymous session reference (already keyed-hashed by the caller), or null. */
7
+ session: string | null;
8
+ skill: string | null;
9
+ digests: readonly string[];
10
+ trustRootVersion: number | null;
11
+ revocationsVersion: number | null;
12
+ /** Verdict or closed gate-error code. */
13
+ result: string;
14
+ build: string;
15
+ elapsedMs: number;
16
+ }
17
+ export interface LogOptions {
18
+ rootUid: number;
19
+ maxSegmentBytes?: number;
20
+ maxSegments?: number;
21
+ checkpointEvery?: number;
22
+ now?: () => Date;
23
+ /** Tests: return true to make the next append fail before touching the disk. */
24
+ fault?: () => boolean;
25
+ /** Tests: return true to make the fsync of a durable append fail (the record is already written). */
26
+ syncFault?: () => boolean;
27
+ }
28
+ export interface DecisionLog {
29
+ append(input: LogInput, durable: boolean): Promise<void>;
30
+ status(): {
31
+ segment: string | null;
32
+ lastSeq: number;
33
+ chainBreaks: number;
34
+ };
35
+ /** Drains pending appends and writes a checkpoint. */
36
+ close(): Promise<void>;
37
+ }
38
+ export declare function openDecisionLog(dir: string, opts: LogOptions): Promise<DecisionLog>;
@@ -0,0 +1,251 @@
1
+ // Protected decision log (E3 packet 8). Linux only. Append-only JSONL segments in a root-only directory.
2
+ //
3
+ // INTEGRITY LIMIT. Each record carries `prev` = SHA-256 (hex) of the previous record's line, and a checkpoint file
4
+ // holds the last sequence + hash. A chain stored next to a log that root can rewrite does NOT authenticate history
5
+ // against root: it detects accidental corruption and tampering by non-root users only. There is no integrity key here.
6
+ //
7
+ // RECORDS hold only the fixed fields in `Record` (no bodies, prompts, hook payloads, paths, certificate reasons or
8
+ // verifier stderr); the record is built field by field, so extra input is dropped.
9
+ //
10
+ // DURABILITY. `append(..., durable=true)` returns after fsync of the segment (the service uses it for an enforce allow,
11
+ // which is returned only after this). Non-durable appends skip fsync (a later fsync of the same file flushes them too).
12
+ //
13
+ // SEGMENTS `segment-<10-digit index>.jsonl` rotate at `maxSegmentBytes`; the first record of the next segment chains to
14
+ // the last hash of the previous one, and a checkpoint of that last record is written first. At most `maxSegments` are kept.
15
+ //
16
+ // RECOVERY (open, and before the next append after a failed one) checks the last segment: every line parses, `prev`
17
+ // matches the previous line, `seq` is consecutive, the last line is complete, and the checkpoint (when present) matches
18
+ // (same segment: the record with its seq has its hash; older segment: this segment starts at checkpoint.seq + 1 and chains
19
+ // to checkpoint.hash). Anything else is a BREAK: a new segment starts, its first record has `prev` null and `chain_break`
20
+ // = the old segment's file name, and the sequence continues from max(last valid, checkpoint). Limit: a checkpoint is the
21
+ // only anchor for earlier segments (they are not re-read), and a lost checkpoint plus a fully invalid last segment can
22
+ // restart the sequence low; the break marker still records it.
23
+ // Before each append the directory inode and the open segment are checked; when the segment is gone or the directory is a
24
+ // different inode, the next record starts a new segment with `chain_break` = the missing segment's name. Recovery re-runs
25
+ // the directory safety checks (a loose directory stays refused) and is rate-limited to one attempt per second; while
26
+ // limited, an append fails fast. If the fsync of a durable record fails, the next append first writes a correction
27
+ // (`action` deny, `result` internal, `supersedes` = that seq). shortcut: a correction not yet written at shutdown is lost,
28
+ // the next process cannot know about it; the caller already answered gate-error for that request.
29
+ import { createHash } from 'node:crypto';
30
+ import { constants as fsConstants } from 'node:fs';
31
+ import { lstat, mkdir, open, readdir, unlink } from 'node:fs/promises';
32
+ import path from 'node:path';
33
+ import { readRegularFile, writeFileAtomic } from "../fs-safe.js";
34
+ const SEG = /^segment-([0-9]{10})\.jsonl$/u;
35
+ const CP = 'checkpoint.json';
36
+ const HEX64 = /^[0-9a-f]{64}$/u;
37
+ const MAX_DIGESTS = 64;
38
+ const noFollow = fsConstants.O_NOFOLLOW ?? 0;
39
+ const sha = (bytes) => createHash('sha256').update(bytes).digest('hex');
40
+ const segName = (i) => `segment-${String(i).padStart(10, '0')}.jsonl`;
41
+ const idxOf = (name) => { const m = SEG.exec(name); return m ? Number(m[1]) : undefined; };
42
+ async function safeDir(dir, uid) {
43
+ await mkdir(dir, { mode: 0o700 }).catch((e) => { if (e?.code !== 'EEXIST')
44
+ throw e; });
45
+ const info = await lstat(dir);
46
+ if (info.isSymbolicLink() || !info.isDirectory())
47
+ throw new Error(`${dir} must be a real directory`);
48
+ if (info.uid !== uid)
49
+ throw new Error(`${dir} must be owned by uid ${uid}`);
50
+ if ((info.mode & 0o077) !== 0)
51
+ throw new Error(`${dir} has unsafe permissions`);
52
+ return info.ino;
53
+ }
54
+ export async function openDecisionLog(dir, opts) {
55
+ dir = path.resolve(dir);
56
+ const maxBytes = opts.maxSegmentBytes ?? 16 * 1024 * 1024;
57
+ const maxSegments = opts.maxSegments ?? 8;
58
+ const every = opts.checkpointEvery ?? 100;
59
+ const now = opts.now ?? (() => new Date());
60
+ let dirIno = await safeDir(dir, opts.rootUid);
61
+ const segments = async () => {
62
+ const names = (await readdir(dir)).filter((n) => SEG.test(n)).sort();
63
+ for (const n of names) { // refuse, never repair: a symlink or loose file here is not ours
64
+ const info = await lstat(path.join(dir, n));
65
+ if (info.isSymbolicLink() || !info.isFile() || info.uid !== opts.rootUid || (info.mode & 0o077) !== 0)
66
+ throw new Error(`${n} is not a root-only regular file`);
67
+ }
68
+ return names;
69
+ };
70
+ async function readCheckpoint() {
71
+ let bytes;
72
+ try {
73
+ bytes = await readRegularFile(path.join(dir, CP), 'checkpoint', 4096);
74
+ }
75
+ catch (e) {
76
+ return e?.code === 'ENOENT' ? undefined : 'invalid';
77
+ }
78
+ try {
79
+ const v = JSON.parse(bytes.toString('utf8'));
80
+ return Number.isSafeInteger(v.seq) && typeof v.hash === 'string' && HEX64.test(v.hash) && typeof v.segment === 'string' && SEG.test(v.segment) && Object.keys(v).length === 3
81
+ ? { seq: v.seq, hash: v.hash, segment: v.segment } : 'invalid';
82
+ }
83
+ catch {
84
+ return 'invalid';
85
+ }
86
+ }
87
+ let breaks = 0;
88
+ async function recover() {
89
+ const names = await segments();
90
+ const cp = await readCheckpoint();
91
+ const cpOk = cp !== undefined && cp !== 'invalid' ? cp : undefined;
92
+ const cpSeq = cpOk?.seq ?? 0;
93
+ const last = names.at(-1);
94
+ const brk = (from, seq, index) => {
95
+ breaks++;
96
+ return { index: index + 1, size: 0, seq: Math.max(seq, cpSeq), hash: null, newSeg: true, breakFrom: from };
97
+ };
98
+ if (last === undefined) {
99
+ if (cp === undefined)
100
+ return { index: 1, size: 0, seq: 0, hash: null, newSeg: true, breakFrom: null }; // fresh
101
+ return brk(cpOk?.segment ?? null, 0, cpOk ? idxOf(cpOk.segment) : 0); // log deleted but a checkpoint remains
102
+ }
103
+ const index = idxOf(last);
104
+ let content;
105
+ try {
106
+ content = await readRegularFile(path.join(dir, last), 'log segment', maxBytes + 1024 * 1024);
107
+ }
108
+ catch {
109
+ return brk(last, 0, index);
110
+ }
111
+ const lines = content.toString('utf8').split('\n');
112
+ const complete = lines.pop() === ''; // anything after the last newline is a partial write
113
+ let ok = complete && lines.length > 0 && cp !== 'invalid';
114
+ let seq = 0, hash = null, valid = 0, firstSeq = 0, firstPrev, cpHashSeen = cpOk?.segment === last ? false : true;
115
+ for (const line of lines) {
116
+ let r;
117
+ try {
118
+ r = JSON.parse(line);
119
+ }
120
+ catch {
121
+ ok = false;
122
+ break;
123
+ }
124
+ if (!Number.isSafeInteger(r.seq) || (r.prev !== null && typeof r.prev !== 'string')) {
125
+ ok = false;
126
+ break;
127
+ }
128
+ if (valid === 0) {
129
+ firstSeq = r.seq;
130
+ firstPrev = r.prev;
131
+ }
132
+ else if (r.seq !== seq + 1 || r.prev !== hash) {
133
+ ok = false;
134
+ break;
135
+ }
136
+ seq = r.seq;
137
+ hash = sha(line);
138
+ valid++;
139
+ if (cpOk?.segment === last && seq === cpOk.seq)
140
+ cpHashSeen = hash === cpOk.hash;
141
+ }
142
+ if (valid === 0)
143
+ return brk(last, 0, index);
144
+ if (cpOk) {
145
+ const ci = idxOf(cpOk.segment);
146
+ if (ci > index || (ci === index && !cpHashSeen) || (ci < index && (firstSeq !== cpOk.seq + 1 || firstPrev !== cpOk.hash)))
147
+ ok = false;
148
+ }
149
+ if (!ok)
150
+ return brk(last, seq, index);
151
+ return { index, size: content.length, seq, hash, newSeg: false, breakFrom: null };
152
+ }
153
+ let st = await recover();
154
+ let dirty = false;
155
+ let lastRecovery = 0;
156
+ let pending; // an enforce allow whose fsync failed: it needs a correction record
157
+ let sinceCheckpoint = 0;
158
+ let queue = Promise.resolve();
159
+ const checkpoint = async () => {
160
+ if (st.hash === null || st.newSeg && st.breakFrom !== null)
161
+ return; // nothing written since a break
162
+ const cp = { seq: st.seq, hash: st.hash, segment: segName(st.index) };
163
+ await writeFileAtomic(path.join(dir, CP), Buffer.from(JSON.stringify(cp)), 0o600);
164
+ sinceCheckpoint = 0;
165
+ };
166
+ async function doAppend(input, durable) {
167
+ if (opts.fault?.())
168
+ throw new Error('injected log fault');
169
+ if (!dirty) { // a deleted or replaced directory/segment is noticed here, not by a failing open
170
+ const stale = await Promise.all([lstat(dir), st.newSeg ? 0 : lstat(path.join(dir, segName(st.index)))]).then(([d]) => d.ino !== dirIno, () => true);
171
+ if (stale)
172
+ dirty = true;
173
+ }
174
+ if (dirty) {
175
+ if (Date.now() - lastRecovery < 1000)
176
+ throw new Error('log recovery rate-limited'); // fail fast instead of re-reading a segment per append
177
+ lastRecovery = Date.now();
178
+ const prev = st;
179
+ const ino = await safeDir(dir, opts.rootUid); // a loose or replaced directory stays refused
180
+ const prevName = prev.newSeg ? null : segName(prev.index);
181
+ const gone = prevName !== null && (ino !== dirIno || await lstat(path.join(dir, prevName)).then(() => false, () => true));
182
+ if (gone) {
183
+ breaks++;
184
+ const lastIdx = (await segments()).map((n) => idxOf(n)).at(-1) ?? 0;
185
+ st = { index: Math.max(prev.index, lastIdx) + 1, size: 0, seq: prev.seq, hash: null, newSeg: true, breakFrom: prevName };
186
+ }
187
+ else
188
+ st = await recover();
189
+ dirIno = ino;
190
+ dirty = false;
191
+ }
192
+ if (pending) { // the user never got that allow: say so before anything else
193
+ const p = pending;
194
+ await writeRecord({ ...p.input, action: 'deny', result: 'internal' }, false, p.seq);
195
+ pending = undefined;
196
+ }
197
+ await writeRecord(input, durable, null);
198
+ }
199
+ async function writeRecord(input, durable, supersedes) {
200
+ const rotate = !st.newSeg && st.size > 0 && st.size + 4096 > maxBytes; // 4 KiB is above any record's size
201
+ let wrote;
202
+ try {
203
+ if (rotate) {
204
+ await checkpoint();
205
+ st = { ...st, index: st.index + 1, size: 0, newSeg: true };
206
+ }
207
+ const record = {
208
+ seq: st.seq + 1, boot_ms: input.bootMs, at: now().toISOString(), mode: input.mode, action: input.action, event: input.event,
209
+ session: input.session, skill: input.skill, digests: input.digests.slice(0, MAX_DIGESTS), trust_root_version: input.trustRootVersion,
210
+ revocations_version: input.revocationsVersion, result: input.result, build: input.build, elapsed_ms: input.elapsedMs,
211
+ prev: st.hash, chain_break: st.breakFrom, supersedes,
212
+ };
213
+ const line = JSON.stringify(record);
214
+ const bytes = Buffer.from(`${line}\n`);
215
+ const file = path.join(dir, segName(st.index));
216
+ const flags = fsConstants.O_WRONLY | fsConstants.O_APPEND | noFollow | (st.newSeg ? fsConstants.O_CREAT | fsConstants.O_EXCL : 0);
217
+ const handle = await open(file, flags, 0o600);
218
+ try {
219
+ await handle.writeFile(bytes);
220
+ wrote = record.seq;
221
+ if (durable) {
222
+ if (opts.syncFault?.())
223
+ throw new Error('injected fsync fault');
224
+ await handle.sync();
225
+ }
226
+ }
227
+ finally {
228
+ await handle.close();
229
+ }
230
+ const created = st.newSeg;
231
+ st = { index: st.index, size: st.size + bytes.length, seq: record.seq, hash: sha(line), newSeg: false, breakFrom: null };
232
+ if (created)
233
+ for (const old of (await segments().catch(() => [])).slice(0, -maxSegments))
234
+ await unlink(path.join(dir, old)).catch(() => { });
235
+ if (++sinceCheckpoint >= every)
236
+ await checkpoint().catch(() => { }); // a stale checkpoint is still consistent
237
+ }
238
+ catch (error) {
239
+ dirty = true;
240
+ if (durable && wrote !== undefined)
241
+ pending = { seq: wrote, input }; // written but not synced: the caller reports failure
242
+ throw error;
243
+ }
244
+ }
245
+ return {
246
+ append(input, durable) { const run = queue.then(() => doAppend(input, durable)); queue = run.catch(() => { }); return run; },
247
+ status: () => ({ segment: st.newSeg ? null : segName(st.index), lastSeq: st.seq, chainBreaks: breaks }),
248
+ async close() { await queue; if (!dirty)
249
+ await checkpoint(); },
250
+ };
251
+ }
@@ -0,0 +1,67 @@
1
+ import { type FileHandle } from 'node:fs/promises';
2
+ import { type TreeFile } from '../tree-digest.ts';
3
+ import { type CertificateSource, type TrustContext, type Verdict } from '../verify.ts';
4
+ export declare const GENERATION_TYPE = "mago.gate-generation/v1";
5
+ export type Rejection = 'symlink' | 'special-file' | 'hard-link' | 'unsafe-name' | 'too-large' | 'ignored-content-not-allowed' | 'not-verified' | 'generation-mismatch' | 'generation-incomplete' | 'io-error';
6
+ export interface Failure {
7
+ ok: false;
8
+ reason: Rejection;
9
+ detail: string;
10
+ verdict?: Verdict;
11
+ }
12
+ export interface GenerationManifest {
13
+ type: typeof GENERATION_TYPE;
14
+ skill: string;
15
+ treeDigest: string;
16
+ files: TreeFile[];
17
+ certificateId: string;
18
+ trustRootVersion: number;
19
+ revocationsVersion: number;
20
+ buildProfile: string;
21
+ }
22
+ export type PublishResult = {
23
+ ok: true;
24
+ created: boolean;
25
+ manifest: GenerationManifest;
26
+ dir: string;
27
+ } | Failure;
28
+ export type ReadResult = {
29
+ ok: true;
30
+ manifest: GenerationManifest;
31
+ } | Failure;
32
+ /**
33
+ * Opaque handle to a staged copy: the open staging root, the open stage directory and the stage name. publishStaged
34
+ * is the only consumer; it reads the tree and renames through these descriptors, never through a caller path.
35
+ * `stagedDir` is informational (display / tests) and is never used for I/O by this module.
36
+ */
37
+ export declare class StagedSkill {
38
+ readonly stagedDir: string;
39
+ stagingH: FileHandle;
40
+ stageH: FileHandle;
41
+ name: string;
42
+ closed: boolean;
43
+ constructor(stagedDir: string, stagingH: FileHandle, stageH: FileHandle, name: string);
44
+ /** Removes the staged copy and closes both handles (idempotent). publishStaged calls this on every path. */
45
+ discard(): Promise<void>;
46
+ }
47
+ export type StageResult = {
48
+ ok: true;
49
+ staged: StagedSkill;
50
+ } | Failure;
51
+ /** Copies `sourceDir` into a fresh 0700 directory under `stagingRoot`. The caller must publish or discard the result. */
52
+ export declare function stageSkill(sourceDir: string, stagingRoot: string): Promise<StageResult>;
53
+ /** Re-verifies a published generation against its manifest: bytes, exec bits, modes, no extras, no links. */
54
+ export declare function readGeneration(generationsRoot: string, name: string, digest: string): Promise<ReadResult>;
55
+ export interface PublishOptions {
56
+ generationsRoot: string;
57
+ skillName: string;
58
+ certificates: readonly CertificateSource[];
59
+ context: TrustContext;
60
+ now: Date;
61
+ /** Opaque build/profile identifier recorded in the manifest. */
62
+ buildProfile: string;
63
+ }
64
+ /** Verifies the staged copy and publishes it as an immutable generation. The staged copy is always removed and its handles closed. */
65
+ export declare function publishStaged(staged: StagedSkill, o: PublishOptions): Promise<PublishResult>;
66
+ /** Stage, verify the copy, publish. */
67
+ export declare function installSkill(sourceDir: string, stagingRoot: string, o: PublishOptions): Promise<PublishResult>;