neurastream 0.3.21 → 0.3.23
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 +1 -0
- package/package.json +1 -1
- package/src/adapters/omp/doctor.ts +6 -0
- package/src/adapters/omp/index.ts +6 -1
- package/src/adapters/omp/limit-wake.ts +83 -0
- package/src/adapters/omp/rate-limit-controller.ts +1 -1
- package/src/cli/dispatch.ts +7 -0
- package/src/cli/reuse.ts +109 -0
- package/src/cli/setup.ts +25 -1
- package/src/core/config.ts +29 -0
- package/src/core/guards/plan-edit.ts +200 -8
- package/src/core/guards/spawn.ts +13 -3
- package/src/core/guards/state.ts +21 -0
- package/src/core/guards/stop.ts +15 -1
- package/src/core/guards/tool.ts +7 -4
- package/src/core/queue/lib.ts +58 -4
- package/src/core/reuse-map.ts +742 -0
- package/src/core/setup-detect.ts +8 -3
- package/src/core/uninstall.ts +14 -0
- package/templates/config.yml +7 -0
|
@@ -0,0 +1,742 @@
|
|
|
1
|
+
// Reuse map (plan 20261122_1828_reuse_map P1): the opt-in Graphify code map a new plan's
|
|
2
|
+
// `## Reuse` must cite. Seam first — no harness names, unit tests inject a fake ReuseGraph,
|
|
3
|
+
// CLI tests put a fake `graphify` on a sandbox PATH. Off (config) means nothing here runs.
|
|
4
|
+
|
|
5
|
+
import { spawnSync } from "node:child_process";
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
import { closeSync, constants as fsConstants, existsSync, fstatSync, mkdirSync, openSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync, type Stats } from "node:fs";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
import { configFile, loadConfig, type Config } from "./config.ts";
|
|
10
|
+
import { checkEdited, setConfigKeys, yamlValue } from "./config-edit.ts";
|
|
11
|
+
import { isBusy, writeAtomicSync, withFileLock } from "./file-lock.ts";
|
|
12
|
+
import { repoDirs } from "./setup-detect.ts";
|
|
13
|
+
|
|
14
|
+
/** The only pinned mapping tool (PyPI `graphifyy`; other `graphify*` names are typosquats). */
|
|
15
|
+
export const GRAPHIFY_VERSION = "0.9.100";
|
|
16
|
+
|
|
17
|
+
/** Terms per map/none line: each is one `graphify query` spawn, so a bloated line is capped (reviewer 2026-11-26). */
|
|
18
|
+
export const MAX_TERMS = 8;
|
|
19
|
+
|
|
20
|
+
/** Distinct terms a none line must search before "none to reuse" counts (plan Done 3). */
|
|
21
|
+
export const NONE_TERMS_MIN = 3;
|
|
22
|
+
|
|
23
|
+
/** A repo-relative path as the map names it: no leading ./, no double slashes. */
|
|
24
|
+
export function normRel(p: string): string {
|
|
25
|
+
return path.posix.normalize(p.replace(/^\.\//, ""));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** `graphify query` and `--version` bounds; a build (`extract . --code-only`) may take 10 minutes. */
|
|
29
|
+
const QUERY_TIMEOUT_MS = 30_000;
|
|
30
|
+
const BUILD_TIMEOUT_MS = 600_000;
|
|
31
|
+
|
|
32
|
+
/** The time one plan check may spend on graphify queries in all: its before and after passes share it. */
|
|
33
|
+
export const QUERY_BUDGET_MS = 120_000;
|
|
34
|
+
|
|
35
|
+
/** The refusal when the budget ran out: retry the edit; a slow check never passes. */
|
|
36
|
+
export const SLOW_RETRY = "reuse map slow — retry";
|
|
37
|
+
|
|
38
|
+
const GRAPH_DIR = "graphify-out";
|
|
39
|
+
const STAMP_FILE = path.join(GRAPH_DIR, ".neurastream-stamp");
|
|
40
|
+
const LOCK_FILE = path.join(GRAPH_DIR, ".neurastream.lock");
|
|
41
|
+
|
|
42
|
+
/** The argv-runner result; same shape as pages-setup.ts's RunnerResult (status, stderr, stdout). */
|
|
43
|
+
export interface GraphifyResult {
|
|
44
|
+
status: number | null;
|
|
45
|
+
stdout: string;
|
|
46
|
+
stderr: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The external CLI seam: real one spawns `graphify` in the repo (each term its own argv item,
|
|
51
|
+
* never a shell); tests inject fakes.
|
|
52
|
+
*/
|
|
53
|
+
export interface ReuseGraph {
|
|
54
|
+
version(): GraphifyResult;
|
|
55
|
+
build(repo: string, exclude: string[]): GraphifyResult;
|
|
56
|
+
query(repo: string, term: string, timeoutMs?: number): GraphifyResult;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function runGraphify(repo: string, args: string[], timeoutMs: number): GraphifyResult {
|
|
60
|
+
const r = spawnSync("graphify", args, { cwd: repo || undefined, encoding: "utf8", timeout: timeoutMs });
|
|
61
|
+
return { status: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export const realGraphify: ReuseGraph = {
|
|
65
|
+
version: () => runGraphify("", ["--version"], QUERY_TIMEOUT_MS),
|
|
66
|
+
build: (repo, exclude) =>
|
|
67
|
+
runGraphify(repo, ["extract", ".", "--code-only", ...exclude.flatMap((g) => ["--exclude", g])], BUILD_TIMEOUT_MS),
|
|
68
|
+
query: (repo, term, timeoutMs = QUERY_TIMEOUT_MS) => runGraphify(repo, ["query", term, "--budget", "2000"], timeoutMs),
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
/** Null when graphify is the pinned version on PATH; else the one-line install fix. */
|
|
72
|
+
export function versionProblem(graph: ReuseGraph = realGraphify): string | null {
|
|
73
|
+
const r = graph.version();
|
|
74
|
+
const found = r.stdout.trim() || r.stderr.trim().split("\n")[0] || "(no output)";
|
|
75
|
+
if (r.status === 0 && found === `graphify ${GRAPHIFY_VERSION}`) return null;
|
|
76
|
+
return `graphify ${GRAPHIFY_VERSION} is not on PATH (found: ${found.slice(0, 80)}) — install the pinned tool: uv tool install ${GRAPHIFY_PIN}`;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// --- line helpers: the exact strings a plan's `## Reuse` must carry when the map is on ---
|
|
80
|
+
|
|
81
|
+
/** `- map: graphify "t1", "t2" → a.ts, b.ts — cite: N` (N = min(minCited, files)). */
|
|
82
|
+
export function mapLine(terms: string[], files: string[], minCited: number): string {
|
|
83
|
+
return `- map: graphify ${terms.map((w) => `"${w}"`).join(", ")} → ${files.join(", ")} — cite: ${Math.min(minCited, files.length)}`;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** `- new: none to reuse — searched: "t1", "t2", "t3"` */
|
|
87
|
+
export function noneLine(terms: string[]): string {
|
|
88
|
+
return `- new: none to reuse — searched: ${terms.map((w) => `"${w}"`).join(", ")}`;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** `checked: <path>:<n> "<exact text>"` — the citation every `new:` line carries under the map gate. */
|
|
92
|
+
export function checkedCite(file: string, n: number, text: string): string {
|
|
93
|
+
return `checked: ${file}:${n} "${text}"`;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// --- parsers (text only; never a graphify run) ---
|
|
97
|
+
|
|
98
|
+
export interface ParsedMapLine {
|
|
99
|
+
terms: string[];
|
|
100
|
+
files: string[];
|
|
101
|
+
cite: number;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export interface ParsedNoneLine {
|
|
105
|
+
terms: string[];
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const QUOTED_WORD = /"([^"]*)"/g;
|
|
109
|
+
|
|
110
|
+
/** Parses a `- map: graphify "t1", "t2" → a.ts, b.ts — cite: N` line; null when the line is not one. */
|
|
111
|
+
export function parseMapLine(line: string): ParsedMapLine | null {
|
|
112
|
+
const m = /^-?\s*map:\s*graphify\s+(.+?)\s*→\s*(.+?)\s*—\s*cite:\s*(\d+)\s*$/.exec(line.trim());
|
|
113
|
+
if (!m) return null;
|
|
114
|
+
const terms = [...(m[1] ?? "").matchAll(QUOTED_WORD)].map((q) => q[1] ?? "").filter(Boolean);
|
|
115
|
+
const files = (m[2] ?? "")
|
|
116
|
+
.split(",")
|
|
117
|
+
.map((f) => f.trim())
|
|
118
|
+
.filter(Boolean);
|
|
119
|
+
if (!terms.length || !files.length) return null;
|
|
120
|
+
return { terms, files, cite: Number(m[3]) };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Parses a `- new: none to reuse — searched: "t1", "t2", "t3"` line; null when the line is not one. */
|
|
124
|
+
export function parseNoneLine(line: string): ParsedNoneLine | null {
|
|
125
|
+
const m = /^-?\s*new:\s*none to reuse\s*—\s*searched:\s*(.+)$/.exec(line.trim());
|
|
126
|
+
if (!m) return null;
|
|
127
|
+
const terms = [...(m[1] ?? "").matchAll(QUOTED_WORD)].map((q) => q[1] ?? "").filter(Boolean);
|
|
128
|
+
return terms.length ? { terms } : null;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** True for either map-gate line: such a Reuse section follows the map rule, not the plain checked: rule. */
|
|
132
|
+
export function isMapOrNoneLine(line: string): boolean {
|
|
133
|
+
return parseMapLine(line) !== null || parseNoneLine(line) !== null;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export interface CitedQuote {
|
|
137
|
+
file: string;
|
|
138
|
+
n: number;
|
|
139
|
+
quote: string;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Every `checked: <path>:<n> "<quote>"` citation on a line, in order. */
|
|
143
|
+
export function citedQuotes(line: string): CitedQuote[] {
|
|
144
|
+
return [...line.matchAll(/checked:\s*`?([^`\s—"]+):(\d+)`?\s+"([^"]*)"/g)].map((m) => ({
|
|
145
|
+
file: m[1] ?? "",
|
|
146
|
+
n: Number(m[2]),
|
|
147
|
+
quote: m[3] ?? "",
|
|
148
|
+
}));
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** A `checked:` citation on the line without a `"<quote>"` part — the map gate requires the quote. */
|
|
152
|
+
export function hasBareChecked(line: string): boolean {
|
|
153
|
+
return [...line.matchAll(/checked:\s*[^—]*/g)].some((m) => !m[0]?.includes('"'));
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// --- searchTerms: one `graphify query <term>` per term, memoised by (repo, graph mtime, term) ---
|
|
157
|
+
|
|
158
|
+
export interface TermResult {
|
|
159
|
+
/** `slow`: the plan check's budget ran out before this term got a verdict; retry, never a pass. */
|
|
160
|
+
status: "hit" | "none" | "slow";
|
|
161
|
+
/** Repo-relative files the term matched; on an ambiguous hit, the candidates named. */
|
|
162
|
+
files: string[];
|
|
163
|
+
/** Set when graphify failed or named no files: the one-line problem, never a silent pass. */
|
|
164
|
+
problem?: string;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const queryMemo = new Map<string, TermResult>();
|
|
168
|
+
|
|
169
|
+
/** Files a query stdout names: `src=<file>` NODE attributes, or the candidate paths of an `Ambiguous:` refusal. */
|
|
170
|
+
export function filesFromQuery(stdout: string): string[] {
|
|
171
|
+
const matches = stdout.includes("Ambiguous:")
|
|
172
|
+
? [...stdout.matchAll(/^ (\S+)$/gm)].map((m) => m[1] ?? "")
|
|
173
|
+
: [...stdout.matchAll(/\bsrc=(\S+)/g)].map((m) => m[1] ?? "");
|
|
174
|
+
return [...new Set(matches.filter(Boolean))];
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Exit 0 = hit; exit 3 = several (an `Ambiguous:` refusal listing candidate files — still a hit);
|
|
179
|
+
* exit 4 = none; anything else, a timeout or output naming no files is a problem.
|
|
180
|
+
*/
|
|
181
|
+
function termResult(term: string, r: GraphifyResult): TermResult {
|
|
182
|
+
if (r.status === 0 || r.status === 3) {
|
|
183
|
+
const files = filesFromQuery(r.stdout);
|
|
184
|
+
if (files.length) return { status: "hit", files };
|
|
185
|
+
return { status: "none", files: [], problem: `graphify query "${term}" exited ${r.status} without naming files` };
|
|
186
|
+
}
|
|
187
|
+
if (r.status === 4) return { status: "none", files: [] };
|
|
188
|
+
const why = r.status === null ? "timed out" : `exited ${r.status}`;
|
|
189
|
+
const line = firstLine(r.stderr) || firstLine(r.stdout);
|
|
190
|
+
return { status: "none", files: [], problem: `graphify query "${term}" ${why}${line ? `: ${line}` : ""}` };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function firstLine(text: string): string {
|
|
194
|
+
return (text.trim().split("\n")[0] ?? "").slice(0, 120);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Returned for a term the budget never reached; never memoised, so a retry queries it again. */
|
|
198
|
+
const SLOW: TermResult = { status: "slow", files: [] };
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* One query per uncached term, each capped at the budget's time left. Once the budget is spent the
|
|
202
|
+
* rest come back `slow`: the plan check refuses and is retried, rather than running past its budget.
|
|
203
|
+
*/
|
|
204
|
+
export function searchTerms(
|
|
205
|
+
graph: ReuseGraph,
|
|
206
|
+
repo: string,
|
|
207
|
+
terms: string[],
|
|
208
|
+
memo: Map<string, TermResult> = queryMemo,
|
|
209
|
+
budget: QueryBudget = queryBudget(),
|
|
210
|
+
): TermResult[] {
|
|
211
|
+
return terms.map((term) => {
|
|
212
|
+
const key = `${repo}|${graphMtime(repo)}|${term}`;
|
|
213
|
+
const hit = memo.get(key);
|
|
214
|
+
if (hit) return hit;
|
|
215
|
+
const left = budget.until - Date.now();
|
|
216
|
+
if (left <= 0) return SLOW;
|
|
217
|
+
const r = graph.query(repo, term, Math.min(QUERY_TIMEOUT_MS, left));
|
|
218
|
+
// A timeout that ran into the budget is the budget's doing, not graphify's: slow, not memoised.
|
|
219
|
+
if (r.status === null && Date.now() >= budget.until) return SLOW;
|
|
220
|
+
const result = termResult(term, r);
|
|
221
|
+
memo.set(key, result);
|
|
222
|
+
return result;
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function graphMtime(repo: string): number {
|
|
227
|
+
try {
|
|
228
|
+
return statSync(path.join(repo, GRAPH_DIR, "graph.json")).mtimeMs;
|
|
229
|
+
} catch {
|
|
230
|
+
return 0;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// --- freshGraph: the map, rebuilt on demand under the graphify-out lock ---
|
|
235
|
+
|
|
236
|
+
function gitOut(repo: string, args: string[]): string | null {
|
|
237
|
+
const r = spawnSync("git", args, { cwd: repo, encoding: "utf8" });
|
|
238
|
+
return r.status === 0 ? (r.stdout ?? "") : null;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* The freshness stamp: HEAD sha + sha256 of `git diff HEAD` and the untracked names — both
|
|
243
|
+
* without `*.md` and graphify-out/ (code-only ingests non-md files under docs/, so only `.md`
|
|
244
|
+
* is excluded) — plus graph.json's mtime, so a foreign `update`/hook rewrite counts as stale.
|
|
245
|
+
* Null when the repo is not a git repository.
|
|
246
|
+
*/
|
|
247
|
+
export function reuseStamp(repo: string): string | null {
|
|
248
|
+
const head = gitOut(repo, ["rev-parse", "HEAD"]);
|
|
249
|
+
if (head === null) return null;
|
|
250
|
+
const diff = gitOut(repo, ["diff", "HEAD", "--", ":(exclude)*.md", ":(exclude)graphify-out"]) ?? "";
|
|
251
|
+
const untracked = gitOut(repo, ["ls-files", "--others", "--exclude-standard", "--", ":(exclude)*.md", ":(exclude)graphify-out"]) ?? "";
|
|
252
|
+
const code = createHash("sha256").update(`${diff}\n${untracked}`).digest("hex");
|
|
253
|
+
return `${head.trim()}\n${code}\n${graphMtime(repo)}`;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function readStamp(repo: string): string | null {
|
|
257
|
+
try {
|
|
258
|
+
return readFileSync(path.join(repo, STAMP_FILE), "utf8").trim();
|
|
259
|
+
} catch {
|
|
260
|
+
return null;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function parseableGraph(graphFile: string): boolean {
|
|
265
|
+
if (!existsSync(graphFile)) return false;
|
|
266
|
+
try {
|
|
267
|
+
const g: unknown = JSON.parse(readFileSync(graphFile, "utf8"));
|
|
268
|
+
if (typeof g !== "object" || g === null || !("nodes" in g)) return false;
|
|
269
|
+
return Array.isArray(g.nodes);
|
|
270
|
+
} catch {
|
|
271
|
+
return false;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* The repo's code map, current before this returns: `extract . --code-only` runs when graph.json
|
|
277
|
+
* is missing or unparseable or the freshness stamp differs (a commit, dirty code, or a foreign
|
|
278
|
+
* rewrite of graph.json — its mtime is in the stamp). Under the graphify-out lock; any failure is
|
|
279
|
+
* a one-line problem, never a silent pass. `build: false` (the spawn check) never builds: a held
|
|
280
|
+
* lock means a rebuild is running now, else the map is stale until the owner's `reuse map` runs.
|
|
281
|
+
*/
|
|
282
|
+
export function freshGraph(
|
|
283
|
+
repo: string,
|
|
284
|
+
exclude: string[],
|
|
285
|
+
graph: ReuseGraph = realGraphify,
|
|
286
|
+
{ build = true }: { build?: boolean } = {},
|
|
287
|
+
): string[] {
|
|
288
|
+
const graphFile = path.join(repo, GRAPH_DIR, "graph.json");
|
|
289
|
+
const lockFile = path.join(repo, LOCK_FILE);
|
|
290
|
+
if (reuseStamp(repo) === null) return [`graphify: ${repo} is not a git repository — run \`neurastream reuse on\` from a git repo`];
|
|
291
|
+
if (readStamp(repo) === reuseStamp(repo) && parseableGraph(graphFile)) return [];
|
|
292
|
+
if (!build) {
|
|
293
|
+
// `existsSync` first: isBusy would create the graphify-out directory, and the spawn check writes at most the empty lock file.
|
|
294
|
+
const rebuilding = existsSync(path.join(repo, GRAPH_DIR)) && isBusy(lockFile);
|
|
295
|
+
return [
|
|
296
|
+
rebuilding
|
|
297
|
+
? `the map of ${repo} is rebuilding — retry`
|
|
298
|
+
: `the map of ${repo} is stale — run \`neurastream reuse map <plan> "<term>"...\` (rebuilds it) and paste its line`,
|
|
299
|
+
];
|
|
300
|
+
}
|
|
301
|
+
mkdirSync(path.join(repo, GRAPH_DIR), { recursive: true });
|
|
302
|
+
return withFileLock(lockFile, () => {
|
|
303
|
+
// Another holder may have built while this call waited for the lock: re-check before building.
|
|
304
|
+
if (readStamp(repo) === reuseStamp(repo) && parseableGraph(graphFile)) return [];
|
|
305
|
+
const r = graph.build(repo, exclude);
|
|
306
|
+
if (r.status !== 0) {
|
|
307
|
+
const why = r.status === null ? "timed out" : `exit ${r.status}`;
|
|
308
|
+
const line = firstLine(r.stderr) || firstLine(r.stdout);
|
|
309
|
+
return [`graphify extract failed in ${repo} (${why})${line ? `: ${line}` : ""} — fix the error or run \`neurastream reuse off\``];
|
|
310
|
+
}
|
|
311
|
+
if (!parseableGraph(graphFile))
|
|
312
|
+
return [`graphify extract wrote no readable ${GRAPH_DIR}/graph.json in ${repo} — rerun \`graphify extract . --code-only\` there`];
|
|
313
|
+
writeAtomicSync(path.join(repo, STAMP_FILE), `${reuseStamp(repo) ?? ""}\n`);
|
|
314
|
+
return [];
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** The budget one plan check spends across its queries; a before and an after pass pass the same one. */
|
|
319
|
+
export interface QueryBudget {
|
|
320
|
+
until: number;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
export function queryBudget(): QueryBudget {
|
|
324
|
+
return { until: Date.now() + QUERY_BUDGET_MS };
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** graphify has no end-of-options marker, so a term starting with "-" would be read as an option: refused before any query. */
|
|
328
|
+
export function optionTermProblems(terms: string[]): string[] {
|
|
329
|
+
return terms
|
|
330
|
+
.filter((t) => t.startsWith("-"))
|
|
331
|
+
.map((t) => `reuse map: term "${t}" starts with "-" — graphify reads it as an option; search a word that does not start with "-"`);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** Every term a plan's map or none lines name, in order. */
|
|
335
|
+
export function planTerms(lines: string[]): string[] {
|
|
336
|
+
return lines.flatMap((l) => parseMapLine(l)?.terms ?? parseNoneLine(l)?.terms ?? []);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* The roots a `new:` citation may read under: the plan's repo, its registered worktrees, and every
|
|
341
|
+
* mapped repo, all realpath'd. The plan's own `Worktree:` line is never a root: the plan text is not trusted.
|
|
342
|
+
*/
|
|
343
|
+
export function citeRoots(planDir: string, mapped: string[]): string[] {
|
|
344
|
+
const top = gitOut(planDir, ["rev-parse", "--show-toplevel"])?.trim() ?? "";
|
|
345
|
+
const trees = [...(top ? (gitOut(top, ["worktree", "list", "--porcelain"]) ?? "") : "").matchAll(/^worktree (.+)$/gm)].map((m) => m[1] ?? "");
|
|
346
|
+
const found = [top, ...trees, ...mapped].filter(Boolean).flatMap((p) => {
|
|
347
|
+
try {
|
|
348
|
+
return [realpathSync(p)];
|
|
349
|
+
} catch {
|
|
350
|
+
return [];
|
|
351
|
+
}
|
|
352
|
+
});
|
|
353
|
+
return [...new Set(found)];
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** Inside `root` by path arithmetic: not the root itself, not above it, not on another drive. */
|
|
357
|
+
function inside(root: string, p: string): boolean {
|
|
358
|
+
const rel = path.relative(root, p);
|
|
359
|
+
return rel !== "" && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* A cited file's text, or null with nothing read. It must resolve (through symlinks) inside a root,
|
|
364
|
+
* be committed in that root's HEAD, and still be a regular file inside the root once opened
|
|
365
|
+
* (O_NOFOLLOW, an fstat check, then the open descriptor re-resolved). `beforeOpen` is the test seam
|
|
366
|
+
* for a swap between the resolve and the open.
|
|
367
|
+
*/
|
|
368
|
+
export function readConfined(abs: string, roots: string[], beforeOpen: () => void = () => {}): string | null {
|
|
369
|
+
let real: string;
|
|
370
|
+
try {
|
|
371
|
+
real = realpathSync(abs);
|
|
372
|
+
} catch {
|
|
373
|
+
return null;
|
|
374
|
+
}
|
|
375
|
+
// Roots are compared resolved, like `real`: a symlinked root (macOS tmpdir is /var → /private/var) still contains its files.
|
|
376
|
+
const root = roots.flatMap((r) => {
|
|
377
|
+
try {
|
|
378
|
+
return [realpathSync(r)];
|
|
379
|
+
} catch {
|
|
380
|
+
return [];
|
|
381
|
+
}
|
|
382
|
+
}).find((r) => inside(r, real));
|
|
383
|
+
if (root === undefined) return null;
|
|
384
|
+
if (spawnSync("git", ["-C", root, "cat-file", "-e", `HEAD:${path.relative(root, real)}`]).status !== 0) return null;
|
|
385
|
+
beforeOpen();
|
|
386
|
+
let fd: number;
|
|
387
|
+
try {
|
|
388
|
+
fd = openSync(real, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK);
|
|
389
|
+
} catch {
|
|
390
|
+
return null;
|
|
391
|
+
}
|
|
392
|
+
try {
|
|
393
|
+
const st = fstatSync(fd);
|
|
394
|
+
return st.isFile() && openedInside(fd, real, st, root) ? readFileSync(fd, "utf8") : null;
|
|
395
|
+
} finally {
|
|
396
|
+
closeSync(fd);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/** Whether the open descriptor still names a file inside `root`: /proc on Linux, else dev/ino against the re-resolved path. */
|
|
401
|
+
function openedInside(fd: number, real: string, st: Stats, root: string): boolean {
|
|
402
|
+
if (process.platform === "linux") return inside(root, realpathSync(`/proc/self/fd/${fd}`));
|
|
403
|
+
const now = realpathSync(real);
|
|
404
|
+
const same = statSync(now);
|
|
405
|
+
return inside(root, now) && same.dev === st.dev && same.ino === st.ino;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
// --- P3 (plan 20261122_1828_reuse_map): the routines behind `neurastream reuse` ---
|
|
409
|
+
|
|
410
|
+
/** The pinned package spec; the only thing `reuse on` installs (double y; other names are typosquats). */
|
|
411
|
+
export const GRAPHIFY_PIN = `graphifyy==${GRAPHIFY_VERSION}`;
|
|
412
|
+
|
|
413
|
+
/** A stored repo path resolved against this HOME (`~/x` allowed, like the gate reads repos). */
|
|
414
|
+
function inHome(p: string, home: string): string {
|
|
415
|
+
return path.resolve(p === "~" ? home : p.startsWith("~/") ? path.join(home, p.slice(2)) : p);
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* The `reuse on` candidates: git repos with a docs/plans directory one level below the given
|
|
420
|
+
* work roots, sorted, deduplicated. Walks with setup-detect's exported walk — no second one.
|
|
421
|
+
*/
|
|
422
|
+
export function reuseCandidates(workRoots: string[]): string[] {
|
|
423
|
+
const repos = workRoots.flatMap((root) => repoDirs(root)).filter((repo) => existsSync(path.join(repo, "docs", "plans")));
|
|
424
|
+
return [...new Set(repos.map((r) => path.resolve(r)))].toSorted();
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
// --- the per-repo footprint: one marked line in .git/info/exclude, removed by `reuse off` ---
|
|
428
|
+
|
|
429
|
+
const EXCLUDE_MARK = "# neurastream reuse map (neurastream reuse off removes this)";
|
|
430
|
+
|
|
431
|
+
/** The repo's info/exclude — `git rev-parse --git-path`, so a worktree resolves into its main .git. */
|
|
432
|
+
function excludeFile(repo: string): string | null {
|
|
433
|
+
const rel = gitOut(repo, ["rev-parse", "--git-path", "info/exclude"]);
|
|
434
|
+
return rel === null || !rel.trim() ? null : path.resolve(repo, rel.trim());
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/** True when graphify-out/ is excluded — by our mark, or by an owner line written before `reuse on`. */
|
|
438
|
+
export function excludePresent(repo: string): boolean {
|
|
439
|
+
try {
|
|
440
|
+
const lines = readFileSync(excludeFile(repo) ?? "", "utf8").split("\n");
|
|
441
|
+
return lines.includes(EXCLUDE_MARK) || lines.some((l) => l.trim() === `${GRAPH_DIR}/`);
|
|
442
|
+
} catch {
|
|
443
|
+
return false;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** Adds our marked exclude block; false when graphify-out/ is already excluded (idempotent). */
|
|
448
|
+
export function addExclude(repo: string): boolean {
|
|
449
|
+
if (excludePresent(repo)) return false;
|
|
450
|
+
const file = excludeFile(repo);
|
|
451
|
+
if (file === null) return false;
|
|
452
|
+
const cur = existsSync(file) ? readFileSync(file, "utf8") : "";
|
|
453
|
+
const base = cur === "" || cur.endsWith("\n") ? cur : `${cur}\n`;
|
|
454
|
+
writeFileSync(file, `${base}${EXCLUDE_MARK}\n${GRAPH_DIR}/\n`);
|
|
455
|
+
return true;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/** Removes our marked exclude block; an owner's own graphify-out/ line survives. */
|
|
459
|
+
export function removeExclude(repo: string): void {
|
|
460
|
+
const file = excludeFile(repo);
|
|
461
|
+
if (file === null) return;
|
|
462
|
+
let text: string;
|
|
463
|
+
try {
|
|
464
|
+
text = readFileSync(file, "utf8");
|
|
465
|
+
} catch {
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
const lines = text.split("\n");
|
|
469
|
+
const at = lines.indexOf(EXCLUDE_MARK);
|
|
470
|
+
if (at < 0) return;
|
|
471
|
+
const end = lines[at + 1]?.trim() === `${GRAPH_DIR}/` ? at + 2 : at + 1;
|
|
472
|
+
lines.splice(at, end - at);
|
|
473
|
+
writeFileSync(file, lines.join("\n"));
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
// --- install: uv, else pipx; never system pip, never sudo ---
|
|
477
|
+
|
|
478
|
+
function onPath(bin: string, env: NodeJS.ProcessEnv): boolean {
|
|
479
|
+
for (const dir of (env.PATH ?? "").split(":")) {
|
|
480
|
+
if (dir === "") continue;
|
|
481
|
+
try {
|
|
482
|
+
if (statSync(path.join(dir, bin)).isFile()) return true;
|
|
483
|
+
} catch {}
|
|
484
|
+
}
|
|
485
|
+
return false;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
function spawnTool(tool: "uv" | "pipx", args: string[], env: NodeJS.ProcessEnv): { status: number | null; line: string } {
|
|
489
|
+
const r = spawnSync(tool, args, { encoding: "utf8", env, timeout: BUILD_TIMEOUT_MS });
|
|
490
|
+
const line = (r.stderr ?? "").trim().split("\n")[0] || (r.stdout ?? "").trim().split("\n")[0] || "(no output)";
|
|
491
|
+
return { status: r.status, line };
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/** Installs the pinned package with uv, else pipx; false (reason on err) when neither works. */
|
|
495
|
+
function installGraphify(env: NodeJS.ProcessEnv, err: (line: string) => void): boolean {
|
|
496
|
+
for (const tool of ["uv", "pipx"] as const) {
|
|
497
|
+
if (!onPath(tool, env)) continue;
|
|
498
|
+
const r = spawnTool(tool, tool === "uv" ? ["tool", "install", GRAPHIFY_PIN] : ["install", GRAPHIFY_PIN], env);
|
|
499
|
+
if (r.status === 0) return true;
|
|
500
|
+
err(`reuse: ${tool} install failed (${r.status === null ? "timed out" : `exit ${r.status}`}): ${r.line.slice(0, 120)}`);
|
|
501
|
+
return false;
|
|
502
|
+
}
|
|
503
|
+
err("reuse: graphify is not installed and neither uv nor pipx is on PATH — install uv or pipx, then rerun: neurastream reuse on");
|
|
504
|
+
return false;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/** Uninstalls graphifyy with whichever of uv/pipx is present; true when done or nothing to do. */
|
|
508
|
+
function uninstallGraphify(env: NodeJS.ProcessEnv, err: (line: string) => void): boolean {
|
|
509
|
+
for (const tool of ["uv", "pipx"] as const) {
|
|
510
|
+
if (!onPath(tool, env)) continue;
|
|
511
|
+
const r = spawnTool(tool, tool === "uv" ? ["tool", "uninstall", "graphifyy"] : ["uninstall", "graphifyy"], env);
|
|
512
|
+
if (r.status === 0 || /not installed|nothing to uninstall|no such tool/i.test(r.line)) return true;
|
|
513
|
+
err(`reuse: ${tool} uninstall failed (${r.status === null ? "timed out" : `exit ${r.status}`}): ${r.line.slice(0, 120)}`);
|
|
514
|
+
return false;
|
|
515
|
+
}
|
|
516
|
+
return true;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/** What a reuse routine needs: where the config lives, the env for uv/pipx, and the terminal. */
|
|
520
|
+
export interface ReuseDeps {
|
|
521
|
+
home: string;
|
|
522
|
+
env: NodeJS.ProcessEnv;
|
|
523
|
+
/** stdin and stdout are a terminal: `reuse on` asks y/N per candidate repo. */
|
|
524
|
+
terminal: boolean;
|
|
525
|
+
ask: (prompt: string) => string;
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
export interface ReuseOutcome {
|
|
529
|
+
code: number;
|
|
530
|
+
/** Normal output lines (stdout). */
|
|
531
|
+
out: string[];
|
|
532
|
+
/** Error and usage lines (stderr). */
|
|
533
|
+
err: string[];
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
/**
|
|
537
|
+
* `reuse on [<repo>...]`: map repos with graphify. With args, no prompt; without, a terminal
|
|
538
|
+
* asks y/N per candidate repo and a non-terminal exits 2 listing the candidates, nothing
|
|
539
|
+
* written. Installs the pinned tool (uv, else pipx) unless `graphify --version` already
|
|
540
|
+
* matches. Per repo: the exclude line, then freshGraph (extract . --code-only with the
|
|
541
|
+
* config's excludes, graph.json checked, stamp written). Any failure undoes this run's repos;
|
|
542
|
+
* config.yml is written last and only then (enabled true, repos = old ∪ new), so a failure
|
|
543
|
+
* leaves it byte-identical. Idempotent.
|
|
544
|
+
*/
|
|
545
|
+
export function reuseOn(args: string[], deps: ReuseDeps, graph: ReuseGraph = realGraphify): ReuseOutcome {
|
|
546
|
+
const out: string[] = [];
|
|
547
|
+
const err: string[] = [];
|
|
548
|
+
const cfg = loadConfig({ home: deps.home, env: deps.env });
|
|
549
|
+
const have = new Set(cfg.reuse_map.repos.map((r) => inHome(r, deps.home)));
|
|
550
|
+
let repos: string[];
|
|
551
|
+
if (args.length) {
|
|
552
|
+
repos = args.map((a) => inHome(a, deps.home));
|
|
553
|
+
const bad = repos.filter((r) => !existsSync(path.join(r, ".git")));
|
|
554
|
+
if (bad.length) {
|
|
555
|
+
for (const r of bad) err.push(`reuse: ${r} is not a git repository`);
|
|
556
|
+
err.push("usage: neurastream reuse on [<repo>...]");
|
|
557
|
+
return { code: 2, out, err };
|
|
558
|
+
}
|
|
559
|
+
} else {
|
|
560
|
+
const candidates = reuseCandidates(cfg.paths.work_roots.map((w) => inHome(w, deps.home))).filter((r) => !have.has(r));
|
|
561
|
+
if (!candidates.length) {
|
|
562
|
+
out.push("reuse: no unmapped repos with docs/plans under paths.work_roots — pass one: neurastream reuse on <repo>");
|
|
563
|
+
return { code: 0, out, err };
|
|
564
|
+
}
|
|
565
|
+
if (!deps.terminal) {
|
|
566
|
+
err.push("reuse: no repos given and stdin is not a terminal — pass them: neurastream reuse on <repo>...");
|
|
567
|
+
err.push("candidates:");
|
|
568
|
+
for (const c of candidates) err.push(` ${c}`);
|
|
569
|
+
return { code: 2, out, err };
|
|
570
|
+
}
|
|
571
|
+
repos = [];
|
|
572
|
+
for (const c of candidates) if (/^y(es)?$/i.test(deps.ask(`Map ${c} with graphify? [y/N] `).trim())) repos.push(c);
|
|
573
|
+
if (!repos.length) {
|
|
574
|
+
out.push("reuse: nothing selected — nothing changed");
|
|
575
|
+
return { code: 0, out, err };
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
// The pinned tool: install only when the version check fails. Still nothing on disk.
|
|
579
|
+
if (versionProblem(graph) !== null && !installGraphify(deps.env, (l) => err.push(l))) return { code: 1, out, err };
|
|
580
|
+
// Per repo; every failure undoes everything this run touched — config included (it is last).
|
|
581
|
+
const touched: { repo: string; exclude: boolean; graphDir: boolean; stamp: boolean }[] = [];
|
|
582
|
+
const undo = (): void => {
|
|
583
|
+
for (const t of touched.toReversed()) {
|
|
584
|
+
if (t.exclude) removeExclude(t.repo);
|
|
585
|
+
if (!t.graphDir) rmSync(path.join(t.repo, GRAPH_DIR), { recursive: true, force: true });
|
|
586
|
+
else if (!t.stamp) rmSync(path.join(t.repo, STAMP_FILE), { force: true });
|
|
587
|
+
}
|
|
588
|
+
};
|
|
589
|
+
for (const repo of repos) {
|
|
590
|
+
const graphDir = existsSync(path.join(repo, GRAPH_DIR));
|
|
591
|
+
const stamp = existsSync(path.join(repo, STAMP_FILE));
|
|
592
|
+
touched.push({ repo, exclude: addExclude(repo), graphDir, stamp });
|
|
593
|
+
const problems = freshGraph(repo, cfg.reuse_map.exclude, graph);
|
|
594
|
+
if (problems.length) {
|
|
595
|
+
undo();
|
|
596
|
+
for (const p of problems) err.push(`reuse: ${p}`);
|
|
597
|
+
err.push("reuse: rolled back — nothing mapped, config.yml unchanged");
|
|
598
|
+
return { code: 1, out, err };
|
|
599
|
+
}
|
|
600
|
+
out.push(`mapped ${repo} (map built, stamp written)`);
|
|
601
|
+
}
|
|
602
|
+
const union = [...cfg.reuse_map.repos];
|
|
603
|
+
for (const r of repos) if (!union.some((u) => inHome(u, deps.home) === r)) union.push(r);
|
|
604
|
+
const file = configFile(deps.home);
|
|
605
|
+
const edited = setConfigKeys(
|
|
606
|
+
existsSync(file) ? readFileSync(file, "utf8") : null,
|
|
607
|
+
{ "reuse_map.enabled": yamlValue(true), "reuse_map.repos": yamlValue(union) },
|
|
608
|
+
);
|
|
609
|
+
if (!checkEdited(edited, deps.home, (l) => err.push(l))) {
|
|
610
|
+
undo();
|
|
611
|
+
err.push("reuse: the edited config would not load — rolled back, config.yml unchanged");
|
|
612
|
+
return { code: 1, out, err };
|
|
613
|
+
}
|
|
614
|
+
mkdirSync(path.dirname(file), { recursive: true });
|
|
615
|
+
writeFileSync(file, edited);
|
|
616
|
+
out.push(`reuse map on: ${union.length} repo(s) — new plans in them must cite the map under ## Reuse (off: neurastream reuse off)`);
|
|
617
|
+
return { code: 0, out, err };
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
/**
|
|
621
|
+
* `reuse off [--purge]`: removes our exclude line in every mapped repo (an owner's own
|
|
622
|
+
* graphify-out/ line survives), then writes enabled false / repos [] — config last, after the
|
|
623
|
+
* repo work. --purge also deletes each repo's graphify-out/ and uninstalls graphifyy.
|
|
624
|
+
*/
|
|
625
|
+
export function reuseOff(args: string[], deps: ReuseDeps): ReuseOutcome {
|
|
626
|
+
const purge = args.includes("--purge");
|
|
627
|
+
const unknown = args.find((a) => a !== "--purge");
|
|
628
|
+
if (unknown) return { code: 2, out: [], err: [`reuse: unknown flag ${unknown}`, "usage: neurastream reuse off [--purge]"] };
|
|
629
|
+
const out: string[] = [];
|
|
630
|
+
const err: string[] = [];
|
|
631
|
+
const cfg = loadConfig({ home: deps.home, env: deps.env });
|
|
632
|
+
if (!cfg.reuse_map.enabled && !cfg.reuse_map.repos.length) {
|
|
633
|
+
out.push("reuse map is already off");
|
|
634
|
+
return { code: 0, out, err };
|
|
635
|
+
}
|
|
636
|
+
for (const r of cfg.reuse_map.repos) {
|
|
637
|
+
const repo = inHome(r, deps.home);
|
|
638
|
+
removeExclude(repo);
|
|
639
|
+
if (purge) rmSync(path.join(repo, GRAPH_DIR), { recursive: true, force: true });
|
|
640
|
+
out.push(`${purge ? "purged" : "unmapped"} ${repo}`);
|
|
641
|
+
}
|
|
642
|
+
const file = configFile(deps.home);
|
|
643
|
+
const edited = setConfigKeys(
|
|
644
|
+
existsSync(file) ? readFileSync(file, "utf8") : null,
|
|
645
|
+
{ "reuse_map.enabled": yamlValue(false), "reuse_map.repos": yamlValue([]) },
|
|
646
|
+
);
|
|
647
|
+
if (!checkEdited(edited, deps.home, (l) => err.push(l))) {
|
|
648
|
+
err.push("reuse: the edited config would not load — config.yml unchanged, repos still mapped");
|
|
649
|
+
return { code: 1, out, err };
|
|
650
|
+
}
|
|
651
|
+
mkdirSync(path.dirname(file), { recursive: true });
|
|
652
|
+
writeFileSync(file, edited);
|
|
653
|
+
if (purge && !uninstallGraphify(deps.env, (l) => err.push(l))) return { code: 1, out, err };
|
|
654
|
+
out.push(`reuse map off${purge ? " (graphify-out deleted, graphifyy uninstalled)" : ""}`);
|
|
655
|
+
return { code: 0, out, err };
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
export interface GraphState {
|
|
659
|
+
/** graph.json's age in ms; null when there is none. */
|
|
660
|
+
ageMs: number | null;
|
|
661
|
+
/** The stamp matches HEAD + dirty code + graph mtime: freshGraph would not rebuild. */
|
|
662
|
+
fresh: boolean;
|
|
663
|
+
/** The repo is a git repository (worktrees included). */
|
|
664
|
+
git: boolean;
|
|
665
|
+
/** graph.json exists and parses as a node list. */
|
|
666
|
+
readable: boolean;
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
/** A mapped repo's graph state, for `reuse status` and doctor — never a build, never a query. */
|
|
670
|
+
export function graphState(repo: string, now: number = Date.now()): GraphState {
|
|
671
|
+
const stamp = reuseStamp(repo);
|
|
672
|
+
const graphFile = path.join(repo, GRAPH_DIR, "graph.json");
|
|
673
|
+
let ageMs: number | null = null;
|
|
674
|
+
try {
|
|
675
|
+
ageMs = now - statSync(graphFile).mtimeMs;
|
|
676
|
+
} catch {}
|
|
677
|
+
return { ageMs, git: stamp !== null, fresh: stamp !== null && readStamp(repo) === stamp, readable: parseableGraph(graphFile) };
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
/**
|
|
681
|
+
* `reuse status [--json]`: the tool version and each mapped repo's graph age and fresh/stale.
|
|
682
|
+
* Exit 1 on a problem: the tool missing or another version, a repo no longer a git repository,
|
|
683
|
+
* a missing or unparseable graph. Stale-but-readable is a state, not a problem — the gate
|
|
684
|
+
* rebuilds it at the next plan write.
|
|
685
|
+
*/
|
|
686
|
+
export function reuseStatus(args: string[], deps: ReuseDeps, graph: ReuseGraph = realGraphify): ReuseOutcome {
|
|
687
|
+
const json = args.includes("--json");
|
|
688
|
+
const unknown = args.find((a) => a !== "--json");
|
|
689
|
+
if (unknown) return { code: 2, out: [], err: [`reuse: unknown flag ${unknown}`, "usage: neurastream reuse status [--json]"] };
|
|
690
|
+
const cfg = loadConfig({ home: deps.home, env: deps.env });
|
|
691
|
+
if (!cfg.reuse_map.enabled)
|
|
692
|
+
return {
|
|
693
|
+
code: 0,
|
|
694
|
+
out: json ? [JSON.stringify({ enabled: false, repos: [], problems: [] })] : ["reuse map: off (turn on: neurastream reuse on <repo>)"],
|
|
695
|
+
err: [],
|
|
696
|
+
};
|
|
697
|
+
const problems: string[] = [];
|
|
698
|
+
const vp = versionProblem(graph);
|
|
699
|
+
if (vp) problems.push(vp);
|
|
700
|
+
const repos = cfg.reuse_map.repos.map((r) => {
|
|
701
|
+
const repo = inHome(r, deps.home);
|
|
702
|
+
const st = graphState(repo);
|
|
703
|
+
if (!st.git) problems.push(`${repo} is not a git repository any more — neurastream reuse off removes it`);
|
|
704
|
+
else if (!st.readable) problems.push(`${repo} has no readable ${GRAPH_DIR}/graph.json — the gate rebuilds it at the next plan write`);
|
|
705
|
+
return { repo, fresh: st.fresh, ageSec: st.ageMs === null ? null : Math.round(st.ageMs / 1000) };
|
|
706
|
+
});
|
|
707
|
+
if (json)
|
|
708
|
+
return {
|
|
709
|
+
code: problems.length ? 1 : 0,
|
|
710
|
+
out: [JSON.stringify({ enabled: true, version: vp ? null : GRAPHIFY_VERSION, problems, repos }, null, 2)],
|
|
711
|
+
err: [],
|
|
712
|
+
};
|
|
713
|
+
const out = [vp ?? `graphify ${GRAPHIFY_VERSION} on PATH`];
|
|
714
|
+
for (const r of repos) {
|
|
715
|
+
const age = r.ageSec === null ? "no graph" : `${Math.max(1, r.ageSec)}s old`;
|
|
716
|
+
out.push(`${r.repo}: ${r.fresh ? "fresh" : "stale"}, ${age}`);
|
|
717
|
+
}
|
|
718
|
+
for (const p of problems) out.push(`problem: ${p}`);
|
|
719
|
+
return { code: problems.length ? 1 : 0, out, err: [] };
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/**
|
|
723
|
+
* The doctor's lines (printed beside tailscale's): off is one ok line and
|
|
724
|
+
* never touches the seam; on, a version other than the pin, a repo that stopped being a git
|
|
725
|
+
* repository, and a missing or unparseable graph are problems; stale is only reported.
|
|
726
|
+
*/
|
|
727
|
+
export function reuseMapDoctor(cfg: Config, graph: ReuseGraph = realGraphify): { ok: string[]; problems: string[] } {
|
|
728
|
+
if (!cfg.reuse_map.enabled) return { ok: ["reuse map: off"], problems: [] };
|
|
729
|
+
const ok: string[] = [];
|
|
730
|
+
const problems: string[] = [];
|
|
731
|
+
const vp = versionProblem(graph);
|
|
732
|
+
if (vp) problems.push(`reuse map: ${vp}`);
|
|
733
|
+
else ok.push(`reuse map: graphify ${GRAPHIFY_VERSION}, ${cfg.reuse_map.repos.length} repo(s)`);
|
|
734
|
+
for (const r of cfg.reuse_map.repos) {
|
|
735
|
+
const repo = inHome(r, cfg.paths.home);
|
|
736
|
+
const st = graphState(repo);
|
|
737
|
+
if (!st.git) problems.push(`reuse map: ${repo} is not a git repository any more — neurastream reuse off removes it`);
|
|
738
|
+
else if (!st.readable) problems.push(`reuse map: ${repo} has no readable ${GRAPH_DIR}/graph.json — the gate rebuilds it at the next plan write`);
|
|
739
|
+
else ok.push(`reuse map: ${repo} ${st.fresh ? "fresh" : "stale"}`);
|
|
740
|
+
}
|
|
741
|
+
return { ok, problems };
|
|
742
|
+
}
|