neurastream 0.1.23 → 0.1.25

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.
Files changed (57) hide show
  1. package/README.md +7 -3
  2. package/package.json +2 -3
  3. package/src/adapters/omp/doctor.ts +6 -2
  4. package/src/adapters/omp/index.ts +3 -3
  5. package/src/cli/commands.ts +4 -8
  6. package/src/cli/dispatch.ts +56 -3
  7. package/src/cli/init.ts +34 -14
  8. package/src/core/agents-md.ts +17 -0
  9. package/src/core/brief-lint.ts +9 -34
  10. package/src/core/config.ts +40 -2
  11. package/src/core/file-lock.ts +89 -0
  12. package/src/core/guards.ts +22 -6
  13. package/src/core/heavy-run.ts +37 -29
  14. package/src/core/host.ts +19 -0
  15. package/src/core/machine-guard.ts +5 -2
  16. package/src/core/main-start.ts +4 -1
  17. package/src/core/queue/lib.ts +21 -1
  18. package/src/core/queue-close.ts +5 -3
  19. package/src/core/quota-reset.ts +112 -0
  20. package/src/core/subagents.ts +83 -0
  21. package/src/core/tmp-snapshot.ts +26 -14
  22. package/src/core/uninstall.ts +228 -0
  23. package/templates/agents/example.md +32 -0
  24. package/templates/config.yml +27 -27
  25. package/templates/help/agent-score.txt +2 -2
  26. package/templates/help/brief-lint.txt +1 -1
  27. package/templates/help/uninstall.txt +14 -0
  28. package/templates/help/wip-backup.txt +14 -8
  29. package/templates/help/wip-check.txt +1 -1
  30. package/templates/help/wip-snapshot.txt +3 -2
  31. package/templates/machine-guard.sh +57 -16
  32. package/templates/notes/subagents.md +1 -11
  33. package/templates/queue/TEMPLATE.md +1 -1
  34. package/templates/tmp-snapshot.sh +21 -12
  35. package/bin/pm-fail-facts +0 -6
  36. package/src/adapters/omp/herdr-agent-state.ts +0 -440
  37. package/src/core/glm-reset.ts +0 -32
  38. package/src/core/pm-fail-facts.ts +0 -116
  39. package/templates/agents/apodex.md +0 -6
  40. package/templates/agents/bunny-user.md +0 -13
  41. package/templates/agents/bunny.md +0 -213
  42. package/templates/agents/composer.md +0 -9
  43. package/templates/agents/deepseek.md +0 -214
  44. package/templates/agents/gemini.md +0 -213
  45. package/templates/agents/glm.md +0 -214
  46. package/templates/agents/grok.md +0 -213
  47. package/templates/agents/haiku.md +0 -213
  48. package/templates/agents/hiko.md +0 -213
  49. package/templates/agents/ling.md +0 -213
  50. package/templates/agents/local-qwen.md +0 -220
  51. package/templates/agents/luna-medium.md +0 -211
  52. package/templates/agents/luna.md +0 -224
  53. package/templates/agents/muse.md +0 -214
  54. package/templates/agents/sol-xhigh.md +0 -217
  55. package/templates/agents/sol.md +0 -217
  56. package/templates/help/pm-fail-facts.txt +0 -6
  57. /package/bin/{glm-reset → quota-reset} +0 -0
@@ -6,7 +6,7 @@
6
6
  // Callers must first map config into the queue paths (applyQueueEnv): the queue library resolves
7
7
  // INDEX.md, blockers, state, subagents, cancelled and unlock from those env vars.
8
8
  //
9
- // Ported rules (owner 2026-10-15..17):
9
+ // Ported rules:
10
10
  // - protected guard files, unlockable by the owner for `guards.unlock_minutes`
11
11
  // - subs: no queue-close/queue-cancel, call budget 90/100, plan edits only inside "## Progress",
12
12
  // blocker execution, invalid plans refuse
@@ -15,7 +15,7 @@
15
15
  // through the same plan gate, cancel-pending blocks spawns and stops, keep-working stop rule
16
16
  // - incidents: while an incident is open (src/core/incidents.ts: no plan/dismiss/fixed record)
17
17
  // every Main prompt lists it, a spawn must be fix work (its plan cites `INCIDENT <id>`), and
18
- // the stop is refused; an incident with a plan no longer blocks (owner 2026-10-22)
18
+ // the stop is refused; an incident with a plan no longer blocks
19
19
 
20
20
  import { execFileSync } from "node:child_process";
21
21
  import { appendFileSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
@@ -39,7 +39,7 @@ export function log(file: string, line: string): void {
39
39
  } catch {}
40
40
  }
41
41
 
42
- // Owner message that may call work off (owner 2026-10-16: "don't do X" must hold even if no plan
42
+ // Owner message that may call work off ("don't do X" must hold even if no plan
43
43
  // exists yet). Flagged until Main records it with queue-cancel; no spawn and no stop until then.
44
44
  export const CANCEL_TODO =
45
45
  'the owner\'s message may call work off. Record it first: an indexed plan → `queue-cancel <plan> "<owner words>"`; ' +
@@ -146,7 +146,7 @@ function protectedHit(paths: string[], cfg: Config): string | null {
146
146
  return null;
147
147
  }
148
148
 
149
- // Text files never count (owner 2026-10-15: "only ... anything apart from .md or .txt").
149
+ // Text files never count: only files apart from .md or .txt do.
150
150
  function freeExt(cfg: Config): RegExp {
151
151
  return new RegExp(cfg.guards.free_ext, "i");
152
152
  }
@@ -265,10 +265,26 @@ function runBlockers(plan: Plan, hit: string[], e: ToolEvent, cfg: Config): stri
265
265
  return null;
266
266
  }
267
267
 
268
+ // Words a shell line may put before the tool: launchers, shells with -c, VAR=value, and a script path ending in main.ts.
269
+ const LAUNCHERS: Record<string, true> = { bun: true, run: true, neurastream: true, node: true, npx: true, bunx: true, env: true, sudo: true, nohup: true, exec: true, bash: true, sh: true, zsh: true, "-c": true };
270
+
271
+ // True when a command segment runs queue-close or queue-cancel: the tool is the segment's first word after launchers.
272
+ // Segments also split at $( and backticks, so substitutions and `sh -c "..."` bodies are checked too.
273
+ function runsCloser(input: Record<string, unknown>): boolean {
274
+ const text = Object.values(input).filter((v): v is string => typeof v === "string").join("\n");
275
+ return text.split(/&&|\|\||;|\||\n|\$\(|`/).some(seg => {
276
+ const words = seg.trim().split(/\s+/).filter(Boolean).map(w => w.replace(/^["'(]+|["')]+$/g, ""));
277
+ let i = 0;
278
+ while (i < words.length && (LAUNCHERS[words[i] ?? ""] === true || /^\w+=/.test(words[i] ?? "") || /(^|\/)main\.ts$/.test(words[i] ?? ""))) i++;
279
+ const cmd = (words[i] ?? "").split("/").pop() ?? "";
280
+ return /^queue-(close|cancel)$/.test(cmd);
281
+ });
282
+ }
283
+
268
284
  // Subagent half of a tool call (the original plan-guard checkCall without the main return).
269
285
  function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[], writes: string[], cfg: Config): string | null {
270
- // Closing and cancelling are Main's decisions (owner 2026-10-15/16).
271
- if (cfg.guards.shell_tools.includes(e.tool) && /\bqueue-(?:close|cancel)\b/.test(JSON.stringify(input)))
286
+ // Closing and cancelling are Main's decisions: a shell that runs the tool is refused; one that only names its path is not.
287
+ if (cfg.guards.shell_tools.includes(e.tool) && runsCloser(input))
272
288
  return 'queue-close and queue-cancel are Main\'s; report in your plan\'s "## Progress" instead.';
273
289
  const plans = q.activePlans();
274
290
  if (e.calls >= cfg.guards.sub_max_calls) {
@@ -1,26 +1,36 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { appendFileSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import type { Config } from "./config.ts";
4
+ import { type HeldLock, isBusy, lock, tryLock } from "./file-lock.ts";
4
5
 
5
- function flock(lock: string, opts: string[], cmd: string): boolean {
6
- const r = spawnSync("flock", [...opts, lock, cmd], { encoding: "utf8" });
7
- return r.status === 0;
6
+ // The original cats the owner file with 2>/dev/null: missing/unreadable is just an empty name.
7
+ function ownerName(owner: string): string {
8
+ try {
9
+ return readFileSync(owner, "utf8").trimEnd();
10
+ } catch {
11
+ return "";
12
+ }
13
+ }
14
+
15
+ // Takes the lock, waiting if another heavy-run holds it. null when the wait fails.
16
+ function acquire(lockPath: string, owner: string): HeldLock | null {
17
+ const held = tryLock(lockPath);
18
+ if (held) return held;
19
+ process.stderr.write(`[heavy-run] waiting — busy: ${ownerName(owner)}\n`);
20
+ try {
21
+ return lock(lockPath);
22
+ } catch {
23
+ return null;
24
+ }
8
25
  }
9
26
 
10
27
  export function heavyRun(args: string[], cfg: Config): number {
11
- const lock = cfg.paths.heavy_lock;
28
+ const lockPath = cfg.paths.heavy_lock;
12
29
  const owner = cfg.paths.heavy_owner;
13
30
  const log = cfg.paths.heavy_log;
14
31
  if (args[0] === "--status") {
15
- // The original cats the owner file with 2>/dev/null: missing/unreadable is just an empty name.
16
- if (flock(lock, ["-n"], "true")) console.log("free");
17
- else {
18
- let name = "";
19
- try {
20
- name = readFileSync(owner, "utf8").trimEnd();
21
- } catch {}
22
- console.log(`busy: ${name}`);
23
- }
32
+ if (isBusy(lockPath)) console.log(`busy: ${ownerName(owner)}`);
33
+ else console.log("free");
24
34
  return 0;
25
35
  }
26
36
  if (args.length < 4 || args[2] !== "--") {
@@ -30,21 +40,19 @@ export function heavyRun(args: string[], cfg: Config): number {
30
40
  const who = args[0]!;
31
41
  const what = args[1]!;
32
42
  const cmdArgs = args.slice(3);
33
- if (!flock(lock, ["-n"], "true")) {
34
- let name = "";
35
- try {
36
- name = readFileSync(owner, "utf8").trimEnd();
37
- } catch {}
38
- process.stderr.write(`[heavy-run] waiting — busy: ${name}\n`);
39
- if (!flock(lock, [], "true")) return 1;
43
+ const held = acquire(lockPath, owner);
44
+ if (!held) return 1;
45
+ try {
46
+ const stamp = spawnSync("date", ["+%F %T"], { encoding: "utf8" }).stdout?.trim() ?? "";
47
+ writeFileSync(owner, `${who} | ${what} | since ${stamp} | pid ${process.pid}\n`);
48
+ appendFileSync(log, `${stamp} START ${who} | ${what}\n`);
49
+ const r = spawnSync(cmdArgs[0]!, cmdArgs.slice(1), { stdio: "inherit" });
50
+ const rc = r.status ?? 1;
51
+ const end = spawnSync("date", ["+%F %T"], { encoding: "utf8" }).stdout?.trim() ?? "";
52
+ appendFileSync(log, `${end} END ${who} | ${what} | exit ${rc}\n`);
53
+ writeFileSync(owner, "");
54
+ return rc;
55
+ } finally {
56
+ held.release();
40
57
  }
41
- const stamp = spawnSync("date", ["+%F %T"], { encoding: "utf8" }).stdout?.trim() ?? "";
42
- writeFileSync(owner, `${who} | ${what} | since ${stamp} | pid ${process.pid}\n`);
43
- appendFileSync(log, `${stamp} START ${who} | ${what}\n`);
44
- const r = spawnSync(cmdArgs[0]!, cmdArgs.slice(1), { stdio: "inherit" });
45
- const rc = r.status ?? 1;
46
- const end = spawnSync("date", ["+%F %T"], { encoding: "utf8" }).stdout?.trim() ?? "";
47
- appendFileSync(log, `${end} END ${who} | ${what} | exit ${rc}\n`);
48
- writeFileSync(owner, "");
49
- return rc;
50
58
  }
@@ -0,0 +1,19 @@
1
+ // Host probes that differ by OS: the load line and the CPU count. Plain TypeScript, no harness names.
2
+
3
+ import { existsSync, readFileSync } from "node:fs";
4
+ import { availableParallelism, loadavg } from "node:os";
5
+
6
+ const PROC_LOADAVG = "/proc/loadavg";
7
+
8
+ /** The load averages as one line: the /proc/loadavg text where it exists, else the three os.loadavg() values. */
9
+ export function loadavgLine(): string {
10
+ if (existsSync(PROC_LOADAVG)) return readFileSync(PROC_LOADAVG, "utf8").trim();
11
+ return loadavg()
12
+ .map((v) => v.toFixed(2))
13
+ .join(" ");
14
+ }
15
+
16
+ /** Logical CPUs this process may use. */
17
+ export function cpuCount(): number {
18
+ return availableParallelism();
19
+ }
@@ -2,14 +2,16 @@ import { dirname, join } from "node:path";
2
2
  import { fileURLToPath } from "node:url";
3
3
  import { spawnSync } from "node:child_process";
4
4
  import type { Config } from "./config.ts";
5
+ import { cpuCount } from "./host.ts";
5
6
 
6
7
  const SCRIPT = join(dirname(fileURLToPath(import.meta.url)), "../../templates/machine-guard.sh");
7
8
 
8
9
  function envFor(cfg: Config): NodeJS.ProcessEnv {
9
- const cores = Number(spawnSync("nproc", [], { encoding: "utf8" }).stdout?.trim() || "1");
10
+ const cores = cpuCount();
10
11
  const loadMax = cfg.machine.load_max > 0 ? cfg.machine.load_max : cores + cfg.machine.load_over_cores;
11
12
  return {
12
13
  ...process.env,
14
+ CORES: String(cores),
13
15
  LOAD_MAX: String(loadMax),
14
16
  AVAIL_MIN_MB: String(cfg.machine.avail_min_mb),
15
17
  DISK_MIN_GB: String(cfg.machine.disk_min_gb),
@@ -19,7 +21,8 @@ function envFor(cfg: Config): NodeJS.ProcessEnv {
19
21
  HEAVY_LOCK: cfg.paths.heavy_lock,
20
22
  HEAVY_OWNER: cfg.paths.heavy_owner,
21
23
  HEAVY_IDLE_STATE: cfg.paths.heavy_idle_state,
22
- HEAVY_RUN: cfg.brief.heavy_path,
24
+ HEAVY_STATUS: process.execPath,
25
+ HEAVY_MAIN: join(dirname(fileURLToPath(import.meta.url)), "../cli/main.ts"),
23
26
  DISK_PATH: cfg.machine.disk_path,
24
27
  WORK_ROOT: cfg.paths.work_roots[0] ?? join(cfg.paths.home, "Work"),
25
28
  WATCH_SEC: String(cfg.machine.watch_sec),
@@ -11,6 +11,7 @@ import { addIncident, type IncidentView } from "./incidents.ts";
11
11
  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
+ import { loadavgLine } from "./host.ts";
14
15
 
15
16
  function bin(name: string, cfg: Config): string {
16
17
  return join(cfg.paths.home, ".local/bin", name);
@@ -83,6 +84,8 @@ export async function mainStartText(args: string[], cfg: Config, opts: { inherit
83
84
  const out: string[] = [];
84
85
  const say = (line: string) => out.push(`${line}\n`);
85
86
  runMainStartDetectors(cfg, deps);
87
+ // Config notices (legacy keys renamed or removed by loadConfig): one line each, above the sections.
88
+ for (const n of cfg.notices) say(`notice: ${n}`);
86
89
  const h = args[0] ?? String(cfg.health.default_hours);
87
90
  const childStdin = opts.inheritStdin ? "inherit" : "ignore";
88
91
  const childStderr = opts.inheritStdin ? "inherit" : "pipe";
@@ -111,7 +114,7 @@ export async function mainStartText(args: string[], cfg: Config, opts: { inherit
111
114
  const mg = await run(bin("machine-guard", cfg), [], { stderr: "ignore" });
112
115
  const mgLines = mg.stdout.trim().split("\n");
113
116
  say(mgLines.at(-1) ?? "");
114
- say(readFileSync("/proc/loadavg", "utf8").trim());
117
+ say(loadavgLine());
115
118
  say("");
116
119
  say(`=== agents (last ${h}h; DIED = check its worktree, relaunch FRESH with its progress file)`);
117
120
  const ledger = await run(bin("agent-ledger", cfg), ["--hours", h], { stderr: "ignore" });
@@ -433,6 +433,24 @@ function withoutHeredocBodies(code: string): string {
433
433
  return keep.join("\n");
434
434
  }
435
435
 
436
+ // `neurastream agents allow|deny` and `neurastream init --allow` edit the subagent allow-list,
437
+ // a protected guard file, so they count as writes to it (also when run as `bun .../src/cli/main.ts`).
438
+ function subagentsOpWrites(code: string): boolean {
439
+ for (const seg of code.split(/&&|\|\||;|\n|\|/)) {
440
+ const toks = seg.trim().split(/\s+/).filter(Boolean);
441
+ let i = 0;
442
+ while (i < toks.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(toks[i] ?? "")) i++;
443
+ const cmd = (toks[i] ?? "").replace(/^["']|["']$/g, "").replace(/^.*\//, "");
444
+ const rest = toks.slice(i + 1).map(t => t.replace(/^["']+|["']+$/g, ""));
445
+ const off = cmd === "neurastream" ? 0 : cmd === "bun" && (rest[0] ?? "").endsWith("src/cli/main.ts") ? 1 : -1;
446
+ if (off < 0) continue;
447
+ const sub = rest[off] ?? "";
448
+ if (sub === "agents" && ["allow", "deny"].includes(rest[off + 1] ?? "")) return true;
449
+ if (sub === "init" && rest.some(t => t === "--allow" || t.startsWith("--allow="))) return true;
450
+ }
451
+ return false;
452
+ }
453
+
436
454
  export function writeTargets(toolName: string, input: Record<string, unknown>, cwd: string): string[] {
437
455
  const out = new Set<string>();
438
456
  const add = (raw: string, from: string) => {
@@ -464,7 +482,8 @@ export function writeTargets(toolName: string, input: Record<string, unknown>, c
464
482
  // A package/plugin/cutover command is a write even though none of the
465
483
  // generic mutating heuristics fire on its text.
466
484
  const pkgOp = packageOpTarget(code);
467
- if (!MUTATING.test(code) && !pkgOp) return [];
485
+ const subOp = subagentsOpWrites(code);
486
+ if (!MUTATING.test(code) && !pkgOp && !subOp) return [];
468
487
  let dir = typeof input?.cwd === "string" ? path.resolve(cwd, expandHome(input.cwd)) : cwd;
469
488
  for (const seg of withoutHeredocBodies(code).split(/&&|\|\||;|\n|\|/)) {
470
489
  const s = seg.trim();
@@ -499,6 +518,7 @@ export function writeTargets(toolName: string, input: Record<string, unknown>, c
499
518
  ])
500
519
  for (const m of code.matchAll(re)) add((m[1] ?? "").replace(/`/g, ""), dir);
501
520
  if (pkgOp) out.add(pkgOp);
521
+ if (subOp) out.add(subagentsPath());
502
522
  return [...out];
503
523
  }
504
524
 
@@ -1,5 +1,5 @@
1
1
  import { spawnSync } from "node:child_process";
2
- import { appendFileSync, existsSync, fstatSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { appendFileSync, existsSync, fstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import type { Config } from "./config.ts";
@@ -115,10 +115,12 @@ export function queueClose(args: string[], cfg: Config): number {
115
115
  git(plan.repo, "fetch", "-q", "origin");
116
116
  const head = git(plan.repo, "symbolic-ref", "-q", "refs/remotes/origin/HEAD");
117
117
  const base = upstreamBase(plan.repo, head.ok ? head.out : "refs/remotes/origin/main");
118
+ // git reports worktree paths through symlinks resolved (macOS: /tmp -> /private/tmp); match resolved paths on both sides.
119
+ const real = (p: string): string => { try { return realpathSync(p); } catch { return path.resolve(p); } };
118
120
  const worktrees = (): { path: string; branch: string | null; head: string }[] => {
119
121
  const list: { path: string; branch: string | null; head: string }[] = [];
120
122
  for (const line of git(plan.repo, "worktree", "list", "--porcelain").out.split("\n")) {
121
- if (line.startsWith("worktree ")) list.push({ path: path.resolve(line.slice(9)), branch: null, head: "" });
123
+ if (line.startsWith("worktree ")) list.push({ path: real(line.slice(9)), branch: null, head: "" });
122
124
  const cur = list.at(-1);
123
125
  if (!cur) continue;
124
126
  if (line.startsWith("HEAD ")) cur.head = line.slice(5);
@@ -126,7 +128,7 @@ export function queueClose(args: string[], cfg: Config): number {
126
128
  }
127
129
  return list;
128
130
  };
129
- const wtEntry = plan.worktree ? worktrees().find(w => w.path === path.resolve(plan.worktree!)) : undefined;
131
+ const wtEntry = plan.worktree ? worktrees().find(w => w.path === real(plan.worktree!)) : undefined;
130
132
  const wtExists = !!plan.worktree && existsSync(plan.worktree);
131
133
  // A plan worktree is the plan's only while it sits on the plan's branch (or a detached HEAD already merged into it).
132
134
  const owned = wtExists && !!plan.branch && !!wtEntry && (wtEntry.branch !== null
@@ -0,0 +1,112 @@
1
+ import type { Config } from "./config.ts";
2
+
3
+ // Converts a provider's rate-limit reset time (wall clock in the provider's zone) into the caller's
4
+ // local time. Intl does the zone math, so this needs no GNU date and behaves the same on macOS.
5
+
6
+ const USAGE =
7
+ 'usage: quota-reset "YYYY-MM-DD HH:MM[:SS]" [--tz <zone>] (reset time from your provider\'s rate-limit message)\n';
8
+
9
+ // Offset in ms of `zone` from UTC at the instant `epochMs` (local wall clock minus UTC).
10
+ function zoneOffsetMs(epochMs: number, zone: string): number {
11
+ const parts = new Intl.DateTimeFormat("en-US", {
12
+ timeZone: zone,
13
+ hourCycle: "h23",
14
+ year: "numeric",
15
+ month: "numeric",
16
+ day: "numeric",
17
+ hour: "numeric",
18
+ minute: "numeric",
19
+ second: "numeric",
20
+ }).formatToParts(new Date(epochMs));
21
+ const get = (type: string): number => Number(parts.find((p) => p.type === type)?.value);
22
+ const wallAsUtc = Date.UTC(get("year"), get("month") - 1, get("day"), get("hour"), get("minute"), get("second"));
23
+ return wallAsUtc - Math.floor(epochMs / 1000) * 1000;
24
+ }
25
+
26
+ // Epoch seconds for a wall-clock time in `zone`; two passes settle the DST edge.
27
+ function wallToEpoch(wall: { y: number; mo: number; d: number; h: number; mi: number; s: number }, zone: string): number {
28
+ const wallUtc = Date.UTC(wall.y, wall.mo - 1, wall.d, wall.h, wall.mi, wall.s);
29
+ const first = wallUtc - zoneOffsetMs(wallUtc, zone);
30
+ const second = wallUtc - zoneOffsetMs(first, zone);
31
+ return Math.floor(second / 1000);
32
+ }
33
+
34
+ const WHEN = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2}))?$/;
35
+
36
+ function parseWhen(text: string): { y: number; mo: number; d: number; h: number; mi: number; s: number } | null {
37
+ const m = WHEN.exec(text.trim());
38
+ if (!m) return null;
39
+ const [, ys = "", mos = "", ds = "", hs = "", mis = "", ss = ""] = m;
40
+ const wall = { y: +ys, mo: +mos, d: +ds, h: +hs, mi: +mis, s: ss ? +ss : 0 };
41
+ const check = new Date(Date.UTC(wall.y, wall.mo - 1, wall.d, wall.h, wall.mi, wall.s));
42
+ const valid =
43
+ check.getUTCFullYear() === wall.y &&
44
+ check.getUTCMonth() === wall.mo - 1 &&
45
+ check.getUTCDate() === wall.d &&
46
+ check.getUTCHours() === wall.h &&
47
+ check.getUTCMinutes() === wall.mi &&
48
+ check.getUTCSeconds() === wall.s;
49
+ return valid ? wall : null;
50
+ }
51
+
52
+ // Local wall clock of the process, "YYYY-MM-DD HH:MM:SS ZONE".
53
+ function localStamp(epoch: number): string {
54
+ const parts = new Intl.DateTimeFormat("en-US", {
55
+ hourCycle: "h23",
56
+ year: "numeric",
57
+ month: "2-digit",
58
+ day: "2-digit",
59
+ hour: "2-digit",
60
+ minute: "2-digit",
61
+ second: "2-digit",
62
+ timeZoneName: "short",
63
+ }).formatToParts(new Date(epoch * 1000));
64
+ const get = (type: string): string => parts.find((p) => p.type === type)?.value ?? "";
65
+ return `${get("year")}-${get("month")}-${get("day")} ${get("hour")}:${get("minute")}:${get("second")} ${get("timeZoneName")}`;
66
+ }
67
+
68
+ export function quotaReset(args: string[], cfg: Config): number {
69
+ let zone = cfg.quota.reset_tz;
70
+ const words: string[] = [];
71
+ for (let i = 0; i < args.length; i++) {
72
+ const arg = args[i] ?? "";
73
+ if (arg === "--tz") {
74
+ const value = args[i + 1];
75
+ if (value === undefined) {
76
+ process.stderr.write(USAGE);
77
+ return 2;
78
+ }
79
+ zone = value;
80
+ i++;
81
+ } else {
82
+ words.push(arg);
83
+ }
84
+ }
85
+ if (words.length < 1) {
86
+ process.stderr.write(USAGE);
87
+ return 2;
88
+ }
89
+ const when = words.join(" ");
90
+ const wall = parseWhen(when);
91
+ if (!wall) {
92
+ process.stderr.write(`quota-reset: cannot parse "${when}" as YYYY-MM-DD HH:MM[:SS]\n`);
93
+ return 1;
94
+ }
95
+ let epoch: number;
96
+ try {
97
+ epoch = wallToEpoch(wall, zone);
98
+ } catch {
99
+ process.stderr.write(`quota-reset: unknown time zone "${zone}"\n`);
100
+ return 1;
101
+ }
102
+ const now = Math.floor(Date.now() / 1000);
103
+ const local = localStamp(epoch);
104
+ const label = cfg.quota.label;
105
+ if (epoch <= now) {
106
+ console.log(`${label} reset (local): ${local} — ALREADY BACK (${Math.floor((now - epoch) / 60)} min ago). Use ${label} now.`);
107
+ } else {
108
+ const d = epoch - now;
109
+ console.log(`${label} reset (local): ${local} — in ${Math.floor(d / 3600)}h ${Math.floor((d % 3600) / 60)}m`);
110
+ }
111
+ return 0;
112
+ }
@@ -0,0 +1,83 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { allowedAgents } from "./queue/lib.ts";
4
+
5
+ const TEMPLATE = join(import.meta.dir, "../../templates/notes/subagents.md");
6
+ const SLUG = /^[a-z0-9-]+$/;
7
+ const ALLOWED_HEAD = /^## allowed\s*$/i;
8
+ const BULLET = /^\s*[-*]\s+`([a-z0-9-]+)`/;
9
+
10
+ /** A slug that is not a valid allow-list entry. The CLI maps it to exit 2. */
11
+ export class InvalidSlugError extends Error {}
12
+
13
+ /** Slugs that are not valid allow-list entries. */
14
+ export function invalidSlugs(slugs: string[]): string[] {
15
+ return slugs.filter(s => !SLUG.test(s));
16
+ }
17
+
18
+ /** Index of the `## Allowed` heading and of the line that ends its section. */
19
+ function allowedSection(lines: string[]): { head: number; end: number } | null {
20
+ const head = lines.findIndex(l => ALLOWED_HEAD.test(l));
21
+ if (head === -1) return null;
22
+ let end = lines.findIndex((l, i) => i > head && /^## /.test(l));
23
+ if (end === -1) end = lines.length;
24
+ return { head, end };
25
+ }
26
+
27
+ /**
28
+ * Append `- \`slug\`` bullets at the end of the `## Allowed` section. Creates the file from the
29
+ * template and the section when missing. Slugs already listed are skipped. Every other line is
30
+ * left as it was.
31
+ */
32
+ export function allowAgents(file: string, slugs: string[]): { added: string[]; kept: string[] } {
33
+ const bad = invalidSlugs(slugs);
34
+ if (bad.length) throw new InvalidSlugError(`invalid slug: ${bad.join(", ")} (use a-z, 0-9 and -)`);
35
+ const wanted = [...new Set(slugs)];
36
+ const present = existsSync(file);
37
+ const listed = present ? allowedAgents(file) : new Set<string>();
38
+ const added = wanted.filter(s => !listed.has(s));
39
+ const kept = wanted.filter(s => listed.has(s));
40
+ if (present && added.length === 0) return { added, kept };
41
+
42
+ const text = present ? readFileSync(file, "utf8") : readFileSync(TEMPLATE, "utf8");
43
+ const bullets = added.map(s => `- \`${s}\``);
44
+ const lines = text.split("\n");
45
+ const sec = allowedSection(lines);
46
+ let next: string;
47
+ if (!sec) {
48
+ const base = text === "" || text.endsWith("\n") ? text : `${text}\n`;
49
+ next = `${base}\n## Allowed\n\n${bullets.join("\n")}\n`;
50
+ } else {
51
+ let last = sec.head;
52
+ for (let i = sec.head + 1; i < sec.end; i++) if ((lines[i] ?? "").trim() !== "") last = i;
53
+ const insert = last === sec.head ? ["", ...bullets] : bullets;
54
+ lines.splice(last + 1, 0, ...insert);
55
+ next = lines.join("\n");
56
+ }
57
+ mkdirSync(dirname(file), { recursive: true });
58
+ writeFileSync(file, next);
59
+ return { added, kept };
60
+ }
61
+
62
+ /** Remove the bullet lines for these slugs from the `## Allowed` section; nothing else changes. */
63
+ export function denyAgents(file: string, slugs: string[]): { removed: string[]; absent: string[] } {
64
+ const bad = invalidSlugs(slugs);
65
+ if (bad.length) throw new InvalidSlugError(`invalid slug: ${bad.join(", ")} (use a-z, 0-9 and -)`);
66
+ const wanted = [...new Set(slugs)];
67
+ if (!existsSync(file)) return { removed: [], absent: wanted };
68
+ const listed = allowedAgents(file);
69
+ const removed = wanted.filter(s => listed.has(s));
70
+ const absent = wanted.filter(s => !listed.has(s));
71
+ if (removed.length === 0) return { removed, absent };
72
+
73
+ const lines = readFileSync(file, "utf8").split("\n");
74
+ const sec = allowedSection(lines);
75
+ if (!sec) return { removed, absent };
76
+ const kept = lines.filter((l, i) => {
77
+ if (i <= sec.head || i >= sec.end) return true;
78
+ const m = BULLET.exec(l);
79
+ return !(m && removed.includes(m[1] ?? ""));
80
+ });
81
+ writeFileSync(file, kept.join("\n"));
82
+ return { removed, absent };
83
+ }
@@ -1,23 +1,35 @@
1
+ import { mkdirSync } from "node:fs";
1
2
  import { dirname, join } from "node:path";
2
3
  import { fileURLToPath } from "node:url";
3
4
  import { spawnSync } from "node:child_process";
4
5
  import type { Config } from "./config.ts";
6
+ import { tryLock } from "./file-lock.ts";
5
7
 
6
8
  const SCRIPT = join(dirname(fileURLToPath(import.meta.url)), "../../templates/tmp-snapshot.sh");
7
9
 
8
10
  export function tmpSnapshot(_args: string[], cfg: Config): number {
9
- const r = spawnSync("bash", [SCRIPT], {
10
- env: {
11
- ...process.env,
12
- SNAP_DEST: cfg.snapshot.tmp_dest,
13
- SNAP_GIT_REPO: cfg.snapshot.git_repo,
14
- SNAP_GIT_BACKUP: cfg.snapshot.git_backup,
15
- SNAP_LOCK: cfg.paths.snapshot_lock,
16
- SNAP_EXCLUDES: cfg.snapshot.excludes.join(" "),
17
- },
18
- encoding: "utf8",
19
- });
20
- if (r.stdout) process.stdout.write(r.stdout);
21
- if (r.stderr) process.stderr.write(r.stderr);
22
- return r.status ?? 0;
11
+ const lockPath = cfg.paths.snapshot_lock;
12
+ mkdirSync(dirname(lockPath), { recursive: true });
13
+ const held = tryLock(lockPath);
14
+ if (!held) {
15
+ console.log("snapshot already running");
16
+ return 0;
17
+ }
18
+ try {
19
+ const r = spawnSync("bash", [SCRIPT], {
20
+ env: {
21
+ ...process.env,
22
+ SNAP_DEST: cfg.snapshot.tmp_dest,
23
+ SNAP_GIT_REPO: cfg.snapshot.git_repo,
24
+ SNAP_GIT_BACKUP: cfg.snapshot.git_backup,
25
+ SNAP_EXCLUDES: cfg.snapshot.excludes.join(" "),
26
+ },
27
+ encoding: "utf8",
28
+ });
29
+ if (r.stdout) process.stdout.write(r.stdout);
30
+ if (r.stderr) process.stderr.write(r.stderr);
31
+ return r.status ?? 0;
32
+ } finally {
33
+ held.release();
34
+ }
23
35
  }