@sundownreel/mcp 0.0.0-stage → 0.1.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 (171) hide show
  1. package/README.md +65 -2
  2. package/brand.json +29 -0
  3. package/chunks/chunk-ONI7QK5B.mjs +63 -0
  4. package/chunks/chunk-YUE6XWVB.mjs +2 -0
  5. package/dsl/index.mjs +2 -0
  6. package/dsl/semantic.mjs +5 -0
  7. package/dsl/types.ts +240 -0
  8. package/engine/fonts/ArchivoBlack.ttf +0 -0
  9. package/engine/fonts/Caveat-Bold.ttf +0 -0
  10. package/engine-geo/data-manifest.json +460 -0
  11. package/engine-remotion/public/music/README.md +6 -0
  12. package/engine-remotion/public/music/bed-curious.mp3 +0 -0
  13. package/engine-remotion/public/music/bed-explainer.mp3 +0 -0
  14. package/engine-remotion/public/music/bed-reflective.mp3 +0 -0
  15. package/engine-remotion/public/music/bed-tense.mp3 +0 -0
  16. package/engine-remotion/public/music/bed-upbeat.mp3 +0 -0
  17. package/engine-remotion/public/music/music-index.json +52 -0
  18. package/engine-remotion/public/sfx/README.md +6 -0
  19. package/engine-remotion/public/sfx/alarm-buzz.mp3 +0 -0
  20. package/engine-remotion/public/sfx/beep-happy.mp3 +0 -0
  21. package/engine-remotion/public/sfx/boing-small.mp3 +0 -0
  22. package/engine-remotion/public/sfx/cash-register.mp3 +0 -0
  23. package/engine-remotion/public/sfx/chart-draw.mp3 +0 -0
  24. package/engine-remotion/public/sfx/click-key.mp3 +0 -0
  25. package/engine-remotion/public/sfx/click-sharp.mp3 +0 -0
  26. package/engine-remotion/public/sfx/click-switch.mp3 +0 -0
  27. package/engine-remotion/public/sfx/cloth-swish.mp3 +0 -0
  28. package/engine-remotion/public/sfx/counter-tick.mp3 +0 -0
  29. package/engine-remotion/public/sfx/ding.mp3 +0 -0
  30. package/engine-remotion/public/sfx/error-beep.mp3 +0 -0
  31. package/engine-remotion/public/sfx/glass-ping.mp3 +0 -0
  32. package/engine-remotion/public/sfx/glass-tick.mp3 +0 -0
  33. package/engine-remotion/public/sfx/impact-light.mp3 +0 -0
  34. package/engine-remotion/public/sfx/impact-punch.mp3 +0 -0
  35. package/engine-remotion/public/sfx/impact-soft.mp3 +0 -0
  36. package/engine-remotion/public/sfx/impact-thud.mp3 +0 -0
  37. package/engine-remotion/public/sfx/impact-tin.mp3 +0 -0
  38. package/engine-remotion/public/sfx/impact-wood.mp3 +0 -0
  39. package/engine-remotion/public/sfx/office-ambience-1.mp3 +0 -0
  40. package/engine-remotion/public/sfx/paper-feed.mp3 +0 -0
  41. package/engine-remotion/public/sfx/paper-rustle.mp3 +0 -0
  42. package/engine-remotion/public/sfx/paper-slide.mp3 +0 -0
  43. package/engine-remotion/public/sfx/paper-tear.mp3 +0 -0
  44. package/engine-remotion/public/sfx/pencil-scratch.mp3 +0 -0
  45. package/engine-remotion/public/sfx/pop-drop.mp3 +0 -0
  46. package/engine-remotion/public/sfx/pop-pluck.mp3 +0 -0
  47. package/engine-remotion/public/sfx/pop.mp3 +0 -0
  48. package/engine-remotion/public/sfx/printer-chatter.mp3 +0 -0
  49. package/engine-remotion/public/sfx/receipt-tick.mp3 +0 -0
  50. package/engine-remotion/public/sfx/room-tone.mp3 +0 -0
  51. package/engine-remotion/public/sfx/sfx-index.json +322 -0
  52. package/engine-remotion/public/sfx/slide-whoosh.mp3 +0 -0
  53. package/engine-remotion/public/sfx/stamp-thud.mp3 +0 -0
  54. package/engine-remotion/public/sfx/stinger-8bit.mp3 +0 -0
  55. package/engine-remotion/public/sfx/stinger-hit.mp3 +0 -0
  56. package/engine-remotion/public/sfx/stinger-pizzi.mp3 +0 -0
  57. package/engine-remotion/public/sfx/stinger-sax.mp3 +0 -0
  58. package/engine-remotion/public/sfx/stinger-steel.mp3 +0 -0
  59. package/engine-remotion/public/sfx/sweat-drop.mp3 +0 -0
  60. package/engine-remotion/public/sfx/swipe.mp3 +0 -0
  61. package/engine-remotion/public/sfx/tick-crisp.mp3 +0 -0
  62. package/engine-remotion/public/sfx/tick-soft.mp3 +0 -0
  63. package/engine-remotion/public/sfx/type-click.mp3 +0 -0
  64. package/engine-remotion/public/sfx/typewriter-soft.mp3 +0 -0
  65. package/engine-remotion/public/sfx/ui-confirm.mp3 +0 -0
  66. package/engine-remotion/public/sfx/wheel-roll.mp3 +0 -0
  67. package/engine-remotion/public/sfx/whoosh-rise.mp3 +0 -0
  68. package/engine-remotion/public/sfx/whoosh-ui-rise.mp3 +0 -0
  69. package/engine-remotion/public/sfx/whoosh.mp3 +0 -0
  70. package/library/music/bed.wav +0 -0
  71. package/library/sfx/thud.wav +0 -0
  72. package/library/sfx/tick.wav +0 -0
  73. package/library/sfx/whoosh.wav +0 -0
  74. package/package.json +38 -4
  75. package/pipeline/scripts/master_audio.sh +12 -0
  76. package/prompts/engine-engineer.md +26 -0
  77. package/prompts/fact-checker.md +22 -0
  78. package/prompts/idea-scout.md +21 -0
  79. package/prompts/library-artist.md +15 -0
  80. package/prompts/qa.md +20 -0
  81. package/prompts/researcher.md +22 -0
  82. package/prompts/shot-dsl-writer.md +63 -0
  83. package/prompts/style-shot-writer.md +46 -0
  84. package/registry/styles.mjs +89 -0
  85. package/render/fonts/Anton-Regular.ttf +0 -0
  86. package/render/fonts/ArchivoBlack.ttf +0 -0
  87. package/render/fonts/Caveat-Bold.ttf +0 -0
  88. package/render/fonts/Caveat.ttf +0 -0
  89. package/render/fonts/Cinzel-Black.ttf +0 -0
  90. package/render/fonts/Cinzel-SemiBold.ttf +0 -0
  91. package/render/fonts/CormorantGaramond-MediumItalic.ttf +0 -0
  92. package/render/fonts/CourierPrime-Regular.ttf +0 -0
  93. package/render/fonts/IBMPlexMono-SemiBold.ttf +0 -0
  94. package/render/fonts/IBMPlexSerif-SemiBold.ttf +0 -0
  95. package/render/fonts/Kalam-Bold.ttf +0 -0
  96. package/render/fonts/KaushanScript-Regular.ttf +0 -0
  97. package/render/fonts/LibreBaskerville-Bold.ttf +0 -0
  98. package/render/fonts/LibreBaskerville-Italic.ttf +0 -0
  99. package/render/fonts/PlayfairDisplay-Bold.ttf +0 -0
  100. package/render/fonts/PlayfairDisplay-Regular.ttf +0 -0
  101. package/render/fonts/README.md +15 -0
  102. package/render/fonts/ZillaSlab-Bold-Lining.ttf +0 -0
  103. package/render/fonts/licenses/Anton-OFL.txt +93 -0
  104. package/render/fonts/licenses/ArchivoBlack-OFL.txt +93 -0
  105. package/render/fonts/licenses/Caveat-OFL.txt +93 -0
  106. package/render/fonts/licenses/Cinzel-OFL.txt +93 -0
  107. package/render/fonts/licenses/CormorantGaramond-OFL.txt +93 -0
  108. package/render/fonts/licenses/CourierPrime-OFL.txt +93 -0
  109. package/render/fonts/licenses/IBMPlexMono-OFL.txt +93 -0
  110. package/render/fonts/licenses/IBMPlexSerif-OFL.txt +93 -0
  111. package/render/fonts/licenses/Kalam-OFL.txt +93 -0
  112. package/render/fonts/licenses/KaushanScript-OFL.txt +95 -0
  113. package/render/fonts/licenses/LibreBaskerville-OFL.txt +93 -0
  114. package/render/fonts/licenses/PlayfairDisplay-OFL.txt +93 -0
  115. package/render/fonts/licenses/ZillaSlab-OFL.txt +93 -0
  116. package/render/render.mjs +59539 -0
  117. package/render3d/data/footprints/README.md +27 -0
  118. package/render3d/data/footprints/test-district.geojson +1 -0
  119. package/render3d/fonts/ArchivoBlack.ttf +0 -0
  120. package/render3d/fonts/IBMPlexMono-400.ttf +0 -0
  121. package/render3d/fonts/IBMPlexMono-600.ttf +0 -0
  122. package/render3d/fonts/Inter-400.ttf +0 -0
  123. package/render3d/fonts/Inter-600.ttf +0 -0
  124. package/render3d/fonts/Inter-800.ttf +0 -0
  125. package/render3d/fonts/licenses/ArchivoBlack-OFL.txt +93 -0
  126. package/render3d/fonts/licenses/BlockfolkCaps-OFL.txt +96 -0
  127. package/render3d/fonts/licenses/IBMPlexMono-OFL.txt +93 -0
  128. package/render3d/fonts/licenses/Inter-OFL.txt +93 -0
  129. package/render3d/render.mjs +41191 -0
  130. package/render3d/runtime.js +4532 -0
  131. package/rendergeo/fonts/Anton-Regular.ttf +0 -0
  132. package/rendergeo/fonts/ArchivoBlack.ttf +0 -0
  133. package/rendergeo/fonts/BarlowCondensed-Bold.ttf +0 -0
  134. package/rendergeo/fonts/BarlowCondensed-SemiBold.ttf +0 -0
  135. package/rendergeo/fonts/Caveat-Bold.ttf +0 -0
  136. package/rendergeo/fonts/Caveat.ttf +0 -0
  137. package/rendergeo/fonts/Cinzel-Black.ttf +0 -0
  138. package/rendergeo/fonts/Cinzel-SemiBold.ttf +0 -0
  139. package/rendergeo/fonts/CormorantGaramond-Medium.ttf +0 -0
  140. package/rendergeo/fonts/CormorantGaramond-MediumItalic.ttf +0 -0
  141. package/rendergeo/fonts/CormorantGaramond-SemiBold.ttf +0 -0
  142. package/rendergeo/fonts/CourierPrime-Regular.ttf +0 -0
  143. package/rendergeo/fonts/IBMPlexMono-Medium.ttf +0 -0
  144. package/rendergeo/fonts/IBMPlexMono-Regular.ttf +0 -0
  145. package/rendergeo/fonts/IBMPlexMono-SemiBold.ttf +0 -0
  146. package/rendergeo/fonts/IBMPlexSansCondensed-Medium.ttf +0 -0
  147. package/rendergeo/fonts/IBMPlexSansCondensed-SemiBold.ttf +0 -0
  148. package/rendergeo/fonts/IBMPlexSerif-SemiBold.ttf +0 -0
  149. package/rendergeo/fonts/Kalam-Bold.ttf +0 -0
  150. package/rendergeo/fonts/KaushanScript-Regular.ttf +0 -0
  151. package/rendergeo/fonts/LibreBaskerville-Bold.ttf +0 -0
  152. package/rendergeo/fonts/LibreBaskerville-Italic.ttf +0 -0
  153. package/rendergeo/fonts/OldStandard-Bold.ttf +0 -0
  154. package/rendergeo/fonts/OldStandard-Italic.ttf +0 -0
  155. package/rendergeo/fonts/OldStandard-Regular.ttf +0 -0
  156. package/rendergeo/fonts/PlayfairDisplay-Bold.ttf +0 -0
  157. package/rendergeo/fonts/PlayfairDisplay-Regular.ttf +0 -0
  158. package/rendergeo/fonts/ZillaSlab-Bold-Lining.ttf +0 -0
  159. package/rendergeo/render-geo.mjs +45063 -0
  160. package/server.js +293 -0
  161. package/studio-cli/bin/sundownreel-gate.mjs +205 -0
  162. package/studio-cli/src/gate.mjs +704 -0
  163. package/styles/README.md +32 -0
  164. package/styles/broadsheet/STYLE.md +5 -0
  165. package/styles/broadsheet/style.json +11 -0
  166. package/styles/cartoon/STYLE.md +37 -0
  167. package/styles/cartoon/style.json +12 -0
  168. package/styles/chalkline/STYLE.md +30 -0
  169. package/styles/chalkline/style.json +11 -0
  170. package/thumbnails/dist/make.mjs +62995 -0
  171. package/vendor/gsap.min.js +11 -0
@@ -0,0 +1,704 @@
1
+ // sundownreel-gate core: the per-install Ed25519 signing key, the pin set of each gate, and signed, append-only
2
+ // decision records in videos/<id>/_gates/gate<N>.jsonl. Node built-ins only (no dependencies).
3
+ //
4
+ // The MCP server verifies these records in mcp/src/cartoon/episodes.ts with the PUBLIC key only. The canonical
5
+ // payload, the required pins and the verification rules here must stay in step with that file; the tests in
6
+ // mcp/test/gates.test.ts sign with this module and verify with the MCP.
7
+ import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, sign, verify } from "node:crypto";
8
+ import { appendFileSync, chmodSync, closeSync, existsSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, statSync, writeFileSync } from "node:fs";
9
+ import os from "node:os";
10
+ import path from "node:path";
11
+
12
+ export const RECORD_VERSION = 1;
13
+ export const GATE_NAMES = { 1: "topic + title direction", 2: "script + facts", 3: "animatic by shot id", 4: "package (you upload by hand)" };
14
+
15
+ // ---- keys ----
16
+
17
+ /** ~/.sundownreel/keys, or $SUNDOWNREEL_HOME/keys. Never inside a studio or episode folder. */
18
+ export function keyDir() {
19
+ const home = process.env.SUNDOWNREEL_HOME ? path.resolve(process.env.SUNDOWNREEL_HOME) : path.join(os.homedir(), ".sundownreel");
20
+ return path.join(home, "keys");
21
+ }
22
+
23
+ export function keyPaths() {
24
+ const dir = keyDir();
25
+ return { dir, privateKey: path.join(dir, "gate-ed25519.key"), publicKey: path.join(dir, "gate-ed25519.pub") };
26
+ }
27
+
28
+ export function keyIdOf(publicKey) {
29
+ return createHash("sha256").update(publicKey.export({ type: "spki", format: "der" })).digest("hex").slice(0, 16);
30
+ }
31
+
32
+ function isWithin(parent, child) {
33
+ const r = path.relative(parent, child);
34
+ return r === "" || (!r.startsWith("..") && !path.isAbsolute(r));
35
+ }
36
+
37
+ function realish(p) {
38
+ // realpath of the deepest existing ancestor, so a not-yet-created key dir is still compared correctly.
39
+ let cur = path.resolve(p);
40
+ const tail = [];
41
+ while (!existsSync(cur) && path.dirname(cur) !== cur) {
42
+ tail.unshift(path.basename(cur));
43
+ cur = path.dirname(cur);
44
+ }
45
+ return path.join(realpathSync(cur), ...tail);
46
+ }
47
+
48
+ /** Refuse a key location inside the episode, its studio home or REELFORGE_HOME (places agents write to). */
49
+ export function assertKeyDirSafe(videoDir) {
50
+ const dir = realish(keyDir());
51
+ const forbidden = [videoDir];
52
+ const parent = path.dirname(path.resolve(videoDir));
53
+ if (path.basename(parent) === "videos") forbidden.push(path.dirname(parent));
54
+ if (process.env.REELFORGE_HOME) forbidden.push(process.env.REELFORGE_HOME);
55
+ for (const f of forbidden) {
56
+ if (isWithin(realish(f), dir)) {
57
+ throw new Error(`The approval key folder ${dir} is inside ${f}, which agents write to. Set SUNDOWNREEL_HOME to a private folder (default ~/.sundownreel).`);
58
+ }
59
+ }
60
+ }
61
+
62
+ /** The installed public key, or null. */
63
+ export function loadPublicKey() {
64
+ const { publicKey } = keyPaths();
65
+ try {
66
+ const st = lstatSync(publicKey);
67
+ if (!st.isFile()) return null;
68
+ const key = createPublicKey(readFileSync(publicKey));
69
+ if (key.asymmetricKeyType !== "ed25519") return null;
70
+ return { key, keyId: keyIdOf(key) };
71
+ } catch {
72
+ return null;
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Load the signing key, creating it on first use (dir 0700, private key 0600, public key 0644).
78
+ * Returns { privateKey, publicKey, keyId, created }.
79
+ */
80
+ export function loadOrCreateSigningKey({ create = true } = {}) {
81
+ const p = keyPaths();
82
+ const hasPriv = existsSync(p.privateKey);
83
+ const hasPub = existsSync(p.publicKey);
84
+ if (!hasPriv) {
85
+ if (hasPub) {
86
+ throw new Error(
87
+ `${p.publicKey} exists but its private key ${p.privateKey} does not. Approvals can't be signed. ` +
88
+ "If you deliberately want a new key (all earlier approvals on this machine become unverified), remove the .pub file and run again.",
89
+ );
90
+ }
91
+ if (!create) throw new Error(`No approval key at ${p.privateKey}. Run sundownreel-gate approve in your own terminal to create it.`);
92
+ mkdirSync(p.dir, { recursive: true, mode: 0o700 });
93
+ chmodSync(p.dir, 0o700);
94
+ const { privateKey, publicKey } = generateKeyPairSync("ed25519");
95
+ writeFileSync(p.privateKey, privateKey.export({ type: "pkcs8", format: "pem" }), { mode: 0o600, flag: "wx" });
96
+ writeFileSync(p.publicKey, publicKey.export({ type: "spki", format: "pem" }), { mode: 0o644, flag: "wx" });
97
+ return { privateKey, publicKey, keyId: keyIdOf(publicKey), created: true };
98
+ }
99
+ const st = lstatSync(p.privateKey);
100
+ if (!st.isFile()) throw new Error(`${p.privateKey} is not a regular file.`);
101
+ if (st.mode & 0o077) chmodSync(p.privateKey, 0o600);
102
+ const privateKey = createPrivateKey(readFileSync(p.privateKey));
103
+ if (privateKey.asymmetricKeyType !== "ed25519") throw new Error(`${p.privateKey} is not an Ed25519 key.`);
104
+ const publicKey = createPublicKey(privateKey);
105
+ const installed = loadPublicKey();
106
+ if (!installed) writeFileSync(p.publicKey, publicKey.export({ type: "spki", format: "pem" }), { mode: 0o644 });
107
+ else if (installed.keyId !== keyIdOf(publicKey)) {
108
+ throw new Error(`${p.publicKey} does not belong to ${p.privateKey} (someone replaced it?). Refusing to sign until that is resolved.`);
109
+ }
110
+ return { privateKey, publicKey, keyId: keyIdOf(publicKey), created: false };
111
+ }
112
+
113
+ // ---- records ----
114
+
115
+ const sortedObj = (o) => Object.fromEntries(Object.keys(o).sort().map((k) => [k, o[k]]));
116
+
117
+ /** Exact signed fields in signed order. Must match normaliseGateRecord() in mcp/src/cartoon/episodes.ts. */
118
+ export function canonicalRecord(r) {
119
+ return {
120
+ v: RECORD_VERSION,
121
+ episode: r.episode,
122
+ gate: r.gate,
123
+ decision: r.decision,
124
+ decided_by: r.decided_by,
125
+ at: r.at,
126
+ pins: sortedObj(r.pins ?? {}),
127
+ flags: sortedObj(r.flags ?? {}),
128
+ skipped_gates: [...new Set(r.skipped_gates ?? [])].sort((a, b) => a - b),
129
+ supersedes: r.supersedes ?? null,
130
+ delta: [...(r.delta ?? [])].sort(),
131
+ note: r.note ?? "",
132
+ key_id: r.key_id,
133
+ };
134
+ }
135
+
136
+ export function canonicalPayload(r) {
137
+ return JSON.stringify(canonicalRecord(r));
138
+ }
139
+
140
+ /** Sign a record with the given private key; returns the line object { ...fields, sig }. */
141
+ export function signRecord(fields, privateKey) {
142
+ const key_id = keyIdOf(createPublicKey(privateKey));
143
+ const rec = canonicalRecord({ ...fields, key_id });
144
+ const sig = sign(null, Buffer.from(JSON.stringify(rec)), privateKey).toString("base64");
145
+ return { ...rec, sig };
146
+ }
147
+
148
+ export function sha256Text(text) {
149
+ return createHash("sha256").update(text).digest("hex");
150
+ }
151
+
152
+ export function sha256File(file) {
153
+ const hash = createHash("sha256");
154
+ const fd = openSync(file, "r");
155
+ const buf = Buffer.allocUnsafe(1 << 20);
156
+ try {
157
+ let n;
158
+ while ((n = readSync(fd, buf, 0, buf.length, null)) > 0) hash.update(buf.subarray(0, n));
159
+ } finally {
160
+ closeSync(fd);
161
+ }
162
+ return hash.digest("hex");
163
+ }
164
+
165
+ // ---- pins ----
166
+
167
+ /** Minimum pins of an approval (mirrors GATE_REQUIRED_PINS in episodes.ts). */
168
+ export const REQUIRED_PINS = {
169
+ 1: [{ role: "01-topic/gate1.md", test: /^01-topic\/gate1\.md$/ }],
170
+ 2: [
171
+ { role: "04-script/script_vo.txt", test: /^04-script\/script_vo\.txt$/ },
172
+ { role: "03-research/facts.csv (or facts.checked.csv)", test: /^03-research\/facts(\.checked)?\.csv$/ },
173
+ ],
174
+ 3: [
175
+ { role: "07-shots/shots.validated.json", test: /^07-shots\/shots\.validated\.json$/ },
176
+ { role: "an animatic (08-render/<run>/animatic.mp4)", test: /^08-render\/(?:[^/]+\/)?animatic\.mp4$/ },
177
+ ],
178
+ 4: [{ role: "12-package/package.json (or 08-package/description.md)", test: /^(12-package\/package\.json|08-package\/description\.md)$/ }],
179
+ };
180
+
181
+ const IGNORED_NAMES = /(^\.|\.tmp$|\.bak$|~$)/;
182
+ const MAX_PINS = 400;
183
+
184
+ function regular(dir, rel) {
185
+ const abs = path.join(dir, rel);
186
+ try {
187
+ const st = lstatSync(abs);
188
+ if (!st.isFile()) return null;
189
+ const r = path.relative(realpathSync(dir), realpathSync(abs));
190
+ if (r.startsWith("..") || path.isAbsolute(r)) return null;
191
+ return abs;
192
+ } catch {
193
+ return null;
194
+ }
195
+ }
196
+
197
+ /** Regular files under rel (depth-limited), as posix relpaths. Symlinks are skipped. */
198
+ function walk(dir, rel, depth = 2) {
199
+ const root = path.join(dir, rel);
200
+ let entries;
201
+ try {
202
+ if (!lstatSync(root).isDirectory()) return [];
203
+ entries = readdirSync(root, { withFileTypes: true });
204
+ } catch {
205
+ return [];
206
+ }
207
+ const out = [];
208
+ for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
209
+ if (IGNORED_NAMES.test(e.name)) continue;
210
+ const child = `${rel}/${e.name}`;
211
+ if (e.isFile()) out.push(child);
212
+ else if (e.isDirectory() && depth > 1 && e.name !== "versions" && e.name !== "stills") out.push(...walk(dir, child, depth - 1));
213
+ }
214
+ return out;
215
+ }
216
+
217
+ /** Newest (by mtime) existing file among relpaths, or null. */
218
+ function newest(dir, rels) {
219
+ let best = null;
220
+ let bestT = -1;
221
+ for (const r of rels) {
222
+ const abs = regular(dir, r);
223
+ if (!abs) continue;
224
+ const t = statSync(abs).mtimeMs;
225
+ if (t > bestT) {
226
+ best = r;
227
+ bestT = t;
228
+ }
229
+ }
230
+ return best;
231
+ }
232
+
233
+ function runFiles(dir, folder, name) {
234
+ const out = [];
235
+ if (regular(dir, `${folder}/${name}`)) out.push(`${folder}/${name}`);
236
+ try {
237
+ for (const d of readdirSync(path.join(dir, folder), { withFileTypes: true })) {
238
+ if (d.isDirectory() && regular(dir, `${folder}/${d.name}/${name}`)) out.push(`${folder}/${d.name}/${name}`);
239
+ }
240
+ } catch {
241
+ /* no folder */
242
+ }
243
+ return out;
244
+ }
245
+
246
+ export function activeFactsFile(dir) {
247
+ for (const rel of ["03-research/facts.checked.csv", "03-research/facts.csv"]) if (regular(dir, rel)) return rel;
248
+ return null;
249
+ }
250
+
251
+ export function readManifest(dir) {
252
+ const abs = regular(dir, "episode.json");
253
+ if (!abs) return null;
254
+ try {
255
+ return JSON.parse(readFileSync(abs, "utf8"));
256
+ } catch {
257
+ return null;
258
+ }
259
+ }
260
+
261
+ export function isHypothetical(dir) {
262
+ return readManifest(dir)?.hypothetical === true;
263
+ }
264
+
265
+ // Mirrors mcp/src/cartoon/profile.ts (episodeStyleId / gateProfileOf): the EFFECTIVE values, which the MCP compares.
266
+ const OPERATOR_STYLE_IDS = new Set(["cutout", "cartoon", "paper-puppet", "paper-cutout", "puppet-explainer", "ledger-cartoon"]);
267
+ export function episodeStyleId(dir) {
268
+ const style = readManifest(dir)?.style;
269
+ return typeof style === "string" && style.trim() ? style.trim() : "cutout";
270
+ }
271
+ export function gateProfileOf(dir) {
272
+ const raw = readManifest(dir)?.gateProfile;
273
+ if (raw === "quick" || raw === "strict") return raw;
274
+ return OPERATOR_STYLE_IDS.has(episodeStyleId(dir).replace(/@\d+$/, "")) ? "strict" : "quick";
275
+ }
276
+
277
+ /** Gate 2 signs the human-controlled episode.json fields; editing any of them later makes Gate 2 stale. */
278
+ export function gate2Flags(dir) {
279
+ return { hypothetical: isHypothetical(dir), gateProfile: gateProfileOf(dir), style: episodeStyleId(dir) };
280
+ }
281
+
282
+ /**
283
+ * The files a decision on this gate pins: the required ones plus every optional input that exists.
284
+ * Returns { candidates: relpath[], extras: { animatic?, final?, qa? } }.
285
+ */
286
+ export function gateFiles(dir, gate) {
287
+ const extras = {};
288
+ let rels = [];
289
+ if (gate === 1) rels = walk(dir, "01-topic", 2);
290
+ if (gate === 2) {
291
+ rels = [
292
+ "04-script/script_vo.txt",
293
+ "04-script/script.md",
294
+ "04-script/meta.json",
295
+ "04-script/gate2.md",
296
+ "03-research/facts.csv",
297
+ "03-research/facts.checked.csv",
298
+ "03-research/sources.csv",
299
+ "03-research/factcheck.md",
300
+ ];
301
+ }
302
+ if (gate === 3) {
303
+ const animatic = newest(dir, runFiles(dir, "08-render", "animatic.mp4"));
304
+ if (animatic) extras.animatic = animatic;
305
+ rels = [
306
+ "07-shots/shots.validated.json",
307
+ "07-shots/shots.json",
308
+ "07-shots/shots.compiled.json",
309
+ "07-shots/gate3.md",
310
+ "06-vo/words.json",
311
+ "06-vo/vo.wav",
312
+ "06-vo/script_vo.txt",
313
+ ...(animatic ? [animatic, path.posix.join(path.posix.dirname(animatic), "render.json")] : []),
314
+ ];
315
+ }
316
+ if (gate === 4) {
317
+ const final = newest(dir, runFiles(dir, "08-render", "final.mp4"));
318
+ const qa = newest(dir, runFiles(dir, "09-qa", "qa.json"));
319
+ if (final) extras.final = final;
320
+ if (qa) extras.qa = qa;
321
+ rels = [
322
+ ...walk(dir, "12-package", 2),
323
+ ...walk(dir, "08-package", 2),
324
+ "10-credits.json",
325
+ ...(final ? [final, path.posix.join(path.posix.dirname(final), "render.json")] : []),
326
+ ...(qa ? [qa] : []),
327
+ ];
328
+ }
329
+ const candidates = [...new Set(rels)].filter((r) => regular(dir, r)).slice(0, MAX_PINS);
330
+ return { candidates, extras };
331
+ }
332
+
333
+ /** { pins: {rel: sha}, missing: [role], extras } for the gate, hashed now. */
334
+ export function collectPins(dir, gate) {
335
+ const { candidates, extras } = gateFiles(dir, gate);
336
+ const pins = {};
337
+ for (const rel of candidates) pins[rel] = sha256File(path.join(dir, rel));
338
+ const missing = REQUIRED_PINS[gate].filter((r) => !Object.keys(pins).some((p) => r.test.test(p))).map((r) => r.role);
339
+ return { pins: sortedObj(pins), missing, extras };
340
+ }
341
+
342
+ function currentSha(dir, rel) {
343
+ if (rel.startsWith("_gates/") || rel.includes("\\")) return null;
344
+ const abs = path.resolve(dir, rel);
345
+ if (!isWithin(dir, abs)) return null;
346
+ const ok = regular(dir, path.relative(dir, abs));
347
+ return ok ? sha256File(ok) : null;
348
+ }
349
+
350
+ // ---- verification (mirror of episodes.ts readGate/readGates, used for status, delta and upstream checks) ----
351
+
352
+ const SHA_HEX = /^[0-9a-f]{64}$/;
353
+ const DECISIONS = new Set(["approved", "sent_back", "rejected"]);
354
+
355
+ export function gateFile(dir, gate) {
356
+ return path.join(dir, "_gates", `gate${gate}.jsonl`);
357
+ }
358
+
359
+ function verifyParsed(raw, dir, gate, key) {
360
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return "not a JSON object";
361
+ if (typeof raw.sig !== "string" || !raw.sig) return "unsigned";
362
+ if (raw.v !== RECORD_VERSION) return "unsigned or unknown record format (no v:1)";
363
+ if (typeof raw.episode !== "string" || ![1, 2, 3, 4].includes(raw.gate) || !DECISIONS.has(raw.decision)) return "malformed";
364
+ if (typeof raw.decided_by !== "string" || typeof raw.at !== "string" || Number.isNaN(Date.parse(raw.at)) || typeof raw.key_id !== "string") return "malformed";
365
+ if (raw.pins && !Object.values(raw.pins).every((s) => typeof s === "string" && SHA_HEX.test(s))) return "bad pins";
366
+ if (!key) return "no approval key installed on this machine";
367
+ if (raw.key_id !== key.keyId) return `signed by another key (${raw.key_id}), not this machine's ${key.keyId}`;
368
+ let good = false;
369
+ try {
370
+ good = verify(null, Buffer.from(canonicalPayload(raw)), key.key, Buffer.from(raw.sig, "base64"));
371
+ } catch {
372
+ good = false;
373
+ }
374
+ if (!good) return "bad signature";
375
+ if (raw.gate !== gate) return `record is for Gate ${raw.gate}`;
376
+ if (raw.episode !== path.basename(dir)) return `record is for episode "${raw.episode}"`;
377
+ if (!raw.decided_by.startsWith("human:")) return `not a human decision (${raw.decided_by})`;
378
+ if (raw.decision === "approved") {
379
+ const pins = Object.keys(raw.pins ?? {});
380
+ if (pins.some((p) => !isWithin(dir, path.resolve(dir, p)) || p.startsWith("_gates/"))) return "pin outside the episode";
381
+ const missing = REQUIRED_PINS[gate].filter((r) => !pins.some((p) => r.test.test(p)));
382
+ if (missing.length) return `approval does not pin ${missing.map((m) => m.role).join(", ")}`;
383
+ if (gate === 2 && typeof raw.flags?.hypothetical !== "boolean") return "Gate 2 approval without the hypothetical flag";
384
+ }
385
+ return null;
386
+ }
387
+
388
+ /** Verified and ignored records of one gate file. Verified entries: { rec, line, lineSha }. */
389
+ export function readRecords(dir, gate, key = loadPublicKey()) {
390
+ const file = gateFile(dir, gate);
391
+ const verified = [];
392
+ const ignored = [];
393
+ let text = "";
394
+ try {
395
+ if (lstatSync(file).isFile()) text = readFileSync(file, "utf8");
396
+ } catch {
397
+ return { verified, ignored };
398
+ }
399
+ text.split(/\r?\n/).forEach((line, i) => {
400
+ if (!line.trim()) return;
401
+ let raw;
402
+ try {
403
+ raw = JSON.parse(line);
404
+ } catch {
405
+ ignored.push(`unverified gate record (ignored): line ${i + 1}: not JSON`);
406
+ return;
407
+ }
408
+ const why = verifyParsed(raw, dir, gate, key);
409
+ if (why) ignored.push(`unverified gate record (ignored): line ${i + 1}: ${why}`);
410
+ else verified.push({ rec: canonicalRecord(raw), line: i + 1, lineSha: sha256Text(line) });
411
+ });
412
+ return { verified, ignored };
413
+ }
414
+
415
+ /** Newest verified record by signed timestamp (ties: later line). */
416
+ export function newestRecord(verified, filter = () => true) {
417
+ let best = null;
418
+ for (const v of verified) if (filter(v.rec) && (!best || Date.parse(v.rec.at) >= Date.parse(best.rec.at))) best = v;
419
+ return best;
420
+ }
421
+
422
+ function drift(dir, rec) {
423
+ const changed = [];
424
+ for (const [rel, sha] of Object.entries(rec.pins)) if (currentSha(dir, rel) !== sha) changed.push(rel);
425
+ if (rec.gate === 2) {
426
+ const active = activeFactsFile(dir);
427
+ if (active && !(active in rec.pins)) changed.push(`${active} (not pinned)`);
428
+ if (rec.flags.hypothetical !== isHypothetical(dir)) changed.push("episode.json hypothetical flag");
429
+ if (typeof rec.flags.gateProfile === "string" && rec.flags.gateProfile !== gateProfileOf(dir)) changed.push("episode.json gateProfile");
430
+ if (typeof rec.flags.style === "string" && rec.flags.style !== episodeStyleId(dir)) changed.push("episode.json style");
431
+ }
432
+ return changed;
433
+ }
434
+
435
+ /** States of all four gates, with the same rules as the MCP. */
436
+ export function gateStatus(dir) {
437
+ const key = loadPublicKey();
438
+ const gates = [1, 2, 3, 4].map((gate) => {
439
+ const { verified, ignored } = readRecords(dir, gate, key);
440
+ const g = { gate, name: GATE_NAMES[gate], state: "none", ignored };
441
+ if (!key) g.detail = "not approved (no approval key — run sundownreel-gate on this machine)";
442
+ const top = newestRecord(verified);
443
+ if (!top) return g;
444
+ delete g.detail;
445
+ Object.assign(g, { decidedBy: top.rec.decided_by, at: top.rec.at, note: top.rec.note || undefined, record: top.rec });
446
+ if (top.rec.decision === "approved") {
447
+ const changed = drift(dir, top.rec);
448
+ g.state = changed.length ? "stale" : "approved";
449
+ if (changed.length) g.changedPins = changed;
450
+ g.skippedGates = top.rec.skipped_gates;
451
+ } else g.state = top.rec.decision;
452
+ return g;
453
+ });
454
+ for (const g of gates) {
455
+ if (g.state !== "approved") continue;
456
+ for (const e of gates.slice(0, g.gate - 1)) {
457
+ if (e.state === "approved") continue;
458
+ if (e.state === "none" && g.skippedGates?.includes(e.gate)) continue;
459
+ g.state = "stale";
460
+ g.staleReason = `Gate ${e.gate} is ${e.state}${e.state === "none" ? " and this approval did not skip it" : ""}`;
461
+ break;
462
+ }
463
+ }
464
+ return { key, gates };
465
+ }
466
+
467
+ // ---- facts (Gate 2 summary) ----
468
+
469
+ /** Minimal RFC 4180 reader (quotes, doubled quotes, CRLF, BOM). */
470
+ export function parseCsv(text) {
471
+ const rows = [];
472
+ let row = [];
473
+ let cell = "";
474
+ let quoted = false;
475
+ const t = text.replace(/^/, "");
476
+ for (let i = 0; i < t.length; i++) {
477
+ const c = t[i];
478
+ if (quoted) {
479
+ if (c === '"' && t[i + 1] === '"') {
480
+ cell += '"';
481
+ i++;
482
+ } else if (c === '"') quoted = false;
483
+ else cell += c;
484
+ } else if (c === '"') quoted = true;
485
+ else if (c === ",") {
486
+ row.push(cell);
487
+ cell = "";
488
+ } else if (c === "\n" || c === "\r") {
489
+ if (c === "\r" && t[i + 1] === "\n") i++;
490
+ row.push(cell);
491
+ rows.push(row);
492
+ row = [];
493
+ cell = "";
494
+ } else cell += c;
495
+ }
496
+ if (cell || row.length) {
497
+ row.push(cell);
498
+ rows.push(row);
499
+ }
500
+ const [head, ...body] = rows.filter((r) => r.some((c) => c.trim()));
501
+ if (!head) return [];
502
+ const keys = head.map((h) => h.trim());
503
+ return body.map((r) => Object.fromEntries(keys.map((k, i) => [k, (r[i] ?? "").trim()])));
504
+ }
505
+
506
+ /** Fact ids referenced by the script (04-script/*) or the shots (07-shots/*: factId / factIds, or the id as a word). */
507
+ export function usedFactIds(dir, ids) {
508
+ const texts = [];
509
+ for (const rel of ["04-script/script.md", "04-script/script_vo.txt", "04-script/meta.json", "07-shots/shots.json", "07-shots/shots.validated.json"]) {
510
+ const abs = regular(dir, rel);
511
+ if (abs) texts.push(readFileSync(abs, "utf8"));
512
+ }
513
+ const all = texts.join("\n");
514
+ const esc = (x) => x.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
515
+ return new Set(ids.filter((id) => new RegExp(`(^|[^A-Za-z0-9_-])${esc(id)}(?![A-Za-z0-9_-])`).test(all)));
516
+ }
517
+
518
+ /**
519
+ * Fact eligibility and Gate 2 blockers (decision #13). A fact is USED when its on_screen string is set (it is meant
520
+ * for the screen) or the script or shots reference its id. Every used fact must be verified or computed (scenario
521
+ * only in a hypothetical episode), and checked by a session other than its researcher. Unused facts only warn.
522
+ */
523
+ export function factsSummary(dir) {
524
+ const rel = activeFactsFile(dir);
525
+ const hypothetical = isHypothetical(dir);
526
+ if (!rel) return { file: null, hypothetical, total: 0, byStatus: {}, eligible: [], notEligible: [], used: [], blockers: ["no facts file (03-research/facts.csv)"], warnings: [] };
527
+ const rows = parseCsv(readFileSync(path.join(dir, rel), "utf8")).filter((r) => r.id);
528
+ const referenced = usedFactIds(dir, rows.map((r) => r.id));
529
+ const byStatus = {};
530
+ const eligible = [];
531
+ const notEligible = [];
532
+ const used = [];
533
+ const bad = { unchecked: [], disputed: [], scenario: [], noChecker: [], selfChecked: [] };
534
+ const unusedProblems = [];
535
+ for (const r of rows) {
536
+ const st = (r.status ?? "").toLowerCase() || "(none)";
537
+ (byStatus[st] ??= []).push(r.id);
538
+ const ok = st === "verified" || st === "computed" || (st === "scenario" && hypothetical);
539
+ (ok ? eligible : notEligible).push(r.id);
540
+ const isUsed = !!(r.on_screen ?? "").trim() || referenced.has(r.id);
541
+ const checker = (r.checker ?? "").trim().split(/\s+/)[0] ?? "";
542
+ const researcher = (r.researcher ?? "").trim();
543
+ const problems = [];
544
+ if (st === "unverified" || st === "(none)") problems.push("unchecked");
545
+ else if (st === "disputed") problems.push("disputed");
546
+ else if (st === "scenario" && !hypothetical) problems.push("scenario");
547
+ else if (!ok) problems.push("unchecked");
548
+ if (!problems.includes("unchecked")) {
549
+ if (!checker) problems.push("noChecker");
550
+ else if (researcher && checker === researcher) problems.push("selfChecked");
551
+ }
552
+ if (isUsed) {
553
+ used.push(r.id);
554
+ for (const p of problems) bad[p].push(r.id);
555
+ } else if (problems.length) unusedProblems.push(`${r.id} (${problems.join(", ")})`);
556
+ }
557
+ const blockers = [];
558
+ const warnings = [];
559
+ if (bad.unchecked.length) blockers.push(`facts used by the script or shots are not fact-checked (unverified or no status): ${bad.unchecked.join(", ")}`);
560
+ if (bad.disputed.length) blockers.push(`disputed facts: ${bad.disputed.join(", ")} (fix or remove them; never waivable)`);
561
+ if (bad.scenario.length) blockers.push(`scenario facts ${bad.scenario.join(", ")} but episode.json does not flag the episode hypothetical`);
562
+ if (bad.noChecker.length) blockers.push(`facts with no checker recorded: ${bad.noChecker.join(", ")} (an independent session must check them with factcheck_record)`);
563
+ if (bad.selfChecked.length) blockers.push(`facts checked by their own researcher: ${bad.selfChecked.join(", ")} (decision #13: the checker must be a different session)`);
564
+ if (unusedProblems.length) warnings.push(`facts not used by the script or shots, never on screen: ${unusedProblems.join("; ")}`);
565
+ const noOnScreen = rows.filter((r) => !(r.on_screen ?? "").trim()).map((r) => r.id);
566
+ if (noOnScreen.length) warnings.push(`${noOnScreen.length} fact(s) with an empty on_screen string`);
567
+ return { file: rel, hypothetical, total: rows.length, byStatus, eligible, notEligible, used, blockers, warnings };
568
+ }
569
+
570
+ // ---- decisions ----
571
+
572
+ export const VERBS = { approved: "approve", sent_back: "send back", rejected: "reject" };
573
+
574
+ export function osActor() {
575
+ let user = "";
576
+ try {
577
+ user = os.userInfo().username;
578
+ } catch {
579
+ user = process.env.USER ?? process.env.USERNAME ?? "unknown";
580
+ }
581
+ return `human:${user || "unknown"}`;
582
+ }
583
+
584
+ /**
585
+ * Everything the human is shown before deciding: pins (or only the changed pins for a delta re-approval,
586
+ * decision #21), upstream state, gate-specific summary and blockers. Writes nothing.
587
+ */
588
+ export function prepareDecision(videoDir, gate, decision, opts = {}) {
589
+ const dir = path.resolve(videoDir);
590
+ if (!existsSync(dir) || !statSync(dir).isDirectory()) throw new Error(`Not an episode folder: ${dir}`);
591
+ if (![1, 2, 3, 4].includes(gate)) throw new Error("--gate must be 1, 2, 3 or 4");
592
+ if (!DECISIONS.has(decision)) throw new Error(`Unknown decision ${decision}`);
593
+ const episode = path.basename(dir);
594
+ const { pins, missing, extras } = collectPins(dir, gate);
595
+ const status = gateStatus(dir);
596
+ const { verified } = readRecords(dir, gate, status.key);
597
+ const previousApproval = newestRecord(verified, (r) => r.decision === "approved");
598
+ const previousAny = newestRecord(verified);
599
+ const blockers = [];
600
+ const warnings = [];
601
+ const skipped = [];
602
+
603
+ let delta = null;
604
+ if (previousApproval) {
605
+ const old = previousApproval.rec.pins;
606
+ const changed = Object.keys(pins).filter((p) => p in old && old[p] !== pins[p]);
607
+ const added = Object.keys(pins).filter((p) => !(p in old));
608
+ const removed = Object.keys(old).filter((p) => !(p in pins));
609
+ const unchanged = Object.keys(pins).filter((p) => old[p] === pins[p]);
610
+ delta = { since: previousApproval.rec.at, changed, added, removed, unchanged };
611
+ }
612
+
613
+ let facts = null;
614
+ if (gate === 2) facts = factsSummary(dir);
615
+
616
+ if (decision === "approved") {
617
+ if (missing.length) blockers.push(`missing required file(s): ${missing.join(", ")}`);
618
+ for (const e of status.gates.slice(0, gate - 1)) {
619
+ if (e.state === "approved") continue;
620
+ if (e.state === "none") {
621
+ if (opts.skipEarlier) skipped.push(e.gate);
622
+ else blockers.push(`Gate ${e.gate} (${e.name}) has no approval. Approve it first, or pass --skip-earlier to record that you skip it.`);
623
+ } else {
624
+ blockers.push(`Gate ${e.gate} (${e.name}) is ${e.state}${e.changedPins ? ` (${e.changedPins.join(", ")} changed)` : ""}; decide it again first.`);
625
+ }
626
+ }
627
+ if (facts) blockers.push(...facts.blockers);
628
+ if (gate === 3) {
629
+ const shots = regular(dir, "07-shots/shots.json");
630
+ const validated = regular(dir, "07-shots/shots.validated.json");
631
+ if (shots && validated && statSync(shots).mtimeMs > statSync(validated).mtimeMs) blockers.push("shots.json changed after the last shots_compile; compile and re-render the animatic first");
632
+ }
633
+ const current = status.gates[gate - 1];
634
+ if (current.state === "approved" && delta && !delta.changed.length && !delta.added.length && !delta.removed.length) {
635
+ warnings.push(`Gate ${gate} is already approved and fresh (since ${current.at}); nothing changed.`);
636
+ }
637
+ }
638
+ if (facts) warnings.push(...facts.warnings);
639
+ if ((decision === "sent_back" || decision === "rejected") && !opts.note) warnings.push("No --note: the agent won't know what to change.");
640
+
641
+ return {
642
+ dir,
643
+ episode,
644
+ gate,
645
+ name: GATE_NAMES[gate],
646
+ decision,
647
+ note: opts.note ?? "",
648
+ pins,
649
+ extras,
650
+ delta,
651
+ facts,
652
+ skipped,
653
+ hypothetical: isHypothetical(dir),
654
+ gate2Flags: gate2Flags(dir),
655
+ supersedes: previousAny ? previousAny.lineSha : null,
656
+ previousAt: previousAny ? previousAny.rec.at : null,
657
+ blockers,
658
+ warnings,
659
+ status: status.gates,
660
+ };
661
+ }
662
+
663
+ /**
664
+ * Re-hash the pins (refusing if anything changed since the human was shown them), sign and append.
665
+ * The caller is responsible for the human confirmation; the CLI only calls this after a typed confirmation on a TTY.
666
+ */
667
+ export function commitDecision(plan, signingKey, { actor = osActor(), now = new Date() } = {}) {
668
+ if (plan.decision === "approved" && plan.blockers.length) throw new Error(`Refused: ${plan.blockers.join("; ")}`);
669
+ assertKeyDirSafe(plan.dir);
670
+ const again = collectPins(plan.dir, plan.gate);
671
+ const before = JSON.stringify(plan.pins);
672
+ if (JSON.stringify(again.pins) !== before || (plan.gate === 2 && JSON.stringify(gate2Flags(plan.dir)) !== JSON.stringify(plan.gate2Flags))) {
673
+ throw new Error("Files changed while you were reviewing. Nothing was written; run the command again to see the current versions.");
674
+ }
675
+ let at = now;
676
+ if (plan.previousAt && Date.parse(plan.previousAt) >= at.getTime()) at = new Date(Date.parse(plan.previousAt) + 1);
677
+ const delta = plan.delta ? [...plan.delta.changed, ...plan.delta.added, ...plan.delta.removed] : [];
678
+ const fields = {
679
+ episode: plan.episode,
680
+ gate: plan.gate,
681
+ decision: plan.decision,
682
+ decided_by: actor,
683
+ at: at.toISOString(),
684
+ pins: plan.pins,
685
+ flags: plan.gate === 2 ? plan.gate2Flags : {},
686
+ skipped_gates: plan.decision === "approved" ? plan.skipped : [],
687
+ supersedes: plan.supersedes,
688
+ delta: plan.decision === "approved" ? delta : [],
689
+ note: plan.note,
690
+ };
691
+ const record = signRecord(fields, signingKey.privateKey);
692
+ const gatesDir = path.join(plan.dir, "_gates");
693
+ if (existsSync(gatesDir) && !lstatSync(gatesDir).isDirectory()) throw new Error(`${gatesDir} is not a folder.`);
694
+ mkdirSync(gatesDir, { recursive: true });
695
+ const file = gateFile(plan.dir, plan.gate);
696
+ if (existsSync(file) && !lstatSync(file).isFile()) throw new Error(`${file} is not a regular file (symlink?). Refusing to write.`);
697
+ let prefix = "";
698
+ if (existsSync(file)) {
699
+ const text = readFileSync(file, "utf8");
700
+ if (text && !text.endsWith("\n")) prefix = "\n";
701
+ }
702
+ appendFileSync(file, `${prefix}${JSON.stringify(record)}\n`, { flag: "a" });
703
+ return { file, record };
704
+ }