neurastream 0.2.36 → 0.2.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,6 +12,8 @@ import { runMetrics } from "./metrics.ts";
12
12
  import { runIncident } from "./incident.ts";
13
13
  import { runTraces } from "./traces.ts";
14
14
  import { runUi } from "./ui.ts";
15
+ import { runDiagram } from "./diagram.ts";
16
+ import { runNotes } from "./notes.ts";
15
17
  import { runPages } from "./pages.ts";
16
18
  import { runUninstall } from "../core/uninstall.ts";
17
19
  import { queueMigrate } from "../core/queue-migrate.ts";
@@ -30,6 +32,7 @@ const BINS = [
30
32
  "queue-check",
31
33
  "queue-trim",
32
34
  "queue-close",
35
+ "queue-finished",
33
36
  "queue-cancel",
34
37
  "main-start",
35
38
  "machine-guard",
@@ -86,6 +89,9 @@ export function helpText(): string {
86
89
  " installs and restarts the neurastream-ui user unit, prints the phone",
87
90
  " link; `neurastream ui off` stops and disables it, sets enabled: false",
88
91
  " neurastream pages on|off|serve|publish|list host static files over the tailnet",
92
+ " publish --plan <plan.md> adds the Approve bar that records the plan's approval",
93
+ " neurastream notes check <page> list the notes without an answer, exit 1 while any is open",
94
+ " neurastream diagram check <html> <plan.md> every phase and path of the plan is in a box, 2+ kids per drilldown",
89
95
  " neurastream agents list | allow <slug>... | deny <slug>...",
90
96
  " the subagent allow-list (## Allowed in notes/subagents.md)",
91
97
  "",
@@ -109,6 +115,8 @@ export async function run(cmd: string, args: string[]): Promise<number> {
109
115
  if (cmd === "traces") return runTraces(args);
110
116
  if (cmd === "ui") return runUi(args);
111
117
  if (cmd === "pages") return runPages(args);
118
+ if (cmd === "notes") return runNotes(args);
119
+ if (cmd === "diagram") return runDiagram(args);
112
120
  if (cmd === "adapter") return getAdapter().install(args);
113
121
  if (cmd === "config") {
114
122
  try {
@@ -0,0 +1,36 @@
1
+ // `neurastream notes check <page>` (plan 20261026_0930 P8): every note the owner submitted on a
2
+ // published page must get an answer in Main's answer file. Exit 1 lists the ids still open, and
3
+ // `pages publish` refuses the next version of that page while any id is open.
4
+ import { ConfigError, loadConfig } from "../core/config.ts";
5
+ import { notesAnswersPath, openNoteIds, readAnswers, readNotes } from "../core/page-notes.ts";
6
+
7
+ export interface NotesDeps { home?: string }
8
+
9
+ export function runNotes(args: string[] = [], deps: NotesDeps = {}): number {
10
+ const [sub, page] = args;
11
+ if (sub !== "check" || page === undefined || args.length !== 2) {
12
+ console.error("usage: neurastream notes check <page>");
13
+ return 2;
14
+ }
15
+ let cfg;
16
+ try {
17
+ cfg = loadConfig({ home: deps.home });
18
+ } catch (err) {
19
+ console.error(err instanceof ConfigError ? err.message : String(err));
20
+ return 1;
21
+ }
22
+ const notes = readNotes(cfg, page);
23
+ const answers = readAnswers(cfg, page);
24
+ const open = openNoteIds(cfg, page);
25
+ for (const note of notes) {
26
+ const answer = answers[note.id];
27
+ const quote = note.quote === "" ? "" : ` "${note.quote.slice(0, 80)}"`;
28
+ console.log(`${note.id}${quote}: ${note.note.slice(0, 200)}${answer === undefined ? "" : `\n answer: ${answer.slice(0, 200)}`}`);
29
+ }
30
+ if (open.length > 0) {
31
+ console.error(`notes: ${open.length} unanswered on ${page} (${open.join(", ")}) — write them in ${notesAnswersPath(cfg, page)}`);
32
+ return 1;
33
+ }
34
+ console.log(`notes: all ${notes.length} answered on ${page}`);
35
+ return 0;
36
+ }
package/src/cli/pages.ts CHANGED
@@ -4,6 +4,7 @@ import { getAdapter } from "../adapters/index.ts";
4
4
  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
+ import { pageNotesGate } from "../core/page-notes.ts";
7
8
  import { pagesOff, pagesOn, publishPage, type Runner } from "../core/pages-setup.ts";
8
9
  import { realTailscale, type Tailscale } from "../core/tailscale.ts";
9
10
 
@@ -24,9 +25,16 @@ export async function runPages(args: string[] = [], deps: PagesDeps = {}): Promi
24
25
  return new Promise<number>(() => {});
25
26
  }
26
27
  if (args[0] === "publish" && args[1]) {
27
- let force = false, keep = false;
28
+ let force = false, keep = false, plan: string | undefined;
28
29
  const rest: string[] = [];
29
- for (const arg of args.slice(1)) { if (arg === "--force") force = true; else if (arg === "--keep") keep = true; else rest.push(arg); }
30
+ for (let i = 1; i < args.length; i++) {
31
+ const arg = args[i]!;
32
+ if (arg === "--force") force = true;
33
+ else if (arg === "--keep") keep = true;
34
+ else if (arg === "--plan") plan = args[++i] ?? "";
35
+ else rest.push(arg);
36
+ }
37
+ if (plan === "") { console.error("pages publish: --plan needs the plan file"); return 2; }
30
38
  // file first, then the optional name; flags may sit anywhere (2026-10-27: `--force <file>` used
31
39
  // to be read as file "--force" because only args.slice(2) was scanned)
32
40
  const file = rest[0];
@@ -34,7 +42,7 @@ export async function runPages(args: string[] = [], deps: PagesDeps = {}): Promi
34
42
  if (!file || rest.length > 2) return 2;
35
43
  const now = clock();
36
44
  sweepPages(cfg.pages.dir, cfg.pages.keep_days, now);
37
- const n = publishPage(file, name, force, cfg.pages.dir, keep, 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 });
38
46
  const host = (deps.tailscale ?? realTailscale).dnsName() ?? "tailnet";
39
47
  console.log(`http://${host}:${cfg.pages.port}/${encodeURIComponent(n)}`);
40
48
  const expires = readExpiry(cfg.pages.dir)[n]?.expires;
@@ -5,6 +5,7 @@ import { nowSec, strftime } from "./clock.ts";
5
5
  import { exitText } from "./help.ts";
6
6
  import { formatG, pyFixed, pyFixedWidth } from "./pyfmt.ts";
7
7
  import { pyDictInt } from "./pyjson.ts";
8
+ import { providersLine } from "./provider-state.ts";
8
9
  import { cmd } from "./proc.ts";
9
10
 
10
11
  function opt(args: string[], name: string): string | undefined {
@@ -66,6 +67,10 @@ export function agentLedger(args: string[], cfg: Config, source: RunSource): num
66
67
  process.stdout.write(`TOTAL ${pyFixed(tt / 1e6, 1)} Mtok, $${pyFixed(tc, 2)} list: whole-run totals of sessions active in the last ${formatG(hours)}h\n`);
67
68
 
68
69
  if (!args.includes("--cap")) return 0;
70
+ // Who is rate-limited comes from live data (plan 20261025_1700 P2), printed before every
71
+ // other cap line so the spawn decision reads the recorded state, never memory.
72
+ const providers = providersLine(cfg);
73
+ if (providers) process.stdout.write(`${providers}\n`);
69
74
  // --incident <id>: the cap check runs while Main is spawning the fix for a recorded incident;
70
75
  // then OVER-BUDGET lines must not fail the cap (a ledger bug cannot block its own fix).
71
76
  // Provider slots and the priority check stay binding.
@@ -25,6 +25,8 @@ function needOpt(args: string[], name: string): string {
25
25
  return args[i + 1]!;
26
26
  }
27
27
 
28
+ import { outUntil, pinModel, providerOfModel } from "./provider-state.ts";
29
+
28
30
  function eventsPath(cfg: Config): string {
29
31
  return join(cfg.paths.score_state, "events.jsonl");
30
32
  }
@@ -540,6 +542,41 @@ export function agentScore(args: string[], cfg: Config, source: RunSource, trace
540
542
  const { rows, byAgent } = table(cfg.score.gate_days, cfg, source);
541
543
  const target = byAgent.get(who)?.model ?? who;
542
544
  const ranked = rows.filter(r => r.acc).map(r => r.model);
545
+ if (cfg.ledger.prefer.length) {
546
+ // The owner's pick order outranks the score (plan 20261025_1700 P3, owner 2026-10-27:
547
+ // paid haiku spawned over free glm five times). A higher prefer agent with a free
548
+ // provider — known from its pin, accepted work or not — is named instead of the
549
+ // target; a later paid agent is never recommended while an earlier one is free.
550
+ const prefer = cfg.ledger.prefer;
551
+ const lower = (s: string): string => s.toLowerCase();
552
+ const rankOf = (model: string): number => prefer.findIndex(p => lower(model).includes(lower(p)));
553
+ const targetRank = rankOf(target);
554
+ let blocked: string | null = null;
555
+ for (let j = 0; j < (targetRank === -1 ? prefer.length : targetRank); j++) {
556
+ const name = prefer[j]!;
557
+ const provider = providerOfModel(pinModel(cfg, name));
558
+ if (provider !== null && outUntil(cfg, provider) === null) {
559
+ blocked = j === 0
560
+ ? `gate: ${name} is first in prefer and free → use it`
561
+ : `gate: ${name} is higher in prefer and free → use it (not ${target})`;
562
+ break;
563
+ }
564
+ }
565
+ if (blocked !== null) {
566
+ printText(blocked);
567
+ } else if (targetRank !== -1) {
568
+ const provider = providerOfModel(target);
569
+ printText(provider === null || outUntil(cfg, provider) === null
570
+ ? `gate: ${target} is free and no higher prefer agent is free → use it`
571
+ : `gate: ${target} is out and no higher prefer agent is free`);
572
+ } else {
573
+ const mine = ranked.findIndex(m => m.includes(target));
574
+ if (mine < 0) printText(`gate: ${target} has no accepted work in ${cfg.score.gate_days} days (unrated)`);
575
+ else if (mine > 0) printText(`WARN gate: ${ranked[mine]} ranks #${mine + 1}; better-ranked: ${ranked.slice(0, mine).join(", ")}. Use one of those if available, or say why not.`);
576
+ else printText(`gate: ${ranked[mine]} ranks #1`);
577
+ }
578
+ return 0;
579
+ }
543
580
  const mine = ranked.findIndex(m => m.includes(target));
544
581
  if (mine < 0) printText(`gate: ${target} has no accepted work in ${cfg.score.gate_days} days (unrated)`);
545
582
  else if (mine > 0) printText(`WARN gate: ${ranked[mine]} ranks #${mine + 1}; better-ranked: ${ranked.slice(0, mine).join(", ")}. Use one of those if available, or say why not.`);
@@ -617,12 +617,25 @@ export function denyText(env: BlockerEnv): void {
617
617
  }
618
618
  }
619
619
 
620
+ // Eval code's words: the same subcommand test as the bash path, so `git stash push` is not a push
621
+ // (I-20261027-266). Global options before the subcommand (-C <dir>, -c k=v) are skipped as there.
622
+ const CODE_WORDS = /[A-Za-z0-9_@%+=:.,/~-]+/g;
623
+
624
+ function evalPushes(code: string): boolean {
625
+ const words = code.match(CODE_WORDS) ?? [];
626
+ return words.some((w, i) => {
627
+ if (w !== "git" && !w.endsWith("/git")) return false;
628
+ const args = words.slice(i + 1).map((text) => ({ text, raw: text, quoted: false }));
629
+ return gitSub(args)?.sub === "push";
630
+ });
631
+ }
632
+
620
633
  /** no-push: subagents never push or merge (Main pushes and merges). Matched as commands, never as words inside arguments. */
621
634
  export function noPush(env: BlockerEnv): void {
622
635
  if (!env.shell || env.call.agent === "main") return;
623
636
  const hit =
624
637
  env.call.tool === "eval"
625
- ? /\bgit\b[^;&|\n]*\bpush\b|\bglab\s+mr\s+merge\b|\bgh\s+pr\s+merge\b/.test(env.command)
638
+ ? evalPushes(env.command) || /\bglab\s+mr\s+merge\b|\bgh\s+pr\s+merge\b/.test(env.command)
626
639
  : executed(env.command).some(pushesOrMerges);
627
640
  if (hit) block("subagents never push or merge; commit on the feature branch and report");
628
641
  }
@@ -19,6 +19,11 @@ export class ConfigError extends Error {
19
19
  export interface Config {
20
20
  /** Which adapter (src/adapters/index.ts) serves runs, traces, launch, install and doctor. The template ships the only one; a second harness adds its name here (docs/adapter.md). */
21
21
  harness: string;
22
+ /** Live project rules (src/core/repo-rules.ts): a repo's own AGENTS.md, handed to the agent that works in it. */
23
+ rules: {
24
+ /** Largest rules text a hook injects; past it the text is cut and one line names the file. */
25
+ max_bytes: number;
26
+ };
22
27
  paths: {
23
28
  home: string;
24
29
  work_roots: string[];
@@ -60,6 +65,8 @@ export interface Config {
60
65
  max_running_per_provider: number;
61
66
  max_slots: number;
62
67
  providers: string[];
68
+ /** Agent names in the owner's pick order, first = preferred; empty = off. */
69
+ prefer: string[];
63
70
  };
64
71
  brief: {
65
72
  method_marker: string;
@@ -151,6 +158,8 @@ export interface Config {
151
158
  ui: { enabled: boolean; port: number; owner_login: string };
152
159
  /** Static pages hosted over the tailnet. */
153
160
  pages: { enabled: boolean; port: number; dir: string; keep_days: number };
161
+ /** Repo-local HTML explainers under docs/knowledge/ (owner page Knowledge tab). */
162
+ knowledge: { roots: string[]; max_age_s: number };
154
163
  rollover: { enabled: boolean; max_session_mb: number; exit_grace_s: number };
155
164
  metrics: { report_days: number; correction_patterns: string[]; ci_pipelines_cmd: string };
156
165
  /** Incident detectors (src/core/incident-detectors.ts): when a sighting becomes an incident. */
@@ -418,6 +427,8 @@ function check(cfg: Config): void {
418
427
  throw new ConfigError("score.waste_weight must be between 0 and 1");
419
428
  }
420
429
  if (cfg.ledger.max_slots < 1) throw new ConfigError("ledger.max_slots must be >= 1");
430
+ if (!Array.isArray(cfg.ledger.prefer) || cfg.ledger.prefer.some(p => typeof p !== "string" || p === ""))
431
+ throw new ConfigError("ledger.prefer must be a list of agent names in pick order (may be empty)");
421
432
  if (cfg.guards.sub_warn_calls > cfg.guards.sub_max_calls) {
422
433
  throw new ConfigError("guards.sub_warn_calls must be <= guards.sub_max_calls");
423
434
  }
@@ -445,6 +456,11 @@ function check(cfg: Config): void {
445
456
  if (!Number.isInteger(cfg.pages.port) || cfg.pages.port < 1 || cfg.pages.port > 65535) throw new ConfigError("pages.port must be an integer between 1 and 65535");
446
457
  if (typeof cfg.pages.dir !== "string" || cfg.pages.dir.length === 0) throw new ConfigError("pages.dir must be a non-empty path");
447
458
  if (!Number.isInteger(cfg.pages.keep_days) || cfg.pages.keep_days < 1) throw new ConfigError("pages.keep_days must be an integer >= 1");
459
+ if (!Array.isArray(cfg.knowledge.roots) || cfg.knowledge.roots.length === 0) throw new ConfigError("knowledge.roots must be a non-empty list of paths");
460
+ for (const r of cfg.knowledge.roots) {
461
+ if (typeof r !== "string" || r.length === 0) throw new ConfigError("knowledge.roots entries must be non-empty paths");
462
+ }
463
+ if (!Number.isInteger(cfg.knowledge.max_age_s) || cfg.knowledge.max_age_s < 1) throw new ConfigError("knowledge.max_age_s must be an integer >= 1");
448
464
  for (const p of cfg.metrics.correction_patterns) {
449
465
  try {
450
466
  new RegExp(p, "i");
@@ -0,0 +1,128 @@
1
+ // Diagram coverage (plan 20261026_0930 P10, INCIDENT I-20261027-73: the owner's "the architecture
2
+ // diagram should fucking have everything … from smallest to biggest, everything should be drilled
3
+ // down"). A plan's diagram is checked against the plan itself: every phase and every file or command
4
+ // path its phase lines name must appear in the page's diagram data, and a box that drills down must
5
+ // drill into at least two things. The styling half — no arrow crossing a box, no arrow label on a box
6
+ // at 1280 and 390 width — is a browser check the architecture-drilldown skill runs; no code here can
7
+ // see a rendered arrow.
8
+ import { readFileSync } from "node:fs";
9
+
10
+ export interface DiagramReport {
11
+ /** Phases and paths the plan names that no box mentions. */
12
+ missing: string[];
13
+ /** Boxes that drill down into one thing (or none). */
14
+ thin: string[];
15
+ }
16
+
17
+ /** Index of the bracket matching the one at `open`, skipping string contents; -1 when unbalanced. */
18
+ function matchBracket(text: string, open: number): number {
19
+ let depth = 0;
20
+ let quote = "";
21
+ for (let i = open; i < text.length; i++) {
22
+ const c = text[i]!;
23
+ if (quote !== "") {
24
+ if (c === "\\") i++;
25
+ else if (c === quote) quote = "";
26
+ continue;
27
+ }
28
+ if (c === '"' || c === "'" || c === "`") quote = c;
29
+ else if (c === "{" || c === "[") depth++;
30
+ else if (c === "}" || c === "]") {
31
+ depth--;
32
+ if (depth === 0) return i;
33
+ }
34
+ }
35
+ return -1;
36
+ }
37
+
38
+ /** The diagram data a drilldown page carries: `const T={…}` up to its matching brace. */
39
+ export function diagramData(html: string): string | null {
40
+ const at = /\b(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*=\s*\{/.exec(html);
41
+ if (at === null) return null;
42
+ const open = at.index + at[0].length - 1;
43
+ const end = matchBracket(html, open);
44
+ return end < 0 ? null : html.slice(open, end + 1);
45
+ }
46
+
47
+ /** How many objects a `kids:[` array holds directly. */
48
+ function kidCount(data: string, open: number): number {
49
+ const end = matchBracket(data, open);
50
+ if (end < 0) return 0;
51
+ let n = 0;
52
+ for (let i = open + 1; i < end; i++) {
53
+ if (data[i] !== "{") continue;
54
+ n++;
55
+ const close = matchBracket(data, i);
56
+ if (close < 0) break;
57
+ i = close;
58
+ }
59
+ return n;
60
+ }
61
+
62
+ /** The id of the box whose `kids` sits at `at`, for the message. */
63
+ function boxId(data: string, at: number): string {
64
+ const head = data.slice(Math.max(0, at - 4000), at);
65
+ const ids = [...head.matchAll(/\bid\s*:\s*"([^"]+)"/g)];
66
+ return ids.length === 0 ? "a box" : ids[ids.length - 1]![1]!;
67
+ }
68
+
69
+ const PHASE = /^\s*[-*]\s+\[[ x]\]\s+(P\d+[a-z]?)\b/;
70
+ const SPAN = /`([^`\n]+)`/g;
71
+ /** A word that looks like a file or a path: it has a directory part or a short extension. */
72
+ const PATHISH = /[A-Za-z0-9_~/.-]*(?:\/[A-Za-z0-9_~/.-]+|\.[A-Za-z][A-Za-z0-9]{0,4}\b)/g;
73
+
74
+ export interface PlanItems {
75
+ phases: string[];
76
+ /** path → the phase whose line names it (first one wins). */
77
+ paths: Map<string, string>;
78
+ }
79
+
80
+ function clean(word: string): string {
81
+ return word.replace(/^[("'`]+/, "").replace(/[)"'`,;:.]+$/, "");
82
+ }
83
+
84
+ /** The phases of a plan and the files or commands their lines name in backticks. */
85
+ export function planItems(markdown: string): PlanItems {
86
+ const phases: string[] = [];
87
+ const paths = new Map<string, string>();
88
+ for (const line of markdown.split("\n")) {
89
+ const phase = PHASE.exec(line);
90
+ if (phase === null) continue;
91
+ const id = phase[1]!;
92
+ if (!phases.includes(id)) phases.push(id);
93
+ for (const span of line.matchAll(SPAN)) {
94
+ for (const raw of span[1]!.matchAll(PATHISH)) {
95
+ const word = clean(raw[0]);
96
+ // Short noise ("e.g", "y/N", "Pn") and web addresses are not what a box must name.
97
+ if (word.length < 4 || /^https?:/i.test(word) || word.includes("…")) continue;
98
+ if (!paths.has(word)) paths.set(word, id);
99
+ }
100
+ }
101
+ }
102
+ return { phases, paths };
103
+ }
104
+
105
+ /** What the diagram of `planText` is missing, checked against the page's own data. */
106
+ export function checkDiagram(html: string, planText: string): DiagramReport {
107
+ const data = diagramData(html);
108
+ if (data === null) return { missing: ["the page carries no diagram data (expected `const NAME={` … `}`)"], thin: [] };
109
+ const items = planItems(planText);
110
+ const missing: string[] = [];
111
+ for (const phase of items.phases) {
112
+ if (!new RegExp(`\\b${phase}\\b`).test(data)) missing.push(`${phase}: the phase is in no box`);
113
+ }
114
+ for (const [path, phase] of items.paths) {
115
+ if (!data.includes(path)) missing.push(`${path} (${phase}): named in the plan, in no box`);
116
+ }
117
+ const thin: string[] = [];
118
+ for (const hit of data.matchAll(/kids\s*:\s*\[/g)) {
119
+ const count = kidCount(data, hit.index + hit[0].length - 1);
120
+ if (count < 2) thin.push(`${boxId(data, hit.index)} has ${count} kid${count === 1 ? "" : "s"}`);
121
+ }
122
+ return { missing, thin };
123
+ }
124
+
125
+ /** The check for two files on disk; a page without data reads as one missing item, never a crash. */
126
+ export function checkDiagramFiles(htmlFile: string, planFile: string): DiagramReport {
127
+ return checkDiagram(readFileSync(htmlFile, "utf8"), readFileSync(planFile, "utf8"));
128
+ }
@@ -26,6 +26,7 @@ import { appendFileSync, mkdirSync, readFileSync, statSync, writeFileSync } from
26
26
  import path from "node:path";
27
27
  import type { Decision, InjectEvent, PlanEditEvent, SpawnEvent, StopEvent, ToolEvent } from "./adapter.ts";
28
28
  import { currentTier, takeGo, type Tier } from "./autonomy.ts";
29
+ import { approvalProblem } from "./plan-approval.ts";
29
30
  import type { Config } from "./config.ts";
30
31
  import { addIncident, openIncidents, type IncidentView } from "./incidents.ts";
31
32
  import { notifyProtectedPaths, notifySecretReadHit } from "./notify.ts";
@@ -33,6 +34,7 @@ import * as q from "./queue/lib.ts";
33
34
  import type { Plan } from "./queue/lib.ts";
34
35
 
35
36
  import { nowSec } from "./clock.ts";
37
+ import { outUntil, pinModel, providerOfModel, readOut } from "./provider-state.ts";
36
38
  const ALLOW: Decision = { allow: true, reason: "" };
37
39
 
38
40
  /**
@@ -334,7 +336,7 @@ function unticked(p: Plan): string[] {
334
336
  }
335
337
 
336
338
  // Plans an implementer brief may run on; returns [reason, null] or [null, plan files].
337
- export function planGate(text: string, label: string): [string | null, string[]] {
339
+ export function planGate(text: string, label: string, cfg?: Config): [string | null, string[]] {
338
340
  const plans = q.activePlans();
339
341
  const unclosed = plans.filter(p => (p.status === "complete" || p.status === "cancelled") && !q.awaitingMerge(p));
340
342
  if (unclosed.length)
@@ -369,6 +371,10 @@ export function planGate(text: string, label: string): [string | null, string[]]
369
371
  `${label}: plan ${p.file} has no new "## Progress" entry since the last agent ran on it. Write that run's progress (from its report) into the plan first.`,
370
372
  [],
371
373
  ];
374
+ if (cfg) {
375
+ const approval = approvalProblem(p.text, p.file, cfg.pages.dir);
376
+ if (approval) return [approval, []];
377
+ }
372
378
  const open = unticked(p);
373
379
  if (!open.length) return [`${label}: plan ${p.file} has no unticked phase left.`, []];
374
380
  if (!open.some(id => new RegExp(`\\b${id}\\b`).test(text)))
@@ -455,6 +461,55 @@ function priorityGate(named: string[], runningJobs: string[] | undefined, brief:
455
461
  return outcome?.problem ? `${label}: ${outcome.problem}` : null;
456
462
  }
457
463
 
464
+ /**
465
+ * The owner's pick order (plan 20261025_1700 P3): refuse a later `ledger.prefer` agent while an
466
+ * earlier one is free and under its provider cap, unless the brief carries "Pick note: <why>".
467
+ * Free comes from the pin's provider and provider-out.jsonl (absence of a record is free);
468
+ * "under its cap" counts the caller's running jobs whose label embeds the higher agent's name —
469
+ * a caller without job info counts 0, erring toward the owner's order, which Pick note unlocks.
470
+ */
471
+ export function preferProblem(agent: string, brief: string, runningJobs: readonly string[] | undefined, cfg: Config): string | null {
472
+ const prefer = cfg.ledger.prefer;
473
+ if (!prefer.length) return null;
474
+ const mine = prefer.indexOf(agent);
475
+ if (mine <= 0) return null; // the first pick, or an agent the order does not name
476
+ if (/\bPick note:/i.test(brief)) return null;
477
+ for (let j = 0; j < mine; j++) {
478
+ const higher = prefer[j]!;
479
+ const provider = providerOfModel(pinModel(cfg, higher));
480
+ if (provider === null || outUntil(cfg, provider) !== null) continue; // unknown or out
481
+ const running = (runningJobs ?? []).filter(l => l.toLowerCase().includes(higher.toLowerCase())).length;
482
+ if (running >= cfg.ledger.max_running_per_provider) continue; // the higher pick is at its provider cap
483
+ return `${higher} is ahead of ${agent} in ledger.prefer and free (under its provider cap) — spawn ${higher}, or add "Pick note: <why>" to the brief.`;
484
+ }
485
+ return null;
486
+ }
487
+
488
+ /**
489
+ * Who is rate-limited comes from live data (plan 20261025_1700 P1): refuse a brief that asserts a
490
+ * provider shown free by providerStatus is rate-limited — named directly or through a prefer
491
+ * agent's pin. providerStatus lists only providers with a record, so a never-recorded provider is
492
+ * not protected here; a past-tense mention does not match, because the claim must say "is …".
493
+ */
494
+ export function providerClaimProblem(text: string, cfg: Config): string | null {
495
+ const recorded = new Set(readOut(cfg).map(r => r.provider));
496
+ const free = (provider: string | null): boolean => provider !== null && recorded.has(provider) && outUntil(cfg, provider) === null;
497
+ const names = new Map<string, string>();
498
+ for (const p of cfg.ledger.providers) if (free(p)) names.set(p, p);
499
+ for (const agent of cfg.ledger.prefer) {
500
+ const provider = providerOfModel(pinModel(cfg, agent));
501
+ if (free(provider) && !names.has(agent) && provider !== null) names.set(agent, provider);
502
+ }
503
+ if (!names.size || !/\bis\b/i.test(text)) return null;
504
+ const esc = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
505
+ const m = new RegExp(`\\b(${[...names.keys()].map(esc).join("|")})\\b[^.\\n]{0,80}?\\b(?:is|are)\\s+(?:still\\s+|now\\s+)?(?:rate[ -]?limited|rate limiting|throttled|out until|limited)`, "i").exec(text);
506
+ if (!m) return null;
507
+ const hit = [...names.entries()].find(([n]) => n.toLowerCase() === (m[1] ?? "").toLowerCase());
508
+ if (hit === undefined) return null;
509
+ const [name, provider] = hit;
510
+ return `${name === provider ? provider : `${name} (provider ${provider})`} is free per the recorded provider state — do not claim it is rate-limited; read the providers line from agent-ledger --cap.`;
511
+ }
512
+
458
513
  /** Reason to refuse a `task` brief, or null; `files` receives the plans to record, `budgets` every named task's call budget (null = none), `staffing` each plan's named tasks of this call, `runningJobs` the caller's running job labels (undefined = no job info). */
459
514
  export function spawnProblem(
460
515
  input: Record<string, unknown>,
@@ -473,7 +528,7 @@ export function spawnProblem(
473
528
  const agent = String(t?.agent ?? "task");
474
529
  const label = String(t?.name ?? agent);
475
530
  if (!allowed.has(agent)) return `${label}: agent "${agent}" is not in "## Allowed" of ${q.SUBAGENTS_MD} (no expensive or unpinned models).`;
476
- const [why, plans] = planGate(`${context}\n${String(t?.task ?? "")}`, label);
531
+ const [why, plans] = planGate(`${context}\n${String(t?.task ?? "")}`, label, cfg);
477
532
  if (why) return why;
478
533
  // The task's own `Call budget:` line wins over the shared context's.
479
534
  const budget = briefBudget(String(t?.task ?? "")) ?? shared;
@@ -489,6 +544,14 @@ export function spawnProblem(
489
544
  files.push(...plans);
490
545
  }
491
546
  Object.assign(budgets, named);
547
+ // Who is limited and who goes first come from live data and ledger.prefer (plan 20261025_1700
548
+ // P3): the same rules checkSpawn applies to single-spawn events, per task.
549
+ const claim = providerClaimProblem(`${context}\n${tasks.map(t => String(t?.task ?? "")).join("\n")}`, cfg);
550
+ if (claim) return claim;
551
+ for (const t of tasks) {
552
+ const pick = preferProblem(String(t?.agent ?? "task"), `${context}\n${String(t?.task ?? "")}`, runningJobs, cfg);
553
+ if (pick) return `${String(t?.name ?? t?.agent ?? "task")}: ${pick}`;
554
+ }
492
555
  // Priority gate (20261025_0215 P3): once per `task` call, over the plans this call names; the
493
556
  // skip lines may sit in the shared context or any task text.
494
557
  const gate = priorityGate(
@@ -575,12 +638,33 @@ function landingCommand(input: Record<string, unknown>): boolean {
575
638
  });
576
639
  }
577
640
 
641
+ // The read tool's stand-in for a value it hid. A file may hold one only where it is produced
642
+ // (secret-redact.ts) or exercised (its tests).
643
+ const PLACEHOLDER = "[REDACTED:";
644
+ const PLACEHOLDER_FILES = [/\/src\/core\/secret-redact\.ts$/, /\/tests\/secret-redact[^/]*\.test\.ts$/];
645
+ /** What a write/edit/ast_edit call would add: every text argument but the targets and the replaced text. */
646
+ function addedText(input: Record<string, unknown>): string {
647
+ const skip = ["path", "file", "cwd", "old_string", "old", "oldText", "i"];
648
+ return Object.entries(input)
649
+ .filter(([key, value]) => typeof value === "string" && !skip.includes(key))
650
+ .map(([, value]) => value as string)
651
+ .join("\n");
652
+ }
653
+
578
654
  // Subagent half of a tool call (the original plan-guard checkCall without the main return).
579
655
  // `cap` is the sub's hard call cap: its recorded per-spawn budget, else the global sub_max_calls.
580
656
  function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[], writes: string[], cfg: Config, cap: number): string | null {
581
657
  // Closing and cancelling are Main's decisions: a shell that runs the tool is refused; one that only names its path is not.
582
658
  if (cfg.guards.shell_tools.includes(e.tool) && runsCloser(input))
583
659
  return 'queue-close and queue-cancel are Main\'s; report in your plan\'s "## Progress" instead.';
660
+ // The read tool prints a placeholder for a value it hid, never the value (I-20261027-158,
661
+ // I-20261027-160: one copy silently broke the shipped config template). Writing that text back
662
+ // is refused; the file that produces one and the tests that exercise it are the exceptions.
663
+ if ((e.tool === "write" || e.tool === "edit" || e.tool === "ast_edit") && addedText(input).includes(PLACEHOLDER)) {
664
+ const keeper = writes.length > 0 && writes.every(p => PLACEHOLDER_FILES.some(rx => rx.test(p)));
665
+ if (!keeper)
666
+ return "this is the read tool's redaction placeholder, not the real value; re-read the file raw or keep the original line";
667
+ }
584
668
  const plans = q.activePlans();
585
669
  if (e.calls >= cap) {
586
670
  // Plan edit targets come from writeTargets (write and structured/hashline edit)
@@ -728,7 +812,7 @@ function mainTool(e: ToolEvent, input: Record<string, unknown>, cfg: Config): De
728
812
  log(cfg.paths.guard_log, `BLOCK bypass launch: cancel pending (${pending.words})`);
729
813
  return deny(`main-guard: ${CANCEL_TODO} Flagged: "${pending.words}"`);
730
814
  }
731
- const [why, named] = planGate(command, entry);
815
+ const [why, named] = planGate(command, entry, cfg);
732
816
  if (why) {
733
817
  log(cfg.paths.guard_log, `BLOCK bypass launch: ${why}`);
734
818
  return deny(`main-guard: ${why}`);
@@ -917,7 +1001,7 @@ export function checkSpawn(e: SpawnEvent, cfg: Config): Decision {
917
1001
  return deny(`main-guard: ${e.agent}: agent "${e.agent}" is not in "## Allowed" of ${q.SUBAGENTS_MD} (no expensive or unpinned models).`);
918
1002
  if (e.invocationKind !== "task")
919
1003
  return deny("main-guard: spawn implementers with the task tool (the plan gate checks its brief).");
920
- const [why, named] = planGate(e.brief, e.agent);
1004
+ const [why, named] = planGate(e.brief, e.agent, cfg);
921
1005
  if (why) {
922
1006
  log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${why}`);
923
1007
  return deny(`main-guard: ${why}`);
@@ -929,6 +1013,17 @@ export function checkSpawn(e: SpawnEvent, cfg: Config): Decision {
929
1013
  }
930
1014
  const inc = incidentSpawnProblem(`spawn ${e.agent}`, e.brief, named, cfg);
931
1015
  if (inc) return deny(`main-guard: ${inc}`);
1016
+ // The owner's pick order and live provider state (plan 20261025_1700 P3), before the spawn records.
1017
+ const claim = providerClaimProblem(e.brief, cfg);
1018
+ if (claim) {
1019
+ log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${claim}`);
1020
+ return deny(`main-guard: ${e.agent}: ${claim}`);
1021
+ }
1022
+ const pick = preferProblem(e.agent, e.brief, e.runningJobs, cfg);
1023
+ if (pick) {
1024
+ log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${pick}`);
1025
+ return deny(`main-guard: ${e.agent}: ${pick}`);
1026
+ }
932
1027
  const staffing: Record<string, string[]> = {};
933
1028
  for (const f of named) staffing[f] = [e.agent];
934
1029
  recordSpawns(named, staffing);