neurastream 0.2.68 → 0.2.70
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 +21 -0
- package/package.json +1 -1
- package/src/adapters/omp/doctor.ts +13 -0
- package/src/cli/dispatch.ts +5 -0
- package/src/cli/init.ts +6 -0
- package/src/cli/wip.ts +91 -0
- package/src/core/config.ts +14 -0
- package/src/core/guards.ts +21 -7
- package/src/core/main-start.ts +8 -0
- package/src/core/wip-alerts.ts +75 -0
- package/src/core/wip-backup.ts +65 -36
- package/src/core/wip-fail.ts +82 -0
- package/src/core/wip-private.ts +93 -0
- package/src/core/wip-restore.ts +101 -0
- package/src/core/wip-roots.ts +58 -0
- package/src/core/wip-setup.ts +197 -0
- package/src/core/wip-snapshot.ts +123 -52
- package/templates/AGENTS.md +2 -0
- package/templates/config.yml +6 -0
- package/templates/help/wip-backup.txt +3 -0
- package/templates/help/wip-snapshot.txt +2 -0
- package/templates/launchd/neurastream-wip-backup.plist +23 -0
- package/templates/launchd/neurastream-wip-snapshot.plist +18 -0
- package/templates/systemd/neurastream-wip-backup.service +6 -0
- package/templates/systemd/neurastream-wip-backup.timer +9 -0
- package/templates/systemd/neurastream-wip-snapshot.service +6 -0
- package/templates/systemd/neurastream-wip-snapshot.timer +10 -0
package/README.md
CHANGED
|
@@ -95,6 +95,27 @@ Every tool is one program, selected by the name it was called with: `agent-score
|
|
|
95
95
|
|
|
96
96
|
The first skill is `architecture-drilldown`: a self-contained HTML atlas with drill-down boxes. Its data is the `T` tree between `/* === DATA === */` and `/* === END DATA === */` in `template.html`; replace that block and leave the engine below it alone. `SKILL.md` lists the schema and the checks.
|
|
97
97
|
|
|
98
|
+
## Saving unsaved work (wip)
|
|
99
|
+
|
|
100
|
+
`neurastream wip on` turns the hourly safety net on: every hour each worktree with uncommitted
|
|
101
|
+
changes gets a hidden commit at `refs/wip/<key>/<stamp>` (working tree, index, HEAD and branches are
|
|
102
|
+
never touched), and the nightly backup sends those saves to one repo.
|
|
103
|
+
|
|
104
|
+
- Roots: `neurastream wip add <path>`, `wip remove <path>`, `wip list` - any number of folders, or a
|
|
105
|
+
single repo on its own; `.git` folders are found down to `wip.depth`. Every root is independent: a
|
|
106
|
+
corrupt or vanished repo is recorded in `WIP-STATUS.md` and `wip-last.json` and the run goes on.
|
|
107
|
+
- Private only: the target URL is checked before anything is uploaded - GitHub through `gh`, GitLab
|
|
108
|
+
through `glab`, any other host through `wip.private_check`. Only an exact `private` answer uploads;
|
|
109
|
+
`public`, `internal`, `unknown`, an error or bad JSON uploads nothing, is listed as refused and
|
|
110
|
+
alerts you. Making the repo private again resumes the backup.
|
|
111
|
+
- Hooks are never bypassed: a repo with a pre-push hook is skipped until `wip.backup_hook_off` names
|
|
112
|
+
it (a substring, or `owner` / `host/owner/repo` to name it exactly).
|
|
113
|
+
- Restore: `neurastream wip restore [--repo <path>] [--pick N]` lists a worktree's saves and puts one
|
|
114
|
+
back - files and index by default, `--worktree` for files only.
|
|
115
|
+
- Alerts: a failed run, a refused target or a run that never happened is posted once per state to
|
|
116
|
+
`cfg.wip.alert_url`, listed by `neurastream wip`, and reported by the heartbeat check.
|
|
117
|
+
- Off: `neurastream wip off` removes the hourly timer and the nightly backup timer.
|
|
118
|
+
|
|
98
119
|
## Develop
|
|
99
120
|
|
|
100
121
|
```sh
|
package/package.json
CHANGED
|
@@ -17,6 +17,7 @@ import { allowedAgents, readIndex, reviewAgentsProblem } from "../../core/queue/
|
|
|
17
17
|
import { systemRunner, type Runner } from "../../core/pages-setup.ts";
|
|
18
18
|
import { packageJsonPath } from "./package-root.ts";
|
|
19
19
|
import { realTailscale, type Tailscale } from "../../core/tailscale.ts";
|
|
20
|
+
import { wipHealth } from "../../core/wip-setup.ts";
|
|
20
21
|
|
|
21
22
|
const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
|
|
22
23
|
|
|
@@ -226,6 +227,18 @@ export function doctorReport(home: string, env: NodeJS.ProcessEnv = process.env,
|
|
|
226
227
|
if (!cfg.ui.owner_login) problems.push("ui.enabled but ui.owner_login is empty");
|
|
227
228
|
else if (state === "running") ok.push(`ui owner page: login ${cfg.ui.owner_login}`);
|
|
228
229
|
}
|
|
230
|
+
// WIP timers (plan 20261027_1130 P6): roots set with nothing scheduled is a silent stop, and so
|
|
231
|
+
// is a run that failed — the state that went unnoticed for a week before this plan.
|
|
232
|
+
if (cfg.wip.roots.length > 0) {
|
|
233
|
+
const health = wipHealth(cfg);
|
|
234
|
+
if (!health.installed) problems.push("wip: timers missing — run: neurastream wip on");
|
|
235
|
+
else {
|
|
236
|
+
ok.push(`wip: ${health.backupInstalled ? "snapshot + backup" : "snapshot only"}`);
|
|
237
|
+
for (const rec of [health.last.snapshot, health.last.backup]) {
|
|
238
|
+
if (rec && !rec.ok) problems.push(`wip: last ${rec.kind} run failed — ${rec.failed[0] ?? rec.refused ?? "see wip-last.json"}`);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
229
242
|
// One index (20261024_1400_one_index): repo-directory lines in the main index are the old
|
|
230
243
|
// two-level queue; the plans they hold are invisible to queue-check until migrate folds them.
|
|
231
244
|
const idx = cfg.paths.queue_index;
|
package/src/cli/dispatch.ts
CHANGED
|
@@ -26,6 +26,7 @@ import { runDiagram } from "./diagram.ts";
|
|
|
26
26
|
import { runNotes } from "./notes.ts";
|
|
27
27
|
import { runPages } from "./pages.ts";
|
|
28
28
|
import { watchOn, watchOff } from "./watch-setup.ts";
|
|
29
|
+
import { runWip } from "./wip.ts";
|
|
29
30
|
import { runUninstall } from "../core/uninstall.ts";
|
|
30
31
|
import { queueMigrate } from "../core/queue-migrate.ts";
|
|
31
32
|
import { activePlans, allowedAgents, enforceReadOnlyIndex, gitTop, indexPath, readIndex, subagentsPath, writeIndex } from "../core/queue/lib.ts";
|
|
@@ -90,6 +91,9 @@ export function helpText(): string {
|
|
|
90
91
|
" these two commands are the only agent writes to it",
|
|
91
92
|
" neurastream config [--json] print the merged config (defaults + file + env)",
|
|
92
93
|
" neurastream config set|get|list <key> [value] read or write one key (ui.port, paths.work_roots, ...)",
|
|
94
|
+
" neurastream wip add|remove|list [path] add or remove a root in wip.roots, or list them",
|
|
95
|
+
" neurastream wip on [--backup-url <url>]|off hourly snapshot (+ nightly private backup) on or off",
|
|
96
|
+
" neurastream wip restore [<worktree>] [--pick N] list the hidden saves, or put one back",
|
|
93
97
|
" neurastream guard <event> --json",
|
|
94
98
|
` (${GUARD_USAGE.slice(GUARD_USAGE.indexOf("(") + 1, -1)})`,
|
|
95
99
|
" neurastream main [args] run omp under the launcher (automatic session rollover)",
|
|
@@ -145,6 +149,7 @@ export async function run(cmd: string, args: string[]): Promise<number> {
|
|
|
145
149
|
if (cmd === "adapter") return getAdapter().install(args);
|
|
146
150
|
if (cmd === "setup") return runSetup(args, realSetupDeps(async () => runNotify(["test"])));
|
|
147
151
|
if (cmd === "config" && ["set", "get", "list"].includes(args[0] ?? "")) return runConfigKeys(args);
|
|
152
|
+
if (cmd === "wip") return runWip(args);
|
|
148
153
|
if (cmd === "config") {
|
|
149
154
|
try {
|
|
150
155
|
const cfg = loadConfig();
|
package/src/cli/init.ts
CHANGED
|
@@ -9,6 +9,7 @@ import { fileURLToPath } from "node:url";
|
|
|
9
9
|
import { configFile, loadConfig, TEMPLATE_PATH, type Config } from "../core/config.ts";
|
|
10
10
|
import { allowedAgents } from "../core/queue/lib.ts";
|
|
11
11
|
import { allowAgents, invalidSlugs, InvalidSlugError } from "../core/subagents.ts";
|
|
12
|
+
import { wipOn } from "../core/wip-setup.ts";
|
|
12
13
|
import { watchOn } from "./watch-setup.ts";
|
|
13
14
|
|
|
14
15
|
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
@@ -190,6 +191,11 @@ export function runInit(args: string[] = []): number {
|
|
|
190
191
|
if ((answer === "" || answer === "y" || answer === "yes") && watchOn() !== 0) {
|
|
191
192
|
console.log("watch not set up; fix the error above, then run `neurastream watch on`");
|
|
192
193
|
}
|
|
194
|
+
// P6 (plan 20261027_1130): empty or n leaves it off; the same path as `neurastream wip on`.
|
|
195
|
+
const save = askLine("Save unsaved work every hour? [y/N] ").trim().toLowerCase();
|
|
196
|
+
if ((save === "y" || save === "yes") && wipOn() !== 0) {
|
|
197
|
+
console.log("wip not set up; fix the error above, then run `neurastream wip on`");
|
|
198
|
+
}
|
|
193
199
|
}
|
|
194
200
|
return 0;
|
|
195
201
|
} catch (err) {
|
package/src/cli/wip.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
import { checkEdited, setConfigKeys, yamlValue } from "../core/config-edit.ts";
|
|
5
|
+
import { configFile, loadConfig } from "../core/config.ts";
|
|
6
|
+
import { wipRestore } from "../core/wip-restore.ts";
|
|
7
|
+
import { wipOff, wipOn } from "../core/wip-setup.ts";
|
|
8
|
+
|
|
9
|
+
export function runWip(args: string[], home: string = homedir()): number {
|
|
10
|
+
const verb = args[0];
|
|
11
|
+
if (!verb || verb === "--help" || verb === "-h") {
|
|
12
|
+
console.log("usage: neurastream wip add|remove|list|on|off|restore [path]");
|
|
13
|
+
return 0;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// P6 (plan 20261027_1130): the timers that run the snapshot hourly and the backup nightly.
|
|
17
|
+
if (verb === "on") {
|
|
18
|
+
const i = args.indexOf("--backup-url");
|
|
19
|
+
if (i >= 0 && !args[i + 1]) {
|
|
20
|
+
console.error("usage: neurastream wip on [--backup-url <url>]");
|
|
21
|
+
return 2;
|
|
22
|
+
}
|
|
23
|
+
return wipOn({ home, backupUrl: i >= 0 ? args[i + 1] : null });
|
|
24
|
+
}
|
|
25
|
+
if (verb === "off") return wipOff({ home });
|
|
26
|
+
// P7 (plan 20261027_1130): list a worktree's saves, or put one back.
|
|
27
|
+
if (verb === "restore") {
|
|
28
|
+
try {
|
|
29
|
+
return wipRestore(args.slice(1), loadConfig({ home }));
|
|
30
|
+
} catch (err) {
|
|
31
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
32
|
+
return 1;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if (verb === "list") {
|
|
37
|
+
const file = configFile(home);
|
|
38
|
+
if (existsSync(file)) {
|
|
39
|
+
try {
|
|
40
|
+
const parsed = Bun.YAML.parse(readFileSync(file, "utf8")) as { wip?: { roots?: unknown } } | null;
|
|
41
|
+
if (Array.isArray(parsed?.wip?.roots)) {
|
|
42
|
+
for (const r of parsed.wip.roots) console.log(String(r));
|
|
43
|
+
return 0;
|
|
44
|
+
}
|
|
45
|
+
} catch {}
|
|
46
|
+
}
|
|
47
|
+
const cfg = loadConfig({ home });
|
|
48
|
+
for (const r of cfg.wip.roots) console.log(r);
|
|
49
|
+
return 0;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (verb !== "add" && verb !== "remove") {
|
|
53
|
+
console.error("usage: neurastream wip add|remove|list|on|off|restore [path]");
|
|
54
|
+
return 2;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const target = args[1];
|
|
58
|
+
if (!target) {
|
|
59
|
+
console.error("usage: neurastream wip add|remove|list|on|off|restore [path]");
|
|
60
|
+
return 2;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const file = configFile(home);
|
|
64
|
+
const original = existsSync(file) ? readFileSync(file, "utf8") : null;
|
|
65
|
+
let currentRoots: string[] = [];
|
|
66
|
+
if (original) {
|
|
67
|
+
try {
|
|
68
|
+
const parsed = Bun.YAML.parse(original) as { wip?: { roots?: unknown } } | null;
|
|
69
|
+
if (Array.isArray(parsed?.wip?.roots)) {
|
|
70
|
+
currentRoots = parsed.wip.roots.map((r: unknown) => String(r));
|
|
71
|
+
} else {
|
|
72
|
+
currentRoots = [...loadConfig({ home }).wip.roots];
|
|
73
|
+
}
|
|
74
|
+
} catch {
|
|
75
|
+
currentRoots = [...loadConfig({ home }).wip.roots];
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (verb === "add") {
|
|
80
|
+
if (!currentRoots.includes(target)) currentRoots.push(target);
|
|
81
|
+
} else {
|
|
82
|
+
currentRoots = currentRoots.filter((r) => r !== target);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const text = yamlValue(currentRoots);
|
|
86
|
+
const edited = setConfigKeys(original, { "wip.roots": text });
|
|
87
|
+
if (!checkEdited(edited, home, (line) => console.error(line))) return 1;
|
|
88
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
89
|
+
writeFileSync(file, edited);
|
|
90
|
+
return 0;
|
|
91
|
+
}
|
package/src/core/config.ts
CHANGED
|
@@ -85,12 +85,18 @@ export interface Config {
|
|
|
85
85
|
};
|
|
86
86
|
oc: { model_prefix: string; tail_lines: number; tail_chars: number };
|
|
87
87
|
wip: {
|
|
88
|
+
roots: string[];
|
|
89
|
+
depth: number;
|
|
88
90
|
limit: number;
|
|
89
91
|
days: number;
|
|
92
|
+
keep_hourly: number;
|
|
93
|
+
keep_days: number;
|
|
94
|
+
stale_hours: number;
|
|
90
95
|
backup_url: string;
|
|
91
96
|
backup_log: string;
|
|
92
97
|
backup_hook_off: string[];
|
|
93
98
|
backup_max_repo_mb: number;
|
|
99
|
+
private_check: string;
|
|
94
100
|
secret_gate: string;
|
|
95
101
|
snapshot_max_mb: number;
|
|
96
102
|
status_log: string;
|
|
@@ -351,6 +357,10 @@ const ENV_MAP: Record<string, { path: string[]; kind: EnvKind }> = {
|
|
|
351
357
|
PLAN_GUARD_LOG: { path: ["paths", "plan_guard_log"], kind: "string" },
|
|
352
358
|
WIP_LIMIT: { path: ["wip", "limit"], kind: "number" },
|
|
353
359
|
WIP_DAYS: { path: ["wip", "days"], kind: "number" },
|
|
360
|
+
WIP_DEPTH: { path: ["wip", "depth"], kind: "number" },
|
|
361
|
+
WIP_KEEP_HOURLY: { path: ["wip", "keep_hourly"], kind: "number" },
|
|
362
|
+
WIP_KEEP_DAYS: { path: ["wip", "keep_days"], kind: "number" },
|
|
363
|
+
WIP_STALE_HOURS: { path: ["wip", "stale_hours"], kind: "number" },
|
|
354
364
|
WIP_BACKUP_MAX_REPO_MB: { path: ["wip", "backup_max_repo_mb"], kind: "number" },
|
|
355
365
|
WIP_SNAPSHOT_MAX_MB: { path: ["wip", "snapshot_max_mb"], kind: "number" },
|
|
356
366
|
LOAD_MAX: { path: ["machine", "load_max"], kind: "number" },
|
|
@@ -613,6 +623,10 @@ function check(cfg: Config): void {
|
|
|
613
623
|
for (const [job, hours] of Object.entries(cfg.watch.expect)) {
|
|
614
624
|
if (typeof hours !== "number" || !(hours > 0)) throw new ConfigError(`watch.expect.${job} must be a positive number of hours`);
|
|
615
625
|
}
|
|
626
|
+
// P8 (plan 20261027_1130): an empty entry would match nothing under the exact match, but a
|
|
627
|
+
// whitespace one is a typo the owner cannot see — refuse both instead of silently ignoring them.
|
|
628
|
+
if (!Array.isArray(cfg.wip.backup_hook_off) || cfg.wip.backup_hook_off.some(h => typeof h !== "string" || h.trim() === ""))
|
|
629
|
+
throw new ConfigError("wip.backup_hook_off must list host/owner or host/owner/repo entries, none empty");
|
|
616
630
|
if (!Array.isArray(cfg.watch.units) || cfg.watch.units.some(u => typeof u !== "string" || u === "")) {
|
|
617
631
|
throw new ConfigError("watch.units must be a list of non-empty glob strings");
|
|
618
632
|
}
|
package/src/core/guards.ts
CHANGED
|
@@ -1302,9 +1302,15 @@ function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[],
|
|
|
1302
1302
|
// (isOrchestrationPath + planAt both false), so the refusal fires here — never by accident of
|
|
1303
1303
|
// indexing — and covers shell redirects through writeTargets too.
|
|
1304
1304
|
const delegatedPlanner = currentPlanner(cfg) === "delegated" ? plannerSpawnPlan(e.agentId) : null;
|
|
1305
|
+
// I-20261102-27: the seam above also refused the REVIEW spawn, and a review spawn's only write
|
|
1306
|
+
// is its own PLAN REVIEW / CODE REVIEW line — so in delegated mode no plan could ever record a
|
|
1307
|
+
// PASS and no implementer could spawn. The named review spawn of a plan may still write that
|
|
1308
|
+
// plan; the REVIEW_LINE rule below then decides whether the line is its verdict.
|
|
1309
|
+
const delegatedReview = currentPlanner(cfg) === "delegated" ? (matchReviewSpawn(readReviewSpawns(), e.agentId ?? "")?.spawn.plan ?? null) : null;
|
|
1305
1310
|
if (currentPlanner(cfg) === "delegated") {
|
|
1306
1311
|
for (const p of writes) {
|
|
1307
1312
|
if (!MAIN_PLAN_FILE.test(p) || p === delegatedPlanner) continue;
|
|
1313
|
+
if (delegatedReview && path.resolve(e.cwd, p) === path.resolve(delegatedReview)) continue;
|
|
1308
1314
|
if (delegatedPlanner) return `planner is delegated — your Planner role names ${delegatedPlanner} only; ${p} is not yours to write.`;
|
|
1309
1315
|
return `planner is delegated — plan files are the planner agent's; your brief carries no "Planner role for <plan path>" line, so ${p} is refused.`;
|
|
1310
1316
|
}
|
|
@@ -1971,8 +1977,11 @@ export function checkPlanEdit(e: PlanEditEvent, cfg: Config): PlanEditDecision {
|
|
|
1971
1977
|
};
|
|
1972
1978
|
}
|
|
1973
1979
|
const name = e.agentId ?? "";
|
|
1980
|
+
// The header records the agent the owner picked, not the spawn instance: a `glm-3` spawn
|
|
1981
|
+
// satisfies `Planner: glm`, and the spawn form still works for plans written before this.
|
|
1982
|
+
const names = new Set([name, name.replace(/-\d+$/, "")]);
|
|
1974
1983
|
const head = e.after.split(/^## /m)[0] ?? "";
|
|
1975
|
-
if (!head.split("\n").some((l) => l.trim()
|
|
1984
|
+
if (!head.split("\n").some((l) => l.trim().startsWith("Planner: ") && names.has(l.trim().slice("Planner: ".length).trim()))) {
|
|
1976
1985
|
log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (no Planner header)`);
|
|
1977
1986
|
return {
|
|
1978
1987
|
allow: false,
|
|
@@ -2064,12 +2073,17 @@ function codeReviewProblem(file: string, after: string, ids: string[]): string |
|
|
|
2064
2073
|
return null;
|
|
2065
2074
|
}
|
|
2066
2075
|
|
|
2067
|
-
/** The plan text a planner agent owns: everything outside "## Progress" and the Main-only lines (planner mode P2a, plan 20261102_1515). */
|
|
2068
|
-
function plannerBody(text: string): string {
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
.
|
|
2076
|
+
/** The plan text a planner agent owns: everything outside "## Progress" and the Main-only lines (planner mode P2a, plan 20261102_1515) — minus the two zones Main may still correct (punch list, plan 20261102_2315): a "## Done check" section's body, and the backticked `verify:` span on a "## Phases" checkbox line. */
|
|
2077
|
+
export function plannerBody(text: string): string {
|
|
2078
|
+
const body = q.outsideProgress(text).split("\n");
|
|
2079
|
+
let section = "";
|
|
2080
|
+
return body
|
|
2081
|
+
.map((l) => {
|
|
2082
|
+
if (l.startsWith("## ")) section = l;
|
|
2083
|
+
if (/^## +Done check\b/i.test(section)) return "";
|
|
2084
|
+
if (/^## +Phases\b/i.test(section) && /^- \[[ x]\]/.test(l)) l = l.replace(/`verify:[^`]*`/g, "`verify:`");
|
|
2085
|
+
return MAIN_ONLY_LINE.test(l) ? "" : l;
|
|
2086
|
+
})
|
|
2073
2087
|
.join("\n");
|
|
2074
2088
|
}
|
|
2075
2089
|
|
package/src/core/main-start.ts
CHANGED
|
@@ -15,6 +15,7 @@ import { loadavgLine } from "./host.ts";
|
|
|
15
15
|
import { providersLine } from "./provider-state.ts";
|
|
16
16
|
import { mrSweep } from "./mr-sweep.ts";
|
|
17
17
|
import { watchHealth } from "./watch.ts";
|
|
18
|
+
import { wipAlerts } from "./wip-alerts.ts";
|
|
18
19
|
|
|
19
20
|
function bin(name: string, cfg: Config): string {
|
|
20
21
|
return join(cfg.paths.home, ".local/bin", name);
|
|
@@ -139,6 +140,13 @@ export async function mainStartText(args: string[], cfg: Config, opts: { inherit
|
|
|
139
140
|
}
|
|
140
141
|
}
|
|
141
142
|
}
|
|
143
|
+
// WIP health (plan 20261027_1130 P5): the last snapshot and backup runs, one incident per state
|
|
144
|
+
// and one post per new state; nothing prints when both are fresh and clean.
|
|
145
|
+
try {
|
|
146
|
+
for (const line of wipAlerts(cfg)) say(line);
|
|
147
|
+
} catch (err) {
|
|
148
|
+
logGuard(cfg.paths.guard_log, `wip alerts failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
149
|
+
}
|
|
142
150
|
say("=== machine");
|
|
143
151
|
const mg = await run(bin("machine-guard", cfg), [], { stderr: "ignore" });
|
|
144
152
|
const mgLines = mg.stdout.trim().split("\n");
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// The last snapshot and backup runs turned into the lines main-start prints, one incident per state
|
|
2
|
+
// and one post per NEW state. A state counts as announced once it is in wip-last.json, so the next
|
|
3
|
+
// main start of the same failure stays quiet; a healthy run clears it, so a recurrence posts again.
|
|
4
|
+
import { nowSec, strftime } from "./clock.ts";
|
|
5
|
+
import type { Config } from "./config.ts";
|
|
6
|
+
import { addIncident } from "./incidents.ts";
|
|
7
|
+
import { postReply } from "./notify.ts";
|
|
8
|
+
import { readWipLast, writeWipLast, type WipRunRec } from "./wip-fail.ts";
|
|
9
|
+
|
|
10
|
+
/** A backup run this old means the nightly job stopped running. */
|
|
11
|
+
const BACKUP_STALE_HOURS = 30;
|
|
12
|
+
|
|
13
|
+
interface Alert {
|
|
14
|
+
rec: WipRunRec;
|
|
15
|
+
key: string;
|
|
16
|
+
kind: "wip-snapshot-failed" | "wip-backup-failed" | "wip-backup-refused" | "wip-stale";
|
|
17
|
+
line: string;
|
|
18
|
+
post: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function alertOf(cfg: Config, rec: WipRunRec, now: number): Alert | null {
|
|
22
|
+
if (rec.failed.length) {
|
|
23
|
+
const line = `wip: ${rec.kind} failed at ${strftime(rec.at, "%Y-%m-%d %H:%M")}: ${rec.failed[0]}`;
|
|
24
|
+
const kind = rec.kind === "snapshot" ? "wip-snapshot-failed" : "wip-backup-failed";
|
|
25
|
+
return { rec, key: `${kind}:${rec.failed[0]}`, kind, line, post: line };
|
|
26
|
+
}
|
|
27
|
+
if (rec.kind === "backup" && rec.refused) {
|
|
28
|
+
const line = `wip: backup refused: ${rec.refused}`;
|
|
29
|
+
return {
|
|
30
|
+
rec,
|
|
31
|
+
key: `wip-backup-refused:${cfg.wip.backup_url}`,
|
|
32
|
+
kind: "wip-backup-refused",
|
|
33
|
+
line,
|
|
34
|
+
post: `Backup stopped: ${rec.refused}. Make it private; nothing was uploaded.`,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
// An empty wip.roots is a config choice, not a failure: the runners record it, nothing alerts on it.
|
|
38
|
+
const limit = rec.kind === "snapshot" ? cfg.wip.stale_hours : BACKUP_STALE_HOURS;
|
|
39
|
+
if (!rec.refused && now - rec.at > limit * 3600) {
|
|
40
|
+
const line = `wip: no ${rec.kind} for ${Math.floor((now - rec.at) / 3600)} h`;
|
|
41
|
+
return { rec, key: `wip-stale:${rec.kind}`, kind: "wip-stale", line, post: line };
|
|
42
|
+
}
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The wip lines for main-start; raises one incident per state and posts once per new one. */
|
|
47
|
+
export function wipAlerts(cfg: Config, deps: { notify?: (text: string) => void; now?: number } = {}): string[] {
|
|
48
|
+
const now = deps.now ?? nowSec();
|
|
49
|
+
const post = deps.notify ?? ((text: string) => void postReply(text, cfg));
|
|
50
|
+
const last = readWipLast(cfg);
|
|
51
|
+
const alerts: Alert[] = [];
|
|
52
|
+
for (const rec of [last.snapshot, last.backup]) {
|
|
53
|
+
const alert = rec ? alertOf(cfg, rec, now) : null;
|
|
54
|
+
if (alert) alerts.push(alert);
|
|
55
|
+
}
|
|
56
|
+
for (const alert of alerts) {
|
|
57
|
+
if (alert.rec.notified !== alert.key) post(alert.post);
|
|
58
|
+
try {
|
|
59
|
+
addIncident(cfg, {
|
|
60
|
+
source: "watch",
|
|
61
|
+
kind: alert.kind,
|
|
62
|
+
summary: alert.line,
|
|
63
|
+
evidence: `wip-last.json: ${alert.rec.kind} run at ${strftime(alert.rec.at, "%Y-%m-%d %H:%M")}`,
|
|
64
|
+
fingerprint: alert.key,
|
|
65
|
+
});
|
|
66
|
+
} catch {
|
|
67
|
+
// the incident store is best effort; the line and the post still reach Main
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
for (const rec of [last.snapshot, last.backup]) {
|
|
71
|
+
if (rec) rec.notified = alerts.find((a) => a.rec === rec)?.key ?? "";
|
|
72
|
+
}
|
|
73
|
+
if (last.snapshot || last.backup) writeWipLast(cfg, last);
|
|
74
|
+
return alerts.map((alert) => alert.line);
|
|
75
|
+
}
|
package/src/core/wip-backup.ts
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
|
-
import { accessSync, constants,
|
|
2
|
-
import { join,
|
|
1
|
+
import { accessSync, constants, writeFileSync } from "node:fs";
|
|
2
|
+
import { join, resolve } from "node:path";
|
|
3
3
|
import type { Config } from "./config.ts";
|
|
4
4
|
import { nowSec, strftime } from "./clock.ts";
|
|
5
5
|
import { printText } from "./help.ts";
|
|
6
|
+
import { addIncident } from "./incidents.ts";
|
|
6
7
|
import { cmd, gitRaw } from "./proc.ts";
|
|
8
|
+
import { failureLine, gitOrFail, realpathOrFail, recordWipRun } from "./wip-fail.ts";
|
|
9
|
+
import { backupVisibility, originMatches, type Visibility } from "./wip-private.ts";
|
|
10
|
+
import { keyOf, wipRepos } from "./wip-roots.ts";
|
|
7
11
|
|
|
8
12
|
function executable(path: string): boolean {
|
|
9
13
|
try {
|
|
@@ -14,23 +18,38 @@ function executable(path: string): boolean {
|
|
|
14
18
|
}
|
|
15
19
|
}
|
|
16
20
|
|
|
17
|
-
function keyOf(path: string, home: string): string {
|
|
18
|
-
return relative(home, path).replace(/[^A-Za-z0-9._-]+/g, "_").replace(/^_+|_+$/g, "");
|
|
19
|
-
}
|
|
20
21
|
|
|
21
|
-
function
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
22
|
+
export function wipBackup(
|
|
23
|
+
args: string[],
|
|
24
|
+
cfg: Config,
|
|
25
|
+
visibility?: (target: string) => Visibility,
|
|
26
|
+
): number {
|
|
27
|
+
if (cfg.wip.roots.length === 0) {
|
|
28
|
+
console.log("wip: no wip.roots set — run `neurastream wip add <path>`");
|
|
29
|
+
recordWipRun(cfg, "backup", [], "no wip.roots set");
|
|
30
|
+
return 0;
|
|
31
|
+
}
|
|
32
|
+
// The target is checked first, on every run, even when there is nothing to push: a repo that
|
|
33
|
+
// turned public must stop the upload before any ref is sent.
|
|
34
|
+
const target = cfg.wip.backup_url;
|
|
35
|
+
const state = target === "" ? "unknown" : (visibility ?? ((url: string) => backupVisibility(url, (a) => cmd(a), cfg.wip.private_check)))(target);
|
|
36
|
+
if (target === "" || state !== "private") {
|
|
37
|
+
const refused = target === "" ? "no wip.backup_url set" : `${target} is ${state}`;
|
|
38
|
+
console.log(
|
|
39
|
+
target === ""
|
|
40
|
+
? "Backup stopped: no wip.backup_url set; nothing was uploaded."
|
|
41
|
+
: `Backup stopped: ${refused}. Make it private; nothing was uploaded.`,
|
|
42
|
+
);
|
|
43
|
+
addIncident(cfg, {
|
|
44
|
+
source: "watch",
|
|
45
|
+
kind: "wip-backup-refused",
|
|
46
|
+
summary: `wip backup refused: ${refused}`,
|
|
47
|
+
evidence: `wip-backup ran at ${strftime(nowSec(), "%Y-%m-%d %H:%M")}`,
|
|
48
|
+
fingerprint: `wip-backup-refused:${target}`,
|
|
49
|
+
});
|
|
50
|
+
recordWipRun(cfg, "backup", [], refused);
|
|
51
|
+
return 1;
|
|
28
52
|
}
|
|
29
|
-
out.sort();
|
|
30
|
-
return out;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
export function wipBackup(args: string[], cfg: Config): number {
|
|
34
53
|
const dry = args.includes("--dry-run");
|
|
35
54
|
const quiet = args.includes("--quiet");
|
|
36
55
|
const seen = new Set<string>();
|
|
@@ -38,10 +57,11 @@ export function wipBackup(args: string[], cfg: Config): number {
|
|
|
38
57
|
const skipped: string[] = [];
|
|
39
58
|
const failed: string[] = [];
|
|
40
59
|
|
|
41
|
-
for (const repo of
|
|
42
|
-
const commonRaw =
|
|
43
|
-
|
|
44
|
-
|
|
60
|
+
for (const repo of wipRepos(cfg)) {
|
|
61
|
+
const commonRaw = gitOrFail(failed, repo, ["rev-parse", "--git-common-dir"]);
|
|
62
|
+
if (!commonRaw) continue;
|
|
63
|
+
const common = realpathOrFail(failed, resolve(repo, commonRaw.stdout || "."));
|
|
64
|
+
if (common === null || seen.has(common)) continue;
|
|
45
65
|
seen.add(common);
|
|
46
66
|
const du = cmd(["du", "-sm", common]);
|
|
47
67
|
const mb = Number(du.stdout.split(/\s+/)[0] ?? "NaN");
|
|
@@ -50,30 +70,39 @@ export function wipBackup(args: string[], cfg: Config): number {
|
|
|
50
70
|
skipped.push(`${rkeyWhole}: whole repo (${mb} MB git dir > ${cfg.wip.backup_max_repo_mb} MB limit)`);
|
|
51
71
|
continue;
|
|
52
72
|
}
|
|
53
|
-
const hooks =
|
|
54
|
-
|
|
73
|
+
const hooks = gitOrFail(failed, repo, ["rev-parse", "--git-path", "hooks"]);
|
|
74
|
+
if (!hooks) continue;
|
|
75
|
+
const prePush = join(repo, hooks.stdout, "pre-push");
|
|
76
|
+
// No origin (exit 2) is normal: it only feeds the hook opt-in match; the push goes to wip.backup_url.
|
|
55
77
|
const origin = gitRaw(repo, ["remote", "get-url", "origin"]).stdout;
|
|
56
|
-
|
|
78
|
+
// Exact `host/owner` or `host/owner/repo` only: a substring would opt in every repo at once.
|
|
79
|
+
const noHooks = cfg.wip.backup_hook_off.some(entry => originMatches(entry, origin));
|
|
57
80
|
if (executable(prePush) && !noHooks) {
|
|
58
|
-
skipped.push(`${rkeyWhole}: whole repo (has a pre-push gate; not bypassed)`);
|
|
81
|
+
skipped.push(`${rkeyWhole}: whole repo (has a pre-push gate; not bypassed — add its origin to wip.backup_hook_off to back it up)`);
|
|
59
82
|
continue;
|
|
60
83
|
}
|
|
61
|
-
|
|
84
|
+
const shallow = gitOrFail(failed, repo, ["rev-parse", "--is-shallow-repository"]);
|
|
85
|
+
if (!shallow) continue;
|
|
86
|
+
if (shallow.stdout === "true") {
|
|
62
87
|
skipped.push(`${rkeyWhole}: whole repo (shallow clone; GitHub refuses it)`);
|
|
63
88
|
continue;
|
|
64
89
|
}
|
|
65
|
-
const top =
|
|
66
|
-
|
|
90
|
+
const top = gitOrFail(failed, repo, ["worktree", "list", "--porcelain"]);
|
|
91
|
+
if (!top) continue;
|
|
92
|
+
const mainWt = top.stdout ? top.stdout.split("\n")[0]!.slice(9) : repo;
|
|
67
93
|
const rkey = keyOf(mainWt, cfg.paths.home);
|
|
68
94
|
const specs: { src: string; dst: string }[] = [];
|
|
69
|
-
const heads =
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
95
|
+
const heads = gitOrFail(failed, repo, ["for-each-ref", "--format=%(refname:short)", "refs/heads"]);
|
|
96
|
+
if (!heads) continue;
|
|
97
|
+
for (const b of heads.stdout.split("\n").filter(Boolean)) {
|
|
98
|
+
const n = gitOrFail(failed, repo, ["rev-list", "--count", b, "--not", "--remotes"]);
|
|
99
|
+
if (!n) continue;
|
|
100
|
+
if (/^\d+$/.test(n.stdout) && Number(n.stdout) > 0) specs.push({ src: `refs/heads/${b}`, dst: `refs/heads/${rkey}/${b}` });
|
|
73
101
|
}
|
|
74
|
-
const wips =
|
|
102
|
+
const wips = gitOrFail(failed, repo, ["for-each-ref", "--sort=-refname", "--format=%(refname)", "refs/wip"]);
|
|
103
|
+
if (!wips) continue;
|
|
75
104
|
const newest: Record<string, string> = {};
|
|
76
|
-
for (const r of wips.split("\n").filter(Boolean)) {
|
|
105
|
+
for (const r of wips.stdout.split("\n").filter(Boolean)) {
|
|
77
106
|
const prefix = r.slice(0, r.lastIndexOf("/"));
|
|
78
107
|
if (!(prefix in newest)) newest[prefix] = r;
|
|
79
108
|
}
|
|
@@ -95,7 +124,7 @@ export function wipBackup(args: string[], cfg: Config): number {
|
|
|
95
124
|
const hookOff = noHooks ? ["-c", "core.hooksPath=/dev/null"] : [];
|
|
96
125
|
const pushedRun = cmd(["git", "-C", repo, ...hookOff, "push", "--quiet", cfg.wip.backup_url, ...ok]);
|
|
97
126
|
if (pushedRun.code) {
|
|
98
|
-
failed.push(
|
|
127
|
+
failed.push(failureLine(repo, `git push --quiet ${cfg.wip.backup_url} ${ok.join(" ")}`, pushedRun.stderr));
|
|
99
128
|
} else {
|
|
100
129
|
pushed.push(...ok.map(s => `${rkey}: ${s}`));
|
|
101
130
|
}
|
|
@@ -115,5 +144,5 @@ export function wipBackup(args: string[], cfg: Config): number {
|
|
|
115
144
|
lines.push("## Pushed", ...pushed.map(s => `- ${s}`));
|
|
116
145
|
if (!dry) writeFileSync(cfg.wip.backup_log, `${lines.join("\n")}\n`);
|
|
117
146
|
printText((quiet ? lines.slice(0, 6) : lines).join("\n"));
|
|
118
|
-
return failed.length ?
|
|
147
|
+
return recordWipRun(cfg, "backup", failed, null, skipped.length) ? 0 : 1;
|
|
119
148
|
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import type { Config } from "./config.ts";
|
|
4
|
+
import { nowSec } from "./clock.ts";
|
|
5
|
+
import { gitRaw, type CmdResult } from "./proc.ts";
|
|
6
|
+
|
|
7
|
+
/** What one wip run ended with; main-start reads it from `<alert_state>/wip-last.json`. */
|
|
8
|
+
export interface WipRunRec {
|
|
9
|
+
kind: "snapshot" | "backup";
|
|
10
|
+
at: number;
|
|
11
|
+
ok: boolean;
|
|
12
|
+
failed: string[];
|
|
13
|
+
refused: string | null;
|
|
14
|
+
/** Refs the run left behind on purpose (hook opt-in, secret, too big); the backup reports it. */
|
|
15
|
+
skipped?: number;
|
|
16
|
+
/** The failure state main-start already announced: one state posts once. */
|
|
17
|
+
notified?: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** One record per kind, so the snapshot's and the backup's freshness are read independently. */
|
|
21
|
+
export interface WipLast {
|
|
22
|
+
snapshot?: WipRunRec;
|
|
23
|
+
backup?: WipRunRec;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function wipLastFile(cfg: Config): string {
|
|
27
|
+
return join(cfg.paths.alert_state, "wip-last.json");
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function readWipLast(cfg: Config): WipLast {
|
|
31
|
+
try {
|
|
32
|
+
const parsed: unknown = JSON.parse(readFileSync(wipLastFile(cfg), "utf8"));
|
|
33
|
+
return parsed && typeof parsed === "object" ? (parsed as WipLast) : {};
|
|
34
|
+
} catch {
|
|
35
|
+
return {};
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function writeWipLast(cfg: Config, last: WipLast): void {
|
|
40
|
+
const file = wipLastFile(cfg);
|
|
41
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
42
|
+
writeFileSync(file, `${JSON.stringify(last)}\n`);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** `FAILED: <path>: <step>: <first stderr line>` — one recorded failure; the run keeps going. */
|
|
46
|
+
export function failureLine(path: string, step: string, detail: string): string {
|
|
47
|
+
return `FAILED: ${path}: ${step}: ${detail.trim().split("\n")[0] ?? ""}`;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** git for one path; a non-zero exit is recorded in `failed` and the caller moves on to the next one. */
|
|
51
|
+
export function gitOrFail(failed: string[], path: string, args: string[], env?: NodeJS.ProcessEnv): CmdResult | null {
|
|
52
|
+
const r = gitRaw(path, args, env);
|
|
53
|
+
if (r.code === 0) return r;
|
|
54
|
+
failed.push(failureLine(path, `git ${args.join(" ")}`, r.stderr));
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** realpath or a recorded failure: a repo that cannot be resolved is skipped, never fatal. */
|
|
59
|
+
export function realpathOrFail(failed: string[], path: string): string | null {
|
|
60
|
+
try {
|
|
61
|
+
return realpathSync(path);
|
|
62
|
+
} catch (e) {
|
|
63
|
+
failed.push(failureLine(path, "realpath", e instanceof Error ? e.message : String(e)));
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Write how the run ended; returns true when it was clean, which is the exit code the runners use. */
|
|
69
|
+
export function recordWipRun(
|
|
70
|
+
cfg: Config,
|
|
71
|
+
kind: WipRunRec["kind"],
|
|
72
|
+
failed: string[],
|
|
73
|
+
refused: string | null = null,
|
|
74
|
+
skipped = 0,
|
|
75
|
+
): boolean {
|
|
76
|
+
const ok = failed.length === 0 && refused === null;
|
|
77
|
+
const last = readWipLast(cfg);
|
|
78
|
+
// The announced state survives a re-run: the same failure twice stays one state and one post.
|
|
79
|
+
last[kind] = { kind, at: nowSec(), ok, failed, refused, skipped, notified: last[kind]?.notified };
|
|
80
|
+
writeWipLast(cfg, last);
|
|
81
|
+
return ok;
|
|
82
|
+
}
|