neurastream 0.1.24 → 0.1.26
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 +4 -1
- package/package.json +2 -3
- package/src/adapters/omp/doctor.ts +6 -2
- package/src/adapters/omp/index.ts +3 -3
- package/src/cli/commands.ts +4 -8
- package/src/cli/dispatch.ts +50 -3
- package/src/cli/init.ts +34 -10
- package/src/core/brief-lint.ts +3 -16
- package/src/core/config.ts +24 -2
- package/src/core/file-lock.ts +89 -0
- package/src/core/guards.ts +22 -6
- package/src/core/heavy-run.ts +37 -29
- package/src/core/host.ts +19 -0
- package/src/core/incidents.ts +14 -1
- package/src/core/machine-guard.ts +5 -2
- package/src/core/main-start.ts +4 -1
- package/src/core/queue/lib.ts +21 -1
- package/src/core/queue-close.ts +5 -3
- package/src/core/quota-reset.ts +127 -0
- package/src/core/subagents.ts +83 -0
- package/src/core/tmp-snapshot.ts +26 -14
- package/templates/config.yml +6 -11
- package/templates/help/agent-score.txt +1 -1
- package/templates/help/brief-lint.txt +1 -1
- package/templates/help/wip-check.txt +1 -1
- package/templates/help/wip-snapshot.txt +1 -1
- package/templates/machine-guard.sh +57 -16
- package/templates/tmp-snapshot.sh +13 -7
- package/bin/pm-fail-facts +0 -6
- package/src/adapters/omp/herdr-agent-state.ts +0 -440
- package/src/core/glm-reset.ts +0 -32
- package/src/core/pm-fail-facts.ts +0 -116
- package/templates/help/pm-fail-facts.txt +0 -6
- /package/bin/{glm-reset → quota-reset} +0 -0
package/src/core/heavy-run.ts
CHANGED
|
@@ -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
|
-
|
|
6
|
-
|
|
7
|
-
|
|
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
|
|
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
|
-
|
|
16
|
-
|
|
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
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
|
|
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
|
}
|
package/src/core/host.ts
ADDED
|
@@ -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
|
+
}
|
package/src/core/incidents.ts
CHANGED
|
@@ -168,6 +168,18 @@ export function addIncident(cfg: Config, input: IncidentInput, now = nowSec()):
|
|
|
168
168
|
return { incident: { ...rec, resolution: null }, deduped: false };
|
|
169
169
|
}
|
|
170
170
|
|
|
171
|
+
/**
|
|
172
|
+
* The repo a plan belongs to: the nearest directory from the plan's folder upward that holds the
|
|
173
|
+
* repo INDEX.md. Plans live at any depth under the repo (docs/plans/immediate/…), so a fixed
|
|
174
|
+
* number of dirname steps lands short of the root.
|
|
175
|
+
*/
|
|
176
|
+
function repoForPlan(abs: string): string | null {
|
|
177
|
+
for (let dir = dirname(abs); ; dir = dirname(dir)) {
|
|
178
|
+
if (existsSync(join(dir, q.REPO_INDEX))) return dir;
|
|
179
|
+
if (dirname(dir) === dir) return null;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
171
183
|
/**
|
|
172
184
|
* Records the plan that fixes an incident: refused unless the file exists, is listed in its repo
|
|
173
185
|
* INDEX.md, and contains `INCIDENT <id>` (the spawn gates look for that text). Returns the
|
|
@@ -181,7 +193,8 @@ export function planIncident(cfg: Config, id: string, planPath: string): string
|
|
|
181
193
|
if (res) return `incident ${id} already has a ${res.type} record`;
|
|
182
194
|
const abs = resolve(q.expandHome(planPath));
|
|
183
195
|
if (!existsSync(abs)) return `plan file not found: ${abs}`;
|
|
184
|
-
const repo =
|
|
196
|
+
const repo = repoForPlan(abs);
|
|
197
|
+
if (!repo) return `${abs} is not under a directory holding ${q.REPO_INDEX}`;
|
|
185
198
|
if (!q.readRepoIndex(repo).includes(abs)) return `${abs} is not listed in ${join(repo, q.REPO_INDEX)}`;
|
|
186
199
|
let text: string;
|
|
187
200
|
try {
|
|
@@ -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 =
|
|
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
|
-
|
|
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),
|
package/src/core/main-start.ts
CHANGED
|
@@ -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(
|
|
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" });
|
package/src/core/queue/lib.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
|
package/src/core/queue-close.ts
CHANGED
|
@@ -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:
|
|
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 ===
|
|
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,127 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import type { Config } from "./config.ts";
|
|
3
|
+
|
|
4
|
+
// Converts a provider's rate-limit reset time (wall clock in the provider's zone) into the caller's
|
|
5
|
+
// local time. Intl does the zone math; date(1) supplies the local zone abbreviation, because Intl's
|
|
6
|
+
// short timeZoneName is a tzdata abbreviation only for US zones (Europe/Berlin prints "GMT+2" where
|
|
7
|
+
// date +%Z prints "CEST"). macOS's BSD date is used there, so no GNU date is needed.
|
|
8
|
+
|
|
9
|
+
const USAGE =
|
|
10
|
+
'usage: quota-reset "YYYY-MM-DD HH:MM[:SS]" [--tz <zone>] (reset time from your provider\'s rate-limit message)\n';
|
|
11
|
+
|
|
12
|
+
// Offset in ms of `zone` from UTC at the instant `epochMs` (local wall clock minus UTC).
|
|
13
|
+
function zoneOffsetMs(epochMs: number, zone: string): number {
|
|
14
|
+
const parts = new Intl.DateTimeFormat("en-US", {
|
|
15
|
+
timeZone: zone,
|
|
16
|
+
hourCycle: "h23",
|
|
17
|
+
year: "numeric",
|
|
18
|
+
month: "numeric",
|
|
19
|
+
day: "numeric",
|
|
20
|
+
hour: "numeric",
|
|
21
|
+
minute: "numeric",
|
|
22
|
+
second: "numeric",
|
|
23
|
+
}).formatToParts(new Date(epochMs));
|
|
24
|
+
const get = (type: string): number => Number(parts.find((p) => p.type === type)?.value);
|
|
25
|
+
const wallAsUtc = Date.UTC(get("year"), get("month") - 1, get("day"), get("hour"), get("minute"), get("second"));
|
|
26
|
+
return wallAsUtc - Math.floor(epochMs / 1000) * 1000;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Epoch seconds for a wall-clock time in `zone`; two passes settle the DST edge.
|
|
30
|
+
function wallToEpoch(wall: { y: number; mo: number; d: number; h: number; mi: number; s: number }, zone: string): number {
|
|
31
|
+
const wallUtc = Date.UTC(wall.y, wall.mo - 1, wall.d, wall.h, wall.mi, wall.s);
|
|
32
|
+
const first = wallUtc - zoneOffsetMs(wallUtc, zone);
|
|
33
|
+
const second = wallUtc - zoneOffsetMs(first, zone);
|
|
34
|
+
return Math.floor(second / 1000);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const WHEN = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2}))?$/;
|
|
38
|
+
|
|
39
|
+
function parseWhen(text: string): { y: number; mo: number; d: number; h: number; mi: number; s: number } | null {
|
|
40
|
+
const m = WHEN.exec(text.trim());
|
|
41
|
+
if (!m) return null;
|
|
42
|
+
const [, ys = "", mos = "", ds = "", hs = "", mis = "", ss = ""] = m;
|
|
43
|
+
const wall = { y: +ys, mo: +mos, d: +ds, h: +hs, mi: +mis, s: ss ? +ss : 0 };
|
|
44
|
+
const check = new Date(Date.UTC(wall.y, wall.mo - 1, wall.d, wall.h, wall.mi, wall.s));
|
|
45
|
+
const valid =
|
|
46
|
+
check.getUTCFullYear() === wall.y &&
|
|
47
|
+
check.getUTCMonth() === wall.mo - 1 &&
|
|
48
|
+
check.getUTCDate() === wall.d &&
|
|
49
|
+
check.getUTCHours() === wall.h &&
|
|
50
|
+
check.getUTCMinutes() === wall.mi &&
|
|
51
|
+
check.getUTCSeconds() === wall.s;
|
|
52
|
+
return valid ? wall : null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// The tzdata abbreviation for this instant (CEST, CET, CST, +05) as date(1) prints it in the zone
|
|
56
|
+
// env this process runs in (the child inherits it, so the abbreviation always matches the wall
|
|
57
|
+
// clock next to it). Falls back to the Intl short name only when date fails.
|
|
58
|
+
function zoneAbbrev(epoch: number): string {
|
|
59
|
+
const probe =
|
|
60
|
+
process.platform === "darwin"
|
|
61
|
+
? spawnSync("date", ["-r", String(epoch), "+%Z"], { encoding: "utf8" })
|
|
62
|
+
: spawnSync("date", ["-d", `@${epoch}`, "+%Z"], { encoding: "utf8" });
|
|
63
|
+
if (probe.status === 0 && probe.stdout?.trim()) return probe.stdout.trim();
|
|
64
|
+
const parts = new Intl.DateTimeFormat("en-US", { timeZoneName: "short" }).formatToParts(new Date(epoch * 1000));
|
|
65
|
+
return parts.find(p => p.type === "timeZoneName")?.value ?? "";
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Local wall clock of the process, "YYYY-MM-DD HH:MM:SS ZONE".
|
|
69
|
+
function localStamp(epoch: number): string {
|
|
70
|
+
const parts = new Intl.DateTimeFormat("en-US", {
|
|
71
|
+
hourCycle: "h23",
|
|
72
|
+
year: "numeric",
|
|
73
|
+
month: "2-digit",
|
|
74
|
+
day: "2-digit",
|
|
75
|
+
hour: "2-digit",
|
|
76
|
+
minute: "2-digit",
|
|
77
|
+
second: "2-digit",
|
|
78
|
+
}).formatToParts(new Date(epoch * 1000));
|
|
79
|
+
const get = (type: string): string => parts.find(p => p.type === type)?.value ?? "";
|
|
80
|
+
return `${get("year")}-${get("month")}-${get("day")} ${get("hour")}:${get("minute")}:${get("second")} ${zoneAbbrev(epoch)}`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function quotaReset(args: string[], cfg: Config): number {
|
|
84
|
+
let zone = cfg.quota.reset_tz;
|
|
85
|
+
const words: string[] = [];
|
|
86
|
+
for (let i = 0; i < args.length; i++) {
|
|
87
|
+
const arg = args[i] ?? "";
|
|
88
|
+
if (arg === "--tz") {
|
|
89
|
+
const value = args[i + 1];
|
|
90
|
+
if (value === undefined) {
|
|
91
|
+
process.stderr.write(USAGE);
|
|
92
|
+
return 2;
|
|
93
|
+
}
|
|
94
|
+
zone = value;
|
|
95
|
+
i++;
|
|
96
|
+
} else {
|
|
97
|
+
words.push(arg);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
if (words.length < 1) {
|
|
101
|
+
process.stderr.write(USAGE);
|
|
102
|
+
return 2;
|
|
103
|
+
}
|
|
104
|
+
const when = words.join(" ");
|
|
105
|
+
const wall = parseWhen(when);
|
|
106
|
+
if (!wall) {
|
|
107
|
+
process.stderr.write(`quota-reset: cannot parse "${when}" as YYYY-MM-DD HH:MM[:SS]\n`);
|
|
108
|
+
return 1;
|
|
109
|
+
}
|
|
110
|
+
let epoch: number;
|
|
111
|
+
try {
|
|
112
|
+
epoch = wallToEpoch(wall, zone);
|
|
113
|
+
} catch {
|
|
114
|
+
process.stderr.write(`quota-reset: unknown time zone "${zone}"\n`);
|
|
115
|
+
return 1;
|
|
116
|
+
}
|
|
117
|
+
const now = Math.floor(Date.now() / 1000);
|
|
118
|
+
const local = localStamp(epoch);
|
|
119
|
+
const label = cfg.quota.label;
|
|
120
|
+
if (epoch <= now) {
|
|
121
|
+
console.log(`${label} reset (local): ${local} — ALREADY BACK (${Math.floor((now - epoch) / 60)} min ago). Use ${label} now.`);
|
|
122
|
+
} else {
|
|
123
|
+
const d = epoch - now;
|
|
124
|
+
console.log(`${label} reset (local): ${local} — in ${Math.floor(d / 3600)}h ${Math.floor((d % 3600) / 60)}m`);
|
|
125
|
+
}
|
|
126
|
+
return 0;
|
|
127
|
+
}
|
|
@@ -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
|
+
}
|
package/src/core/tmp-snapshot.ts
CHANGED
|
@@ -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
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
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
|
}
|
package/templates/config.yml
CHANGED
|
@@ -50,14 +50,14 @@ ledger:
|
|
|
50
50
|
- opencode-zen
|
|
51
51
|
|
|
52
52
|
brief:
|
|
53
|
-
method_marker: "
|
|
54
|
-
heavy_marker: "heavy-run
|
|
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: "
|
|
60
|
-
heavy_path: "
|
|
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
|
-
|
|
153
|
+
quota:
|
|
159
154
|
reset_tz: "Asia/Shanghai"
|
|
160
|
-
label: "
|
|
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
|
|
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
|
-
|
|
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 (
|
|
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
|
-
|
|
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
|