neurastream 0.2.35 → 0.2.37

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
@@ -246,6 +246,12 @@ omp retries a 429 itself while the provider's wait fits its `retry.maxDelayMs` (
246
246
 
247
247
  Before Main reads a message, reset timestamps matching `quota.reset_pattern` are annotated with their local time, for example `reset at 2026-10-25 18:56:22 (= 2026-10-25 11:56:22 CET local)`. Set `quota.reset_tz` to the provider's time zone; an explicit zone or UTC offset in the message takes precedence.
248
248
 
249
+ ## Provider state and pick order
250
+
251
+ Who is rate-limited comes from recorded live data, not from memory (I-20261025-164). An out-until time is recorded — `quota-reset --provider <name> "<429 text>"` stores the time it parses (zone from `quota.reset_tz`), the adapter records a task result quoting a `reset at …` line for the pinned provider, and a rate limit without a parseable time records now plus its wait — as `{provider, until, at, source}` lines in `<paths.queue_state>/provider-out.jsonl`; the newest record per provider wins. `agent-ledger --cap` and `main-start` print the live line, for example `providers: zai free · openrouter out until 18:40`; never state which providers or agents are limited — read that line.
252
+
253
+ The owner's pick order is enforced, not prose: config `ledger.prefer` names agents in order (first = preferred, empty = off). While a higher pick's provider is free, the spawn gates refuse a lower pick unless the brief carries `Pick note: <why>`, and a brief that claims a provider the recorded state shows free is rate-limited is refused outright. `agent-score gate` ranks inside the order: with an earlier pick free it names that one (`gate: glm is first in prefer and free → use it`) instead of recommending a later paid agent by score; with `ledger.prefer` empty the old score-only verdicts stand.
254
+
249
255
  ## Suspicious actions (`neurastream traces actions`)
250
256
 
251
257
  `neurastream traces actions <runId|--since 24h> [--json]` lists the suspicious tool actions a run's trace shows: reads of secret paths (`traces.actions.secret_globs`), network commands (`net_tools`) to unknown hosts, pipes into a shell (`shell_patterns`), and writes outside `write_roots` (empty = `paths.work_roots`; both empty = off) or on `deny_globs`. The high ones also open realtime suspicious-action incidents.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.35",
3
+ "version": "0.2.37",
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",
@@ -39,6 +39,7 @@ import { adapterLog } from "./launch.ts";
39
39
  import { parseTraceFile } from "./traces.ts";
40
40
  import { packageJsonPath, packageVersion } from "./package-root.ts";
41
41
  import * as q from "../../core/queue/lib.ts";
42
+ import { pinModel, providerOfModel, recordOut, resetEpochFromText } from "../../core/provider-state.ts";
42
43
  import { annotateResetTimes } from "../../core/reset-time.ts";
43
44
  // Registers the plugin-command matcher into core's writeTargets (side effect).
44
45
  import "./package-ops.ts";
@@ -79,6 +80,9 @@ interface EventReply {
79
80
  toolCalls: number;
80
81
  /** The provider's error text on a turn that ended on one (`429 … retry-after-ms=…`); null otherwise. */
81
82
  errorMessage: string | null;
83
+ /** The provider and model fields of the assistant message, when the event carries them; the provider-out recording keys on the provider. */
84
+ provider: string | null;
85
+ model: string | null;
82
86
  }
83
87
 
84
88
  function lastAssistantIn(messages: unknown): EventReply | null {
@@ -97,6 +101,8 @@ function lastAssistantIn(messages: unknown): EventReply | null {
97
101
  stopReason: typeof m.stopReason === "string" ? m.stopReason : null,
98
102
  toolCalls: content.filter(c => asRecord(c).type === "toolCall").length,
99
103
  errorMessage: typeof m.errorMessage === "string" ? m.errorMessage : null,
104
+ provider: typeof m.provider === "string" ? m.provider : null,
105
+ model: typeof m.model === "string" ? m.model : null,
100
106
  };
101
107
  }
102
108
  return null;
@@ -287,6 +293,42 @@ function redactToolResult(content: unknown[], cfg: Config): { content: unknown[]
287
293
  return { content: out, note: redactSummary([...hits].map(([type, count]) => ({ type, count }))) };
288
294
  }
289
295
 
296
+ // Provider out-until from live data (plan 20261025_1700 P1). Two automatic recordings, both
297
+ // keyed on the provider half of an agent pin's `model:` frontmatter, both best effort and
298
+ // logged once. The reset-time case trusts the provider's own words; the no-time case falls
299
+ // back to the armed rate-limit wait, so a provider without a quoted reset time still lands in
300
+ // the file the guards and the ledger read.
301
+ const resetRule = (cfg: Config): { pattern: string; zone: string } => ({ pattern: cfg.quota.reset_pattern, zone: cfg.quota.reset_tz });
302
+
303
+ /** Task result that quotes a reset time: record it for the sub's provider. A batch naming
304
+ * several providers cannot attribute the time to one of them, so it records nothing. */
305
+ function recordProviderOutFromTask(e: Record<string, unknown>, content: unknown[], cfg: Config): void {
306
+ if (asString(e.toolName) !== "task" || e.isError === true) return;
307
+ const text = content.map(p => asString(asRecord(p).text)).join("\n");
308
+ const epoch = resetEpochFromText(text, resetRule(cfg));
309
+ if (epoch === null) return;
310
+ const tasks = Array.isArray(asRecord(e.input).tasks) ? (asRecord(e.input).tasks as unknown[]) : [];
311
+ const providers = new Set<string>();
312
+ for (const t of tasks) {
313
+ const provider = providerOfModel(pinModel(cfg, asString(asRecord(t).agent)));
314
+ if (provider) providers.add(provider);
315
+ }
316
+ if (providers.size !== 1) return;
317
+ const provider = [...providers][0]!;
318
+ recordOut(cfg, provider, epoch, "task-result");
319
+ adapterLog(cfg, `PROVIDER-OUT recorded: ${provider} out until ${new Date(epoch * 1000).toISOString()} (task result)`);
320
+ }
321
+
322
+ /** Rate-limited turn end: record the reset time the error text names, else the armed wait. */
323
+ function recordProviderOutFromRateLimit(reply: EventReply | null, untilMs: number, cfg: Config): void {
324
+ const provider = reply?.provider ?? providerOfModel(reply?.model ?? null);
325
+ if (!provider) return;
326
+ const named = reply ? resetEpochFromText(reply.errorMessage ?? "", resetRule(cfg)) : null;
327
+ const epoch = named ?? Math.floor(untilMs / 1000);
328
+ recordOut(cfg, provider, epoch, named !== null ? "rate-limit-reset" : "rate-limit");
329
+ adapterLog(cfg, `PROVIDER-OUT recorded: ${provider} out until ${new Date(epoch * 1000).toISOString()} (${named !== null ? "reset time in error text" : "rate limit, no reset time"})`);
330
+ }
331
+
290
332
  // Session rollover helpers: the harness context read through runtime checks, and the file size and
291
333
  // mtime reads. The decisions are in src/core/rollover.ts.
292
334
  const WAIT_NOTICE_MS = 15 * 60_000;
@@ -775,6 +817,13 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
775
817
  const redacted = redactToolResult(Array.isArray(e.content) ? e.content : [], cfg);
776
818
  const content = redacted.content;
777
819
  const notes: string[] = redacted.note ? [redacted.note] : [];
820
+ // Provider out-until from a task result that quotes a reset time (plan 20261025_1700 P1):
821
+ // recorded from the redacted text before anything else, never thrown.
822
+ try {
823
+ recordProviderOutFromTask(e, content, cfg);
824
+ } catch (err) {
825
+ adapterLog(cfg, `PROVIDER-OUT record failed: ${err instanceof Error ? err.message : String(err)}`);
826
+ }
778
827
  if (snap) {
779
828
  pending.delete(id);
780
829
  for (const [file, before] of snap) {
@@ -850,6 +899,13 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
850
899
  // and without touching the idle-stop counters: checkStop is not consulted.
851
900
  const rl = rateLimitOf(reply);
852
901
  if (rl) {
902
+ // Who is rate-limited is live data (plan 20261025_1700 P1): the error text's own reset
903
+ // time, else the armed wait. Best effort — a failed write never changes the stop.
904
+ try {
905
+ recordProviderOutFromRateLimit(reply, rl.untilMs, cfg);
906
+ } catch (err) {
907
+ adapterLog(cfg, `PROVIDER-OUT record failed: ${err instanceof Error ? err.message : String(err)}`);
908
+ }
853
909
  onRateLimitedStop(rl.untilMs, rl.waitMs);
854
910
  return undefined;
855
911
  }
@@ -12,6 +12,7 @@ import { queueCancel } from "../core/queue-cancel.ts";
12
12
  import { queueCheck } from "../core/queue-check.ts";
13
13
  import { queueTrim } from "../core/queue-trim.ts";
14
14
  import { queueClose } from "../core/queue-close.ts";
15
+ import { queueFinished } from "../core/queue-finished.ts";
15
16
  import { resourceAlerts } from "../core/resource-alerts.ts";
16
17
  import { tmpSnapshot } from "../core/tmp-snapshot.ts";
17
18
  import { wipBackup } from "../core/wip-backup.ts";
@@ -32,6 +33,7 @@ export const PORTED = [
32
33
  "queue-check",
33
34
  "queue-trim",
34
35
  "queue-close",
36
+ "queue-finished",
35
37
  "queue-cancel",
36
38
  "main-start",
37
39
  "machine-guard",
@@ -72,6 +74,8 @@ export async function runPorted(cmd: string, args: string[]): Promise<number> {
72
74
  return queueTrim(args, rt.cfg);
73
75
  case "queue-close":
74
76
  return queueClose(args, rt.cfg);
77
+ case "queue-finished":
78
+ return queueFinished(args, rt.cfg);
75
79
  case "queue-cancel":
76
80
  return queueCancel(args, rt.cfg);
77
81
  case "main-start": {
@@ -30,6 +30,7 @@ const BINS = [
30
30
  "queue-check",
31
31
  "queue-trim",
32
32
  "queue-close",
33
+ "queue-finished",
33
34
  "queue-cancel",
34
35
  "main-start",
35
36
  "machine-guard",
package/src/cli/pages.ts CHANGED
@@ -24,11 +24,17 @@ export async function runPages(args: string[] = [], deps: PagesDeps = {}): Promi
24
24
  return new Promise<number>(() => {});
25
25
  }
26
26
  if (args[0] === "publish" && args[1]) {
27
- let force = false, keep = false, name: string | undefined;
28
- for (const arg of args.slice(2)) { if (arg === "--force") force = true; else if (arg === "--keep") keep = true; else if (!name) name = arg; else return 2; }
27
+ let force = false, keep = false;
28
+ 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
+ // file first, then the optional name; flags may sit anywhere (2026-10-27: `--force <file>` used
31
+ // to be read as file "--force" because only args.slice(2) was scanned)
32
+ const file = rest[0];
33
+ const name = rest[1];
34
+ if (!file || rest.length > 2) return 2;
29
35
  const now = clock();
30
36
  sweepPages(cfg.pages.dir, cfg.pages.keep_days, now);
31
- const n = publishPage(args[1], name, force, cfg.pages.dir, keep, cfg.pages.keep_days, now);
37
+ const n = publishPage(file, name, force, cfg.pages.dir, keep, cfg.pages.keep_days, now);
32
38
  const host = (deps.tailscale ?? realTailscale).dnsName() ?? "tailnet";
33
39
  console.log(`http://${host}:${cfg.pages.port}/${encodeURIComponent(n)}`);
34
40
  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.`);
@@ -60,6 +60,8 @@ export interface Config {
60
60
  max_running_per_provider: number;
61
61
  max_slots: number;
62
62
  providers: string[];
63
+ /** Agent names in the owner's pick order, first = preferred; empty = off. */
64
+ prefer: string[];
63
65
  };
64
66
  brief: {
65
67
  method_marker: string;
@@ -418,6 +420,8 @@ function check(cfg: Config): void {
418
420
  throw new ConfigError("score.waste_weight must be between 0 and 1");
419
421
  }
420
422
  if (cfg.ledger.max_slots < 1) throw new ConfigError("ledger.max_slots must be >= 1");
423
+ if (!Array.isArray(cfg.ledger.prefer) || cfg.ledger.prefer.some(p => typeof p !== "string" || p === ""))
424
+ throw new ConfigError("ledger.prefer must be a list of agent names in pick order (may be empty)");
421
425
  if (cfg.guards.sub_warn_calls > cfg.guards.sub_max_calls) {
422
426
  throw new ConfigError("guards.sub_warn_calls must be <= guards.sub_max_calls");
423
427
  }
@@ -33,6 +33,7 @@ import * as q from "./queue/lib.ts";
33
33
  import type { Plan } from "./queue/lib.ts";
34
34
 
35
35
  import { nowSec } from "./clock.ts";
36
+ import { outUntil, pinModel, providerOfModel, readOut } from "./provider-state.ts";
36
37
  const ALLOW: Decision = { allow: true, reason: "" };
37
38
 
38
39
  /**
@@ -455,6 +456,55 @@ function priorityGate(named: string[], runningJobs: string[] | undefined, brief:
455
456
  return outcome?.problem ? `${label}: ${outcome.problem}` : null;
456
457
  }
457
458
 
459
+ /**
460
+ * The owner's pick order (plan 20261025_1700 P3): refuse a later `ledger.prefer` agent while an
461
+ * earlier one is free and under its provider cap, unless the brief carries "Pick note: <why>".
462
+ * Free comes from the pin's provider and provider-out.jsonl (absence of a record is free);
463
+ * "under its cap" counts the caller's running jobs whose label embeds the higher agent's name —
464
+ * a caller without job info counts 0, erring toward the owner's order, which Pick note unlocks.
465
+ */
466
+ export function preferProblem(agent: string, brief: string, runningJobs: readonly string[] | undefined, cfg: Config): string | null {
467
+ const prefer = cfg.ledger.prefer;
468
+ if (!prefer.length) return null;
469
+ const mine = prefer.indexOf(agent);
470
+ if (mine <= 0) return null; // the first pick, or an agent the order does not name
471
+ if (/\bPick note:/i.test(brief)) return null;
472
+ for (let j = 0; j < mine; j++) {
473
+ const higher = prefer[j]!;
474
+ const provider = providerOfModel(pinModel(cfg, higher));
475
+ if (provider === null || outUntil(cfg, provider) !== null) continue; // unknown or out
476
+ const running = (runningJobs ?? []).filter(l => l.toLowerCase().includes(higher.toLowerCase())).length;
477
+ if (running >= cfg.ledger.max_running_per_provider) continue; // the higher pick is at its provider cap
478
+ 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.`;
479
+ }
480
+ return null;
481
+ }
482
+
483
+ /**
484
+ * Who is rate-limited comes from live data (plan 20261025_1700 P1): refuse a brief that asserts a
485
+ * provider shown free by providerStatus is rate-limited — named directly or through a prefer
486
+ * agent's pin. providerStatus lists only providers with a record, so a never-recorded provider is
487
+ * not protected here; a past-tense mention does not match, because the claim must say "is …".
488
+ */
489
+ export function providerClaimProblem(text: string, cfg: Config): string | null {
490
+ const recorded = new Set(readOut(cfg).map(r => r.provider));
491
+ const free = (provider: string | null): boolean => provider !== null && recorded.has(provider) && outUntil(cfg, provider) === null;
492
+ const names = new Map<string, string>();
493
+ for (const p of cfg.ledger.providers) if (free(p)) names.set(p, p);
494
+ for (const agent of cfg.ledger.prefer) {
495
+ const provider = providerOfModel(pinModel(cfg, agent));
496
+ if (free(provider) && !names.has(agent) && provider !== null) names.set(agent, provider);
497
+ }
498
+ if (!names.size || !/\bis\b/i.test(text)) return null;
499
+ const esc = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
500
+ 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);
501
+ if (!m) return null;
502
+ const hit = [...names.entries()].find(([n]) => n.toLowerCase() === (m[1] ?? "").toLowerCase());
503
+ if (hit === undefined) return null;
504
+ const [name, provider] = hit;
505
+ 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.`;
506
+ }
507
+
458
508
  /** 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
509
  export function spawnProblem(
460
510
  input: Record<string, unknown>,
@@ -489,6 +539,14 @@ export function spawnProblem(
489
539
  files.push(...plans);
490
540
  }
491
541
  Object.assign(budgets, named);
542
+ // Who is limited and who goes first come from live data and ledger.prefer (plan 20261025_1700
543
+ // P3): the same rules checkSpawn applies to single-spawn events, per task.
544
+ const claim = providerClaimProblem(`${context}\n${tasks.map(t => String(t?.task ?? "")).join("\n")}`, cfg);
545
+ if (claim) return claim;
546
+ for (const t of tasks) {
547
+ const pick = preferProblem(String(t?.agent ?? "task"), `${context}\n${String(t?.task ?? "")}`, runningJobs, cfg);
548
+ if (pick) return `${String(t?.name ?? t?.agent ?? "task")}: ${pick}`;
549
+ }
492
550
  // Priority gate (20261025_0215 P3): once per `task` call, over the plans this call names; the
493
551
  // skip lines may sit in the shared context or any task text.
494
552
  const gate = priorityGate(
@@ -929,6 +987,17 @@ export function checkSpawn(e: SpawnEvent, cfg: Config): Decision {
929
987
  }
930
988
  const inc = incidentSpawnProblem(`spawn ${e.agent}`, e.brief, named, cfg);
931
989
  if (inc) return deny(`main-guard: ${inc}`);
990
+ // The owner's pick order and live provider state (plan 20261025_1700 P3), before the spawn records.
991
+ const claim = providerClaimProblem(e.brief, cfg);
992
+ if (claim) {
993
+ log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${claim}`);
994
+ return deny(`main-guard: ${e.agent}: ${claim}`);
995
+ }
996
+ const pick = preferProblem(e.agent, e.brief, e.runningJobs, cfg);
997
+ if (pick) {
998
+ log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${pick}`);
999
+ return deny(`main-guard: ${e.agent}: ${pick}`);
1000
+ }
932
1001
  const staffing: Record<string, string[]> = {};
933
1002
  for (const f of named) staffing[f] = [e.agent];
934
1003
  recordSpawns(named, staffing);
@@ -12,6 +12,7 @@ import { log as logGuard } from "./guards.ts";
12
12
  import { dailyChecks, readBlocks, readMetricEvents, worseThanMean } from "./metrics.ts";
13
13
  import { buildReport } from "./report.ts";
14
14
  import { loadavgLine } from "./host.ts";
15
+ import { providersLine } from "./provider-state.ts";
15
16
  import { mrSweep } from "./mr-sweep.ts";
16
17
 
17
18
  function bin(name: string, cfg: Config): string {
@@ -129,6 +130,10 @@ export async function mainStartText(args: string[], cfg: Config, opts: { inherit
129
130
  for (const line of cap.stdout.split("\n")) {
130
131
  if (/^(PRIORITY IDLE|FULL)/.test(line)) say(line);
131
132
  }
133
+ // Who is rate-limited comes from live data (plan 20261025_1700 P2): printed from the running
134
+ // code, not the installed agent-ledger bin, so a stale install cannot hide the state.
135
+ const providers = providersLine(cfg);
136
+ if (providers) say(providers);
132
137
  say("");
133
138
  say("=== main thread");
134
139
  const health = await run(bin("main-health", cfg), [], { stdin: childStdin, stderr: childStderr });
@@ -866,7 +866,7 @@ var qlist=main.querySelector("#qlist");
866
866
  if(qlist){
867
867
  var moveCard=function(card,how){if(how==="top"){var f=qlist.querySelector(".qcard");if(f&&f!==card)qlist.insertBefore(card,f);}else if(how==="up"){var p=card.previousElementSibling;if(p&&p.classList.contains("qcard"))qlist.insertBefore(card,p);}else if(how==="down"){var n=card.nextElementSibling;if(n&&n.classList.contains("qcard"))qlist.insertBefore(card,n.nextSibling);}};
868
868
  qlist.addEventListener("click",function(e){var t=e.target;if(!t||!t.closest)return;var b=t.closest(".qmove");if(!b)return;var card=t.closest(".qcard");if(!card)return;moveCard(card,b.getAttribute("data-move"));sendReorder(card.getAttribute("data-plan"),qlist);});
869
- qlist.addEventListener("pointerdown",function(e){var t=e.target;if(!t||!t.closest)return;var h=t.closest(".qhandle");if(h&&!drag){var card=t.closest(".qcard");if(card){e.preventDefault();dragging=true;var r=card.getBoundingClientRect();var ph=document.createElement("li");ph.className="qph";ph.style.height=r.height+"px";qlist.insertBefore(ph,card);card.classList.add("dragging");card.style.width=r.width+"px";card.style.left=r.left+"px";card.style.top=r.top+"px";drag={card:card,ph:ph,y0:e.clientY,y:e.clientY,id:e.pointerId,list:qlist,raf:0};try{h.setPointerCapture(e.pointerId);}catch(_){}requestAnimationFrame(dragFrame);}}}});
869
+ qlist.addEventListener("pointerdown",function(e){var t=e.target;if(!t||!t.closest)return;var h=t.closest(".qhandle");if(h&&!drag){var card=t.closest(".qcard");if(card){e.preventDefault();dragging=true;var r=card.getBoundingClientRect();var ph=document.createElement("li");ph.className="qph";ph.style.height=r.height+"px";qlist.insertBefore(ph,card);card.classList.add("dragging");card.style.width=r.width+"px";card.style.left=r.left+"px";card.style.top=r.top+"px";drag={card:card,ph:ph,y0:e.clientY,y:e.clientY,id:e.pointerId,list:qlist,raf:0};try{h.setPointerCapture(e.pointerId);}catch(_){}requestAnimationFrame(dragFrame);}}});
870
870
  }
871
871
  }
872
872
  function busy(){if(dragging)return true;var els=document.querySelectorAll("input:not([type=hidden]), textarea");for(var k=0;k<els.length;k++){if(els[k]===document.activeElement||els[k].value)return true;}return false;}
@@ -0,0 +1,155 @@
1
+ // Provider out-until state (plan 20261025_1700 P1): who is rate-limited comes from live data,
2
+ // recorded by code from the provider's own words, never typed from memory. The state is an
3
+ // append-only JSONL file under <paths.queue_state>/provider-out.jsonl, one
4
+ // {provider, until, at, source} object per line; the newest record per provider wins. Decisions
5
+ // read it (agent-ledger --cap, the guards, the score gate); recordings come from
6
+ // `quota-reset --provider`, from task results that quote a reset time, and from rate-limited
7
+ // turn ends (the adapter wires those; this file stays harness-free).
8
+
9
+ import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import type { Config } from "./config.ts";
12
+ import { nowSec, strftime } from "./clock.ts";
13
+ import { parseWhen, wallToEpoch } from "./reset-time.ts";
14
+
15
+ /** One recorded out-until: `until`/`at` are epoch seconds. */
16
+ export interface OutRecord {
17
+ provider: string;
18
+ until: number;
19
+ at: number;
20
+ source: string;
21
+ }
22
+
23
+ export function outFile(cfg: Config): string {
24
+ return join(cfg.paths.queue_state, "provider-out.jsonl");
25
+ }
26
+
27
+ /** Every parseable record, oldest first; unparseable lines are skipped, never thrown. */
28
+ export function readOut(cfg: Config): OutRecord[] {
29
+ let text: string;
30
+ try {
31
+ text = readFileSync(outFile(cfg), "utf8");
32
+ } catch {
33
+ return [];
34
+ }
35
+ const out: OutRecord[] = [];
36
+ for (const line of text.split("\n")) {
37
+ if (!line.trim()) continue;
38
+ try {
39
+ const r = JSON.parse(line) as Partial<OutRecord>;
40
+ if (typeof r.provider === "string" && typeof r.until === "number" && Number.isFinite(r.until)
41
+ && typeof r.at === "number" && Number.isFinite(r.at) && typeof r.source === "string") {
42
+ out.push({ provider: r.provider, until: r.until, at: r.at, source: r.source });
43
+ }
44
+ } catch {}
45
+ }
46
+ return out;
47
+ }
48
+
49
+ /** Append one record. A failed write is swallowed like the other guard state files. */
50
+ export function recordOut(cfg: Config, provider: string, untilEpoch: number, source: string, at: number = Math.floor(Date.now() / 1000)): void {
51
+ try {
52
+ mkdirSync(cfg.paths.queue_state, { recursive: true });
53
+ appendFileSync(outFile(cfg), `${JSON.stringify({ provider, until: untilEpoch, at, source })}\n`);
54
+ } catch {}
55
+ }
56
+
57
+ /**
58
+ * The provider's active out-until (epoch seconds), or null when it is free: the newest record's
59
+ * until while it is still in the future, else null — absence of a record is free too, because
60
+ * this file is the only source that may claim a limit.
61
+ */
62
+ export function outUntil(cfg: Config, provider: string, now: number = nowSec()): number | null {
63
+ let until: number | null = null;
64
+ for (const r of readOut(cfg)) {
65
+ if (r.provider !== provider) continue;
66
+ until = r.until;
67
+ }
68
+ return until !== null && until > now ? until : null;
69
+ }
70
+
71
+ export interface ProviderOut {
72
+ provider: string;
73
+ /** Epoch seconds while out, null when free. */
74
+ until: number | null;
75
+ }
76
+
77
+ /** Per recorded provider (configured order first, then the rest as first recorded): free or out. */
78
+ export function providerStatus(cfg: Config, now: number = nowSec()): ProviderOut[] {
79
+ const records = readOut(cfg);
80
+ const seen: string[] = [];
81
+ for (const p of cfg.ledger.providers) {
82
+ if (records.some(r => r.provider === p) && !seen.includes(p)) seen.push(p);
83
+ }
84
+ for (const r of records) {
85
+ if (!seen.includes(r.provider)) seen.push(r.provider);
86
+ }
87
+ return seen.map(provider => ({ provider, until: outUntil(cfg, provider, now) }));
88
+ }
89
+
90
+ /**
91
+ * The one `providers:` line for Main's decision points (agent-ledger --cap, main-start): each
92
+ * recorded provider `free` or `out until <local HH:MM>`, configured order first. Null when
93
+ * nothing is recorded — an empty line would invite guessing, the incident's exact mistake.
94
+ */
95
+ export function providersLine(cfg: Config, now: number = nowSec()): string | null {
96
+ const status = providerStatus(cfg, now);
97
+ if (status.length === 0) return null;
98
+ const parts = status.map(s => (s.until === null ? `${s.provider} free` : `${s.provider} out until ${strftime(s.until, "%H:%M")}`));
99
+ return `providers: ${parts.join(" · ")}`;
100
+ }
101
+
102
+ /** The provider half of a `provider/model` pin, or null when the model names no provider. */
103
+ export function providerOfModel(model: string | null): string | null {
104
+ if (!model || !model.includes("/")) return null;
105
+ const provider = model.split("/")[0] ?? "";
106
+ return provider === "" ? null : provider;
107
+ }
108
+
109
+ /**
110
+ * The `model:` line of an agent's pin frontmatter (the shipped pin template's format, the same
111
+ * one the session reader resolves a run's model from), or null when the pin is missing or silent.
112
+ */
113
+ export function pinModel(cfg: Config, agent: string): string | null {
114
+ if (!cfg.adapter?.pins || agent === "") return null;
115
+ let text: string;
116
+ try {
117
+ text = readFileSync(join(cfg.adapter.pins, `${agent}.md`), "utf8");
118
+ } catch {
119
+ return null;
120
+ }
121
+ const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
122
+ return /^model:\s*(\S+)/m.exec(fm?.[1] ?? "")?.[1] ?? null;
123
+ }
124
+
125
+ /**
126
+ * The first reset time a text names, as epoch seconds, or null when it names none we can trust.
127
+ * Reuses parseWhen/wallToEpoch: the wall time comes from capture group 1, the zone from group 2
128
+ * when the text names one (Z/UTC/GMT, ±HH:MM) and `rule.zone` otherwise. reset-time.ts cannot
129
+ * grow an export for this (the plan freezes that file), so the ±HH:MM arithmetic sits here.
130
+ */
131
+ export function resetEpochFromText(text: string, rule: { pattern: string; zone: string }): number | null {
132
+ let pattern: RegExp;
133
+ try {
134
+ pattern = new RegExp(rule.pattern);
135
+ } catch {
136
+ return null;
137
+ }
138
+ const m = pattern.exec(text);
139
+ if (!m) return null;
140
+ const wall = m[1] ? parseWhen(m[1]) : null;
141
+ if (!wall) return null;
142
+ const zone = (m[2] ?? "").trim();
143
+ try {
144
+ if (!zone || zone === rule.zone) return wallToEpoch(wall, rule.zone);
145
+ if (zone === "Z" || zone === "UTC" || zone === "GMT") return wallToEpoch(wall, "UTC");
146
+ const offset = /^([+-])(\d{2}):?(\d{2})$/.exec(zone);
147
+ if (offset) {
148
+ const minutes = (Number(offset[2]) * 60 + Number(offset[3])) * (offset[1] === "+" ? 1 : -1);
149
+ return Math.floor((Date.UTC(wall.y, wall.mo - 1, wall.d, wall.h, wall.mi, wall.s) - minutes * 60_000) / 1000);
150
+ }
151
+ return wallToEpoch(wall, zone);
152
+ } catch {
153
+ return null;
154
+ }
155
+ }
@@ -14,6 +14,10 @@ function agentDir(): string {
14
14
  export function indexPath(): string {
15
15
  return process.env.QUEUE_INDEX ?? `${agentDir()}/INDEX.md`;
16
16
  }
17
+ /** FINISHED.md sits beside the main index: one short entry per closed plan. */
18
+ export function finishedPath(): string {
19
+ return path.join(path.dirname(indexPath()), "FINISHED.md");
20
+ }
17
21
  export function blockersDirPath(): string {
18
22
  return process.env.QUEUE_BLOCKERS ?? `${agentDir()}/blockers`;
19
23
  }
@@ -121,6 +125,14 @@ export function outsideProgress(text: string): string {
121
125
  export function progressBody(text: string): string {
122
126
  return sections(text).get("progress") ?? "";
123
127
  }
128
+ /** Last real Progress bullet, collapsed to one line. Main-only lines and the archive pointer are not entries. */
129
+ export function lastProgressLine(text: string): string {
130
+ let last = "";
131
+ for (const line of progressBody(text).split("\n")) {
132
+ if (/^\s*-\s+/.test(line) && !line.startsWith(POINTER_PREFIX)) last = line.replace(/^\s*-\s+/, "");
133
+ }
134
+ return last.replace(/\s+/g, " ").trim();
135
+ }
124
136
 
125
137
  export type ProgressTrim = { body: string; moved: string; count: number };
126
138
 
@@ -791,6 +803,35 @@ export function cancelledLine(file: string, text: string, date: string): string
791
803
  const owner = (progressBody(text).match(/^Cancelled by owner:\s*(.+?)\s*$/m)?.[1] ?? "").replace(/\|/g, "/");
792
804
  return `- ${path.basename(file)} | ${date} | owner: ${owner} | words: ${planWords(text).join(" ")}`;
793
805
  }
806
+ const FINISHED_HEADER = "# Finished plans (newest first; written by queue-close and queue-finished)\n";
807
+
808
+ /** Heading plus at most 4 body lines: Summary, Result, Plan path. */
809
+ export function finishedEntry(plan: Plan, archived: string, date: string): string {
810
+ const summary = (plan.summary ?? plan.goal[0] ?? "").replace(/\s+/g, " ").trim();
811
+ const result = lastProgressLine(plan.text);
812
+ const body = [`Summary: ${summary}`, `Result: ${result}`, `Plan: ${path.resolve(archived)}`];
813
+ return [`## ${date} · ${path.basename(plan.repo)} · ${plan.title}`, ...body].join("\n");
814
+ }
815
+
816
+ /** Inserts the entry above older ones. Returns false when that Plan path is already listed. */
817
+ export function prependFinished(entry: string, file = finishedPath()): boolean {
818
+ const planLine = entry.split("\n").find(l => l.startsWith("Plan: "));
819
+ let current = "";
820
+ try {
821
+ current = readFileSync(file, "utf8");
822
+ } catch {}
823
+ if (planLine && current.split("\n").includes(planLine)) return false;
824
+ mkdirSync(path.dirname(file), { recursive: true });
825
+ const block = entry.endsWith("\n") ? entry : `${entry}\n`;
826
+ if (!current.trim()) {
827
+ writeFileSync(file, `${FINISHED_HEADER}\n${block}`);
828
+ return true;
829
+ }
830
+ const at = current.search(/^## /m);
831
+ const next = at < 0 ? `${current.replace(/\s*$/, "\n\n")}${block}` : `${current.slice(0, at)}${block}\n${current.slice(at)}`;
832
+ writeFileSync(file, next);
833
+ return true;
834
+ }
794
835
  const slug = (name: string) => name.replace(/\.md$/, "").replace(/^\d{8}_\d{4}_/, "");
795
836
  export function cancelledMatches(plan: Plan): CancelledEntry[] {
796
837
  if (plan.status !== "open") return [];
@@ -798,7 +839,7 @@ export function cancelledMatches(plan: Plan): CancelledEntry[] {
798
839
  const name = path.basename(plan.file);
799
840
  return [...readCancelled(plan.repo), ...readGlobalCancelled()].filter(c => {
800
841
  const cleared = plan.text.split("\n").some(l => {
801
- const m = l.match(/^\s*(?:[-*]\s+)?False positive:\s*`?(\S+?)`?\s*[—:–-]+\s*(.+)$/);
842
+ const m = l.match(/^\s*(?:[-*]\s+)?False positive:\s*`?([^\s`]+)`?\s+[—:–-]+\s*(.+)$/);
802
843
  return m && m[1] === c.name && (m[2] ?? "").trim().length >= 15;
803
844
  });
804
845
  if (cleared || c.name === name) return false;
@@ -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, INDEX, readIndex, sha, STATE_DIR } from "./queue/lib.ts";
7
+ import { activePlans, cancelledFile, cancelledLine, closeLog, finishedEntry, finishedPath, INDEX, prependFinished, readIndex, 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 {
@@ -277,6 +277,11 @@ export function queueClose(args: string[], cfg: Config): number {
277
277
  renameSync(file, dest);
278
278
  console.log(`queue-close: plan moved to ${dest}`);
279
279
  }
280
+ if (!cancelling) {
281
+ const listed = finishedPath();
282
+ const added = prependFinished(finishedEntry(plan, dest, today));
283
+ console.log(added ? `queue-close: recorded in ${listed}` : `queue-close: already in ${listed}`);
284
+ }
280
285
 
281
286
  // One index: the closed plan's line leaves the main index; there is no repo INDEX.md.
282
287
  const lines = readFileSync(INDEX, "utf8").split("\n").filter(l => l.trim());
@@ -0,0 +1,126 @@
1
+ // queue-finished: fill and search FINISHED.md. Backfill reads archived plans; a word prints matches.
2
+
3
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
4
+ import path from "node:path";
5
+ import type { Config } from "./config.ts";
6
+ import { applyQueueEnv } from "./queue/env.ts";
7
+ import { finishedEntry, finishedPath, parsePlan, planRepo, prependFinished } from "./queue/lib.ts";
8
+
9
+ const USAGE = "usage: queue-finished --backfill | queue-finished <word>";
10
+
11
+ function walkMd(dir: string, out: string[]): void {
12
+ let names: string[];
13
+ try {
14
+ names = readdirSync(dir);
15
+ } catch {
16
+ return;
17
+ }
18
+ for (const name of names) {
19
+ const file = path.join(dir, name);
20
+ let st: ReturnType<typeof statSync> | null = null;
21
+ try {
22
+ st = statSync(file);
23
+ } catch {
24
+ continue;
25
+ }
26
+ if (st.isDirectory()) walkMd(file, out);
27
+ else if (name.endsWith(".md")) out.push(file);
28
+ }
29
+ }
30
+
31
+ /** Repos named by work_roots, plus one level of children so a root that holds many checkouts still counts. */
32
+ function repoRoots(roots: string[]): string[] {
33
+ const out: string[] = [];
34
+ for (const root of roots) {
35
+ if (!existsSync(root)) continue;
36
+ out.push(root);
37
+ let names: string[] = [];
38
+ try {
39
+ names = readdirSync(root);
40
+ } catch {
41
+ continue;
42
+ }
43
+ for (const name of names) {
44
+ if (name.startsWith(".")) continue;
45
+ const child = path.join(root, name);
46
+ try {
47
+ if (statSync(child).isDirectory()) out.push(child);
48
+ } catch {}
49
+ }
50
+ }
51
+ return out;
52
+ }
53
+
54
+ function stampDate(file: string): string {
55
+ const stamp = /^(\d{4})(\d{2})(\d{2})_/.exec(path.basename(file));
56
+ if (stamp) return `${stamp[1]}-${stamp[2]}-${stamp[3]}`;
57
+ try {
58
+ return new Date(statSync(file).mtimeMs).toISOString().slice(0, 10);
59
+ } catch {
60
+ return new Date().toISOString().slice(0, 10);
61
+ }
62
+ }
63
+
64
+ function archivedPlans(roots: string[]): string[] {
65
+ const files: string[] = [];
66
+ for (const repo of repoRoots(roots)) walkMd(path.join(repo, "docs/plans/archive"), files);
67
+ return files;
68
+ }
69
+
70
+ function backfill(cfg: Config): number {
71
+ const files = archivedPlans(cfg.paths.work_roots);
72
+ const plans = files
73
+ .map(file => {
74
+ let raw = "";
75
+ try {
76
+ raw = readFileSync(file, "utf8");
77
+ } catch {
78
+ return null;
79
+ }
80
+ const plan = parsePlan(planRepo(file), file, raw);
81
+ return plan.status === "complete" ? plan : null;
82
+ })
83
+ .filter(p => p !== null)
84
+ .sort((a, b) => (path.basename(a.file) < path.basename(b.file) ? -1 : 1));
85
+ let added = 0;
86
+ // Oldest first so each prepend leaves the newer entry on top.
87
+ for (const plan of plans) {
88
+ if (prependFinished(finishedEntry(plan, plan.file, stampDate(plan.file)))) added++;
89
+ }
90
+ console.log(`queue-finished: backfill added ${added} (${plans.length} complete archived)`);
91
+ return 0;
92
+ }
93
+
94
+ function entries(text: string): string[] {
95
+ return text.split(/^(?=## )/m).filter(p => p.startsWith("## ")).map(p => p.trimEnd());
96
+ }
97
+
98
+ function search(word: string): number {
99
+ let text = "";
100
+ try {
101
+ text = readFileSync(finishedPath(), "utf8");
102
+ } catch {}
103
+ const needle = word.toLowerCase();
104
+ const hits = entries(text).filter(e => e.toLowerCase().includes(needle));
105
+ if (!hits.length) {
106
+ console.error(`queue-finished: no entry matches ${word}`);
107
+ return 1;
108
+ }
109
+ console.log(hits.join("\n\n"));
110
+ return 0;
111
+ }
112
+
113
+ export function queueFinished(args: string[], cfg: Config): number {
114
+ applyQueueEnv(cfg);
115
+ if (args[0] === "--help" || args[0] === "-h") {
116
+ console.log(USAGE);
117
+ return 0;
118
+ }
119
+ if (args.includes("--backfill")) return backfill(cfg);
120
+ const word = args.filter(a => !a.startsWith("-")).join(" ").trim();
121
+ if (!word) {
122
+ console.error(USAGE);
123
+ return 2;
124
+ }
125
+ return search(word);
126
+ }
@@ -1,12 +1,14 @@
1
1
  import type { Config } from "./config.ts";
2
+ import { recordOut } from "./provider-state.ts";
2
3
  import { localStamp, parseWhen, wallToEpoch } from "./reset-time.ts";
3
4
 
4
5
  const USAGE =
5
- 'usage: quota-reset "YYYY-MM-DD HH:MM[:SS]" [--tz <zone>] (reset time from your provider\'s rate-limit message)\n';
6
+ 'usage: quota-reset "YYYY-MM-DD HH:MM[:SS]" [--tz <zone>] [--provider <name>] (reset time from your provider\'s rate-limit message; --provider records it)\n';
6
7
 
7
8
 
8
9
  export function quotaReset(args: string[], cfg: Config): number {
9
10
  let zone = cfg.quota.reset_tz;
11
+ let provider: string | null = null;
10
12
  const words: string[] = [];
11
13
  for (let i = 0; i < args.length; i++) {
12
14
  const arg = args[i] ?? "";
@@ -18,6 +20,14 @@ export function quotaReset(args: string[], cfg: Config): number {
18
20
  }
19
21
  zone = value;
20
22
  i++;
23
+ } else if (arg === "--provider") {
24
+ const value = args[i + 1];
25
+ if (value === undefined) {
26
+ process.stderr.write(USAGE);
27
+ return 2;
28
+ }
29
+ provider = value;
30
+ i++;
21
31
  } else {
22
32
  words.push(arg);
23
33
  }
@@ -48,5 +58,13 @@ export function quotaReset(args: string[], cfg: Config): number {
48
58
  const d = epoch - now;
49
59
  console.log(`${label} reset (local): ${local} — in ${Math.floor(d / 3600)}h ${Math.floor((d % 3600) / 60)}m`);
50
60
  }
61
+ if (provider !== null) {
62
+ if (!cfg.ledger.providers.includes(provider)) {
63
+ process.stderr.write(`quota-reset: unknown provider "${provider}" (ledger.providers: ${cfg.ledger.providers.join(", ")})\n`);
64
+ return 1;
65
+ }
66
+ recordOut(cfg, provider, epoch, "quota-reset");
67
+ console.log(`recorded: ${provider} out until ${local} (local) — agent-ledger --cap and the guards read it back`);
68
+ }
51
69
  return 0;
52
70
  }
@@ -119,6 +119,7 @@ export function noteRequest(path: string, auto = false, reason = ""): string {
119
119
  : `${NOTE_REQUEST_PREFIX} this session has grown past rollover.max_session_mb.`,
120
120
  `Write a handoff note to ${path} (overwrite it). Cover the work in progress and its state, the decisions made and why, the next step, and the files involved.`,
121
121
  "Do not list holds or owner blockers in the note; they come from the plans' WAITING on owner lines.",
122
+ "Do not state which agents or providers are rate-limited or free; that comes from agent-ledger --cap.",
122
123
  auto
123
124
  ? "As soon as this note is written and no own jobs run, this session restarts into a fresh one that starts from this note verbatim plus the generated main-start state."
124
125
  : "When the owner's next message arrives, this session closes and a fresh one starts from that note verbatim plus the generated main-start state.",
@@ -3,6 +3,8 @@
3
3
  You are Main, the orchestrator. Main plans, delegates, reviews and lands; implementers do the work.
4
4
 
5
5
  ## Plans
6
+ - Code is a burden: every line we add must be maintained forever, so it must justify its keep. Before adding a file, function, option or dependency, say in one sentence why existing code cannot do it; no sentence → don't add it. Main is the judge: in review, code that cannot justify its keep is deleted, and dead code found anywhere is removed.
7
+ - Tests cost tokens and time: if the repo's CI runs a suite on the MR (e.g. a witnessed end-to-end job), never run that suite locally. Run only the targeted tests for the changed code locally; the MR pipeline is the proof, and Main reads its result.
6
8
  - When the owner asks for work in a repo, write the plan to `<main checkout>/docs/plans/` and list its absolute path in the one index `{{AGENT_DIR}}/INDEX.md` (one plan file per line, never a repo directory). One plan = one worktree: the plan's Worktree line names a worktree no other open plan names.
7
9
  - INDEX.md order is priority: free agents go to the top plans first. A lower plan goes first only when the higher one says `Waits on: <plan>`, is WAITING on owner, or the brief quotes the owner: `Priority skip: <plan> — owner: "<his words>"`.
8
10
  - A hold is one line: `WAITING on owner: <what to do> — blocked: <what stays stuck until then> — why you: <why Main cannot do it>`. The phone page shows those three parts; a missing part is left out.
@@ -10,6 +12,7 @@ You are Main, the orchestrator. Main plans, delegates, reviews and lands; implem
10
12
  - Main writes every plan in `<repo>/docs/plans/`, shaped like `{{AGENT_DIR}}/queue/TEMPLATE.md`. Do the research yourself; never base a plan on another agent's findings.
11
13
  - Phase 0 of every plan: blocker scripts that stop the implementer from going against the plan. They must exist before any spawn.
12
14
  - An open plan gets an implementer subagent. When it claims done, verify (another subagent or yourself). Not done → spawn another implementer for the rest. Done → set `Status: complete`; `queue-close` then archives it and cleans the indexes.
15
+ - Owner asks about a past plan → grep FINISHED.md first; open the archived plan only for details.
13
16
  - An implementer's new `## Progress` entry ends with a `Findings:` line — `Findings: none`, or one item per finding with `file:line` evidence; plan-guard restores an entry without it, and each item becomes an incident.
14
17
  - Main may push and publish once the repo's AGENTS.md test rules are met.
15
18
 
@@ -18,6 +21,7 @@ You are Main, the orchestrator. Main plans, delegates, reviews and lands; implem
18
21
  |---|---|
19
22
  |`main-start`|session start, after an abort, before every status report; prints the MR sweep (open forge MRs vs open plans)|
20
23
  |`queue-check`|after changing a plan or an index, before every spawn; exit 1 = fix first; also fails when a reachable forge lists an open MR no open plan mentions (`MR !N: ignored <reason>` in a plan marks it tracked)|
24
+ |`queue-finished`|owner asks about a past plan (`<word>` prints matching FINISHED.md entries; `--backfill` fills it from archived plans)|
21
25
  |`agent-ledger --cap`|before every spawn|
22
26
  |`agent-score`|`gate <agent>` before every spawn; `accept`/`diagnose`/`penalty` after reviewing a result; `check` after every merge; `board` after a score change|
23
27
  |`brief-lint <plan.md>`|before every spawn on that plan|
@@ -45,6 +45,10 @@ ledger:
45
45
  idle_not_live_min: 60
46
46
  max_running_per_provider: 2
47
47
  max_slots: 2
48
+ # The owner's pick order (plan 20261025_1700 P3): agent names, first = preferred; empty = off.
49
+ # The spawn gates refuse a later agent while an earlier one is free and under its provider cap
50
+ # unless the brief carries "Pick note: <why>"; agent-score gate ranks inside this order.
51
+ prefer: []
48
52
  providers:
49
53
  - zai
50
54
  - openai-codex