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.
@@ -1,24 +1,74 @@
1
- import { copyFileSync, existsSync, lstatSync, mkdtempSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
1
+ import { copyFileSync, existsSync, lstatSync, mkdtempSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join, resolve } from "node:path";
4
4
  import type { Config } from "./config.ts";
5
5
  import { nowSec, strftime } from "./clock.ts";
6
6
  import { printText } from "./help.ts";
7
7
  import { pyFloatStr } from "./pyfmt.ts";
8
- import { cmd, gitRaw } from "./proc.ts";
8
+ import { cmd } from "./proc.ts";
9
+ import { failureLine, gitOrFail, realpathOrFail, recordWipRun } from "./wip-fail.ts";
10
+ import { keyOf, wipRepos } from "./wip-roots.ts";
9
11
 
10
- function repos(roots: string[]): string[] {
11
- const out: string[] = [];
12
- for (const root of roots) {
13
- if (!existsSync(root) || !statSync(root).isDirectory()) continue;
14
- for (const d of readdirSync(root)) {
15
- if (existsSync(join(root, d, ".git"))) out.push(join(root, d));
12
+ const DAY_MS = 86_400_000;
13
+
14
+ /** Midnight of a `YYYYMMDD-HHMM` save stamp, in ms since the epoch. */
15
+ function dayStart(stamp: string): number {
16
+ const parts = /^(\d{4})(\d{2})(\d{2})/.exec(stamp);
17
+ return parts ? Date.UTC(Number(parts[1]), Number(parts[2]) - 1, Number(parts[3])) : Number.NaN;
18
+ }
19
+
20
+ /** The saves to delete: everything but the newest `keepHourly` and the newest of each of the last `keepDays` days. */
21
+ function staleOf(refs: string[], keepHourly: number, keepDays: number): string[] {
22
+ const keep = new Set<string>([refs[refs.length - 1]!]);
23
+ for (const ref of refs.slice(-Math.max(1, keepHourly))) keep.add(ref);
24
+ const days = new Set<string>();
25
+ for (let i = refs.length - 1; i >= 0 && days.size < Math.max(1, keepDays); i--) {
26
+ const ref = refs[i]!;
27
+ const day = ref.slice(ref.lastIndexOf("/") + 1, ref.lastIndexOf("/") + 9);
28
+ if (days.has(day)) continue;
29
+ days.add(day);
30
+ keep.add(ref);
31
+ }
32
+ return refs.filter(ref => !keep.has(ref));
33
+ }
34
+
35
+ /**
36
+ * Keeps refs/wip small: per worktree the newest `keep_hourly` saves plus one per day for
37
+ * `keep_days`, and a vanished worktree's saves until `keep_days` after its last save.
38
+ */
39
+ export function pruneWip(cfg: Config, failed: string[] = [], repos: string[] = wipRepos(cfg)): void {
40
+ const today = dayStart(strftime(nowSec(), "%Y%m%d"));
41
+ for (const repo of repos) {
42
+ const list = gitOrFail(failed, repo, ["worktree", "list", "--porcelain"]);
43
+ if (!list) continue;
44
+ const live = new Set<string>();
45
+ for (const line of list.stdout.split("\n")) {
46
+ if (line.startsWith("worktree ")) live.add(keyOf(line.slice(9), cfg.paths.home));
47
+ }
48
+ const all = gitOrFail(failed, repo, ["for-each-ref", "--sort=refname", "--format=%(refname)", "refs/wip"]);
49
+ if (!all) continue;
50
+ const byKey = new Map<string, string[]>();
51
+ for (const ref of all.stdout.split("\n").filter(Boolean)) {
52
+ const rest = ref.slice("refs/wip/".length);
53
+ const slash = rest.indexOf("/");
54
+ if (slash < 1) continue;
55
+ const key = rest.slice(0, slash);
56
+ byKey.set(key, [...(byKey.get(key) ?? []), ref]);
57
+ }
58
+ for (const [key, refs] of byKey) {
59
+ const newest = refs[refs.length - 1]!;
60
+ const age = (today - dayStart(newest.slice(newest.lastIndexOf("/") + 1))) / DAY_MS;
61
+ const doomed = live.has(key)
62
+ ? staleOf(refs, cfg.wip.keep_hourly, cfg.wip.keep_days)
63
+ : Number.isFinite(age) && age <= cfg.wip.keep_days
64
+ ? []
65
+ : refs;
66
+ for (const ref of doomed) gitOrFail(failed, repo, ["update-ref", "-d", ref]);
16
67
  }
17
68
  }
18
- out.sort();
19
- return out;
20
69
  }
21
70
 
71
+
22
72
  function secretRx(pat: string): RegExp {
23
73
  let src = pat;
24
74
  let flags = "";
@@ -30,22 +80,29 @@ function secretRx(pat: string): RegExp {
30
80
  }
31
81
 
32
82
  export function wipSnapshot(args: string[], cfg: Config): number {
83
+ if (cfg.wip.roots.length === 0) {
84
+ console.log("wip: no wip.roots set — run `neurastream wip add <path>`");
85
+ recordWipRun(cfg, "snapshot", [], "no wip.roots set");
86
+ return 0;
87
+ }
33
88
  const quiet = args.includes("--quiet");
34
89
  const maxMb = cfg.wip.snapshot_max_mb;
35
90
  const secret = secretRx(cfg.wip.secret_file);
36
91
  const stamp = strftime(nowSec(), "%Y%m%d-%H%M");
37
92
  // git prints worktree paths resolved (macOS: /var → /private/var), so the home prefix must be resolved too.
38
93
  const home = existsSync(cfg.paths.home) ? realpathSync(cfg.paths.home) : cfg.paths.home;
39
- const homePrefix = home.endsWith("/") ? home : `${home}/`;
40
- const seen = new Set<string>();
94
+ const failed: string[] = [];
95
+ const seen = new Map<string, string>();
41
96
  const worktrees: string[] = [];
42
- for (const repo of repos(cfg.paths.work_roots)) {
43
- const commonRaw = gitRaw(repo, ["rev-parse", "--git-common-dir"]).stdout || ".";
44
- const common = realpathSync(resolve(repo, commonRaw));
45
- if (seen.has(common)) continue;
46
- seen.add(common);
47
- const out = gitRaw(repo, ["worktree", "list", "--porcelain"]).stdout;
48
- for (const line of out.split("\n")) {
97
+ for (const repo of wipRepos(cfg)) {
98
+ const commonRaw = gitOrFail(failed, repo, ["rev-parse", "--git-common-dir"]);
99
+ if (!commonRaw) continue;
100
+ const common = realpathOrFail(failed, resolve(repo, commonRaw.stdout || "."));
101
+ if (common === null || seen.has(common)) continue;
102
+ seen.set(common, repo);
103
+ const list = gitOrFail(failed, repo, ["worktree", "list", "--porcelain"]);
104
+ if (!list) continue;
105
+ for (const line of list.stdout.split("\n")) {
49
106
  if (line.startsWith("worktree ") && existsSync(line.slice(9)) && statSync(line.slice(9)).isDirectory()) {
50
107
  worktrees.push(line.slice(9));
51
108
  }
@@ -54,23 +111,28 @@ export function wipSnapshot(args: string[], cfg: Config): number {
54
111
 
55
112
  const saved: { wt: string; br: string; n: number; sk: number; ref: string }[] = [];
56
113
  let same = 0;
57
- const failed: string[] = [];
58
114
  for (const wt of worktrees) {
59
- const head = gitRaw(wt, ["rev-parse", "--verify", "HEAD"]);
60
- if (head.code) continue;
61
- const st = gitRaw(wt, ["status", "--porcelain"]);
62
- if (st.code || !st.stdout) continue;
63
- const gitdir = gitRaw(wt, ["rev-parse", "--absolute-git-dir"]).stdout;
115
+ const head = gitOrFail(failed, wt, ["rev-parse", "--verify", "HEAD"]);
116
+ if (!head) continue;
117
+ const st = gitOrFail(failed, wt, ["status", "--porcelain"]);
118
+ if (!st || !st.stdout) continue;
119
+ const gitdir = gitOrFail(failed, wt, ["rev-parse", "--absolute-git-dir"]);
120
+ if (!gitdir) continue;
64
121
  const tmp = mkdtempSync(join(tmpdir(), "wip-snap-"));
65
122
  try {
66
123
  const idx = join(tmp, "index");
67
- if (existsSync(join(gitdir, "index"))) copyFileSync(join(gitdir, "index"), idx);
124
+ if (existsSync(join(gitdir.stdout, "index"))) copyFileSync(join(gitdir.stdout, "index"), idx);
68
125
  const env = { ...process.env, GIT_INDEX_FILE: idx };
69
- cmd(["git", "-C", wt, "add", "-u"], { env });
70
- const untracked = gitRaw(wt, ["ls-files", "-o", "--exclude-standard", "-z"], env).stdout;
126
+ const addAll = cmd(["git", "-C", wt, "add", "-u"], { env });
127
+ if (addAll.code) {
128
+ failed.push(failureLine(wt, "git add -u", addAll.stderr));
129
+ continue;
130
+ }
131
+ const untracked = gitOrFail(failed, wt, ["ls-files", "-o", "--exclude-standard", "-z"], env);
132
+ if (!untracked) continue;
71
133
  const keep: string[] = [];
72
134
  let skipped = 0;
73
- for (const p of untracked.split("\0").filter(Boolean)) {
135
+ for (const p of untracked.stdout.split("\0").filter(Boolean)) {
74
136
  const fp = join(wt, p);
75
137
  let big = false;
76
138
  try {
@@ -83,37 +145,43 @@ export function wipSnapshot(args: string[], cfg: Config): number {
83
145
  else keep.push(p);
84
146
  }
85
147
  if (keep.length) {
86
- cmd(["git", "-C", wt, "add", "--pathspec-from-file=-", "--pathspec-file-nul"], {
148
+ const addNew = cmd(["git", "-C", wt, "add", "--pathspec-from-file=-", "--pathspec-file-nul"], {
87
149
  env,
88
150
  input: Buffer.from(keep.join("\0")),
89
151
  });
152
+ if (addNew.code) {
153
+ failed.push(failureLine(wt, "git add --pathspec-from-file=- --pathspec-file-nul", addNew.stderr));
154
+ continue;
155
+ }
90
156
  }
91
- const tree = gitRaw(wt, ["write-tree"], env);
92
- if (tree.code) {
93
- failed.push(wt);
94
- continue;
95
- }
96
- const headTree = gitRaw(wt, ["rev-parse", "HEAD^{tree}"]).stdout;
97
- if (tree.stdout === headTree) continue;
98
- const key = wt.replaceAll(homePrefix, "").replaceAll("/", "_");
99
- const last = gitRaw(wt, ["for-each-ref", "--sort=-refname", "--count=1", "--format=%(objectname)", `refs/wip/${key}/`]).stdout;
100
- if (last) {
101
- const lastTree = gitRaw(wt, ["rev-parse", `${last}^{tree}`]).stdout;
102
- if (lastTree === tree.stdout) {
157
+ const tree = gitOrFail(failed, wt, ["write-tree"], env);
158
+ if (!tree) continue;
159
+ const headTree = gitOrFail(failed, wt, ["rev-parse", "HEAD^{tree}"]);
160
+ if (!headTree) continue;
161
+ if (tree.stdout === headTree.stdout) continue;
162
+ // P8b (plan 20261027_1130): the one key the backup and restore also read, from the
163
+ // realpath of home and worktree - a HOME behind a symlink, or a root outside it, used to
164
+ // grow a key the other two could never match.
165
+ const key = keyOf(wt, home);
166
+ const lastRef = gitOrFail(failed, wt, ["for-each-ref", "--sort=-refname", "--count=1", "--format=%(objectname)", `refs/wip/${key}/`]);
167
+ if (!lastRef) continue;
168
+ if (lastRef.stdout) {
169
+ const lastTree = gitOrFail(failed, wt, ["rev-parse", `${lastRef.stdout}^{tree}`]);
170
+ if (!lastTree) continue;
171
+ if (lastTree.stdout === tree.stdout) {
103
172
  same += 1;
104
173
  continue;
105
174
  }
106
175
  }
107
- const branch = gitRaw(wt, ["branch", "--show-current"]).stdout;
108
- const message = `wip-snapshot ${stamp} ${wt} (${branch || "detached"}); skipped ${skipped} new files > ${pyFloatStr(maxMb)}MB`;
109
- const commit = gitRaw(wt, ["commit-tree", tree.stdout, "-p", head.stdout, "-m", message]);
110
- if (commit.code || gitRaw(wt, ["update-ref", `refs/wip/${key}/${stamp}`, commit.stdout]).code) {
111
- failed.push(wt);
112
- continue;
113
- }
176
+ const branch = gitOrFail(failed, wt, ["branch", "--show-current"]);
177
+ if (!branch) continue;
178
+ const message = `wip-snapshot ${stamp} ${wt} (${branch.stdout || "detached"}); skipped ${skipped} new files > ${pyFloatStr(maxMb)}MB`;
179
+ const commit = gitOrFail(failed, wt, ["commit-tree", tree.stdout, "-p", head.stdout, "-m", message]);
180
+ if (!commit) continue;
181
+ if (!gitOrFail(failed, wt, ["update-ref", `refs/wip/${key}/${stamp}`, commit.stdout])) continue;
114
182
  saved.push({
115
183
  wt,
116
- br: branch || "detached",
184
+ br: branch.stdout || "detached",
117
185
  n: st.stdout.split("\n").filter(l => l !== "").length,
118
186
  sk: skipped,
119
187
  ref: `refs/wip/${key}/${stamp}`,
@@ -123,6 +191,9 @@ export function wipSnapshot(args: string[], cfg: Config): number {
123
191
  }
124
192
  }
125
193
 
194
+ // Only repos this run already resolved: a corrupt one was reported once and keeps that line.
195
+ pruneWip(cfg, failed, [...seen.values()]);
196
+
126
197
  const wc = cmd(["wip-check"]).stdout;
127
198
  const lines = [
128
199
  `# WIP status ${strftime(nowSec(), "%Y-%m-%d %H:%M")}`,
@@ -136,9 +207,9 @@ export function wipSnapshot(args: string[], cfg: Config): number {
136
207
  for (const row of saved) {
137
208
  lines.push(`- ${row.wt} [${row.br}] ${row.n} changed paths -> \`${row.ref}\`${row.sk ? ` (${row.sk} big new files NOT saved)` : ""}`);
138
209
  }
139
- for (const wt of failed) lines.push(`- FAILED: ${wt}`);
210
+ for (const line of failed) lines.push(`- ${line}`);
140
211
  lines.push("", "```", wc.replace(/\s+$/, ""), "```", "");
141
212
  writeFileSync(cfg.wip.status_log, lines.join("\n"));
142
213
  if (!quiet) printText(lines.slice(0, 8 + saved.length + failed.length).join("\n"));
143
- return failed.length ? 1 : 0;
214
+ return recordWipRun(cfg, "snapshot", failed) ? 0 : 1;
144
215
  }
@@ -10,6 +10,8 @@ You are Main, the orchestrator. Main plans, delegates, reviews and lands; implem
10
10
  - A hold is one line: `WAITING on owner: <what to do> — blocked: <what stays stuck until then> — why you: <why Main cannot do it>`. The phone page shows those three parts; a missing part is left out.
11
11
  - Entering a repo: read its AGENTS.md first.
12
12
  - Main writes every plan in `<repo>/docs/plans/`, shaped like `{{AGENT_DIR}}/queue/TEMPLATE.md`. Do the research yourself; never base a plan on another agent's findings. In `planner delegated` mode the planner agent writes the plan instead (`Planner: <agent>` header; the research and the `## Code read by Main` list are the planner's): Main routes the owner's asks to it, dispatches implementers, checks the outcomes (verify commands, CI, the reviewer's PASS) and lands, and Main does not read repo code to plan. The owner's whole message `planner main` returns this rule; `autonomy.planner` (default `main`) is the same switch in the config.
13
+ - Planner choice is Main's: a small mechanical plan (a tick, a done-check or verify fix, one doc line) goes to `glm`, or `haiku` when the fast planner is unavailable; anything else goes to `opus-planner` (always thinking medium). The plan's `Planner: <agent>` header is the record; no tier code.
14
+ - In delegated mode Main may correct only a plan's `## Done check` command and a phase line's `verify:` command; every other plan line belongs to the planner.
13
15
  - Phase 0 of every plan: blocker scripts that stop the implementer from going against the plan. They must exist before any spawn.
14
16
  - Every plan has `## Reuse`; no spawn without a current reviewer PASS (`templates/plan-review-brief.md`, recorded only from the reviewer's own Progress edit); a brief names every open MR of its plan with an `MR !N:` line.
15
17
  - Plan order: plan → page built from the architecture-drilldown template (`neurastream pages publish <page.html> --plan <plan.md>` refuses anything else) → owner approves (Approve on the page, or types `approve <YYYYMMDD_HHMM>`) → reviewer PASS → implementer. Once `approval.since` is set, a plan stamped at or after it gets no spawn without a page and an approval record for its current text; a body edit voids the approval, a Progress-only edit keeps it.
@@ -86,12 +86,18 @@ oc:
86
86
  tail_chars: 600 # output chars kept from an oc run
87
87
 
88
88
  wip:
89
+ roots: [] # folders or repos to snapshot/backup; empty = off
90
+ depth: 3 # folder walk depth limit
89
91
  limit: 6 # open WIP items the check allows
90
92
  days: 14 # WIP age window in days
93
+ keep_hourly: 48 # hourly snapshots kept per worktree
94
+ keep_days: 14 # days to keep daily snapshots
95
+ stale_hours: 3 # hours without a snapshot before an alert
91
96
  backup_url: "" # your own private backup repo; wip-backup refuses to invent one
92
97
  backup_log: "~/.local/state/neurastream/WIP-BACKUP.md" # backup log file
93
98
  backup_hook_off: [] # origin name fragments whose pre-push hook wip-backup may bypass
94
99
  backup_max_repo_mb: 1000 # largest repo wip-backup will back up
100
+ private_check: "" # command checking backup repo visibility
95
101
  secret_gate: "~/.local/bin/git-secret-gate" # secret scanner run before a backup
96
102
  snapshot_max_mb: 5 # largest file a snapshot keeps
97
103
  status_log: "~/.local/state/neurastream/WIP-STATUS.md" # WIP status file
@@ -16,3 +16,6 @@ git dir exceeds wip.backup_max_repo_mb and shallow clones are skipped whole.
16
16
 
17
17
  Restore: git fetch '<wip.backup_url>' '<repo-key>/<branch>:<branch>'
18
18
  Usage: wip-backup [--dry-run] [--quiet]
19
+
20
+ Private only: the target is checked first (gh, glab, or wip.private_check);
21
+ anything but an exact "private" answer uploads nothing and is listed as refused.
@@ -9,3 +9,5 @@ Writes wip.status_log from config.yml (default ~/.local/state/neurastream/WIP-ST
9
9
  wip-check output + snapshot list.
10
10
  Restore: git -C <wt> restore --source=<ref> --worktree -- <paths or .> | list: git for-each-ref refs/wip
11
11
  Usage: wip-snapshot [--quiet]
12
+
13
+ Roots: `neurastream wip add|remove|list`; a broken repo is recorded and skipped, never fatal.
@@ -0,0 +1,23 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0">
4
+ <dict>
5
+ <key>Label</key>
6
+ <string>com.neurastream.wip-backup</string>
7
+ <key>ProgramArguments</key>
8
+ <array>
9
+ <string>__HOME__/.bun/bin/neurastream</string>
10
+ <string>wip-backup</string>
11
+ <string>--quiet</string>
12
+ </array>
13
+ <key>StartCalendarInterval</key>
14
+ <dict>
15
+ <key>Hour</key>
16
+ <integer>23</integer>
17
+ <key>Minute</key>
18
+ <integer>30</integer>
19
+ </dict>
20
+ <key>RunAtLoad</key>
21
+ <false/>
22
+ </dict>
23
+ </plist>
@@ -0,0 +1,18 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0">
4
+ <dict>
5
+ <key>Label</key>
6
+ <string>com.neurastream.wip-snapshot</string>
7
+ <key>ProgramArguments</key>
8
+ <array>
9
+ <string>__HOME__/.bun/bin/neurastream</string>
10
+ <string>wip-snapshot</string>
11
+ <string>--quiet</string>
12
+ </array>
13
+ <key>StartInterval</key>
14
+ <integer>3600</integer>
15
+ <key>RunAtLoad</key>
16
+ <true/>
17
+ </dict>
18
+ </plist>
@@ -0,0 +1,6 @@
1
+ [Unit]
2
+ Description=neurastream wip backup (the wip refs to the private backup repo)
3
+
4
+ [Service]
5
+ Type=oneshot
6
+ ExecStart=%h/.bun/bin/neurastream wip-backup --quiet
@@ -0,0 +1,9 @@
1
+ [Unit]
2
+ Description=Back up unsaved work once a day
3
+
4
+ [Timer]
5
+ OnCalendar=*-*-* 23:30:00
6
+ Persistent=true
7
+
8
+ [Install]
9
+ WantedBy=timers.target
@@ -0,0 +1,6 @@
1
+ [Unit]
2
+ Description=neurastream wip snapshot (unsaved work into the wip refs)
3
+
4
+ [Service]
5
+ Type=oneshot
6
+ ExecStart=%h/.bun/bin/neurastream wip-snapshot --quiet
@@ -0,0 +1,10 @@
1
+ [Unit]
2
+ Description=Snapshot unsaved work every hour
3
+
4
+ [Timer]
5
+ OnBootSec=5min
6
+ OnUnitActiveSec=1h
7
+ Persistent=true
8
+
9
+ [Install]
10
+ WantedBy=timers.target