neurastream 0.2.55 → 0.2.57

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.
@@ -1,6 +1,6 @@
1
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
2
+ // script into an HTML artifact, so the owner can select a passage — mouse or a phone long-press —
3
+ // and leave a note about that quote. "Submit all" posts them to the pages server, which appends one
4
4
  // owner-inbox row per note — the file Main already delivers as a user message. The page never
5
5
  // changes itself: notes are outbound only, and nothing on it is editable.
6
6
  import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
@@ -53,14 +53,21 @@ const SCRIPT = `<script ${NOTES_MARK}>(function(){
53
53
  panel.hidden=notes.length===0;
54
54
  }
55
55
  function add(text){notes.push({quote:text,note:""});paint();var boxes=list.querySelectorAll("textarea");if(boxes.length)boxes[boxes.length-1].focus();}
56
+ function show(text,r){
57
+ fab.style.left=Math.max(8,Math.min(window.innerWidth-100,r.left))+"px";
58
+ fab.style.top=Math.max(8,r.bottom+8)+"px";
59
+ fab.style.display="block";fab.dataset.quote=text;
60
+ }
61
+ document.addEventListener("selectionchange",function(){
62
+ var text=quote();
63
+ if(!text){fab.style.display="none";return;}
64
+ show(text,window.getSelection().getRangeAt(0).getBoundingClientRect());
65
+ });
56
66
  document.addEventListener("mouseup",function(e){
57
67
  if(panel.contains(e.target))return;
58
68
  var text=quote();
59
69
  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;
70
+ show(text,window.getSelection().getRangeAt(0).getBoundingClientRect());
64
71
  });
65
72
  fab.addEventListener("click",function(){fab.style.display="none";add(fab.dataset.quote||"");});
66
73
  document.addEventListener("contextmenu",function(e){
@@ -115,7 +122,7 @@ function approveBlock(chrome: ApproveChrome): string {
115
122
  <script>(function(){var page="${page}",btn=document.getElementById("ns-approve-btn"),status=document.getElementById("ns-approve-status");
116
123
  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
124
  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;});});
125
+ 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?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
126
  })();</script>
120
127
  </section>`;
121
128
  }
@@ -1,7 +1,8 @@
1
1
  import { lstatSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
+ import { byText } from "./knowledge.ts";
3
4
 
4
- export interface ExpiryRecord { published: string; expires: string | null }
5
+ export interface ExpiryRecord { published: string; expires: string | null; repo?: string }
5
6
  export type ExpiryMap = Record<string, ExpiryRecord>;
6
7
 
7
8
  const RECORD = ".expiry.json";
@@ -13,7 +14,10 @@ function expiryRecord(value: unknown): ExpiryRecord | null {
13
14
  const expires = "expires" in value ? value.expires : undefined;
14
15
  if (typeof published !== "string") return null;
15
16
  if (expires !== null && typeof expires !== "string") return null;
16
- return { published, expires };
17
+ const rec: ExpiryRecord = { published, expires };
18
+ const repo = "repo" in value ? value.repo : undefined;
19
+ if (typeof repo === "string" && repo) rec.repo = repo;
20
+ return rec;
17
21
  }
18
22
 
19
23
  export function readExpiry(dir: string): ExpiryMap {
@@ -39,18 +43,47 @@ function writeExpiry(dir: string, map: ExpiryMap): void {
39
43
  renameSync(tmp, join(dir, RECORD));
40
44
  }
41
45
 
42
- export function recordPublish(dir: string, name: string, keep: boolean, keepDays: number, now: Date): ExpiryRecord {
46
+ export function recordPublish(dir: string, name: string, keep: boolean, keepDays: number, now: Date, repo?: string): ExpiryRecord {
43
47
  const map = readExpiry(dir);
44
48
  const existing = map[name];
45
49
  const rec: ExpiryRecord = {
46
50
  published: now.toISOString(),
47
51
  expires: keep || existing?.expires === null ? null : new Date(now.getTime() + keepDays * DAY_MS).toISOString(),
52
+ // An explicit repo replaces the old one (--repo wins); without one a republish keeps its repo.
53
+ repo: repo ?? existing?.repo,
48
54
  };
49
55
  map[name] = rec;
50
56
  writeExpiry(dir, map);
51
57
  return rec;
52
58
  }
53
59
 
60
+ /** A live published page with its repo (plan 20261029_1436 P2): what the Base tab lists. */
61
+ export interface PublishedPage { name: string; repo: string; published: string }
62
+
63
+ /**
64
+ * The published pages that carry a repo and have not expired, newest first (ties by name). Pages
65
+ * published before the repo tag have no repo in their meta and stay out of the Base list; the
66
+ * sweep, not this reader, deletes expired files — here they are just hidden.
67
+ */
68
+ export function publishedPages(dir: string, now: Date): PublishedPage[] {
69
+ let names: string[] = [];
70
+ try {
71
+ names = readdirSync(dir, { withFileTypes: true }).filter(e => e.isFile() && !e.name.startsWith(".")).map(e => e.name);
72
+ } catch {
73
+ return [];
74
+ }
75
+ const map = readExpiry(dir);
76
+ const out: PublishedPage[] = [];
77
+ for (const name of names) {
78
+ const rec = map[name];
79
+ if (typeof rec?.repo !== "string" || rec.repo === "") continue;
80
+ const at = rec.expires == null ? null : Date.parse(rec.expires);
81
+ if (typeof at === "number" && Number.isFinite(at) && at < now.getTime()) continue;
82
+ out.push({ name, repo: rec.repo, published: rec.published });
83
+ }
84
+ return out.toSorted((a, b) => (a.published === b.published ? byText(a.name, b.name) : a.published < b.published ? 1 : -1));
85
+ }
86
+
54
87
  export function sweepPages(dir: string, keepDays: number, now: Date): { removed: string[] } {
55
88
  let dirStat;
56
89
  try { dirStat = lstatSync(dir); } catch { return { removed: [] }; }
@@ -1,12 +1,14 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
- import { dirname, join, basename, extname } from "node:path";
4
+ import { dirname, join, basename, extname, resolve } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { configFile, loadConfig } from "./config.ts";
7
+ import { repoKey } from "./knowledge.ts";
7
8
  import { injectPageNotes, type NotesGate } from "./page-notes.ts";
8
9
  import { recordPagePlan } from "./plan-approval.ts";
9
10
  import { checkDiagram } from "./diagram-check.ts";
11
+ import { gitRaw } from "./proc.ts";
10
12
  import { recordPublish } from "./pages-expiry.ts";
11
13
  import { realTailscale, type Tailscale } from "./tailscale.ts";
12
14
  const HERE = dirname(fileURLToPath(import.meta.url));
@@ -49,6 +51,19 @@ export function pagesOff(opts: Setup = {}): number {
49
51
  const cfg=loadConfig({home}); writeFileSync(file,editBlock(old,{enabled:false,port:cfg.pages.port,dir:cfg.pages.dir}));
50
52
  const r=runner(["--user","stop","neurastream-pages"]); if(r.status!==0){console.error(r.stderr);return 1;} return 0;
51
53
  }
54
+ /**
55
+ * The repo a published page belongs to (plan 20261029_1436 P1): `--repo` wins; otherwise the file's
56
+ * directory resolved to its main checkout — `git rev-parse --path-format=absolute --git-common-dir`
57
+ * is absolute, so a file in the main checkout itself names the checkout, not a relative ".git" —
58
+ * and the checkout's parent named by knowledge.ts's one repo rule, so a linked worktree's page
59
+ * lands under the main checkout's name. Outside any repo: "other".
60
+ */
61
+ export function repoForPublish(file: string, explicit?: string): string {
62
+ if (explicit) return explicit;
63
+ const top = gitRaw(dirname(resolve(file)), ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
64
+ if (top.code !== 0 || top.stdout === "") return "other";
65
+ return repoKey(dirname(top.stdout));
66
+ }
52
67
  /** Everything a publish carries besides the file: expiry, the notes gate and, on a plan page, the plan. */
53
68
  export interface PublishOptions {
54
69
  keep?: boolean;
@@ -57,6 +72,8 @@ export interface PublishOptions {
57
72
  notes?: NotesGate;
58
73
  /** The plan this page approves (P9). A page without one is a built thing: notes only, no Approve bar. */
59
74
  plan?: string;
75
+ /** The repo the page belongs to in the pages meta (Base tab); resolved by the CLI when absent. */
76
+ repo?: string;
60
77
  }
61
78
 
62
79
  export function publishPage(file: string, name: string | undefined, force: boolean, dir: string, opts: PublishOptions = {}): string {
@@ -79,8 +96,8 @@ export function publishPage(file: string, name: string | undefined, force: boole
79
96
  // one script, injected once — a page that already carries it, or a second publish, stays single.
80
97
  const raw = readFileSync(file);
81
98
  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);
99
+ if(existsSync(target)){const b=readFileSync(target); if(content.equals(b)){recordPublish(dir,targetName,keep,keepDays,now,opts.repo);notes?.settle(targetName);return targetName;} if(!force) throw new Error(`pages: ${targetName} exists with different content (use --force)`);}
100
+ writeFileSync(target, content); recordPublish(dir,targetName,keep,keepDays,now,opts.repo);
84
101
  if(opts.plan !== undefined && diagram !== null) recordPagePlan(dir, targetName, { plan: opts.plan, missing: diagram.missing, thin: diagram.thin });
85
102
  notes?.settle(targetName); return targetName;
86
103
  }
package/src/core/pages.ts CHANGED
@@ -3,7 +3,7 @@ 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
5
  import { appendPageNotes, openNoteIds } from "./page-notes.ts";
6
- import { approvePlanFile, planForPage, readPagePlan } from "./plan-approval.ts";
6
+ import { approvePlanFile, readPagePlan } from "./plan-approval.ts";
7
7
  import type { RunSource } from "./adapter.ts";
8
8
  import type { Tailscale } from "./tailscale.ts";
9
9
 
@@ -27,9 +27,9 @@ export function startPagesServer(opts: PagesOptions): PagesServer {
27
27
  // rows Main delivers. Same origin only, so another site's tab cannot write to the inbox; nothing here
28
28
  // touches the page file, and a submit with no note text is refused.
29
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.
30
+ // Approve from the plan's own page (plan 20261026 P9): the click records a hash of the plan text
31
+ // in the queue state (plan-approvals.json). Only that plan, only from this page's origin, and
32
+ // never while a note on the page has no answer.
33
33
  if (url.pathname === "/_approve") {
34
34
  if (req.headers.get("origin") !== `http://${req.headers.get("host")}`) return plain("forbidden: origin is not this page", 403);
35
35
  const page = url.searchParams.get("page") ?? "";
@@ -41,7 +41,11 @@ export function startPagesServer(opts: PagesOptions): PagesServer {
41
41
  if (unproven.length > 0) return Response.json({ error: `the diagram is not complete (${unproven.slice(0, 3).join("; ")})` }, { status: 409 });
42
42
  const plan = record.plan;
43
43
  if (!existsSync(plan)) return plain("not found: the plan file is gone", 404);
44
- return Response.json({ approved: approvePlanFile(plan, page) });
44
+ try {
45
+ return Response.json({ approved: approvePlanFile(plan, page) });
46
+ } catch (e) {
47
+ return plain(`not approved: ${e instanceof Error ? e.message : String(e)}`, 500);
48
+ }
45
49
  }
46
50
  if (url.pathname !== "/_notes") return plain("method not allowed", 405);
47
51
  if (req.headers.get("origin") !== `http://${req.headers.get("host")}`) return plain("forbidden: origin is not this page", 403);
@@ -1,13 +1,26 @@
1
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";
2
+ // Base is approved there: the Approve bar records a hash of the plan text in the queue state
3
+ // (plan-approvals.json). The plan file is never edited. main-guard refuses a spawn on a plan whose page
4
+ // has no record with the plan's current hash; a plan with no page predates the convention and is left alone, unless it is stamped at or after approval.since (plan 20261029_1455 P3), when it is refused until its page is published.
5
+ import { appendFileSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
6
+ import { basename, join, resolve } from "node:path";
7
+ import * as q from "./queue/lib.ts";
8
+ import type { Config } from "./config.ts";
8
9
 
9
- const APPROVED = /^\s*(?:[-*]\s+)?Approved:.*$/im;
10
- const SELF = /^\s*(?:[-*]\s+)?Approval:\s*self\b[^\n]*owner:\s*["\u201c][^"\u201d\n]+["\u201d]/im;
10
+ /** Lines only Main may write: the status, owner parking, plan waits, owner cancellation, cancelled-list clearance. */
11
+ export const MAIN_ONLY_LINE = /^\s*(?:[-*]\s+)?(Status:|WAITING on owner:|Waits on:|Cancelled by owner:|False positive:)/;
12
+
13
+ /** What a PASS covers: the plan text outside "## Progress" without the Main-only lines, so progress notes never expire a review. */
14
+ export function reviewHash(text: string): string {
15
+ return q.sha(
16
+ q
17
+ .outsideProgress(text)
18
+ .split("\n")
19
+ .filter(l => !MAIN_ONLY_LINE.test(l))
20
+ .map(l => l.replace(/^(\s*[-*]\s+)\[[xX]\]/, "$1[ ]")) // a ticked phase box hashes as unticked: ticking never expires a PASS
21
+ .join("\n"),
22
+ );
23
+ }
11
24
 
12
25
  /** What publishing recorded for a page: the plan it approves and what its diagram check found. */
13
26
  export interface PagePlan {
@@ -60,36 +73,98 @@ export function pageOfPlan(dir: string, file: string): string | null {
60
73
  return null;
61
74
  }
62
75
 
63
- export function isApproved(text: string): boolean {
64
- return APPROVED.test(text) || SELF.test(text);
76
+ // --- Plan approval records (plan 20261026_0930 P9): a hash in the queue state, not a line in the plan ---
77
+
78
+ /** One approval: the plan text it covers, when it was recorded, and how. */
79
+ export interface PlanApproval {
80
+ hash: string;
81
+ at: number;
82
+ via: "page" | "chat";
83
+ page: string;
84
+ }
85
+
86
+ function planApprovalsFile(): string {
87
+ return join(q.STATE_DIR, "plan-approvals.json");
65
88
  }
66
89
 
67
- export function isSelfApproved(text: string): boolean {
68
- return SELF.test(text);
90
+ function readPlanApprovals(): Record<string, PlanApproval> {
91
+ try {
92
+ const parsed = JSON.parse(readFileSync(planApprovalsFile(), "utf8"));
93
+ if (parsed?.approvals && typeof parsed.approvals === "object") return parsed.approvals as Record<string, PlanApproval>;
94
+ } catch {
95
+ }
96
+ return {};
97
+ }
98
+
99
+ function writePlanApprovals(approvals: Record<string, PlanApproval>): boolean {
100
+ try {
101
+ mkdirSync(q.STATE_DIR, { recursive: true });
102
+ writeFileSync(planApprovalsFile(), JSON.stringify({ approvals }, null, 1));
103
+ return true;
104
+ } catch {
105
+ return false;
106
+ }
69
107
  }
70
108
 
71
- export function approvalLine(page: string, now = new Date()): string {
72
- return `Approved: ${now.toISOString().slice(0, 10)} (${page})`;
109
+ function readPlanApproval(file: string): PlanApproval | null {
110
+ return readPlanApprovals()[file] ?? null;
73
111
  }
74
112
 
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)}`;
113
+ /** Record one approval. Throws when the queue state cannot be written, so nobody reports "approved" for a record that is not there. */
114
+ function recordApproval(file: string, approval: PlanApproval): void {
115
+ const approvals = readPlanApprovals();
116
+ approvals[file] = approval;
117
+ if (!writePlanApprovals(approvals)) throw new Error(`cannot write ${planApprovalsFile()}`);
81
118
  }
82
119
 
83
- /** Write the owner's click into the plan and return the line it recorded. */
120
+ /** The owner's click on a plan page: record a hash of the plan text in the queue state and return the page it approved. The plan file itself is never edited. */
84
121
  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);
122
+ const text = readFileSync(file, "utf8");
123
+ recordApproval(file, { hash: reviewHash(text), at: now.getTime(), via: "page", page });
124
+ return `approved ${page}`;
87
125
  }
88
126
 
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>".`;
127
+ export type ChatApproveResult = { applied: true; plan: string } | { applied: false; problem?: string };
128
+
129
+ const APPROVE_CMD = /^approve (\d{8}_\d{4})$/;
130
+
131
+ /**
132
+ * The owner's own chat `approve <YYYYMMDD_HHMM>` (same trust rules as chatGo): the one open indexed
133
+ * plan whose file stamp matches records a chat approval and is logged to plan_guard_log. Any other
134
+ * text is not an approval. A stamp that matches none, or several, or a record that cannot be saved,
135
+ * is a problem for the owner to read; nothing is approved.
136
+ */
137
+ export function chatApprove(text: string, cfg: Config, source: string): ChatApproveResult {
138
+ if (!cfg.guards.chat_unlock) return { applied: false };
139
+ const m = APPROVE_CMD.exec(text.trim());
140
+ if (!m) return { applied: false };
141
+ const stamp = m[1];
142
+ const matches = q.activePlans().filter(p => p.status === "open" && basename(p.file).startsWith(`${stamp}_`));
143
+ const [plan, second] = matches;
144
+ if (!plan) return { applied: false, problem: `no open plan ${stamp}` };
145
+ if (second) return { applied: false, problem: `${matches.length} open plans match ${stamp}; nothing approved` };
146
+ try {
147
+ recordApproval(plan.file, { hash: reviewHash(plan.text), at: Date.now(), via: "chat", page: pageOfPlan(cfg.pages.dir, plan.file) ?? "" });
148
+ } catch (e) {
149
+ return { applied: false, problem: `plan ${stamp} not approved: ${e instanceof Error ? e.message : String(e)}` };
150
+ }
151
+ try {
152
+ appendFileSync(cfg.paths.plan_guard_log, `${new Date().toISOString()} APPROVE chat source=${source} plan=${plan.file}\n`);
153
+ } catch {}
154
+ return { applied: true, plan: plan.file };
95
155
  }
156
+
157
+ /** Why a spawn may not run on this plan, or null. A plan with a page in Base needs a record with its current hash. A plan stamped at or after `since` (approval.since, "" = off) needs a page too (plan 20261029_1455 P3): with no page it is refused until the page is published. A file with no stamp counts as stamped after `since`. */
158
+ export function approvalProblem(text: string, file: string, pagesDir: string, since: string): string | null {
159
+ const page = pageOfPlan(pagesDir, file);
160
+ const stamp = /^\d{8}_\d{4}/.exec(basename(file))?.[0] ?? null;
161
+ const gated = since !== "" && (stamp === null || stamp >= since);
162
+ if (page === null) {
163
+ if (!gated) return null; // predates the convention
164
+ return `plan ${file} has no page: publish its page with neurastream pages publish <page.html> --plan ${file}`;
165
+ }
166
+ const rec = readPlanApproval(file);
167
+ if (rec !== null && rec.hash === reviewHash(text)) return null;
168
+ const hint = stamp !== null ? `, or types: approve ${stamp}` : "";
169
+ return `plan ${file} has no approval record. The owner approves it from ${page} in Base${hint}.`;
170
+ }
@@ -168,7 +168,7 @@ export function splitWaiting(line: string): { ask: string; blocked: string | nul
168
168
  /** Keep the first `keep` entries (the file lists them newest first) and move the rest. Pure. */
169
169
  export function trimProgressBody(body: string, keep: number, pointer: string): ProgressTrim | undefined {
170
170
  const lines = body.split("\n").filter(l => !l.startsWith(POINTER_PREFIX));
171
- const starts = lines.flatMap((l, i) => (/^- /.test(l) && !MAIN_ONLY_LINE.test(l) ? [i] : []));
171
+ const starts = lines.flatMap((l, i) => (l.startsWith('- ') && !MAIN_ONLY_LINE.test(l) ? [i] : []));
172
172
  if (starts.length <= keep) return undefined;
173
173
  const cut = starts[keep];
174
174
  const tail = lines.slice(cut);
@@ -231,28 +231,13 @@ function headerField(text: string, name: string): string | null {
231
231
  return v ? v.replace(/`/g, "").trim() || null : null;
232
232
  }
233
233
 
234
- /** A plan filename stamp (YYYYMMDD_HHMM) as an ISO-ish string ("2026-10-29T01:00") that sorts lexically; "" when unstamped. */
235
- export function stampIso(file: string): string {
236
- const m = /^(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})/.exec(path.basename(file));
237
- return m ? `${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}` : "";
238
- }
239
-
240
- /**
241
- * The review gates (P1 reuse lines, P2 reviewer PASS) apply to a plan stamped at or after the
242
- * `review.since` cutover — a bare date counts as midnight; `since` "" switches them off.
243
- */
244
- export function reviewApplies(file: string, since: string): boolean {
245
- const cutover = since.length === 10 ? `${since}T00:00` : since;
246
- return cutover.length > 0 && stampIso(file) >= cutover;
247
- }
248
-
249
234
  /**
250
235
  * P1 (plan 20261028_1600): every new thing a plan adds carries a reuse line with a checked
251
- * `path:line` citation that exists relative to the plan's repo. Plans stamped before the
252
- * `review.since` cutover are exempt.
236
+ * `path:line` citation that exists relative to the plan's repo. Applies to every plan (P5
237
+ * removed the cutover); an empty `review.agents` list turns the gate off (P5c).
253
238
  */
254
- function reuseProblems(repo: string, file: string, secs: Map<string, string>, since: string): string[] {
255
- if (!reviewApplies(file, since)) return [];
239
+ function reuseProblems(repo: string, file: string, secs: Map<string, string>, reviewAgents: string[]): string[] {
240
+ if (!reviewAgents.length) return [];
256
241
  const lines = items(secs.get("reuse") ?? "");
257
242
  if (!lines.length)
258
243
  return [`missing or empty "## Reuse" section (one line per new thing: - new: <thing> — checked: <path>:<line> — reuse: <how, or why not>; "- new: none — ..." when nothing is new)`];
@@ -265,7 +250,7 @@ function reuseProblems(repo: string, file: string, secs: Map<string, string>, si
265
250
  return probs;
266
251
  }
267
252
 
268
- export function parsePlan(repo: string, file: string, text: string | null, blockersDir = blockersDirPath(), reviewSince = ""): Plan {
253
+ export function parsePlan(repo: string, file: string, text: string | null, blockersDir = blockersDirPath(), reviewAgents: string[] = []): Plan {
269
254
  const empty = { repo, file, text: "", status: null, blockers: [], doneCheck: null, worktree: null, branch: null, appliesTo: [], waiting: false, waitingLine: null, waitingAsk: null, waitingBlocked: null, waitingWhy: null, waitsOn: [], priorityId: null, title: path.basename(file), goal: [], summary: null, phases: { done: 0, total: 0 }, started: false };
270
255
  if (text === null) return { ...empty, errors: ["plan file listed in the index does not exist"] };
271
256
  const errors: string[] = [];
@@ -277,7 +262,7 @@ export function parsePlan(repo: string, file: string, text: string | null, block
277
262
  const stamp = /^(\d{8}_\d{4})/.exec(path.basename(file))?.[1] ?? "";
278
263
  if (stamp >= READ_CUTOVER && !items(secs.get("code read by main") ?? "").length)
279
264
  errors.push(`missing or empty "## Code read by Main" section (plans stamped ${READ_CUTOVER} or later list each file they cite)`);
280
- for (const problem of reuseProblems(repo, file, secs, reviewSince)) errors.push(problem);
265
+ for (const problem of reuseProblems(repo, file, secs, reviewAgents)) errors.push(problem);
281
266
  const known = new Set([...REQUIRED, "applies to", "background", "code read by main", "reuse"]);
282
267
  for (const s of secs.keys()) if (!known.has(s)) errors.push(`unknown section "## ${s}" (allowed: ${[...known].join(", ")})`);
283
268
  const status = statusOf(text);
@@ -295,7 +280,7 @@ export function parsePlan(repo: string, file: string, text: string | null, block
295
280
  if (secs.has("phases") && !phaseLines.length) errors.push('"## Phases" needs checkbox lines: "- [ ] P1 <what> — verify: `<command>`"');
296
281
  for (const p of phaseLines) if (!/verify:\s*`[^`]+`/.test(p)) errors.push(`phase without "verify: \`<command>\`": ${p.slice(0, 60)}`);
297
282
  const phases = { total: phaseLines.length, done: phaseLines.filter(l => /^\[[xX]\]/.test(l)).length };
298
- const started = phases.done > 0 || progressBody(text).split("\n").some(l => /^- /.test(l) && !l.startsWith(POINTER_PREFIX) && !MAIN_ONLY_LINE.test(l));
283
+ const started = phases.done > 0 || progressBody(text).split("\n").some(l => l.startsWith('- ') && !l.startsWith(POINTER_PREFIX) && !MAIN_ONLY_LINE.test(l));
299
284
  const dc = (secs.get("done check") ?? "").match(/```[a-z]*\n([\s\S]*?)```|`([^`\n]+)`/);
300
285
  const doneCheck = dc ? (dc[1] ?? dc[2] ?? "").trim() : null;
301
286
  if (secs.has("done check") && !doneCheck) errors.push('"## Done check" needs one command in backticks (exit 0 = done)');
@@ -339,18 +324,18 @@ export function planRepo(file: string): string {
339
324
  return m?.[1] ? m[1].replace(/\/$/, "") : dir;
340
325
  }
341
326
 
342
- export function readPlans(files: string[], blockersDir = blockersDirPath(), reviewSince = ""): Plan[] {
327
+ export function readPlans(files: string[], blockersDir = blockersDirPath(), reviewAgents: string[] = []): Plan[] {
343
328
  return files.map(file => {
344
329
  let text: string | null = null;
345
330
  try {
346
331
  text = readFileSync(file, "utf8");
347
332
  } catch {}
348
- return parsePlan(planRepo(file), file, text, blockersDir, reviewSince);
333
+ return parsePlan(planRepo(file), file, text, blockersDir, reviewAgents);
349
334
  });
350
335
  }
351
336
 
352
- export function activePlans(index = indexPath(), blockersDir = blockersDirPath(), reviewSince = ""): Plan[] {
353
- return readPlans(readIndex(index), blockersDir, reviewSince);
337
+ export function activePlans(index = indexPath(), blockersDir = blockersDirPath(), reviewAgents: string[] = []): Plan[] {
338
+ return readPlans(readIndex(index), blockersDir, reviewAgents);
354
339
  }
355
340
 
356
341
  /** Owner holds: one line per plan with a WAITING on owner line. The only real holds; the summary, the rollover context and the handoff all read them here. */
@@ -466,7 +451,7 @@ export function touchedPaths(toolName: string, input: Record<string, unknown>, c
466
451
  }
467
452
 
468
453
  export const MUTATING =
469
- /(\brm\b|\bmv\b|\bcp\b|\btouch\b|\btruncate\b|\bchmod\b|\bln\b|\bsed\s+(-\w*\s+)*-i|\bperl\s+(-\w*\s+)*-[a-z]*i|\btee\b|(^|[^0-9&>=\-])>{1,2}\s*[^\s&>]|\bgit\s+(rm|mv|checkout|restore|apply|am|stash|reset|clean)\b|\bpatch\b|\binstall\b|\bdd\b|writeFile|appendFile|Bun\.write|unlink|rmSync|\.write_text\(|\.write_bytes\(|\bopen\([^)]*,\s*["'][wax]b?\+?["']|shutil\.|os\.(remove|rename|replace|unlink|chmod)|\.writelines\()/;
454
+ /(\brm\b|\bmv\b|\bcp\b|\btouch\b|\btruncate\b|\bchmod\b|\bln\b|\bsed\s+(-\w*\s+)*-i|\bperl\s+(-\w*\s+)*-[a-z]*i|\btee\b|(^|[^0-9&>=-])>{1,2}\s*[^\s&>]|\bgit\s+(rm|mv|checkout|restore|apply|am|stash|reset|clean)\b|\bpatch\b|\binstall\b|\bdd\b|writeFile|appendFile|Bun\.write|unlink|rmSync|\.write_text\(|\.write_bytes\(|\bopen\([^)]*,\s*["'][wax]b?\+?["']|shutil\.|os\.(remove|rename|replace|unlink|chmod)|\.writelines\()/;
470
455
 
471
456
  export function withoutQuotedRedirects(code: string): string {
472
457
  return code.replace(/'[^']*'/g, m => m.replace(/>/g, " ")).replace(/"(?:[^"\\]|\\.)*"/g, m => m.replace(/>/g, " "));
@@ -618,7 +603,7 @@ export function writeTargets(toolName: string, input: Record<string, unknown>, c
618
603
  continue;
619
604
  }
620
605
  const noQuotedRedirect = withoutQuotedRedirects(s);
621
- for (const m of noQuotedRedirect.matchAll(/(?:^|[^0-9&>=\-])>{1,2}\s*([^\s&|;)<>]+)/g)) {
606
+ for (const m of noQuotedRedirect.matchAll(/(?:^|[^0-9&>=-])>{1,2}\s*([^\s&|;)<>]+)/g)) {
622
607
  // A target with no letter, digit, `.` or `/` (`>,`) is prose, not a file.
623
608
  const target = (m[1] ?? "").replace(/^["']|["']$/g, "");
624
609
  if (/[\p{L}\p{N}./]/u.test(target)) add(target, dir);
@@ -789,14 +774,16 @@ export function allowedAgents(file = subagentsPath()): Set<string> {
789
774
 
790
775
  // P4d (plan 20261028_1600): a review spawn runs under a review.agents entry that Main may spawn
791
776
  // (## Allowed of the subagents file). When Allowed names agents and none of them is a review.agents
792
- // entry, every review spawn is refused: a problem. When Allowed is empty (a fresh install), no subagent
793
- // can spawn at all yet, so there is no review spawn to refuse. An entry not allowed is a warning.
777
+ // entry, every review spawn is refused: a problem. An empty review.agents list turns both review
778
+ // gates off (P5c, I-20261030-5), so it is valid whatever Allowed holds. When Allowed is empty (a
779
+ // fresh install), no subagent can spawn at all yet, so there is no review spawn to refuse. An
780
+ // entry not allowed is a warning.
794
781
  export function reviewAgentsProblem(cfg: Config, allowed: Set<string>): { problem: string | null; warnings: string[] } {
795
782
  const agents = cfg.review.agents;
796
783
  const warnings = agents
797
784
  .filter(a => !allowed.has(a))
798
785
  .map(a => `review.agents lists "${a}", which is not in "## Allowed" of ${cfg.paths.subagents}; it cannot run a review spawn`);
799
- const problem = allowed.size === 0 || agents.some(a => allowed.has(a))
786
+ const problem = agents.length === 0 || allowed.size === 0 || agents.some(a => allowed.has(a))
800
787
  ? null
801
788
  : `no review.agents entry is in "## Allowed" of ${cfg.paths.subagents}: set review.agents to an allowed agent in config.yml`;
802
789
  return { problem, warnings };
@@ -869,14 +856,17 @@ export function finishedEntry(plan: Plan, archived: string, date: string): strin
869
856
  return [`## ${date} · ${path.basename(plan.repo)} · ${plan.title}`, ...body].join("\n");
870
857
  }
871
858
 
872
- /** Identity of a finished entry: its repo name and archived plan file name. Worktrees of one repo share it. */
859
+ /** Identity of a finished entry: its heading title (the text after the second ` · ` of
860
+ * `## <date> · <repo> · <title>`) plus the `Plan:` line's file basename. The repo name drops
861
+ * out so a plan copied into separate clones with no shared .git still matches once per plan. */
873
862
  export function finishedKey(entry: string): string {
874
863
  const lines = entry.split("\n");
875
- const repo = (lines[0] ?? "").split(" · ")[1] ?? "";
876
- return `${repo}\n${path.basename(lines.find(l => l.startsWith("Plan: ")) ?? "")}`;
864
+ const title = (lines[0] ?? "").split(" · ").slice(2).join(" · ").trim();
865
+ const plan = (lines.find(l => l.startsWith("Plan: ")) ?? "").slice("Plan: ".length);
866
+ return `${title}\n${path.basename(plan)}`;
877
867
  }
878
868
 
879
- /** Inserts the entry above older ones. Returns false when that repo's plan file is already listed. */
869
+ /** Inserts the entry above older ones. Returns false when the same plan (title + file name) is already listed. */
880
870
  export function prependFinished(entry: string, file = finishedPath()): boolean {
881
871
  let current = "";
882
872
  try {
@@ -954,7 +944,7 @@ export function lastCloseResult(file: string): string | null {
954
944
  }
955
945
 
956
946
  export function awaitingMerge(p: Plan): boolean {
957
- return p.status === "complete" && /^queue-close: AWAITING merge/.test(lastCloseResult(p.file) ?? "");
947
+ return p.status === "complete" && (lastCloseResult(p.file) ?? "").startsWith("queue-close: AWAITING merge");
958
948
  }
959
949
 
960
950
  /**
@@ -984,10 +974,10 @@ export interface QueueProblem {
984
974
  problem: string;
985
975
  }
986
976
 
987
- export function queueProblems(index = INDEX, blockersDir = BLOCKERS_DIR, reviewSince = ""): QueueProblem[] {
977
+ export function queueProblems(index = INDEX, blockersDir = BLOCKERS_DIR, reviewAgents: string[] = []): QueueProblem[] {
988
978
  const probs: QueueProblem[] = [];
989
979
  if (!existsSync(index)) probs.push({ where: index, problem: "main index missing: create it (empty = no open work)" });
990
- const plans = readPlans(readIndex(index), blockersDir, reviewSince);
980
+ const plans = readPlans(readIndex(index), blockersDir, reviewAgents);
991
981
  const byWorktree = new Map<string, Plan[]>();
992
982
  for (const p of plans) {
993
983
  for (const e of p.errors) probs.push({ where: p.file, problem: e });
@@ -1014,7 +1004,7 @@ export function queueProblems(index = INDEX, blockersDir = BLOCKERS_DIR, reviewS
1014
1004
  return probs;
1015
1005
  }
1016
1006
 
1017
- export function queueSummary(index = INDEX, reviewSince = ""): string {
1007
+ export function queueSummary(index = INDEX, reviewAgents: string[] = []): string {
1018
1008
  // Index order IS priority (20261025_0215_index_priority): the list is flat and ranked,
1019
1009
  // rank 1 = the index's top line; repos only surface through each plan's own path.
1020
1010
  const plans = activePlans(index);
@@ -1039,7 +1029,7 @@ export function queueSummary(index = INDEX, reviewSince = ""): string {
1039
1029
  });
1040
1030
  const nCancelled = repos.reduce((n, repo) => n + readCancelled(repo).length, 0);
1041
1031
  if (nCancelled) lines.push(`Cancelled rules: ${nCancelled}`);
1042
- const probs = queueProblems(index, BLOCKERS_DIR, reviewSince);
1032
+ const probs = queueProblems(index, BLOCKERS_DIR, reviewAgents);
1043
1033
  if (probs.length) lines.push(`Problems (fix first):`, ...probs.map(q => ` - ${q.where}: ${q.problem}`));
1044
1034
  return lines.join("\n");
1045
1035
  }
@@ -12,9 +12,9 @@ export function queueCheck(args: string[], cfg: Config): number {
12
12
  for (const p of activePlans()) if (p.priorityId && !p.waiting && p.status === "open") console.log(p.priorityId);
13
13
  return 0;
14
14
  }
15
- console.log(queueSummary(undefined, cfg.review.since));
15
+ console.log(queueSummary(undefined, cfg.review.agents));
16
16
  // main-start prints the sweep itself and passes this so the child bin does not print it twice.
17
- let fail = queueProblems(undefined, undefined, cfg.review.since).length > 0;
17
+ let fail = queueProblems(undefined, undefined, cfg.review.agents).length > 0;
18
18
  // P4d (plan 20261028_1600): a review spawn needs a review.agents entry that Main may spawn.
19
19
  const review = reviewAgentsProblem(cfg, allowedAgents(cfg.paths.subagents));
20
20
  if (review.problem) {
@@ -4,7 +4,7 @@ import os from "node:os";
4
4
  import path from "node:path";
5
5
  import type { Config } from "./config.ts";
6
6
  import { applyQueueEnv } from "./queue/env.ts";
7
- import { activePlans, cancelledFile, cancelledLine, closeLog, finishedEntry, finishedPath, INDEX, prependFinished, readIndex, sha, STATE_DIR } from "./queue/lib.ts";
7
+ import { activePlans, cancelledFile, cancelledLine, closeLog, finishedEntry, finishedPath, INDEX, prependFinished, sha, STATE_DIR } from "./queue/lib.ts";
8
8
  import { fixedIncident } from "./incidents.ts";
9
9
 
10
10
  export function queueClose(args: string[], cfg: Config): number {
@@ -19,7 +19,7 @@ export function invalidSlugs(slugs: string[]): string[] {
19
19
  function allowedSection(lines: string[]): { head: number; end: number } | null {
20
20
  const head = lines.findIndex(l => ALLOWED_HEAD.test(l));
21
21
  if (head === -1) return null;
22
- let end = lines.findIndex((l, i) => i > head && /^## /.test(l));
22
+ let end = lines.findIndex((l, i) => i > head && l.startsWith('## '));
23
23
  if (end === -1) end = lines.length;
24
24
  return { head, end };
25
25
  }
@@ -1,4 +1,4 @@
1
- import { copyFileSync, existsSync, lstatSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
1
+ import { copyFileSync, existsSync, lstatSync, mkdtempSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join, resolve } from "node:path";
4
4
  import type { Config } from "./config.ts";