neurastream 0.2.54 → 0.2.56

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.
package/README.md CHANGED
@@ -135,7 +135,7 @@ One setting decides how much Main does without asking: `autonomy.tier` in the co
135
135
 
136
136
  With `ui.enabled: true` and `ui.owner_login` set (`neurastream config`, `docs/config.md`), `neurastream ui` serves one page bound to this machine's tailnet address only (port `ui.port`, default 7787; `templates/systemd/neurastream-ui.service` runs it as a user unit). A sticky top bar holds the "ns" logo, five pill tabs — Now, Queue, Agents, Spend, Base (see "Base tab" below), each a server-rendered view (`/?tab=…`, an unknown value falls back to Now) — and the lock pill ("🔒 Off" / "🔓 12 min") that opens the guard unlock ("Unlock 15 min", "Unlock 30 min", "Lock now"; when `guards.chat_unlock` is off it says so in plain words with the exact config line). Now is the home tab: a Today tile card over the last 24 h (needs-you count in warn color, list-price spend with a sparkline and the Main/agents split, agent runs with running/died counts and a sparkline, open plans), then one card per open `WAITING on owner:` plan that says why it needs him — the plan's `#` title, then Do (what to do), Stuck until then (what stays blocked, including plans this answer unblocks), and Why you (why Main cannot do it), with the goal folded into a Background block. A question ask gets "Yes"/"No"/"Reply…"; a task ask gets "Done". The answer shows as a one-time receipt ("Sent to Main · 08:12"); once the owner inbox already holds an answer for a plan, the card says so ("You answered ‘yes' · 14:19 — Main is on it") with a small change-answer link. The queue is one flat ranked list in `INDEX.md` order. Each card shows the plan title, a two-line summary from the plan's `Summary:` header (one or two plain sentences under Branch; if that line is missing, the first Goal bullet with a leading Owner or INCIDENT prefix cut off), and a status chip — waits you, waits on another plan, not started, phase K of N, or all N done. Drag a card by its ≡ handle, or tap "↑ top"/"↑"/"↓"; the drop rewrites `INDEX.md`, Main gets the move as a message and the page confirms "Moved to #2". Now shows the first 8 rows with a "Show all N ›" link to the Queue tab. The Agents tab lists working-now rows (a run that died before its first reply shows the model from the spawning agent's `model:` frontmatter, never "?"), the agent-score table, open incidents, recent merges/CI and machine health; the Spend tab pairs the spend tile with per-model spend over 24 h. The Now tab also has a "Tell Main" message box for a text note and up to four images; Main receives the text and pictures, and the page keeps a "Sent today" list for 12 hours before removing those messages and their image files. Light and dark follow the OS; there are no external assets and no build step — one server-rendered HTML string, inline CSS and one small inline script under a per-response CSP nonce (`bun scripts/ui-preview.ts <out.html> [--tab <name>]` renders a preview without a server). No chat, no plan editing, no shell.
137
137
 
138
- A request is served only when the peer is a tailnet address that is neither loopback nor this machine's own tailnet IP, `tailscale whois` names the `ui.owner_login` login — and the Host header is this machine: the tailnet address or the MagicDNS name, with the served port. The Host check runs on every request before whois, and a POST's Origin must match it, so a DNS-rebinding page (foreign Host, matching Origin, owner's phone) gets a 403 like everyone else. Every request logs one `UI <method> <path> login=<l> → <code>` line to the guard log.
138
+ A request is served only when the peer is a tailnet address that is neither loopback nor this machine's own tailnet IP, `tailscale whois` names the `ui.owner_login` login — and the Host header is this machine: the tailnet address or the MagicDNS name, with the served port. The Host check runs on every request before whois, and a POST's Origin must match it, so a DNS-rebinding page (foreign Host, matching Origin, owner's phone) gets a 403 like everyone else. `ui.allow_this_machine: true` skips only the two this-machine refusals — loopback and the machine's own tailnet IP are then served as the owner, GET and POST — with the risk in one line: any local process can then press the buttons. Every request logs one `UI <method> <path> login=<l> → <code>` line to the guard log.
139
139
 
140
140
  An answer appends one record to `<queue_state>/owner-inbox.jsonl` (plan, question, answer, login); unlock/lock go through the core unlock and log `UNLOCK ui source=ui:<login> minutes=N`. Main's session delivers each record once as a user message — at turn end and on a 15 s poll while idle — and marks the consumed rows in `<queue_state>/owner-inbox.cursor`; subagent sessions never deliver. Both files sit under the queue state dir, so guards refuse agent writes to them: an agent cannot forge an owner answer. Guards also refuse agent commands that start the page (`neurastream ui`, or `systemctl --user start/restart/enable` of `neurastream-ui`): starting it is the owner's move.
141
141
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.54",
3
+ "version": "0.2.56",
4
4
  "description": "Guardrails for running many AI coding agents at once: plan queue, blockers, call budgets, provider caps, scoring, merge-verified close.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -58,6 +58,7 @@
58
58
  },
59
59
  "scripts": {
60
60
  "typecheck": "tsc --noEmit",
61
+ "lint": "oxlint --deny-warnings --ignore-pattern 'tests/fixtures/**' src tests bin",
61
62
  "test": "bun test"
62
63
  },
63
64
  "omp": {
@@ -67,6 +68,7 @@
67
68
  },
68
69
  "devDependencies": {
69
70
  "@types/bun": "^1.3.14",
71
+ "oxlint": "1.90.0",
70
72
  "typescript": "^5.9.3"
71
73
  }
72
74
  }
@@ -26,7 +26,7 @@ import { configFile, loadConfig, reloadingConfig, type Config } from "../../core
26
26
  import { checkWrite, deferSteer, type WriteCheckConfig } from "../../core/write-check.ts";
27
27
  import { nowSec, strftime } from "../../core/clock.ts";
28
28
  import { runDetectors, runDetectorsGated, type DetectorInput } from "../../core/incident-detectors.ts";
29
- import { checkInject, checkPlanEdit, checkStop, checkTool, findingsValue, MAIN_PLAN_FILE, newProgressEntries, planReadNote, recordMainResult, resetMainCalls, revertMainEdit, rekeySpawnFile, reviewSpawnEnd } from "../../core/guards.ts";
29
+ import { checkInject, checkPlanEdit, checkStop, checkTool, findingsValue, MAIN_PLAN_FILE, newProgressEntries, planReadNote, recordMainResult, resetMainCalls, revertMainEdit, rekeySpawnFile, reviewSpawnEnd, STOP_PLAN_OFFER_REFUSAL } from "../../core/guards.ts";
30
30
  import { rateLimitWait } from "../../core/rate-limit.ts";
31
31
  import { notifyProviders, postReply } from "../../core/notify.ts";
32
32
  import { loadKnownSecrets, redactSecrets, redactSummary } from "../../core/secret-redact.ts";
@@ -565,6 +565,8 @@ export function deliverOwnerInbox(pi: ExtensionHost, cfg: Config): void {
565
565
  adapterLog(cfg, `owner inbox: delivered ${delivered} answer(s) (cursor ${cursor} → ${next})`);
566
566
  }
567
567
 
568
+ /** The most recently registered createOmpAdapter cleanup, for the exported reset(). */
569
+ let activeAdapterReset: (() => void) | null = null;
568
570
  /** Register the guard handlers on one extension host. `initial` is injectable for tests; `freshConfig` re-reads the config per guarded call. */
569
571
  export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig: () => Config = () => initial): void {
570
572
  // Guarded handlers take `cfg = freshConfig()` first, so an edited config.yml reaches the next call (P4e).
@@ -832,7 +834,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
832
834
 
833
835
  // The spawn event carries no brief, so the plan gate runs at the task tool call (original
834
836
  // behaviour); here only the allow-list and the task-only rule apply, with the original texts.
835
- pi.on("before_subagent_spawn", (event, ctx) => {
837
+ pi.on("before_subagent_spawn", (event, _ctx) => {
836
838
  cfg = freshConfig();
837
839
  const agent = asString(asRecord(event).agent);
838
840
  const kind = asString(asRecord(event).invocationKind);
@@ -1200,6 +1202,17 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1200
1202
  }
1201
1203
  };
1202
1204
 
1205
+ // Clear the rollover episode state so a later createOmpAdapter setup in the same
1206
+ // process starts clean: a stale armGraceTimer would otherwise fire with this
1207
+ // closure's cfg and recreate torn-down dirs (P3c).
1208
+ const clearRolloverState = (): void => {
1209
+ clearGrace?.();
1210
+ relaunched = false;
1211
+ flight = null;
1212
+ };
1213
+ // Clear the previous adapter's armed grace timer before this one overwrites the pointer (P3c).
1214
+ activeAdapterReset?.();
1215
+ activeAdapterReset = clearRolloverState;
1203
1216
  // The launcher restarts omp: the request file carries the note and the editor draft, and omp
1204
1217
  // shuts down only after the file is written. A failed write keeps the session running.
1205
1218
  // Returns whether the request was written.
@@ -1320,6 +1333,12 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1320
1333
  }
1321
1334
  // A real hand-back: the turn ended without a rate limit — the episode is over.
1322
1335
  disarmRateEpisode();
1336
+ // A deferred hand-back fires no session_stop: reset the per-turn cap here (I-20261030-24)
1337
+ // and steer a promise like checkStop refuses it (I-20261030-32).
1338
+ resetMainCalls();
1339
+ if (new RegExp(cfg.guards.plan_offer, "i").test(reply.text)) {
1340
+ pi.sendUserMessage(STOP_PLAN_OFFER_REFUSAL);
1341
+ }
1323
1342
  notifyHandback(reply, "agent_end hand-back");
1324
1343
  });
1325
1344
  // Turn end: page answers that arrived during the turn go out (P3b), then open plans that now
@@ -1354,8 +1373,8 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1354
1373
  });
1355
1374
 
1356
1375
  // Terminal hand-back (plan 20261028_1545 P2): a willContinue agent_end keeps the turn going
1357
- // (blocked stop, todo/plan-mode continuation, deferred hand-back), so only its absence ends
1358
- // the turn — the per-turn call budget resets for the next one.
1376
+ // (blocked stop, todo/plan-mode continuation, deferred hand-back); only its absence ends the
1377
+ // turn — the budget resets here and on the deferred hand-back above (I-20261030-24).
1359
1378
  pi.on("agent_end", (e, ctx) => {
1360
1379
  if (!isMain(ctx)) return;
1361
1380
  if (asRecord(e).willContinue === true) return;
@@ -1549,6 +1568,15 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1549
1568
  });
1550
1569
  }
1551
1570
 
1571
+ /** Clear the active adapter's rollover state. Tests call this in afterAll so a stale
1572
+ * grace-period timer does not fire into a later test file's sandbox paths (P3c). */
1573
+ export function reset(): void {
1574
+ if (activeAdapterReset) {
1575
+ activeAdapterReset();
1576
+ activeAdapterReset = null;
1577
+ }
1578
+ }
1579
+
1552
1580
  /** package.json omp.extensions entry. */
1553
1581
  export default function ompExtension(pi: ExtensionHost): void {
1554
1582
  // The one switch (MAIN_ENV): plain `omp` runs nothing of neurastream — no hook, no command,
package/src/cli/pages.ts CHANGED
@@ -5,7 +5,7 @@ import { loadConfig } from "../core/config.ts";
5
5
  import { readExpiry, sweepPages } from "../core/pages-expiry.ts";
6
6
  import { startPagesServer } from "../core/pages.ts";
7
7
  import { pageNotesGate } from "../core/page-notes.ts";
8
- import { pagesOff, pagesOn, publishPage, type Runner } from "../core/pages-setup.ts";
8
+ import { pagesOff, pagesOn, publishPage, repoForPublish, type Runner } from "../core/pages-setup.ts";
9
9
  import { realTailscale, type Tailscale } from "../core/tailscale.ts";
10
10
 
11
11
  export interface PagesDeps { home?: string; runner?: Runner; tailscale?: Tailscale; clock?: () => Date }
@@ -25,24 +25,26 @@ export async function runPages(args: string[] = [], deps: PagesDeps = {}): Promi
25
25
  return new Promise<number>(() => {});
26
26
  }
27
27
  if (args[0] === "publish" && args[1]) {
28
- let force = false, keep = false, plan: string | undefined;
28
+ let force = false, keep = false, plan: string | undefined, repo: string | undefined;
29
29
  const rest: string[] = [];
30
30
  for (let i = 1; i < args.length; i++) {
31
31
  const arg = args[i]!;
32
32
  if (arg === "--force") force = true;
33
33
  else if (arg === "--keep") keep = true;
34
34
  else if (arg === "--plan") plan = args[++i] ?? "";
35
+ else if (arg === "--repo") repo = args[++i] ?? "";
35
36
  else rest.push(arg);
36
37
  }
37
38
  if (plan === "") { console.error("pages publish: --plan needs the plan file"); return 2; }
39
+ if (repo === "") { console.error("pages publish: --repo needs the repo name"); return 2; }
38
40
  // file first, then the optional name; flags may sit anywhere (2026-10-27: `--force <file>` used
39
- // to be read as file "--force" because only args.slice(2) was scanned)
41
+ // to be read as file "--force" because only args.slice(2) was scanned for flags)
40
42
  const file = rest[0];
41
43
  const name = rest[1];
42
44
  if (!file || rest.length > 2) return 2;
43
45
  const now = clock();
44
46
  sweepPages(cfg.pages.dir, cfg.pages.keep_days, now);
45
- const n = publishPage(file, name, force, cfg.pages.dir, { keep, keepDays: cfg.pages.keep_days, now, notes: pageNotesGate(cfg), plan });
47
+ const n = publishPage(file, name, force, cfg.pages.dir, { keep, keepDays: cfg.pages.keep_days, now, notes: pageNotesGate(cfg), plan, repo: repoForPublish(file, repo) });
46
48
  const host = (deps.tailscale ?? realTailscale).dnsName() ?? "tailnet";
47
49
  console.log(`http://${host}:${cfg.pages.port}/${encodeURIComponent(n)}`);
48
50
  const expires = readExpiry(cfg.pages.dir)[n]?.expires;
@@ -54,11 +56,13 @@ export async function runPages(args: string[] = [], deps: PagesDeps = {}): Promi
54
56
  const map = readExpiry(cfg.pages.dir);
55
57
  for (const f of readdirSync(cfg.pages.dir, { withFileTypes: true }).filter(e => e.isFile() && !e.name.startsWith("."))) {
56
58
  const expires = map[f.name]?.expires;
57
- console.log(`${f.name} ${expires ? `expires ${expires.slice(0, 10)}` : "kept"}`);
59
+ // A page published before the repo tag (plan 20261029_1436 P1) has no repo in its meta: "-"
60
+ // marks that, so the columns stay countable.
61
+ console.log(`${f.name} ${map[f.name]?.repo ?? "-"} ${expires ? `expires ${expires.slice(0, 10)}` : "kept"}`);
58
62
  }
59
63
  return 0;
60
64
  }
61
65
  } catch (e) { console.error(e instanceof Error ? e.message : String(e)); return 1; }
62
- console.error("usage: neurastream pages on [--port N] [--dir D] | off | serve | publish <file> [<name>] [--force] [--keep] | list");
66
+ console.error("usage: neurastream pages on [--port N] [--dir D] | off | serve | publish <file> [<name>] [--force] [--keep] [--repo <name>] | list");
63
67
  return 2;
64
68
  }
@@ -1,7 +1,7 @@
1
1
  import { existsSync, readFileSync, statSync } from "node:fs";
2
2
  import { basename, dirname } from "node:path";
3
3
  import type { Config } from "./config.ts";
4
- import { briefBudget, briefNamesPending } from "./guards.ts";
4
+ import { briefBudget, briefNamesPending, MAIN_PLAN_FILE } from "./guards.ts";
5
5
  import { exitText, helpDoc, printText } from "./help.ts";
6
6
  import { readIndex, sections } from "./queue/lib.ts";
7
7
 
@@ -112,7 +112,7 @@ function lint(path: string, cfg: Config): { errs: string[]; warns: string[] } {
112
112
  if (/\bplans?\b/i.test(text)) {
113
113
  const indexed = readIndex(cfg.paths.queue_index);
114
114
  const noPlanLine = "no line names the plan's absolute path in its main checkout (paths.queue_index)";
115
- const planPaths = [...paths].map(clean).filter(p => /\/docs\/plans\/[\w.-]+\.md$/.test(p));
115
+ const planPaths = [...paths].map(clean).filter(p => MAIN_PLAN_FILE.test(p));
116
116
  const named = planPaths.filter(p => indexed.includes(p));
117
117
  if (indexed.length && !named.length) {
118
118
  const copy = planPaths[0];
@@ -164,12 +164,10 @@ export interface Config {
164
164
  go_phrase: string;
165
165
  };
166
166
  /** The owner's phone page (`neurastream ui`): binds the tailnet address only. */
167
- ui: { enabled: boolean; port: number; owner_login: string };
167
+ ui: { enabled: boolean; port: number; owner_login: string; allow_this_machine: boolean };
168
168
  /** Plan review gate (plan 20261028_1600): reuse lines and, from P2 on, the reviewer PASS lock. */
169
169
  review: {
170
- /** Plans stamped before this ISO date are exempt from the reuse-line and reviewer-PASS gates; "" = off. */
171
- since: string;
172
- /** Agents a review spawn may run under: the PASS exemption needs one of these plus the brief's `Plan review: <plan>` line. */
170
+ /** Agents a review spawn may run under: the PASS exemption needs one of these plus the brief's `Plan review: <plan>` line. An empty list turns both review gates off (P5c). */
173
171
  agents: string[];
174
172
  /** Minutes the spawn gate caches a repo's open-MR list in <queue_state>/mr-cache.json; 0 = no cache. */
175
173
  mr_cache_minutes: number;
@@ -503,6 +501,8 @@ function check(cfg: Config): void {
503
501
  throw new ConfigError(`${at}.argv must be a non-empty list of strings containing "{file}"`);
504
502
  if (typeof l.pattern !== "string" || !l.pattern.includes("(?<rule>"))
505
503
  throw new ConfigError(`${at}.pattern must be a regex with a named group rule`);
504
+ if (l.only_with_config !== undefined && (!Array.isArray(l.only_with_config) || l.only_with_config.some((n) => typeof n !== "string" || n === "")))
505
+ throw new ConfigError(`${at}.only_with_config must be a list of file names`);
506
506
  regexes.push([`${at}.pattern`, l.pattern]);
507
507
  }
508
508
  for (const [key, src] of regexes) {
@@ -519,7 +519,6 @@ function check(cfg: Config): void {
519
519
  throw new ConfigError(`guards.plan_offer: not a valid regex: ${cfg.guards.plan_offer}`);
520
520
  }
521
521
  if (!(cfg.rollover.max_session_mb > 0)) throw new ConfigError("rollover.max_session_mb must be > 0");
522
- if (typeof cfg.review.since !== "string") throw new ConfigError("review.since must be an ISO date string (\"\" = off)");
523
522
  if (!Array.isArray(cfg.review.agents) || cfg.review.agents.some(a => typeof a !== "string" || !a.trim()))
524
523
  throw new ConfigError('review.agents must be a list of agent names allowed to run review spawns (default ["reviewer"])');
525
524
  if (!Number.isInteger(cfg.review.mr_cache_minutes) || cfg.review.mr_cache_minutes < 0)
@@ -191,14 +191,14 @@ export type Spawner = "main" | "sub";
191
191
  * P2 (plan 20261028_1600): a spawn on a plan needs a recorded reviewer PASS whose hash still
192
192
  * matches the plan text — progress-only edits keep a PASS valid, any other change expires it,
193
193
  * a FAIL is denied with its first finding. A review spawn itself — an agent from review.agents
194
- * whose brief has the `Plan review: <plan>` line — is exempt when Main launches it, and so is any plan stamped
195
- * before `review.since` (P4c: same cutover as the reuse-line gate).
194
+ * whose brief has the `Plan review: <plan>` line — is exempt when Main launches it. P5 removed
195
+ * the cutover: every named plan is gated.
196
196
  */
197
197
  export function reviewPassProblem(named: string[], brief: string, agent: string, cfg: Config, spawner: Spawner): string | null {
198
+ if (!cfg.review.agents.length) return null; // P5c: an empty review.agents list turns both review gates off
198
199
  const reviews = readPlanReviews();
199
200
  for (const file of named) {
200
201
  if (isReviewSpawn(file, brief, agent, cfg, spawner)) continue;
201
- if (!q.reviewApplies(file, cfg.review.since)) continue;
202
202
  const rec = reviews[file];
203
203
  if (!rec) return `plan ${file} has no current reviewer PASS. Spawn a reviewer with templates/plan-review-brief.md.`;
204
204
  if (rec.verdict === "FAIL")
@@ -562,7 +562,7 @@ function unticked(p: Plan): string[] {
562
562
 
563
563
  // Plans an implementer brief may run on; returns [reason, null] or [null, plan files].
564
564
  export function planGate(text: string, label: string, cfg?: Config): [string | null, string[]] {
565
- const plans = q.activePlans(undefined, undefined, cfg?.review.since ?? "");
565
+ const plans = q.activePlans(undefined, undefined, cfg?.review.agents ?? []);
566
566
  const unclosed = plans.filter(p => (p.status === "complete" || p.status === "cancelled") && !q.awaitingMerge(p));
567
567
  if (unclosed.length)
568
568
  return [
@@ -638,9 +638,12 @@ function priorityIdle(p: Plan, plans: Plan[]): boolean {
638
638
  * Proof is either the higher plan's own `Waits on: <plan>` line for a plan still open in the index
639
639
  * (then it is not idle at all) or a `Priority skip: <path> — owner: "<words>"` line whose quoted
640
640
  * words (≥ 4, normalised) appear in one of `messages` (the owner's recorded words of the last
641
- * 24 h; `now` is the current unix seconds). In tier full (`cfg`) a `Priority skip: <path> —
642
- * Main: "<reason>"` line with ≥ 4 words is proof too; without `cfg` the refusal behaviour is the
643
- * pre-tier one. Any other skip line is refused.
641
+ * 24 h; `now` is the current unix seconds). A higher plan whose branch carries an open MR in the
642
+ * cached forge list (fresh within `review.mr_cache_minutes`; the one list the main-start sweep
643
+ * and pendingWorkProblem maintain — never queried here) is landing, not idle: no proof needed.
644
+ * A stale cache proves nothing, so the refusal stands (I-20261029-435). In tier full (`cfg`) a
645
+ * `Priority skip: <path> — Main: "<reason>"` line with ≥ 4 words is proof too; without `cfg` the
646
+ * refusal behaviour is the pre-tier one. Any other skip line is refused.
644
647
  * `staffed === undefined` means the caller had no running-job info (CLI spawn without it): never
645
648
  * refuse. Plans already named by this call never block it.
646
649
  */
@@ -657,9 +660,12 @@ export function priorityProblem(plans: Plan[], named: string[], staffed: string[
657
660
  if (plan && why) skipLines[plan] = why;
658
661
  }
659
662
  const skips: PrioritySkip[] = [];
663
+ const cache = readMrCache();
664
+ const fresh = cfg ? now - cache.at < cfg.review.mr_cache_minutes * 60 : false;
660
665
  for (let i = 0; i < higher.length; i++) {
661
666
  const p = higher[i]!;
662
667
  if (!priorityIdle(p, plans) || staffed.includes(p.file)) continue;
668
+ if (fresh && p.branch && (cache.repos[p.repo] ?? []).some(mr => mr.branch === p.branch)) continue;
663
669
  const why = skipLines[p.file];
664
670
  // Tier full (20261025_1940 P2): Main's own >= 4-word reason is proof enough; every other
665
671
  // tier refuses it exactly as before — only the owner's recorded words let a skip through.
@@ -1214,8 +1220,8 @@ export function resetMainCalls(): void {
1214
1220
  writeWindow(w);
1215
1221
  }
1216
1222
 
1217
- /** A live plan file (archived plans excluded); Main's plan-text checks run on these. */
1218
- export const MAIN_PLAN_FILE = /\/docs\/plans\/(?!archive\/)[^/]+\.md$/;
1223
+ /** A live plan file (archived plans excluded); Main's plan-text checks run on these. Subfolders like docs/plans/immediate/ hold live plans too. */
1224
+ export const MAIN_PLAN_FILE = /\/docs\/plans\/(?!archive\/)(?:[^/]+\/)*[^/]+\.md$/;
1219
1225
 
1220
1226
  /**
1221
1227
  * pre-tool: plan-guard checkCall for subs (protected files, budget, plan-edit rules, blockers)
@@ -1497,7 +1503,7 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
1497
1503
  recordOwnerMessage(e.inject, cfg);
1498
1504
  let summary: string;
1499
1505
  try {
1500
- summary = q.queueSummary(undefined, cfg.review.since);
1506
+ summary = q.queueSummary(undefined, cfg.review.agents);
1501
1507
  } catch (err) {
1502
1508
  summary = `Queue unreadable (${q.INDEX}): ${err}`;
1503
1509
  }
@@ -1708,10 +1714,11 @@ function planFile(p: string, planPath: string, text: string): string {
1708
1714
  return path.join(root, home);
1709
1715
  }
1710
1716
 
1711
- /** The roots a plan-relative path resolves against: the plan's Worktree (when set), then its repo (dirname³ of the plan file). */
1717
+ /** The roots a plan-relative path resolves against: the plan's Worktree (when set), then its repo (the text before /docs/plans/, so a docs/plans/<subdir>/ plan still resolves repo-relative paths against <repo>). */
1712
1718
  function planRoots(planPath: string, text: string): string[] {
1713
1719
  const wt = /^Worktree:\s*(\S+)/m.exec(text)?.[1];
1714
- const repo = path.dirname(path.dirname(path.dirname(planPath)));
1720
+ const cut = planPath.indexOf("/docs/plans/");
1721
+ const repo = cut >= 0 ? planPath.slice(0, cut) : path.dirname(path.dirname(path.dirname(planPath)));
1715
1722
  return wt && wt !== "-" ? [wt, repo] : [repo];
1716
1723
  }
1717
1724
 
@@ -1803,12 +1810,12 @@ function readMainReads(): Record<string, string> {
1803
1810
  }
1804
1811
 
1805
1812
  // Plans still responsible for: open plans (parked "WAITING on owner" excluded) plus queue problems.
1806
- export function openQueue(reviewSince = ""): string[] {
1813
+ export function openQueue(reviewAgents: string[] = []): string[] {
1807
1814
  const open = q
1808
1815
  .activePlans()
1809
1816
  .filter(p => !p.waiting && !q.awaitingMerge(p))
1810
1817
  .map(p => p.file);
1811
- for (const prob of q.queueProblems(undefined, undefined, reviewSince)) open.push(`${prob.where}: ${prob.problem}`);
1818
+ for (const prob of q.queueProblems(undefined, undefined, reviewAgents)) open.push(`${prob.where}: ${prob.problem}`);
1812
1819
  const unique: string[] = [];
1813
1820
  for (const item of open) if (!unique.includes(item)) unique.push(item);
1814
1821
  return unique;
@@ -1826,6 +1833,8 @@ export function liveSubagents(ledgerOut: string): string[] {
1826
1833
  .map(l => l.split(/\s+/)[0] ?? "");
1827
1834
  }
1828
1835
 
1836
+ export const STOP_PLAN_OFFER_REFUSAL = "main-guard: don't promise it — do it now, or write the plan and index it";
1837
+
1829
1838
  /**
1830
1839
  * stop: Main may not stop while an open plan is not parked "WAITING on owner" (or the queue has a
1831
1840
  * problem) and no subagent is alive to wake it; an open incident (no plan, no dismissal) blocks
@@ -1838,12 +1847,12 @@ export function checkStop(e: StopEvent, cfg: Config): Decision {
1838
1847
  // 20261028_0900 P2: a reply that offers to plan instead of planning is refused for the offer
1839
1848
  // itself; the two-empty-stops valves below never release this block.
1840
1849
  if (e.reply && new RegExp(cfg.guards.plan_offer, "i").test(e.reply)) {
1841
- log(cfg.paths.guard_log, "BLOCK stop: reply offers to plan instead of planning it");
1842
- return { allow: false, reason: "main-guard: don't offer it — write the plan and index it", state };
1850
+ log(cfg.paths.guard_log, "BLOCK stop: reply offers or promises instead of doing it");
1851
+ return { allow: false, reason: STOP_PLAN_OFFER_REFUSAL, state };
1843
1852
  }
1844
1853
  let open: string[];
1845
1854
  try {
1846
- open = openQueue(cfg.review.since);
1855
+ open = openQueue(cfg.review.agents);
1847
1856
  } catch (err) {
1848
1857
  log(cfg.paths.guard_log, `BLOCK stop: cannot read queue: ${err}`);
1849
1858
  open = [`queue unreadable (${q.INDEX}): ${err}`];
@@ -49,7 +49,9 @@ export function urlField(s: string): string {
49
49
  return new TextDecoder().decode(new Uint8Array(bytes));
50
50
  }
51
51
 
52
- function repoKey(repoPath: string): string {
52
+ /** The one repo-name rule (Base tab and pages alike): the origin remote's basename without
53
+ * ".git", else the directory's basename. */
54
+ export function repoKey(repoPath: string): string {
53
55
  const remote = gitRaw(repoPath, ["remote", "get-url", "origin"]).stdout.trim();
54
56
  if (remote) {
55
57
  const base = basename(remote.replace(/\/$/, ""));
@@ -65,7 +67,7 @@ function parseTitle(html: string, fallback: string): string {
65
67
  return t || fallback;
66
68
  }
67
69
 
68
- function topicUpdated(repoPath: string, rel: string, abs: string, now: number): string {
70
+ function topicUpdated(repoPath: string, rel: string, abs: string, _now: number): string {
69
71
  const log = gitRaw(repoPath, ["log", "-1", "--format=%cI", "--", rel]).stdout.trim();
70
72
  if (log) return log;
71
73
  const mtime = statSync(abs).mtimeMs;
@@ -19,6 +19,7 @@ import { cpuCount } from "./host.ts";
19
19
  import { dismissIncident, isFindingKind, openIncidents } from "./incidents.ts";
20
20
  import { byText, knowledgeManifest, readKnowledgeTopicFile, urlField, urlValue, type KnowledgeEntry } from "./knowledge.ts";
21
21
  import { log } from "./guards.ts";
22
+ import { publishedPages } from "./pages-expiry.ts";
22
23
  import { readMetricEvents } from "./metrics.ts";
23
24
  import { activePlans, chatUnlock, dependencyOrderProblems, expandHome, gitTop, stateDirPath, unlockPath, type Plan } from "./queue/lib.ts";
24
25
  import { featuresReport, gatherTags, loadPlans, releasesReport, type FeaturesReport, type ReleaseRow, type ReleaseSideStats, type ReleasesReport } from "./results.ts";
@@ -79,9 +80,10 @@ export function isTailnet(peer: string): boolean {
79
80
  return TAILNET6.test(peer);
80
81
  }
81
82
 
82
- /** Serve only the owner's phone: a tailnet peer that is not this machine and not loopback, whose tailscale whois login equals ui.owner_login. Everything else is a 403. */
83
+ /** Serve only the owner's phone: a tailnet peer that is not this machine and not loopback, whose tailscale whois login equals ui.owner_login. Everything else is a 403. With `ui.allow_this_machine`, this machine itself (loopback and its own tailnet IP) is served as the owner too — any local process can then press the buttons. */
83
84
  export function authenticate(cfg: Config, tailscale: Tailscale, peer: string): Auth {
84
85
  if (!cfg.ui.owner_login) return { ok: false, why: "ui.owner_login is empty" };
86
+ if (cfg.ui.allow_this_machine && (isLoopback(peer) || peer === tailscale.ip4())) return { ok: true, login: cfg.ui.owner_login };
85
87
  if (isLoopback(peer)) return { ok: false, why: "loopback peer" };
86
88
  if (!isTailnet(peer)) return { ok: false, why: "peer is not a tailnet address" };
87
89
  if (peer === tailscale.ip4()) return { ok: false, why: "this machine's own tailnet address" };
@@ -738,6 +740,9 @@ function jsonFail(error: string, status: number): Response {
738
740
 
739
741
  // ---- page assembly: one unreadable source never takes the page down ----
740
742
 
743
+ /** One published page row for the Base tab: the pages-server link is built once, at data build. */
744
+ export interface PublishedPageRow { name: string; repo: string; published: string; url: string }
745
+
741
746
  export interface PageData {
742
747
  questions: QuestionRow[] | null;
743
748
  agents: AgentRow[] | null;
@@ -748,6 +753,8 @@ export interface PageData {
748
753
  machine: MachineRow | null;
749
754
  /** Repo-local HTML explainers from the knowledge manifest; null when unreadable. */
750
755
  knowledge: KnowledgeEntry[] | null;
756
+ /** Published pages (plan 20261029_1436 P2), newest first, with their pages-server URL; null when unreadable. */
757
+ pages: PublishedPageRow[] | null;
751
758
  /** The 24 h tile numbers; null when the run source is unreadable. */
752
759
  stats: NowStats | null;
753
760
  /** The Results tab's saved numbers and build state; absent on every other tab. The numbers come from a background process (computeResults), never from the request. */
@@ -767,6 +774,10 @@ function safe<T>(build: () => T): T | null {
767
774
  }
768
775
  }
769
776
 
777
+ function publishedRows(cfg: Config, host: string): PublishedPageRow[] {
778
+ return publishedPages(cfg.pages.dir, new Date()).map(p => ({ ...p, url: `http://${host}:${cfg.pages.port}/${urlValue(p.name)}` }));
779
+ }
780
+
770
781
  function lockMinutesLeft(cfg: Config): number | null {
771
782
  try {
772
783
  const end = statSync(unlockPath()).mtimeMs + cfg.guards.unlock_minutes * 60_000;
@@ -777,7 +788,7 @@ function lockMinutesLeft(cfg: Config): number | null {
777
788
  }
778
789
  }
779
790
 
780
- export function buildPageData(cfg: Config, source: RunSource, tab: string, build: ResultsBuild = spawnResultsBuild): PageData {
791
+ export function buildPageData(cfg: Config, source: RunSource, tab: string, build: ResultsBuild = spawnResultsBuild, pagesHost = "tailnet"): PageData {
781
792
  return {
782
793
  questions: safe(() => questionRows(cfg)),
783
794
  agents: safe(() => agentRows(cfg, source)),
@@ -787,6 +798,7 @@ export function buildPageData(cfg: Config, source: RunSource, tab: string, build
787
798
  scores: safe(() => scoresData(cfg)),
788
799
  machine: safe(() => machineRow(cfg)),
789
800
  knowledge: safe(() => knowledgeManifest(cfg)),
801
+ pages: safe(() => publishedRows(cfg, pagesHost)),
790
802
  stats: safe(() => nowStats(cfg, source, nowSec())),
791
803
  results: tab === "results" ? safe(() => resultsView(nowSec(), build)) : undefined,
792
804
  messages: safe(() => recentOwnerMessages(nowSec())),
@@ -918,34 +930,46 @@ bindPage();
918
930
  * read-only files at docs/knowledge/<topic>.html in a repo under the configured roots; the page
919
931
  * bytes come from /knowledge/<repo>/<topic> and there is no route that writes one.
920
932
  */
921
- function knowledgeHtml(entries: KnowledgeEntry[], repo: string, topic: string): string {
933
+ function knowledgeHtml(entries: KnowledgeEntry[], repo: string, topic: string, pages: PublishedPageRow[]): string {
922
934
  const repoHref = `/?tab=knowledge&repo=${urlValue(repo)}`;
923
935
  const crumb =
924
936
  repo === ""
925
937
  ? ""
926
938
  : `<p class="sub"><a href="/?tab=knowledge">knowledge-base</a> / ${topic === "" ? esc(repo) : `<a href="${repoHref}">${esc(repo)}</a>`}${topic === "" ? "" : ` / ${esc(topic)}`}</p>`;
927
- if (entries.length === 0) {
928
- return `<h1>Base</h1><div class="card"><p class="empty">No topics yet. Any repo under the configured roots counts: put a page in <span class="mono">docs/knowledge/</span> and it shows up here on the next reload.</p></div>`;
939
+ if (entries.length === 0 && pages.length === 0) {
940
+ return `<h1>Base</h1><div class="card"><p class="empty">Nothing here yet. Any repo under the configured roots counts: put a page in <span class="mono">docs/knowledge/</span> or publish one with <span class="mono">pages publish</span>, and it shows up here on the next reload.</p></div>`;
929
941
  }
930
942
  if (repo === "") {
931
- const repos = new Map<string, KnowledgeEntry[]>();
932
- for (const e of entries) repos.set(e.repo, [...(repos.get(e.repo) ?? []), e]);
943
+ // One card per repo NAME (plan 20261029_1436 P2): a repo's knowledge topics and its published
944
+ // pages share the card; a worktree's page was already tagged with the main checkout's name.
945
+ const repos = new Map<string, { topics: KnowledgeEntry[]; pages: PublishedPageRow[] }>();
946
+ const slot = (name: string) => {
947
+ const r = repos.get(name) ?? { topics: [], pages: [] };
948
+ repos.set(name, r);
949
+ return r;
950
+ };
951
+ for (const e of entries) slot(e.repo).topics.push(e);
952
+ for (const p of pages) slot(p.repo).pages.push(p);
933
953
  const rows = [...repos.entries()]
934
954
  .sort((a, b) => byText(a[0], b[0]))
935
- .map(([name, list]) => {
936
- const newest = list.map(e => e.updated).sort().at(-1)!.slice(0, 10);
937
- return `<div class="mrow"><a href="/?tab=knowledge&repo=${urlValue(name)}">${esc(name)}</a><span class="mono">${list.length} topic${list.length === 1 ? "" : "s"} · ${newest}</span></div>`;
955
+ .map(([name, r]) => {
956
+ const n = r.topics.length + r.pages.length;
957
+ const newest = [...r.topics.map(e => e.updated), ...r.pages.map(p => p.published)].sort().at(-1)!.slice(0, 10);
958
+ return `<div class="mrow"><a href="/?tab=knowledge&repo=${urlValue(name)}">${esc(name)}</a><span class="mono">${n} page${n === 1 ? "" : "s"} · ${newest}</span></div>`;
938
959
  })
939
960
  .join("");
940
- return `<h1>Base</h1><p class="sub">One card per repo with pages in <span class="mono">docs/knowledge/</span> — tap a repo for its topics.</p><div class="card">${rows}</div>`;
961
+ return `<h1>Base</h1><p class="sub">One card per repo: its <span class="mono">docs/knowledge/</span> pages and the pages Main published from it — tap a repo to open its list.</p><div class="card">${rows}</div>`;
941
962
  }
942
963
  const topics = entries.filter(e => e.repo === repo);
943
- if (topics.length === 0) return `${crumb}<div class="card"><p class="empty">No repo named "${esc(repo)}" has a page under the configured roots.</p></div>`;
964
+ const repoPages = pages.filter(p => p.repo === repo);
965
+ if (topics.length === 0 && repoPages.length === 0) return `${crumb}<div class="card"><p class="empty">No repo named "${esc(repo)}" has a page under the configured roots.</p></div>`;
944
966
  if (topic === "") {
945
- const rows = topics
967
+ const topicRows = topics
946
968
  .map(e => `<div class="mrow"><a href="${repoHref}&topic=${urlValue(e.topic)}">${esc(e.title)}</a><span class="mono">${e.updated.slice(0, 10)}</span></div>`)
947
969
  .join("");
948
- return `${crumb}<div class="card">${rows}</div>`;
970
+ // Published pages after the topics, newest first (publishedPages sorts them that way).
971
+ const pageRows = repoPages.map(p => `<div class="mrow"><a href="${p.url}">${esc(p.name)}</a><span class="mono">${p.published.slice(0, 10)}</span></div>`).join("");
972
+ return `${crumb}<div class="card">${topicRows}${pageRows}</div>`;
949
973
  }
950
974
  const hit = topics.find(e => e.topic === topic);
951
975
  if (hit === undefined) return `${crumb}<div class="card"><p class="empty">No topic "${esc(topic)}" in ${esc(repo)}.</p></div>`;
@@ -1268,9 +1292,9 @@ ${merges}
1268
1292
  ${machine}
1269
1293
  </div>`
1270
1294
  : tab === "knowledge"
1271
- ? `${data.knowledge === null ? na("Base") : knowledgeHtml(data.knowledge, params.get("repo") ?? "", params.get("topic") ?? "")}`
1295
+ ? `${data.knowledge === null ? na("Base") : knowledgeHtml(data.knowledge, params.get("repo") ?? "", params.get("topic") ?? "", data.pages ?? [])}`
1272
1296
  : tab === "spend"
1273
- ? `<h1>Spend</h1>
1297
+ ? `<h1>Spend</h1
1274
1298
  <p class="sub">List price over the last 24 hours.</p>
1275
1299
  <div class="card">
1276
1300
  ${spendTileHtml(data)}
@@ -1434,9 +1458,9 @@ function sentTo(tab: string, sent: string): string {
1434
1458
  }
1435
1459
 
1436
1460
  /** The normal page (the GET layout) as a POST reply; the stale-answer reply is this with sent=stale. */
1437
- function pageRes(cfg: Config, source: RunSource, params: URLSearchParams, build: ResultsBuild = spawnResultsBuild): Response {
1461
+ function pageRes(cfg: Config, source: RunSource, params: URLSearchParams, build: ResultsBuild = spawnResultsBuild, pagesHost = "tailnet"): Response {
1438
1462
  const nonce = randomUUID().replaceAll("-", "");
1439
- return new Response(renderPage(cfg, buildPageData(cfg, source, params.get("tab") ?? "", build), params, nonce), {
1463
+ return new Response(renderPage(cfg, buildPageData(cfg, source, params.get("tab") ?? "", build, pagesHost), params, nonce), {
1440
1464
  status: 200,
1441
1465
  headers: {
1442
1466
  "content-type": "text/html; charset=utf-8",
@@ -1459,7 +1483,7 @@ function appendAnswer(plan: string, question: string, answer: string, login: str
1459
1483
  lastAnswerByPlan.set(plan, { answer, ts: now });
1460
1484
  }
1461
1485
 
1462
- function handleAnswer(cfg: Config, source: RunSource, fields: Record<string, string>, login: string, wantsJson: boolean): Response {
1486
+ function handleAnswer(cfg: Config, source: RunSource, fields: Record<string, string>, login: string, wantsJson: boolean, pagesHost: string): Response {
1463
1487
  const planFile = (fields.plan ?? "").trim();
1464
1488
  const answer = (fields.answer_text ?? "").trim() || (fields.answer ?? "").trim();
1465
1489
  if (!planFile || !answer) return wantsJson ? jsonFail("plan and answer are required", 400) : textRes("plan and answer are required", 400);
@@ -1470,7 +1494,7 @@ function handleAnswer(cfg: Config, source: RunSource, fields: Record<string, str
1470
1494
  // Stale answer (P8b): Main cleared the question before the answer arrived; pass it on anyway.
1471
1495
  appendAnswer(planFile, "(already cleared)", answer, login);
1472
1496
  if (wantsJson) return jsonSent("stale", receiptText("stale", new URLSearchParams()));
1473
- return pageRes(cfg, source, new URLSearchParams({ sent: "stale" }));
1497
+ return pageRes(cfg, source, new URLSearchParams({ sent: "stale" }), undefined, pagesHost);
1474
1498
  }
1475
1499
  appendAnswer(planFile, plan.waitingLine, answer, login);
1476
1500
  if (wantsJson) return jsonSent("answer", receiptText("answer", new URLSearchParams()));
@@ -1722,6 +1746,8 @@ function handleReorder(cfg: Config, fields: Record<string, string>, login: strin
1722
1746
  export function startOwnerUi(opts: OwnerUiOptions): OwnerUiServer {
1723
1747
  const { cfg, tailscale, source } = opts;
1724
1748
  const resultsBuild = opts.resultsBuild ?? spawnResultsBuild;
1749
+ // The Base tab links to the pages server by its MagicDNS name, the same URL `pages publish` prints.
1750
+ const pagesHost = tailscale.dnsName() ?? "tailnet";
1725
1751
  // The double-press guard (P8c) is per-server memory: a fresh server starts empty, which also
1726
1752
  // keeps the tests (one server per test) hermetic.
1727
1753
  lastAnswerByPlan.clear();
@@ -1770,7 +1796,7 @@ export function startOwnerUi(opts: OwnerUiOptions): OwnerUiServer {
1770
1796
  code = 403;
1771
1797
  } else if (req.method === "GET" && url.pathname === "/") {
1772
1798
  sweepOwnerMessages(nowSec());
1773
- res = pageRes(cfg, source, url.searchParams, resultsBuild);
1799
+ res = pageRes(cfg, source, url.searchParams, resultsBuild, pagesHost);
1774
1800
  code = 200;
1775
1801
  } else if (req.method === "GET" && url.pathname.startsWith("/knowledge/")) {
1776
1802
  // The Knowledge tab's frame: the topic's own file bytes, GET only, no write path.
@@ -1795,7 +1821,7 @@ export function startOwnerUi(opts: OwnerUiOptions): OwnerUiServer {
1795
1821
  res = handleIncident(cfg, await fieldsOf(req), login, wantsJson);
1796
1822
  code = res.status;
1797
1823
  } else if (url.pathname === "/answer") {
1798
- res = handleAnswer(cfg, source, await fieldsOf(req), login, wantsJson);
1824
+ res = handleAnswer(cfg, source, await fieldsOf(req), login, wantsJson, pagesHost);
1799
1825
  code = res.status;
1800
1826
  } else if (url.pathname === "/unlock") {
1801
1827
  res = handleUnlock(cfg, await fieldsOf(req), login, wantsJson);
@@ -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){
@@ -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
 
@@ -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";
@@ -4,13 +4,16 @@
4
4
 
5
5
  import { spawnSync } from "node:child_process";
6
6
  import { randomBytes } from "node:crypto";
7
- import { rmSync, writeFileSync } from "node:fs";
8
- import { basename, dirname, extname, join } from "node:path";
7
+ import { existsSync, rmSync, writeFileSync } from "node:fs";
8
+ import { basename, dirname, extname, join, resolve } from "node:path";
9
+
10
+ import { gitTop } from "./queue/lib.ts";
9
11
 
10
12
  export interface WriteCheckLinter {
11
13
  ext: string[];
12
14
  argv: string[];
13
15
  pattern: string;
16
+ only_with_config?: string[];
14
17
  }
15
18
 
16
19
  export interface WriteCheckConfig {
@@ -50,10 +53,22 @@ function add(f: Findings, k: string, rule: string, sample: string): void {
50
53
  if (!f.rules.has(k)) f.rules.set(k, rule);
51
54
  }
52
55
 
56
+ // Walks up from dirname(file) to the git top (inclusive: a repo-root config counts), looking for one
57
+ // of `names`; never above it. Outside a git repo only the file's own directory is checked.
58
+ function hasConfig(file: string, names: string[]): boolean {
59
+ const start = resolve(dirname(file));
60
+ const top = gitTop(start)?.top;
61
+ for (let dir = start; ; dir = dirname(dir)) {
62
+ if (names.some((name) => existsSync(join(dir, name)))) return true;
63
+ if (top === undefined || dir === top || dir === dirname(dir)) return false;
64
+ }
65
+ }
66
+
53
67
  // Runs each linter on `path` and counts its findings. Throws when a linter did not finish
54
68
  // (missing binary, timeout, signal); the caller turns that into an allowed edit with a note.
55
69
  function lint(path: string, linters: WriteCheckLinter[], wc: WriteCheckConfig, f: Findings): void {
56
70
  for (const l of linters) {
71
+ if (l.only_with_config && !hasConfig(path, l.only_with_config)) continue;
57
72
  const argv = l.argv.map((a) => (a === "{file}" ? path : a));
58
73
  const [cmd = "", ...args] = argv;
59
74
  const r = spawnSync(cmd, args, {
@@ -100,6 +115,9 @@ function refusal(file: string, now: Findings, old: Findings, newKeys: string[]):
100
115
 
101
116
  export function checkWrite(file: string, before: string | null, after: string | null, wc: WriteCheckConfig): WriteCheckResult {
102
117
  if (after === null || before === after) return { allow: true };
118
+ if (typeof before === "string" && /^(<<<<<<<|>>>>>>>)/m.test(before)) {
119
+ return { allow: true, note: `write-check: ${file} had conflict markers in the before text; the edit was allowed` };
120
+ }
103
121
  const linters = wc.linters.filter((l) => l.ext.includes(extname(file)));
104
122
  if (linters.length === 0) return { allow: true };
105
123
  const old: Findings = { counts: new Map(), samples: new Map(), rules: new Map() };
@@ -125,7 +125,7 @@ guards:
125
125
  chat_unlock: false # the owner's whole chat message "unlock"/"unlock N"/"lock" moves the guard unlock file
126
126
  plan_read_max_hours: 24
127
127
  idle_stops: 3
128
- plan_offer: 'want me to (write|make) a plan|should i plan|shall i plan|if you want, i(''ll)? plan|plan it or' # a Main stop reply matching this (case-insensitive) is refused: don't offer it — write the plan and index it
128
+ plan_offer: 'want me to (write|make) a plan|should i plan|shall i plan|if you want, i(''ll)? plan|plan it or|\bi will\b|\bi(''|’)ll\b' # refused: don't promise or offer it — do it now, or write the plan and index it
129
129
  rate_limit:
130
130
  patterns: ["429", "rate_limit", "rate limit", "overloaded", "529"] # error-text substrings (case-insensitive) that mark a provider rate limit
131
131
  default_wait_s: 300 # wait when the error text names no retry-after
@@ -149,14 +149,14 @@ autonomy:
149
149
  go_phrase: "go push" # the whole chat message that approves one push/merge in tier strict (I-20261025-201); a bare `go` is an ordinary message
150
150
 
151
151
  review: # plan review gate (plan 20261028_1600): reuse lines now, reviewer PASS from P2 (docs/config.md)
152
- since: "2026-10-28" # plans stamped before this ISO date are exempt from the reuse-line and reviewer-PASS gates; "" = off
153
- agents: ["reviewer"] # agents allowed to run a review spawn: one must be in "## Allowed" of notes/subagents.md (doctor and queue-check fail otherwise, e.g. ["glm"]); the PASS exemption needs one plus the brief's `Plan review:` line
152
+ agents: ["reviewer"] # agents allowed to run a review spawn: one must be in "## Allowed" of notes/subagents.md (doctor and queue-check fail otherwise, e.g. ["glm"]); the PASS exemption needs one plus the brief's `Plan review:` line; an empty list turns both review gates off
154
153
  mr_cache_minutes: 10 # minutes the spawn gate caches a repo's open-MR list in <queue_state>/mr-cache.json; 0 = no cache
155
154
 
156
155
  ui:
157
156
  enabled: false # the owner's phone page (neurastream ui); binds the tailnet address only
158
157
  port: 7787
159
158
  owner_login: "" # the tailscale login that may open the page; empty = the page refuses to start
159
+ allow_this_machine: false # admit this machine (loopback and its own tailnet IP) as the owner; any local process can then press the buttons
160
160
 
161
161
 
162
162
  pages:
@@ -230,11 +230,13 @@ write_check: # write-time lint checks (src/core/write-check.ts):
230
230
  defer_rules: ["no-unused-vars", "F401", "F841"] # a new finding of one of these rules is allowed with a logged note and only reported at turn end if still present (I-20261028-166); [] turns the deferral off
231
231
  linters:
232
232
  - ext: [".py"]
233
- argv: ["ruff", "check", "--no-cache", "--output-format=concise", "--select", "E,F,B,S,C90,PERF,SIM", "--ignore", "E501,S101", "{file}"]
233
+ argv: ["ruff", "check", "--no-cache", "--output-format=concise", "{file}"]
234
234
  pattern: '^.+?:\d+:\d+: (?<rule>\S+) (?<message>.+)$'
235
+ only_with_config: ["pyproject.toml", "ruff.toml", ".ruff.toml"]
235
236
  - ext: [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"]
236
- argv: ["oxlint", "-f", "unix", "-D", "correctness", "-D", "suspicious", "-D", "perf", "{file}"]
237
+ argv: ["oxlint", "-f", "unix", "{file}"]
237
238
  pattern: '^.+?:\d+:\d+: (?<message>.+) \[(?:Error|Warning)/(?<rule>[^\]]+)\]'
239
+ only_with_config: [".oxlintrc.json", ".oxlintrc.jsonc", ".oxlintrc.js", ".oxlintrc.mjs", ".oxlintrc.cjs", "eslint.config.js", "eslint.config.mjs", "eslint.config.cjs", "eslint.config.mts", "eslint.config.cts"]
238
240
 
239
241
  priority:
240
242
  sleep_sec: 120