neurastream 0.1.24 → 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.
@@ -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
  }
@@ -50,14 +50,14 @@ ledger:
50
50
  - opencode-zen
51
51
 
52
52
  brief:
53
- method_marker: "opus-implementer-method.md"
54
- heavy_marker: "heavy-run.sh"
53
+ method_marker: "" # empty = no method read required
54
+ heavy_marker: "heavy-run"
55
55
  max_keys: 10
56
56
  warn_chars: 12000
57
57
  aim_chars: 8000
58
58
  path_prefixes: ["$HOME/"]
59
- method_read: "$HOME/projects/opus-implementer-method.md"
60
- heavy_path: "$HOME/.local/bin/heavy-run.sh"
59
+ method_read: ""
60
+ heavy_path: "heavy-run"
61
61
  repo_rules: [] # optional repo-specific lint rules; each fires when `match` (regex, whole brief) hits and the body lacks `require`:
62
62
  # - match: 'legacy-api' # trigger anywhere in the brief (case-insensitive)
63
63
  # first: 'Refactor' # optional: also require this on the title line
@@ -82,11 +82,6 @@ wip:
82
82
  status_log: "~/.local/state/neurastream/WIP-STATUS.md"
83
83
  secret_file: '(?i)(^|/)(\.env(\.(?!example$|sample$|template$|dist$)[\w-]+)?|[^/]*\.env|env\.json|[^/]*\.(pem|p12|pfx|jks|keystore|key)|id_(rsa|dsa|ecdsa|ed25519)|credentials(\.json)?|\.netrc|\.pgpass|\.htpasswd|local-run\.env)$'
84
84
 
85
- pm:
86
- backend_log: "" # your backend service log; pm-fail-facts reads it for errors ("" = only explicit --backend-log runs)
87
- fail_lines: 25
88
- backend_error: 'Traceback|ERROR|CRITICAL|Exception| 5\d\d '
89
-
90
85
  health:
91
86
  warn_ctx: 150000
92
87
  tail_calls: 50
@@ -155,9 +150,9 @@ machine:
155
150
  watch_sec: 60
156
151
  watch_streak: 3
157
152
 
158
- glm:
153
+ quota:
159
154
  reset_tz: "Asia/Shanghai"
160
- label: "GLM"
155
+ label: "quota"
161
156
 
162
157
  priority:
163
158
  sleep_sec: 120
@@ -1,4 +1,4 @@
1
- agent-score: rank subagent workers by CORRECT work per dollar and per hour (owner 2026-10-16, AGENTS.md line 16).
1
+ agent-score: rank subagent workers by CORRECT work per dollar and per hour.
2
2
 
3
3
  Points come only from work Main accepted, weighted by the plan phase's `difficulty: N` (set at plan time).
4
4
  Cost = the worker's own list cost + Main's steering cost (Main tokens spent on turns that mention the agent).
@@ -1,5 +1,5 @@
1
1
  brief-lint: refuse a subagent brief that misses a rule Main keeps forgetting.
2
2
 
3
- Owner 2026-10-11: what can be checked deterministically is checked by a script, not by memory.
3
+ What can be checked deterministically is checked by a script, not by memory.
4
4
  Run on every brief file BEFORE spawning; exit 1 = fix the brief first.
5
5
  Usage: brief-lint <brief.md> [<brief.md> ...]
@@ -1,4 +1,4 @@
1
- wip-check: unlanded work across Main's repos (owner 2026-10-11: land before starting new work).
1
+ wip-check: unlanded work across Main's repos (land before starting new work).
2
2
 
3
3
  Lists every local branch with commits on no remote, and every worktree with uncommitted changes.
4
4
  Exit 1 when unlanded branches exceed WIP_LIMIT (default 6) so the number cannot be ignored.
@@ -1,6 +1,6 @@
1
1
  wip-snapshot: save every uncommitted change in every worktree as a hidden git commit.
2
2
 
3
- Owner 2026-10-11: "how are you ensuring unfinished work is at least committed?"
3
+ Goal: unfinished work is at least committed.
4
4
  For each worktree under ROOTS with tracked changes or new (non-ignored) files, build a commit
5
5
  from a TEMPORARY index (parent = HEAD) and store it at refs/wip/<worktree>/<stamp>.
6
6
  The working tree, the real index, HEAD and every branch stay untouched, so it is safe while