neurastream 0.2.36 → 0.2.39

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.
@@ -0,0 +1,308 @@
1
+ // Page notes (plan 20261026_0930 P6): `pages publish` injects one style block, one panel and one
2
+ // script into an HTML artifact, so the owner can select or right-click a passage he is reading and
3
+ // leave a note about that quote. "Submit all" posts them to the pages server, which appends one
4
+ // owner-inbox row per note — the file Main already delivers as a user message. The page never
5
+ // changes itself: notes are outbound only, and nothing on it is editable.
6
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
7
+ import { dirname, join } from "node:path";
8
+ import type { Config } from "./config.ts";
9
+ import { expandHome } from "./queue/lib.ts";
10
+
11
+ /** Marks the injected block, so a second publish (or a page that already carries one) stays single. */
12
+ export const NOTES_MARK = "data-ns-page-notes";
13
+
14
+ const STYLE = `<style ${NOTES_MARK}>
15
+ #ns-notes{position:fixed;inset-block-end:0;inset-inline-end:0;z-index:2147483000;width:min(420px,100vw);max-height:60vh;overflow:auto;font:13px/1.4 system-ui,sans-serif;background:#111c;color:#fff;backdrop-filter:blur(6px);border-start-start-radius:10px;padding:10px;box-sizing:border-box}
16
+ #ns-notes h2{margin:0 0 6px;font-size:13px;font-weight:600;opacity:.8}
17
+ #ns-notes .ns-row{border-top:1px solid #fff3;padding:6px 0}
18
+ #ns-notes .ns-quote{margin:0 0 4px;opacity:.75;font-style:italic;word-break:break-word}
19
+ #ns-notes textarea{width:100%;box-sizing:border-box;min-height:38px;font:inherit;color:#000;border-radius:6px;border:0;padding:6px}
20
+ #ns-notes .ns-actions{display:flex;gap:6px;align-items:center;margin-top:6px;flex-wrap:wrap}
21
+ #ns-notes button{font:inherit;border:0;border-radius:6px;padding:6px 10px;background:#3b82f6;color:#fff}
22
+ #ns-notes button.ns-quiet{background:#fff2;color:#fff}
23
+ #ns-notes .ns-status{opacity:.8}
24
+ #ns-note-fab{position:fixed;z-index:2147483000;font:12px system-ui,sans-serif;border:0;border-radius:6px;padding:6px 10px;background:#3b82f6;color:#fff;display:none}
25
+ #ns-approve{position:fixed;inset-block-start:0;inset-inline-end:0;z-index:2147483000;display:flex;gap:8px;align-items:center;padding:8px 10px;font:13px/1.4 system-ui,sans-serif;background:#111c;color:#fff;backdrop-filter:blur(6px);border-end-start-radius:8px}
26
+ #ns-approve button{font:inherit;border:0;border-radius:6px;padding:6px 12px;background:#16a34a;color:#fff}
27
+ #ns-approve button[disabled]{background:#fff3;color:#fff9}
28
+ </style>`;
29
+
30
+ const PANEL = `<section id="ns-notes" ${NOTES_MARK} hidden>
31
+ <h2>Notes on this page</h2>
32
+ <div id="ns-list"></div>
33
+ <div class="ns-actions"><button id="ns-submit" type="button">Submit all</button><button id="ns-hide" class="ns-quiet" type="button">Hide</button><span id="ns-status" class="ns-status"></span></div>
34
+ </section>
35
+ <button id="ns-note-fab" type="button">Add note</button>`;
36
+
37
+ // No backticks or interpolation in here: the block is injected verbatim into the artifact.
38
+ const SCRIPT = `<script ${NOTES_MARK}>(function(){
39
+ var panel=document.getElementById("ns-notes"),list=document.getElementById("ns-list"),fab=document.getElementById("ns-note-fab"),status=document.getElementById("ns-status");
40
+ var notes=[];
41
+ function quote(){var s=window.getSelection();return s?s.toString().replace(/\\s+/g," ").trim().slice(0,600):"";}
42
+ function paint(){
43
+ list.textContent="";
44
+ notes.forEach(function(n,at){
45
+ var row=document.createElement("div");row.className="ns-row";
46
+ var q=document.createElement("p");q.className="ns-quote";q.textContent="\\u201c"+n.quote+"\\u201d";
47
+ var ta=document.createElement("textarea");ta.value=n.note;ta.placeholder="What about this passage?";
48
+ ta.addEventListener("input",function(){notes[at].note=ta.value;});
49
+ var del=document.createElement("button");del.className="ns-quiet";del.type="button";del.textContent="Remove";
50
+ del.addEventListener("click",function(){notes.splice(at,1);paint();});
51
+ row.appendChild(q);row.appendChild(ta);row.appendChild(del);list.appendChild(row);
52
+ });
53
+ panel.hidden=notes.length===0;
54
+ }
55
+ function add(text){notes.push({quote:text,note:""});paint();var boxes=list.querySelectorAll("textarea");if(boxes.length)boxes[boxes.length-1].focus();}
56
+ document.addEventListener("mouseup",function(e){
57
+ if(panel.contains(e.target))return;
58
+ var text=quote();
59
+ if(!text){fab.style.display="none";return;}
60
+ var r=window.getSelection().getRangeAt(0).getBoundingClientRect();
61
+ fab.style.left=Math.max(8,Math.min(window.innerWidth-100,r.left))+"px";
62
+ fab.style.top=Math.max(8,r.top-38)+"px";
63
+ fab.style.display="block";fab.dataset.quote=text;
64
+ });
65
+ fab.addEventListener("click",function(){fab.style.display="none";add(fab.dataset.quote||"");});
66
+ document.addEventListener("contextmenu",function(e){
67
+ var text=quote();
68
+ if(!text||panel.contains(e.target))return;
69
+ e.preventDefault();add(text);
70
+ });
71
+ document.getElementById("ns-hide").addEventListener("click",function(){panel.hidden=true;});
72
+ document.getElementById("ns-submit").addEventListener("click",function(){
73
+ var keep=notes.filter(function(n){return n.note.trim()!=="";});
74
+ if(keep.length===0){status.textContent="write a note first";return;}
75
+ status.textContent="sending\\u2026";
76
+ fetch("/_notes",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({page:location.pathname,url:location.href,notes:keep})})
77
+ .then(function(r){if(!r.ok)throw new Error(r.status);return r.json();})
78
+ .then(function(j){notes=[];paint();status.textContent="sent "+j.stored+" note(s)";})
79
+ .catch(function(){status.textContent="not sent \\u2014 try again";});
80
+ });
81
+ })();</script>`;
82
+
83
+ /** One closed note with the answer Main gave it: shown on the page next to the quote (P8). */
84
+ export interface AnsweredNote {
85
+ id: string;
86
+ quote: string;
87
+ note: string;
88
+ answer: string;
89
+ }
90
+
91
+ const ANSWERED_RE = /<section id="ns-answered"[\s\S]*?<\/section>\n?/i;
92
+ const APPROVE_RE = /<section id="ns-approve"[\s\S]*?<\/section>\n?/i;
93
+
94
+ /** What the Approve bar needs: the page it approves, the notes still open on it and what the
95
+ * diagram check found (P9, P10). */
96
+ export interface ApproveChrome {
97
+ page: string;
98
+ open: string[];
99
+ problems?: string[];
100
+ }
101
+
102
+ /** The Approve bar, on a page published from a plan: the notes panel beside it is the same page. */
103
+ function approveBlock(chrome: ApproveChrome): string {
104
+ const page = esc(chrome.page);
105
+ const problems = chrome.problems ?? [];
106
+ const hint =
107
+ chrome.open.length > 0
108
+ ? `Answer every note first (${esc(chrome.open.join(", "))})`
109
+ : problems.length > 0
110
+ ? `The diagram is not complete yet (${problems.length}): ${esc(problems.slice(0, 3).join("; "))}`
111
+ : "Approve and go";
112
+ const disabled = chrome.open.length === 0 && problems.length === 0 ? "" : " disabled";
113
+ return `<section id="ns-approve" ${NOTES_MARK} data-ns-plan="${page}">
114
+ <button id="ns-approve-btn" type="button"${disabled}>Approve</button><span id="ns-approve-status" class="ns-status">${hint}</span>
115
+ <script>(function(){var page="${page}",btn=document.getElementById("ns-approve-btn"),status=document.getElementById("ns-approve-status");
116
+ function set(open,problems){var bad=(problems||[]);btn.disabled=open.length>0||bad.length>0;status.textContent=open.length>0?"Answer every note first ("+open.join(", ")+")":bad.length>0?"The diagram is not complete yet ("+bad.length+"): "+bad.slice(0,3).join("; "):"Approve and go \u2014 the plan records it.";}
117
+ fetch("/_approve?page="+page).then(function(r){return r.json();}).then(function(d){set(d.open||[],d.problems);}).catch(function(){set(["?"],[]);});
118
+ btn.addEventListener("click",function(){btn.disabled=true;fetch("/_approve?page="+page,{method:"POST",headers:{"content-type":"application/json"},body:"{}"}).then(function(r){return r.json().then(function(d){return {ok:r.ok,body:d};});}).then(function(res){status.textContent=res.ok?"Approved: "+res.body.approved:"Not approved: "+res.body.error;btn.disabled=!res.ok;}).catch(function(){status.textContent="Not approved: the pages server did not answer.";btn.disabled=false;});});
119
+ })();</script>
120
+ </section>`;
121
+ }
122
+
123
+ function esc(text: string): string {
124
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
125
+ }
126
+
127
+ function answeredBlock(notes: AnsweredNote[]): string {
128
+ if (notes.length === 0) return "";
129
+ const rows = notes
130
+ .map(n => `<div class="ns-row"><p class="ns-quote">${esc(n.id)} \u00b7 \u201c${esc(n.quote)}\u201d</p><p class="ns-note">${esc(n.note)}</p><p class="ns-answer"><strong>Answer:</strong> ${esc(n.answer)}</p></div>`)
131
+ .join("");
132
+ return `<section id="ns-answered" ${NOTES_MARK}><h2>Answered notes</h2>${rows}</section>`;
133
+ }
134
+
135
+ /** Append the block before `</body>` when there is one; an unchanged block leaves the html alone. */
136
+ function withTail(html: string, block: string): string {
137
+ if (block === "") return html;
138
+ const at = html.toLowerCase().lastIndexOf("</body>");
139
+ return at < 0 ? `${html}\n${block}\n` : `${html.slice(0, at)}${block}\n${html.slice(at)}`;
140
+ }
141
+
142
+ /** Swap a block in place, append it before `</body>` when the page has none, drop it when empty. */
143
+ function replaceOrAppend(html: string, re: RegExp, block: string): string {
144
+ const at = re.exec(html);
145
+ if (at === null) return block === "" ? html : withTail(html, block);
146
+ return `${html.slice(0, at.index)}${block === "" ? "" : `${block}\n`}${html.slice(at.index + at[0].length)}`;
147
+ }
148
+
149
+ /**
150
+ * The artifact with the notes block injected once, before `</body>` when there is one. A page that
151
+ * already carries it keeps its style, panel and script and refreshes the answered list and, on a
152
+ * plan page, the Approve bar — a built-thing republish drops a bar that no longer belongs there.
153
+ */
154
+ export function injectPageNotes(html: string, answered: AnsweredNote[] = [], approve?: ApproveChrome): string {
155
+ const answers = answeredBlock(answered);
156
+ const bar = approve === undefined ? "" : approveBlock(approve);
157
+ if (html.includes(NOTES_MARK)) return replaceOrAppend(replaceOrAppend(html, APPROVE_RE, bar), ANSWERED_RE, answers);
158
+ return withTail(html, `${STYLE}\n${PANEL}\n${bar === "" ? "" : `${bar}\n`}${answers === "" ? "" : `${answers}\n`}${SCRIPT}`);
159
+ }
160
+
161
+ function str(value: unknown, max: number): string {
162
+ return typeof value === "string" ? value.trim().slice(0, max) : "";
163
+ }
164
+
165
+ function asRecord(value: unknown): Record<string, unknown> | null {
166
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? Object.fromEntries(Object.entries(value)) : null;
167
+ }
168
+
169
+ function readRows(file: string): Record<string, unknown>[] {
170
+ let text = "";
171
+ try {
172
+ text = readFileSync(file, "utf8");
173
+ } catch {
174
+ return [];
175
+ }
176
+ const out: Record<string, unknown>[] = [];
177
+ for (const line of text.split("\n")) {
178
+ if (!line.trim()) continue;
179
+ const row = asRecord(JSON.parse(line) as unknown);
180
+ if (row !== null) out.push(row);
181
+ }
182
+ return out;
183
+ }
184
+
185
+ /** A page name as one safe file name: `/why.html` and `why.html` are the same page. */
186
+ function pageSlug(page: string): string {
187
+ const clean = page.replace(/^\/+/, "").replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
188
+ return clean === "" ? "index" : clean;
189
+ }
190
+
191
+ function notesDir(cfg: Config): string {
192
+ return join(expandHome(cfg.paths.queue_state), "page-notes");
193
+ }
194
+
195
+ export function notesStorePath(cfg: Config, page: string): string {
196
+ return join(notesDir(cfg), `${pageSlug(page)}.jsonl`);
197
+ }
198
+
199
+ export function notesAnswersPath(cfg: Config, page: string): string {
200
+ return join(notesDir(cfg), `${pageSlug(page)}.answers.json`);
201
+ }
202
+
203
+ export interface PageNote {
204
+ id: string;
205
+ quote: string;
206
+ note: string;
207
+ url: string;
208
+ ts: number;
209
+ }
210
+
211
+ export function readNotes(cfg: Config, page: string): PageNote[] {
212
+ return readRows(notesStorePath(cfg, page)).flatMap(rec => {
213
+ const id = str(rec.id, 40);
214
+ if (id === "") return [];
215
+ return [{ id, quote: str(rec.quote, 2000), note: str(rec.note, 4000), url: str(rec.url, 1000), ts: typeof rec.ts === "number" ? rec.ts : 0 }];
216
+ });
217
+ }
218
+
219
+ /** Main's answer file for the page: one entry per note id. Ids without an entry are open. */
220
+ export function readAnswers(cfg: Config, page: string): Record<string, string> {
221
+ let parsed: Record<string, unknown> | null = null;
222
+ try {
223
+ parsed = asRecord(JSON.parse(readFileSync(notesAnswersPath(cfg, page), "utf8")) as unknown);
224
+ } catch {
225
+ return {};
226
+ }
227
+ const out: Record<string, string> = {};
228
+ if (parsed === null) return out;
229
+ for (const [id, answer] of Object.entries(parsed)) {
230
+ const text = str(answer, 4000);
231
+ if (text !== "") out[id] = text;
232
+ }
233
+ return out;
234
+ }
235
+
236
+ /** The note ids with no answer yet — what `neurastream notes check` exits 1 on. */
237
+ export function openNoteIds(cfg: Config, page: string): string[] {
238
+ const answers = readAnswers(cfg, page);
239
+ return readNotes(cfg, page)
240
+ .map(n => n.id)
241
+ .filter(id => answers[id] === undefined);
242
+ }
243
+
244
+ /** The page's notes with the answer beside each, in note order, for the published page. */
245
+ export function answeredNotes(cfg: Config, page: string): AnsweredNote[] {
246
+ const answers = readAnswers(cfg, page);
247
+ return readNotes(cfg, page).flatMap(n => {
248
+ const answer = answers[n.id];
249
+ return answer === undefined ? [] : [{ id: n.id, quote: n.quote, note: n.note, answer }];
250
+ });
251
+ }
252
+
253
+ /** Publishing closes the old notes: they are archived and the answer file is spent. */
254
+ export function settleNotes(cfg: Config, page: string, now = Math.floor(Date.now() / 1000)): void {
255
+ const store = notesStorePath(cfg, page);
256
+ if (existsSync(store)) renameSync(store, join(notesDir(cfg), `${pageSlug(page)}.${now}.answered.jsonl`));
257
+ try {
258
+ unlinkSync(notesAnswersPath(cfg, page));
259
+ } catch {}
260
+ }
261
+
262
+ /** What `pages publish` needs from the notes: what is open, what to show, and what to close. */
263
+ export interface NotesGate {
264
+ open(page: string): string[];
265
+ answered(page: string): AnsweredNote[];
266
+ settle(page: string): void;
267
+ }
268
+
269
+ export function pageNotesGate(cfg: Config): NotesGate {
270
+ return { open: page => openNoteIds(cfg, page), answered: page => answeredNotes(cfg, page), settle: page => settleNotes(cfg, page) };
271
+ }
272
+
273
+ /** The next id for this page; the counter survives the archive, so an id is never reused. */
274
+ function nextNoteId(cfg: Config, page: string): number {
275
+ let n = 0;
276
+ try {
277
+ const parsed = Number(readFileSync(join(notesDir(cfg), `${pageSlug(page)}.count`), "utf8").trim());
278
+ if (Number.isInteger(parsed) && parsed >= 0) n = parsed;
279
+ } catch {}
280
+ return n + 1;
281
+ }
282
+
283
+ /**
284
+ * One inbox row per submitted note (`kind: "page-note"`, stable id n1, n2, … per page) and the
285
+ * number stored; null when the submit carries no note text at all. The same rows go to the page's
286
+ * store, which `notes check` and the publish gate read.
287
+ */
288
+ export function appendPageNotes(body: unknown, cfg: Config, login: string, now = Math.floor(Date.now() / 1000)): number | null {
289
+ const rec = asRecord(body) ?? {};
290
+ const page = str(rec.page, 500) === "" ? "/" : str(rec.page, 500);
291
+ const url = str(rec.url, 1000);
292
+ const rows: { quote: string; note: string }[] = [];
293
+ for (const item of Array.isArray(rec.notes) ? rec.notes : []) {
294
+ const one = asRecord(item) ?? {};
295
+ const note = str(one.note, 4000);
296
+ if (note) rows.push({ quote: str(one.quote, 2000), note });
297
+ }
298
+ if (rows.length === 0) return null;
299
+ let id = nextNoteId(cfg, page);
300
+ const stored = rows.map(row => ({ ts: now, id: `n${id++}`, page, url, quote: row.quote, note: row.note, login }));
301
+ const inbox = join(expandHome(cfg.paths.queue_state), "owner-inbox.jsonl");
302
+ const store = notesStorePath(cfg, page);
303
+ mkdirSync(dirname(store), { recursive: true });
304
+ appendFileSync(store, `${stored.map(r => JSON.stringify(r)).join("\n")}\n`);
305
+ writeFileSync(join(notesDir(cfg), `${pageSlug(page)}.count`), `${id - 1}\n`);
306
+ appendFileSync(inbox, `${stored.map(r => JSON.stringify({ ...r, kind: "page-note" })).join("\n")}\n`);
307
+ return rows.length;
308
+ }
@@ -4,6 +4,9 @@ import { homedir } from "node:os";
4
4
  import { dirname, join, basename, extname } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { configFile, loadConfig } from "./config.ts";
7
+ import { injectPageNotes, type NotesGate } from "./page-notes.ts";
8
+ import { recordPagePlan } from "./plan-approval.ts";
9
+ import { checkDiagram } from "./diagram-check.ts";
7
10
  import { recordPublish } from "./pages-expiry.ts";
8
11
  import { realTailscale, type Tailscale } from "./tailscale.ts";
9
12
  const HERE = dirname(fileURLToPath(import.meta.url));
@@ -46,9 +49,38 @@ export function pagesOff(opts: Setup = {}): number {
46
49
  const cfg=loadConfig({home}); writeFileSync(file,editBlock(old,{enabled:false,port:cfg.pages.port,dir:cfg.pages.dir}));
47
50
  const r=runner(["--user","stop","neurastream-pages"]); if(r.status!==0){console.error(r.stderr);return 1;} return 0;
48
51
  }
49
- export function publishPage(file: string, name: string | undefined, force: boolean, dir: string, keep = false, keepDays = 15, now = new Date()): string {
52
+ /** Everything a publish carries besides the file: expiry, the notes gate and, on a plan page, the plan. */
53
+ export interface PublishOptions {
54
+ keep?: boolean;
55
+ keepDays?: number;
56
+ now?: Date;
57
+ notes?: NotesGate;
58
+ /** The plan this page approves (P9). A page without one is a built thing: notes only, no Approve bar. */
59
+ plan?: string;
60
+ }
61
+
62
+ export function publishPage(file: string, name: string | undefined, force: boolean, dir: string, opts: PublishOptions = {}): string {
63
+ const keep = opts.keep ?? false, keepDays = opts.keepDays ?? 15, now = opts.now ?? new Date(), notes = opts.notes;
50
64
  const source=basename(file), base=(name ?? source.slice(0,source.length-extname(source).length)).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");
51
65
  const targetName=base+extname(source).toLowerCase(), target=join(dir,targetName); mkdirSync(dir,{recursive:true});
52
- if(existsSync(target)){const a=readFileSync(file),b=readFileSync(target); if(a.equals(b)){recordPublish(dir,targetName,keep,keepDays,now);return targetName;} if(!force) throw new Error(`pages: ${targetName} exists with different content (use --force)`);}
53
- copyFileSync(file,target); recordPublish(dir,targetName,keep,keepDays,now); return targetName;
66
+ // A page with a note still unanswered is not published (plan 20261026 P8): the owner's note id must
67
+ // get an answer before the page moves on. Publishing then shows each answer by its note and closes it.
68
+ const open = notes?.open(targetName) ?? [];
69
+ // A plan page is only approvable when its diagram covers the plan (plan 20261026 P10), so the check
70
+ // runs here, at publish, and its findings travel with the page.
71
+ let diagram: { missing: string[]; thin: string[] } | null = null;
72
+ if (opts.plan !== undefined) {
73
+ if (extname(source).toLowerCase() !== ".html") throw new Error(`pages: --plan needs an HTML artifact, not ${source}`);
74
+ diagram = checkDiagram(readFileSync(file, "utf8"), readFileSync(opts.plan, "utf8"));
75
+ }
76
+ const approve = opts.plan === undefined || diagram === null ? undefined : { page: targetName, open, problems: [...diagram.missing, ...diagram.thin] };
77
+ if(open.length>0) throw new Error(`pages: ${targetName} has ${open.length} open note(s) (${open.join(", ")}); answer each one before publishing (see \`neurastream notes check ${targetName}\`)`);
78
+ // An HTML artifact carries the notes block from publish on (plan 20261026 P6): one style, one panel,
79
+ // one script, injected once — a page that already carries it, or a second publish, stays single.
80
+ const raw = readFileSync(file);
81
+ const content = extname(source).toLowerCase() === ".html" ? Buffer.from(injectPageNotes(raw.toString("utf8"), notes?.answered(targetName) ?? [], approve), "utf8") : raw;
82
+ if(existsSync(target)){const b=readFileSync(target); if(content.equals(b)){recordPublish(dir,targetName,keep,keepDays,now);notes?.settle(targetName);return targetName;} if(!force) throw new Error(`pages: ${targetName} exists with different content (use --force)`);}
83
+ writeFileSync(target, content); recordPublish(dir,targetName,keep,keepDays,now);
84
+ if(opts.plan !== undefined && diagram !== null) recordPagePlan(dir, targetName, { plan: opts.plan, missing: diagram.missing, thin: diagram.thin });
85
+ notes?.settle(targetName); return targetName;
54
86
  }
package/src/core/pages.ts CHANGED
@@ -2,6 +2,8 @@ import { existsSync, lstatSync, readdirSync, readFileSync } from "node:fs";
2
2
  import { basename, extname, resolve } from "node:path";
3
3
  import type { Config } from "./config.ts";
4
4
  import { isLoopback, isTailnet, type UiHttpServer } from "./owner-ui.ts";
5
+ import { appendPageNotes, openNoteIds } from "./page-notes.ts";
6
+ import { approvePlanFile, planForPage, readPagePlan } from "./plan-approval.ts";
5
7
  import type { RunSource } from "./adapter.ts";
6
8
  import type { Tailscale } from "./tailscale.ts";
7
9
 
@@ -16,11 +18,45 @@ export function startPagesServer(opts: PagesOptions): PagesServer {
16
18
  const root = resolve(opts.root ?? opts.cfg.pages.dir);
17
19
  const peerOf = opts.peerOf ?? ((req: Request, server: UiHttpServer) => server.requestIP(req)?.address ?? "");
18
20
  const server = Bun.serve({ hostname, port: opts.port ?? opts.cfg.pages.port, async fetch(req, srv) {
19
- if (req.method !== "GET" && req.method !== "HEAD") return plain("method not allowed", 405);
21
+ if (req.method !== "GET" && req.method !== "HEAD" && req.method !== "POST") return plain("method not allowed", 405);
20
22
  const peer = peerOf(req, srv);
21
23
  const login = isLoopback(peer) ? null : isTailnet(peer) ? opts.tailscale.whois(peer) : null;
22
24
  if (!isLoopback(peer) && (!login || login !== opts.cfg.ui.owner_login)) return plain("forbidden", 403);
23
- const url = new URL(req.url); let name = decodeURI(url.pathname.slice(1));
25
+ const url = new URL(req.url);
26
+ // The one POST a page may make (plan 20261026 P6): the notes its script collected become owner-inbox
27
+ // rows Main delivers. Same origin only, so another site's tab cannot write to the inbox; nothing here
28
+ // touches the page file, and a submit with no note text is refused.
29
+ if (req.method === "POST") {
30
+ // Approve from the plan's own page (plan 20261026 P9): the click records `Approved: <date> (<page>)`
31
+ // in the plan recorded at publish. Only that plan, only from this page's origin, and never while a
32
+ // note on the page has no answer.
33
+ if (url.pathname === "/_approve") {
34
+ if (req.headers.get("origin") !== `http://${req.headers.get("host")}`) return plain("forbidden: origin is not this page", 403);
35
+ const page = url.searchParams.get("page") ?? "";
36
+ const record = page === "" ? null : readPagePlan(root, page);
37
+ if (record === null) return plain("not found: no plan is published as this page", 404);
38
+ const open = openNoteIds(opts.cfg, page);
39
+ if (open.length > 0) return Response.json({ error: `answer ${open.join(", ")} first` }, { status: 409 });
40
+ const unproven = [...record.missing, ...record.thin];
41
+ if (unproven.length > 0) return Response.json({ error: `the diagram is not complete (${unproven.slice(0, 3).join("; ")})` }, { status: 409 });
42
+ const plan = record.plan;
43
+ if (!existsSync(plan)) return plain("not found: the plan file is gone", 404);
44
+ return Response.json({ approved: approvePlanFile(plan, page) });
45
+ }
46
+ if (url.pathname !== "/_notes") return plain("method not allowed", 405);
47
+ if (req.headers.get("origin") !== `http://${req.headers.get("host")}`) return plain("forbidden: origin is not this page", 403);
48
+ let body: unknown; try { body = await req.json(); } catch { return plain("bad request: not JSON", 400); }
49
+ const stored = appendPageNotes(body, opts.cfg, login ?? "loopback");
50
+ return stored === null ? plain("no notes to submit", 400) : Response.json({ stored });
51
+ }
52
+ // What the Approve bar asks on load: the notes still open on this page. A page with no plan has none.
53
+ if (url.pathname === "/_approve") {
54
+ const page = url.searchParams.get("page") ?? "";
55
+ const record = page === "" ? null : readPagePlan(root, page);
56
+ if (record === null) return plain("not found: no plan is published as this page", 404);
57
+ return Response.json({ open: openNoteIds(opts.cfg, page), problems: [...record.missing, ...record.thin] });
58
+ }
59
+ let name = decodeURI(url.pathname.slice(1));
24
60
  if (name.includes("/") || name.includes("\\") || name === ".." || name.startsWith(".")) return plain("not found", 404);
25
61
  if (!name) {
26
62
  const index = resolve(root, "index.html");
@@ -0,0 +1,95 @@
1
+ // Plan approval from the plan's own diagram page (plan 20261026_0930 P9). A plan that has a page in
2
+ // Base is approved there — the Approve bar records `Approved: <date> (<page>)` in the plan — and a
3
+ // chat "go" is the same thing: Main writes the same line. `Approval: self — owner: "<his words>"`
4
+ // covers the plans he tells Main to do on its own. main-guard refuses a spawn on a plan that has a
5
+ // page and no line; a plan with no page predates the convention and is left alone.
6
+ import { mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
7
+ import { join, resolve } from "node:path";
8
+
9
+ const APPROVED = /^\s*(?:[-*]\s+)?Approved:.*$/im;
10
+ const SELF = /^\s*(?:[-*]\s+)?Approval:\s*self\b[^\n]*owner:\s*["\u201c][^"\u201d\n]+["\u201d]/im;
11
+
12
+ /** What publishing recorded for a page: the plan it approves and what its diagram check found. */
13
+ export interface PagePlan {
14
+ plan: string;
15
+ missing: string[];
16
+ thin: string[];
17
+ }
18
+
19
+ /** The record a page was published with, or null when it was published without `--plan`. */
20
+ export function readPagePlan(dir: string, name: string): PagePlan | null {
21
+ let parsed: unknown;
22
+ try {
23
+ parsed = JSON.parse(readFileSync(join(dir, ".meta", `${name}.json`), "utf8"));
24
+ } catch {
25
+ return null;
26
+ }
27
+ if (parsed === null || typeof parsed !== "object" || !("plan" in parsed)) return null;
28
+ const plan = parsed.plan;
29
+ if (typeof plan !== "string" || plan === "") return null;
30
+ const list = (value: unknown): string[] => (Array.isArray(value) ? value.filter((one): one is string => typeof one === "string") : []);
31
+ const missing = "missing" in parsed ? parsed.missing : [];
32
+ const thin = "thin" in parsed ? parsed.thin : [];
33
+ return { plan, missing: list(missing), thin: list(thin) };
34
+ }
35
+
36
+ /** The plan file a page approves, or null when the page was published without `--plan`. */
37
+ export function planForPage(dir: string, name: string): string | null {
38
+ return readPagePlan(dir, name)?.plan ?? null;
39
+ }
40
+
41
+ /** Remember the plan a page approves and its diagram check: one small JSON beside the pages, never served. */
42
+ export function recordPagePlan(dir: string, name: string, entry: PagePlan): void {
43
+ mkdirSync(join(dir, ".meta"), { recursive: true });
44
+ writeFileSync(join(dir, ".meta", `${name}.json`), JSON.stringify({ plan: resolve(entry.plan), missing: entry.missing, thin: entry.thin }));
45
+ }
46
+
47
+ /** The page that approves this plan, or null when the plan has none in Base. */
48
+ export function pageOfPlan(dir: string, file: string): string | null {
49
+ let names: string[] = [];
50
+ try {
51
+ names = readdirSync(join(dir, ".meta"));
52
+ } catch {
53
+ return null;
54
+ }
55
+ for (const name of names) {
56
+ if (!name.endsWith(".json")) continue;
57
+ const page = name.slice(0, -".json".length);
58
+ if (planForPage(dir, page) === resolve(file)) return page;
59
+ }
60
+ return null;
61
+ }
62
+
63
+ export function isApproved(text: string): boolean {
64
+ return APPROVED.test(text) || SELF.test(text);
65
+ }
66
+
67
+ export function isSelfApproved(text: string): boolean {
68
+ return SELF.test(text);
69
+ }
70
+
71
+ export function approvalLine(page: string, now = new Date()): string {
72
+ return `Approved: ${now.toISOString().slice(0, 10)} (${page})`;
73
+ }
74
+
75
+ /** The plan text with its approval line replaced, or added above the first `## ` section. */
76
+ export function recordApproval(text: string, page: string, now = new Date()): string {
77
+ const line = approvalLine(page, now);
78
+ if (APPROVED.test(text)) return text.replace(APPROVED, line);
79
+ const at = text.search(/^## /m);
80
+ return at < 0 ? `${text.replace(/\s*$/, "")}\n${line}\n` : `${text.slice(0, at)}${line}\n\n${text.slice(at)}`;
81
+ }
82
+
83
+ /** Write the owner's click into the plan and return the line it recorded. */
84
+ export function approvePlanFile(file: string, page: string, now = new Date()): string {
85
+ writeFileSync(file, recordApproval(readFileSync(file, "utf8"), page, now));
86
+ return approvalLine(page, now);
87
+ }
88
+
89
+ /** Why a spawn may not run on this plan, or null; only a plan with a page in Base is gated. */
90
+ export function approvalProblem(text: string, file: string, pagesDir: string): string | null {
91
+ if (isApproved(text)) return null;
92
+ const page = pageOfPlan(pagesDir, file);
93
+ if (page === null) return null;
94
+ return `plan ${file} has no "Approved:" line. The owner approves it from ${page} in Base, or the plan says Approval: self \u2014 owner: "<his words>".`;
95
+ }