wicked-crew 0.18.2 → 0.18.4
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/dist/api/routes.d.ts +4 -0
- package/dist/api/routes.d.ts.map +1 -1
- package/dist/api/routes.js +2 -0
- package/dist/api/routes.js.map +1 -1
- package/dist/api/server.d.ts +8 -0
- package/dist/api/server.d.ts.map +1 -1
- package/dist/api/server.js +49 -2
- package/dist/api/server.js.map +1 -1
- package/dist/core/adapter.d.ts +11 -0
- package/dist/core/adapter.d.ts.map +1 -1
- package/dist/core/adapter.js +11 -0
- package/dist/core/adapter.js.map +1 -1
- package/dist/projects/auto-refresh.d.ts +17 -6
- package/dist/projects/auto-refresh.d.ts.map +1 -1
- package/dist/projects/auto-refresh.js +16 -11
- package/dist/projects/auto-refresh.js.map +1 -1
- package/dist/projects/graph.d.ts +6 -0
- package/dist/projects/graph.d.ts.map +1 -1
- package/dist/projects/graph.js +16 -4
- package/dist/projects/graph.js.map +1 -1
- package/dist/projects/repo-watch-routes.d.ts +16 -0
- package/dist/projects/repo-watch-routes.d.ts.map +1 -0
- package/dist/projects/repo-watch-routes.js +51 -0
- package/dist/projects/repo-watch-routes.js.map +1 -0
- package/dist/projects/repo-watch.d.ts +227 -0
- package/dist/projects/repo-watch.d.ts.map +1 -0
- package/dist/projects/repo-watch.js +851 -0
- package/dist/projects/repo-watch.js.map +1 -0
- package/dist/projects/state-home-registry.d.ts.map +1 -1
- package/dist/projects/state-home-registry.js +2 -0
- package/dist/projects/state-home-registry.js.map +1 -1
- package/dist/studio/assets/{KnowledgeGraph-D05VIXiQ.js → KnowledgeGraph-BegFkdaI.js} +1 -1
- package/dist/studio/assets/{index-CUudUAZ_.js → index-DHJTqNvn.js} +307 -303
- package/dist/studio/assets/index-DRbLc6Zm.css +32 -0
- package/dist/studio/editors/wicked-apps/editor.json +1 -1
- package/dist/studio/editors/wicked-apps/index.html +1 -1
- package/dist/studio/editors/wicked-deck/editor.json +1 -1
- package/dist/studio/editors/wicked-deck/index.html +1 -1
- package/dist/studio/editors/wicked-doc/editor.json +1 -1
- package/dist/studio/editors/wicked-doc/index.html +1 -1
- package/dist/studio/editors/wicked-insights/editor.json +1 -1
- package/dist/studio/editors/wicked-insights/index.html +1 -1
- package/dist/studio/editors/wicked-page/editor.json +1 -1
- package/dist/studio/editors/wicked-page/index.html +1 -1
- package/dist/studio/editors/wicked-video/editor.json +1 -1
- package/dist/studio/editors/wicked-video/index.html +1 -1
- package/dist/studio/index.html +2 -2
- package/dist/studio/testid-inventory.json +188 -103
- package/endpoint-manifest.json +33 -1
- package/package.json +4 -4
- package/dist/studio/assets/index-BPBBSo15.css +0 -32
|
@@ -0,0 +1,851 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE REPO WATCHER (crew-0183, wicked-core#1230): a registered repo's code graph follows its checkout
|
|
3
|
+
* with no click. Without it the repo graph (onboarding's) and the project graphs (refreshed after
|
|
4
|
+
* onboarding or by hand) stayed at whatever they were indexed at while the person edited, pulled,
|
|
5
|
+
* committed and switched branches, and chats, Understand and runs read the stale graph.
|
|
6
|
+
*
|
|
7
|
+
* # One mechanism: git state, polled
|
|
8
|
+
*
|
|
9
|
+
* Per repo, ONE process: `git -c core.fsmonitor=false status --porcelain=v2 -z --branch
|
|
10
|
+
* --untracked-files=all --ignore-submodules=dirty` with `GIT_OPTIONAL_LOCKS=0`. Its fingerprint is
|
|
11
|
+
* HEAD (`branch.oid`), the branch (`branch.head`) and every listed entry with its size and mtime: a
|
|
12
|
+
* commit or pull moves the oid, a switch the head, an edit to an already-modified file its stat, a
|
|
13
|
+
* new file (nested in a new untracked directory too: `all`) adds an entry. Why not `fs.watch`:
|
|
14
|
+
* recursive watching is emulated on Linux with one inotify watch per directory (node_modules
|
|
15
|
+
* exhausts `max_user_watches`, no ignore option); git is the same on macOS, Linux and Windows, holds
|
|
16
|
+
* no OS handle and already knows the ignore rules. `core.fsmonitor=false` because a repo-configured
|
|
17
|
+
* fsmonitor would spawn a `git fsmonitor--daemon` per repo that outlives the poll; optional locks
|
|
18
|
+
* off so a poll never takes `index.lock` beside the person's own git.
|
|
19
|
+
*
|
|
20
|
+
* # Bounded
|
|
21
|
+
*
|
|
22
|
+
* One poll at a time daemon-wide; a repo's next poll comes after `max(5 s, 10 × its last poll)`,
|
|
23
|
+
* at most 30 s (git takes ~10% of the loop's time per repo and slows itself on a loaded machine,
|
|
24
|
+
* while a change is still seen within 30 s); a failing poll backs off to 10 min. A change seen is
|
|
25
|
+
* polled again 5 s later and indexed when that poll sees the same fingerprint (the quiet window),
|
|
26
|
+
* or 60 s after the first change under continuous churn. At most
|
|
27
|
+
* {@link REPO_WATCH_CAP} repos. One index at a time (the queue below).
|
|
28
|
+
*
|
|
29
|
+
* # One writer
|
|
30
|
+
*
|
|
31
|
+
* The repo graph is written ONLY by the engine's `indexRepoGraph` (the onboarding index command,
|
|
32
|
+
* under the lock a launch's D8 base index takes; the engine re-reads the active runs on the repo under
|
|
33
|
+
* that lock and answers `held`). It is never re-indexed while a run holds it at its base: a run
|
|
34
|
+
* actively executing on the repo (its floor's affected set reads the graph at the base), or a
|
|
35
|
+
* `domain-extraction` run, executing or parked (its pages read the graph with no base check, #1230). A parked run does not hold it: its floor finds the graph not at its base and runs the full
|
|
36
|
+
* suite, disclosed (core `floor_affected.rs`, `review_scale::graph_age`). Then every project the repo
|
|
37
|
+
* is in is refreshed through the onboarding hook's own function. Nothing here re-runs
|
|
38
|
+
* `clusters --annotate`: "current" covers symbols, files and references, never clusters.
|
|
39
|
+
*
|
|
40
|
+
* # Restart
|
|
41
|
+
*
|
|
42
|
+
* `<state home>/repo-watch.json` (registered in the state-home registry crew and wicked-core ship) keeps,
|
|
43
|
+
* per repo, the fingerprint last indexed, when, when a launch on the repo last resolved its base, and the
|
|
44
|
+
* off switch. At boot every repo's first poll compares against it and indexes a difference (catch-up). A
|
|
45
|
+
* launch since the last index (`runBaseResolved`, then its D8 re-indexes the graph at that run's base)
|
|
46
|
+
* brings the graph back to the checkout once nothing holds it.
|
|
47
|
+
*/
|
|
48
|
+
import { createHash } from 'node:crypto';
|
|
49
|
+
import { constants, existsSync, realpathSync } from 'node:fs';
|
|
50
|
+
import { lstat, mkdir, open, readFile, readlink, rename, writeFile } from 'node:fs/promises';
|
|
51
|
+
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
|
52
|
+
import { runNameOf } from '../core/run-identity.js';
|
|
53
|
+
import { execCapped } from '../core/exec.js';
|
|
54
|
+
export const REPO_WATCH_CAP = 24;
|
|
55
|
+
export const POLL_MIN_MS = 5_000;
|
|
56
|
+
/** A repo's poll period is at least this many times its last poll's duration (git stays near 10% of its time)… */
|
|
57
|
+
export const POLL_DUTY = 10;
|
|
58
|
+
/** …and never longer than this, so a change is seen within it even when spawning git is slow on a loaded host. */
|
|
59
|
+
export const POLL_MAX_MS = 30_000;
|
|
60
|
+
/** A change seen is looked at again this soon: the quiet window (the index starts when it has not moved since). */
|
|
61
|
+
export const QUIET_MS = 5_000;
|
|
62
|
+
export const POLL_BACKOFF_MAX_MS = 10 * 60_000;
|
|
63
|
+
export const CHANGE_MAX_WAIT_MS = 60_000;
|
|
64
|
+
export const INDEX_BACKOFF_BASE_MS = 60_000;
|
|
65
|
+
export const INDEX_BACKOFF_MAX_MS = 30 * 60_000;
|
|
66
|
+
/** Entries whose size and mtime are read per poll; past it the fingerprint is the status text alone. */
|
|
67
|
+
export const STAT_CAP = 2_000;
|
|
68
|
+
export const GIT_TIMEOUT_MS = 20_000;
|
|
69
|
+
/** How long the repo list is reused before it is read again. */
|
|
70
|
+
export const REPOS_TTL_MS = 30_000;
|
|
71
|
+
/** The poll, verbatim (pinned by a test): no fsmonitor daemon, nested untracked files, dirty submodules ignored. */
|
|
72
|
+
export const POLL_ARGS = [
|
|
73
|
+
'-c', 'core.fsmonitor=false',
|
|
74
|
+
'status', '--porcelain=v2', '-z', '--branch', '--untracked-files=all', '--ignore-submodules=dirty',
|
|
75
|
+
];
|
|
76
|
+
/** An owed project refresh on an unpolled repo is served at least once every this many polls. */
|
|
77
|
+
const DEBT_EVERY = 10;
|
|
78
|
+
/** Path segments a change under never counts (a repo that forgot to ignore its build output must not loop). */
|
|
79
|
+
export const IGNORED_SEGMENTS = new Set(['.git', 'node_modules', 'target', 'dist', 'wicked-worktrees', '.wicked']);
|
|
80
|
+
/** Runs that never read the repo graph at a base (a chat, its analysis, crew's one-turn readers). */
|
|
81
|
+
const NON_GRAPH_RUNS = new Set(['chat', 'analyze', 'detect-shape', 'inspect-unit']);
|
|
82
|
+
const ACTIVE = new Set(['planning', 'distributing', 'executing']);
|
|
83
|
+
const TERMINAL = new Set(['completed', 'cancelled', 'failed']);
|
|
84
|
+
/** The engine's `graph_required` preset (core `actor.rs`): its pages read the graph with no base check. */
|
|
85
|
+
export const DOMAIN_MAPPING = 'domain-extraction';
|
|
86
|
+
/** `git status --porcelain=v2 -z --branch` → HEAD, branch, entries (`2` rename entries carry their origin path as the next field). */
|
|
87
|
+
export function parsePorcelainV2(stdout) {
|
|
88
|
+
const out = { oid: null, head: null, entries: [] };
|
|
89
|
+
const fields = stdout.split('\0');
|
|
90
|
+
for (let i = 0; i < fields.length; i++) {
|
|
91
|
+
const f = fields[i];
|
|
92
|
+
if (f === '')
|
|
93
|
+
continue;
|
|
94
|
+
if (f.startsWith('# ')) {
|
|
95
|
+
const [, key, ...rest] = f.split(' ');
|
|
96
|
+
const value = rest.join(' ');
|
|
97
|
+
if (key === 'branch.oid')
|
|
98
|
+
out.oid = value === '(initial)' ? null : value;
|
|
99
|
+
else if (key === 'branch.head')
|
|
100
|
+
out.head = value;
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
const kind = f[0];
|
|
104
|
+
if (kind === '?' || kind === '!') {
|
|
105
|
+
out.entries.push({ code: kind, path: f.slice(2) });
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
// 1 XY sub mH mI mW hH hI path | 2 XY sub mH mI mW hH hI Xscore path\0orig | u XY sub m1 m2 m3 mW h1 h2 h3 path
|
|
109
|
+
const fixed = kind === '1' ? 8 : kind === '2' ? 9 : kind === 'u' ? 10 : -1;
|
|
110
|
+
if (fixed < 0)
|
|
111
|
+
continue;
|
|
112
|
+
const parts = f.split(' ');
|
|
113
|
+
const entry = { code: `${kind} ${parts[1] ?? ''}`, path: parts.slice(fixed).join(' ') };
|
|
114
|
+
if (kind === '2') {
|
|
115
|
+
i++;
|
|
116
|
+
entry.from = fields[i] ?? '';
|
|
117
|
+
} // the origin path
|
|
118
|
+
out.entries.push(entry);
|
|
119
|
+
}
|
|
120
|
+
return out;
|
|
121
|
+
}
|
|
122
|
+
/** Whether a change at `path` (repo-relative, `/`-separated) counts. `outside` = directories whose writes never count
|
|
123
|
+
* (the state home, the graph roots), compared both as given and as the checkout spells them. */
|
|
124
|
+
export function countsAsChange(path, root, outside) {
|
|
125
|
+
const segs = path.split('/');
|
|
126
|
+
if (segs.some((s) => IGNORED_SEGMENTS.has(s)))
|
|
127
|
+
return false;
|
|
128
|
+
const dirs = outside === null ? [] : typeof outside === 'string' ? [outside] : outside;
|
|
129
|
+
// Both spellings of the checkout (codex r5: a checkout registered through a symlinked path, the state home under its
|
|
130
|
+
// canonical spelling).
|
|
131
|
+
const roots = [resolve(root)];
|
|
132
|
+
try {
|
|
133
|
+
const real = realpathSync(root);
|
|
134
|
+
if (real !== roots[0])
|
|
135
|
+
roots.push(real);
|
|
136
|
+
}
|
|
137
|
+
catch { /* not there */ }
|
|
138
|
+
for (const base of roots) {
|
|
139
|
+
const at = resolve(base, ...segs);
|
|
140
|
+
for (const d of dirs) {
|
|
141
|
+
const rel = relative(d, at);
|
|
142
|
+
if (rel === '' || (!rel.startsWith('..') && !isAbsolute(rel)))
|
|
143
|
+
return false;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return true;
|
|
147
|
+
}
|
|
148
|
+
/** The directories a checkout's changes never count under, canonical (codex r2: `/tmp` vs `/private/tmp`, and the graph
|
|
149
|
+
* roots an operator variable can point inside a checkout). */
|
|
150
|
+
export function outsideDirs(stateHome, env = process.env) {
|
|
151
|
+
const raw = [stateHome, env['WICKED_ESTATE_REPO_GRAPH_ROOT'], env['WICKED_CREW_PROJECT_GRAPH_ROOT']].filter((d) => typeof d === 'string' && d !== '');
|
|
152
|
+
const out = new Set();
|
|
153
|
+
for (const d of raw) {
|
|
154
|
+
const abs = resolve(d);
|
|
155
|
+
out.add(abs);
|
|
156
|
+
// Not created yet: canonicalize the longest existing ancestor and keep the rest (codex r3: `/tmp/x/graphs` made later
|
|
157
|
+
// is later written under its canonical, symlink-resolved spelling).
|
|
158
|
+
let head = abs;
|
|
159
|
+
const tail = [];
|
|
160
|
+
for (;;) {
|
|
161
|
+
try {
|
|
162
|
+
out.add(join(realpathSync(head), ...tail));
|
|
163
|
+
break;
|
|
164
|
+
}
|
|
165
|
+
catch { /* go up */ }
|
|
166
|
+
const up = dirname(head);
|
|
167
|
+
if (up === head)
|
|
168
|
+
break;
|
|
169
|
+
tail.unshift(head.slice(up.length).replace(/^[\\/]+/, ''));
|
|
170
|
+
head = up;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return [...out];
|
|
174
|
+
}
|
|
175
|
+
const statOf = async (p) => {
|
|
176
|
+
try {
|
|
177
|
+
const s = await lstat(p);
|
|
178
|
+
return s.isFile() || s.isSymbolicLink() || s.isDirectory() ? { size: s.size, mtimeMs: Math.trunc(s.mtimeMs) } : null;
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
return null;
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
/** At most `max` bytes of a REGULAR file (a symlink's own target text; never a FIFO or device; codex r2). */
|
|
185
|
+
async function readBounded(p, max) {
|
|
186
|
+
try {
|
|
187
|
+
const st = await lstat(p);
|
|
188
|
+
if (st.isSymbolicLink())
|
|
189
|
+
return Buffer.from(`link:${await readlink(p)}`);
|
|
190
|
+
if (!st.isFile())
|
|
191
|
+
return null;
|
|
192
|
+
// Opened without following a link and without blocking (a FIFO swapped in after the lstat must not stall the one
|
|
193
|
+
// loop), then checked again on the descriptor itself (codex r3). Windows has neither flag; it has no FIFOs either.
|
|
194
|
+
const flags = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
|
|
195
|
+
const fh = await open(p, flags);
|
|
196
|
+
try {
|
|
197
|
+
if (!(await fh.stat()).isFile())
|
|
198
|
+
return null;
|
|
199
|
+
const buf = Buffer.alloc(max + 1);
|
|
200
|
+
const { bytesRead } = await fh.read(buf, 0, max + 1, 0);
|
|
201
|
+
return bytesRead > max ? null : buf.subarray(0, bytesRead);
|
|
202
|
+
}
|
|
203
|
+
finally {
|
|
204
|
+
await fh.close();
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
return null;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
const readOf = (p) => readBounded(p, HASH_FILE_MAX);
|
|
212
|
+
/** Changed files at most this big are hashed by content (pi r1: a 1 s mtime filesystem hides a same-size edit)… */
|
|
213
|
+
export const HASH_FILE_MAX = 64 * 1024;
|
|
214
|
+
/** …within this many bytes per poll; past it, size and mtime alone. */
|
|
215
|
+
export const HASH_BUDGET = 4 * 1024 * 1024;
|
|
216
|
+
/**
|
|
217
|
+
* The fingerprint of a repo's state on disk, from its poll. Every counted entry contributes its status, size and mtime,
|
|
218
|
+
* and a small file its content hash. `coarse`: past {@link STAT_CAP} entries (build output git does not ignore), the
|
|
219
|
+
* stats stop and the fingerprint moves once a minute instead, so a change there is still indexed within ~1 min —
|
|
220
|
+
* never reported current on no evidence (codex r1).
|
|
221
|
+
*/
|
|
222
|
+
export async function fingerprintOf(root, status, stateHome, stat = statOf, read = readOf, now = Date.now) {
|
|
223
|
+
const entries = status.entries.filter((e) => countsAsChange(e.path, root, stateHome) || (e.from !== undefined && countsAsChange(e.from, root, stateHome))).sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
224
|
+
const h = createHash('sha256');
|
|
225
|
+
h.update(`oid ${status.oid ?? '-'}\nhead ${status.head ?? '-'}\n`);
|
|
226
|
+
const coarse = entries.length > STAT_CAP;
|
|
227
|
+
let budget = HASH_BUDGET;
|
|
228
|
+
// A changed file whose bytes were not hashed (too big, past the budget) leaves a same-size edit within one mtime tick
|
|
229
|
+
// unseen: such a fingerprint also moves once a minute (codex r2), like a coarse one.
|
|
230
|
+
let unhashed = false;
|
|
231
|
+
for (const [i, e] of entries.entries()) {
|
|
232
|
+
h.update(`${e.code} ${e.path}${e.from !== undefined ? ` <- ${e.from}` : ''}`);
|
|
233
|
+
if (i < STAT_CAP) {
|
|
234
|
+
const file = join(root, ...e.path.split('/'));
|
|
235
|
+
const st = await stat(file);
|
|
236
|
+
h.update(st === null ? ' gone' : ` ${st.size} ${st.mtimeMs}`);
|
|
237
|
+
if (st !== null && !e.path.endsWith('/')) {
|
|
238
|
+
const bytes = st.size <= HASH_FILE_MAX && st.size <= budget ? await read(file) : null;
|
|
239
|
+
if (bytes !== null) {
|
|
240
|
+
budget -= bytes.length;
|
|
241
|
+
h.update(` ${createHash('sha1').update(bytes).digest('hex')}`);
|
|
242
|
+
}
|
|
243
|
+
else
|
|
244
|
+
unhashed = true;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
h.update('\n');
|
|
248
|
+
}
|
|
249
|
+
// `stable`: the same read without the minute tick, for "did the checkout change during the index" (codex r5: a slow
|
|
250
|
+
// index across a minute boundary otherwise always looked changed).
|
|
251
|
+
const stable = h.copy().digest('hex');
|
|
252
|
+
if (coarse || unhashed)
|
|
253
|
+
h.update(`tick ${Math.floor(now() / CHANGE_MAX_WAIT_MS)}\n`);
|
|
254
|
+
return { fingerprint: h.digest('hex'), stable, coarse, changed: entries.length };
|
|
255
|
+
}
|
|
256
|
+
/** The poll's git: optional locks off, hidden on Windows, bounded, output capped; its env through `execCapped`'s
|
|
257
|
+
* boot-store scrub like every crew child (crew#495). */
|
|
258
|
+
export const pollGit = async (cwd, args) => {
|
|
259
|
+
const { stdout } = await execCapped('git', [...args], {
|
|
260
|
+
cwd,
|
|
261
|
+
env: { ...process.env, GIT_OPTIONAL_LOCKS: '0', GIT_TERMINAL_PROMPT: '0' },
|
|
262
|
+
timeout: GIT_TIMEOUT_MS,
|
|
263
|
+
windowsHide: true,
|
|
264
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
265
|
+
});
|
|
266
|
+
return stdout;
|
|
267
|
+
};
|
|
268
|
+
// ── Who holds a repo's graph ──────────────────────────────────────────────────
|
|
269
|
+
/** The runs on `repoId` that hold its graph at their base now. */
|
|
270
|
+
export function holdsOf(views, repoId) {
|
|
271
|
+
const out = [];
|
|
272
|
+
for (const v of views) {
|
|
273
|
+
if (v.session.repo_ref !== repoId || TERMINAL.has(v.session.status))
|
|
274
|
+
continue;
|
|
275
|
+
const name = runNameOf(v);
|
|
276
|
+
if (name === DOMAIN_MAPPING)
|
|
277
|
+
out.push({ runId: v.session.id, reason: 'domain-mapping' });
|
|
278
|
+
else if (ACTIVE.has(v.session.status) && !NON_GRAPH_RUNS.has(name ?? ''))
|
|
279
|
+
out.push({ runId: v.session.id, reason: 'executing' });
|
|
280
|
+
}
|
|
281
|
+
return out;
|
|
282
|
+
}
|
|
283
|
+
function readRec(v) {
|
|
284
|
+
if (v === null || typeof v !== 'object' || Array.isArray(v))
|
|
285
|
+
return null;
|
|
286
|
+
const o = v;
|
|
287
|
+
const out = {};
|
|
288
|
+
if (typeof o['indexedFp'] === 'string' && /^[0-9a-f]{64}$/.test(o['indexedFp']))
|
|
289
|
+
out.indexedFp = o['indexedFp'];
|
|
290
|
+
if (typeof o['lastIndexedAt'] === 'number' && Number.isFinite(o['lastIndexedAt']))
|
|
291
|
+
out.lastIndexedAt = o['lastIndexedAt'];
|
|
292
|
+
if (Number.isSafeInteger(o['launches']) && o['launches'] >= 0)
|
|
293
|
+
out.launches = o['launches'];
|
|
294
|
+
if (Number.isSafeInteger(o['indexedLaunches']) && o['indexedLaunches'] >= 0)
|
|
295
|
+
out.indexedLaunches = o['indexedLaunches'];
|
|
296
|
+
// Counters that disagree (an index after more launches than were counted) prove nothing: index once (codex r2).
|
|
297
|
+
if ((out.indexedLaunches ?? 0) > (out.launches ?? 0)) {
|
|
298
|
+
delete out.indexedFp;
|
|
299
|
+
delete out.indexedLaunches;
|
|
300
|
+
}
|
|
301
|
+
if (o['enabled'] === false)
|
|
302
|
+
out.enabled = false;
|
|
303
|
+
if (o['projectsOwed'] === true)
|
|
304
|
+
out.projectsOwed = true;
|
|
305
|
+
return out;
|
|
306
|
+
}
|
|
307
|
+
/** The idle poll period after a poll that took `lastPollMs`. */
|
|
308
|
+
export function pollPeriod(lastPollMs) {
|
|
309
|
+
return Math.min(POLL_MAX_MS, Math.max(POLL_MIN_MS, POLL_DUTY * lastPollMs));
|
|
310
|
+
}
|
|
311
|
+
function message(err) {
|
|
312
|
+
return err instanceof Error ? err.message : String(err);
|
|
313
|
+
}
|
|
314
|
+
/** The person-facing remedy for an index failure (the engine's words name the cause). */
|
|
315
|
+
export function indexRemedy(error) {
|
|
316
|
+
if (/could not run the .* indexer/i.test(error))
|
|
317
|
+
return 'wicked-estate is not available to the daemon. Install it, then press Re-index now.';
|
|
318
|
+
const over = /exceeded (\d+)s/i.exec(error);
|
|
319
|
+
if (over !== null) {
|
|
320
|
+
const s = Number(over[1]);
|
|
321
|
+
const words = s % 60 === 0 ? `${s / 60} minute${s === 60 ? '' : 's'}` : `${s} seconds`;
|
|
322
|
+
return `The re-index took longer than ${words} and was stopped. Press Re-index now to try again; a very large change may need the repository to be onboarded again.`;
|
|
323
|
+
}
|
|
324
|
+
if (/no registered repo/i.test(error))
|
|
325
|
+
return 'The repository is no longer registered. Register it again on Repositories.';
|
|
326
|
+
return 'Press Re-index now to try again. If it keeps failing, onboard the repository again from its page.';
|
|
327
|
+
}
|
|
328
|
+
export function pollRemedy() {
|
|
329
|
+
return 'Check that the folder still exists and is a git repository, and that git is installed.';
|
|
330
|
+
}
|
|
331
|
+
const TOO_MANY = (n) => `${n} changed files is more than studio reads closely, so the code map is re-indexed about once a minute while they change. Adding build output to .gitignore fixes it.`;
|
|
332
|
+
export class RepoWatcher {
|
|
333
|
+
deps;
|
|
334
|
+
now;
|
|
335
|
+
git;
|
|
336
|
+
stat;
|
|
337
|
+
read;
|
|
338
|
+
exists;
|
|
339
|
+
outside;
|
|
340
|
+
/** Repo id → record. A Map, so no repo id (`__proto__`) can reach an object's prototype (codex r1). */
|
|
341
|
+
records = new Map();
|
|
342
|
+
loading = null;
|
|
343
|
+
repos = new Map();
|
|
344
|
+
reposReadAt = -Infinity;
|
|
345
|
+
queue = [];
|
|
346
|
+
timer = null;
|
|
347
|
+
running = false;
|
|
348
|
+
stopped = false;
|
|
349
|
+
/** The ONE step in flight; a wake while it runs only marks another step owed (codex + pi r1). */
|
|
350
|
+
busy = null;
|
|
351
|
+
wakeOwed = false;
|
|
352
|
+
saving = Promise.resolve();
|
|
353
|
+
booted = new Set();
|
|
354
|
+
pollsSinceDebt = 0;
|
|
355
|
+
bootOwed = new Set();
|
|
356
|
+
saves = 0;
|
|
357
|
+
constructor(deps) {
|
|
358
|
+
this.deps = deps;
|
|
359
|
+
this.now = deps.now ?? Date.now;
|
|
360
|
+
this.git = deps.git ?? pollGit;
|
|
361
|
+
this.stat = deps.stat ?? statOf;
|
|
362
|
+
this.read = deps.read ?? readOf;
|
|
363
|
+
this.exists = deps.exists ?? existsSync;
|
|
364
|
+
this.outside = outsideDirs(deps.stateHome);
|
|
365
|
+
}
|
|
366
|
+
/** Start the loop (no-op when off for the daemon). */
|
|
367
|
+
start() {
|
|
368
|
+
if (!this.deps.enabled || this.running)
|
|
369
|
+
return;
|
|
370
|
+
this.running = true;
|
|
371
|
+
this.stopped = false;
|
|
372
|
+
this.kick(0);
|
|
373
|
+
}
|
|
374
|
+
/** Stop: no new step starts; the one in flight and any pending save are awaited. */
|
|
375
|
+
async stop() {
|
|
376
|
+
this.stopped = true;
|
|
377
|
+
this.running = false;
|
|
378
|
+
if (this.timer !== null)
|
|
379
|
+
clearTimeout(this.timer);
|
|
380
|
+
this.timer = null;
|
|
381
|
+
await this.busy?.catch(() => undefined);
|
|
382
|
+
await this.saving.catch(() => undefined);
|
|
383
|
+
}
|
|
384
|
+
/** Wake the loop: a step now, unless one is running (then right after it). */
|
|
385
|
+
kick(ms) {
|
|
386
|
+
if (this.stopped || !this.running)
|
|
387
|
+
return;
|
|
388
|
+
if (this.busy !== null) {
|
|
389
|
+
this.wakeOwed = true;
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
if (this.timer !== null)
|
|
393
|
+
clearTimeout(this.timer);
|
|
394
|
+
this.timer = setTimeout(() => {
|
|
395
|
+
this.timer = null;
|
|
396
|
+
this.busy = this.step()
|
|
397
|
+
.catch((err) => this.deps.log(`[repo-watch] step failed: ${message(err)}`))
|
|
398
|
+
.finally(() => {
|
|
399
|
+
this.busy = null;
|
|
400
|
+
const owed = this.wakeOwed;
|
|
401
|
+
this.wakeOwed = false;
|
|
402
|
+
this.kick(owed ? 0 : this.delay());
|
|
403
|
+
});
|
|
404
|
+
}, ms);
|
|
405
|
+
this.timer.unref?.();
|
|
406
|
+
}
|
|
407
|
+
/** How long until the next thing is due (bounded 250 ms … 1 s, so a new repo or a press is picked up). */
|
|
408
|
+
delay() {
|
|
409
|
+
if (this.queue.length > 0)
|
|
410
|
+
return 0;
|
|
411
|
+
const t = this.now();
|
|
412
|
+
let next = Infinity;
|
|
413
|
+
for (const r of this.repos.values())
|
|
414
|
+
if (this.pollable(r))
|
|
415
|
+
next = Math.min(next, r.nextPollAt - t);
|
|
416
|
+
return Math.max(250, Math.min(1_000, Number.isFinite(next) ? next : 1_000));
|
|
417
|
+
}
|
|
418
|
+
pollable(r) {
|
|
419
|
+
return r.forced || (r.enabled && !r.capped);
|
|
420
|
+
}
|
|
421
|
+
load() {
|
|
422
|
+
this.loading ??= this.readRecords();
|
|
423
|
+
return this.loading;
|
|
424
|
+
}
|
|
425
|
+
async readRecords() {
|
|
426
|
+
try {
|
|
427
|
+
const raw = JSON.parse(await readFile(this.deps.statePath, 'utf8'));
|
|
428
|
+
if (raw?.version !== 1 || raw.repos === null || typeof raw.repos !== 'object' || Array.isArray(raw.repos))
|
|
429
|
+
return;
|
|
430
|
+
for (const [id, v] of Object.entries(raw.repos)) {
|
|
431
|
+
const rec = readRec(v);
|
|
432
|
+
if (rec !== null)
|
|
433
|
+
this.records.set(id, rec);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
catch {
|
|
437
|
+
// Missing or unreadable: every repo indexes once (the safe direction).
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
/** Persist, one write at a time, each through its own temporary file (codex + pi r1). */
|
|
441
|
+
save() {
|
|
442
|
+
const body = JSON.stringify({ version: 1, repos: Object.fromEntries(this.records) }, null, 2);
|
|
443
|
+
const path = this.deps.statePath;
|
|
444
|
+
const tmp = `${path}.tmp-${process.pid}-${(this.saves += 1)}`;
|
|
445
|
+
this.saving = this.saving.catch(() => undefined).then(async () => {
|
|
446
|
+
await mkdir(dirname(path), { recursive: true });
|
|
447
|
+
await writeFile(tmp, body, 'utf8');
|
|
448
|
+
await rename(tmp, path);
|
|
449
|
+
});
|
|
450
|
+
return this.saving.catch((err) => this.deps.log(`[repo-watch] could not save ${path}: ${message(err)}`));
|
|
451
|
+
}
|
|
452
|
+
rec(repoId) {
|
|
453
|
+
let r = this.records.get(repoId);
|
|
454
|
+
if (r === undefined) {
|
|
455
|
+
r = {};
|
|
456
|
+
this.records.set(repoId, r);
|
|
457
|
+
}
|
|
458
|
+
return r;
|
|
459
|
+
}
|
|
460
|
+
/** Re-read the registry: onboarded repos with a folder; the first {@link REPO_WATCH_CAP} ENABLED ones are polled. */
|
|
461
|
+
async syncRepos(force = false) {
|
|
462
|
+
await this.load();
|
|
463
|
+
const t = this.now();
|
|
464
|
+
if (!force && t - this.reposReadAt < REPOS_TTL_MS)
|
|
465
|
+
return;
|
|
466
|
+
this.reposReadAt = t;
|
|
467
|
+
const all = (await this.deps.listRepos())
|
|
468
|
+
.filter((r) => typeof r.code_graph_db === 'string' && r.code_graph_db !== '' && this.exists(r.code_graph_db) && this.exists(r.root_path))
|
|
469
|
+
.sort((a, b) => (a.registered_at ?? 0) - (b.registered_at ?? 0) || (a.id < b.id ? -1 : 1));
|
|
470
|
+
const keep = new Set(all.map((r) => r.id));
|
|
471
|
+
for (const id of [...this.repos.keys()])
|
|
472
|
+
if (!keep.has(id))
|
|
473
|
+
this.repos.delete(id);
|
|
474
|
+
let slots = REPO_WATCH_CAP;
|
|
475
|
+
for (const r of all) {
|
|
476
|
+
const enabled = this.records.get(r.id)?.enabled !== false;
|
|
477
|
+
const capped = enabled && (slots -= 1) < 0;
|
|
478
|
+
let cur = this.repos.get(r.id);
|
|
479
|
+
if (cur === undefined) {
|
|
480
|
+
cur = {
|
|
481
|
+
repoId: r.id, root: r.root_path, enabled, capped, state: 'starting', seenFp: null, changedAt: null,
|
|
482
|
+
nextPollAt: t, lastPolledAt: null, lastPollMs: 0, pollFailures: 0, indexFailures: 0, indexBackoffUntil: 0,
|
|
483
|
+
lastIndexMs: null, coarse: false, waitingOn: [], error: null, remedy: null, polls: 0, indexes: 0, forced: false,
|
|
484
|
+
forcedGen: 0, projectsRetryAt: 0, queuedGen: 0, repairOwed: false,
|
|
485
|
+
};
|
|
486
|
+
this.repos.set(r.id, cur);
|
|
487
|
+
}
|
|
488
|
+
cur.root = r.root_path;
|
|
489
|
+
cur.enabled = enabled;
|
|
490
|
+
if (cur.capped && !capped)
|
|
491
|
+
cur.nextPollAt = t; // a slot came free
|
|
492
|
+
cur.capped = capped;
|
|
493
|
+
if (cur.state !== 'indexing')
|
|
494
|
+
this.restate(cur);
|
|
495
|
+
// A launch while this daemon was starting (before its listener) or down left no count: every repo is brought back
|
|
496
|
+
// to its checkout once per start (an incremental index), guarded like any other (codex r4).
|
|
497
|
+
if (!this.booted.has(r.id)) {
|
|
498
|
+
this.booted.add(r.id);
|
|
499
|
+
this.bootOwed.add(r.id);
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
/** The resting state a switch or the cap implies (the operational states stand otherwise). */
|
|
504
|
+
restate(r) {
|
|
505
|
+
if (!r.enabled && !r.forced) {
|
|
506
|
+
r.state = 'off';
|
|
507
|
+
r.waitingOn = [];
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
if (r.capped && !r.forced) {
|
|
511
|
+
r.state = 'capped';
|
|
512
|
+
r.waitingOn = [];
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
if (r.state === 'off' || r.state === 'capped')
|
|
516
|
+
r.state = 'starting';
|
|
517
|
+
}
|
|
518
|
+
/** One unit of work: the next queued index, else the most overdue poll. Exposed for tests. */
|
|
519
|
+
async step() {
|
|
520
|
+
await this.syncRepos();
|
|
521
|
+
const queued = this.queue.shift();
|
|
522
|
+
if (queued !== undefined) {
|
|
523
|
+
await this.index(queued);
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
const t = this.now();
|
|
527
|
+
let due = null;
|
|
528
|
+
for (const r of this.repos.values()) {
|
|
529
|
+
if (!this.pollable(r) || r.nextPollAt > t)
|
|
530
|
+
continue;
|
|
531
|
+
if (due === null || r.nextPollAt < due.nextPollAt)
|
|
532
|
+
due = r;
|
|
533
|
+
}
|
|
534
|
+
// Polls first, but an owed refresh is served at least once every DEBT_EVERY polls (codex r5: under sustained load
|
|
535
|
+
// there is always a poll due).
|
|
536
|
+
const debt = [...this.repos.values()].find((r) => !this.pollable(r) && this.records.get(r.repoId)?.projectsOwed === true && t >= r.projectsRetryAt);
|
|
537
|
+
if (debt !== undefined && (due === null || this.pollsSinceDebt >= DEBT_EVERY)) {
|
|
538
|
+
this.pollsSinceDebt = 0;
|
|
539
|
+
await this.refreshProjectsOf(debt);
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
if (due !== null) {
|
|
543
|
+
this.pollsSinceDebt++;
|
|
544
|
+
await this.poll(due);
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
async poll(r) {
|
|
549
|
+
const started = this.now();
|
|
550
|
+
let fp;
|
|
551
|
+
try {
|
|
552
|
+
const out = await this.git(r.root, POLL_ARGS);
|
|
553
|
+
fp = await fingerprintOf(r.root, parsePorcelainV2(out), this.outside, this.stat, this.read, this.now);
|
|
554
|
+
}
|
|
555
|
+
catch (err) {
|
|
556
|
+
r.pollFailures++;
|
|
557
|
+
r.lastPolledAt = this.now();
|
|
558
|
+
r.nextPollAt = r.lastPolledAt + Math.min(POLL_BACKOFF_MAX_MS, POLL_MIN_MS * 2 ** r.pollFailures);
|
|
559
|
+
r.state = 'failed';
|
|
560
|
+
r.error = `git could not read the folder: ${message(err).split('\n')[0]}`;
|
|
561
|
+
r.remedy = pollRemedy();
|
|
562
|
+
return;
|
|
563
|
+
}
|
|
564
|
+
const ended = this.now();
|
|
565
|
+
r.polls++;
|
|
566
|
+
r.pollFailures = 0;
|
|
567
|
+
r.lastPolledAt = ended;
|
|
568
|
+
r.lastPollMs = ended - started;
|
|
569
|
+
r.nextPollAt = ended + pollPeriod(r.lastPollMs);
|
|
570
|
+
r.coarse = fp.coarse;
|
|
571
|
+
await this.decide(r, fp.fingerprint, ended, fp.coarse ? TOO_MANY(fp.changed) : null);
|
|
572
|
+
}
|
|
573
|
+
async decide(r, fp, t, note) {
|
|
574
|
+
const rec = this.rec(r.repoId);
|
|
575
|
+
// A launch on the repo since the last index ran its D8: the graph may sit at that run's base now.
|
|
576
|
+
const moved = (rec.launches ?? 0) > (rec.indexedLaunches ?? 0) || this.bootOwed.has(r.repoId);
|
|
577
|
+
const wants = r.forced || rec.indexedFp !== fp || moved;
|
|
578
|
+
if (!wants) {
|
|
579
|
+
r.seenFp = fp;
|
|
580
|
+
r.changedAt = null;
|
|
581
|
+
r.waitingOn = [];
|
|
582
|
+
if (rec.projectsOwed === true && t >= r.projectsRetryAt)
|
|
583
|
+
await this.refreshProjectsOf(r);
|
|
584
|
+
if (r.indexFailures === 0) {
|
|
585
|
+
r.state = 'current';
|
|
586
|
+
r.error = null;
|
|
587
|
+
r.remedy = note;
|
|
588
|
+
}
|
|
589
|
+
return;
|
|
590
|
+
}
|
|
591
|
+
let due = r.forced;
|
|
592
|
+
if (r.forced)
|
|
593
|
+
r.seenFp = fp; // the index below records THIS poll's fingerprint (codex r2)
|
|
594
|
+
if (!due) {
|
|
595
|
+
if (r.seenFp !== fp) {
|
|
596
|
+
r.seenFp = fp;
|
|
597
|
+
r.changedAt ??= t;
|
|
598
|
+
// Only the graph moved (a launch's D8), not the checkout: nothing to wait out.
|
|
599
|
+
due = t - r.changedAt >= CHANGE_MAX_WAIT_MS || (rec.indexedFp === fp && moved);
|
|
600
|
+
}
|
|
601
|
+
else {
|
|
602
|
+
due = true; // quiet for one poll
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
r.changedAt ??= t;
|
|
606
|
+
if (!due) {
|
|
607
|
+
if (r.state !== 'failed') {
|
|
608
|
+
r.state = 'changed';
|
|
609
|
+
r.remedy = note;
|
|
610
|
+
}
|
|
611
|
+
r.nextPollAt = Math.min(r.nextPollAt, t + QUIET_MS); // the quiet check comes soon, whatever the idle period
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
614
|
+
// A failing index waits out its backoff whatever changes meanwhile; only a person's press skips it (codex r1).
|
|
615
|
+
if (!r.forced && t < r.indexBackoffUntil)
|
|
616
|
+
return;
|
|
617
|
+
const holds = holdsOf(await this.deps.runViews(), r.repoId);
|
|
618
|
+
if (holds.length > 0) {
|
|
619
|
+
r.state = 'waiting-runs';
|
|
620
|
+
r.waitingOn = holds;
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
r.waitingOn = [];
|
|
624
|
+
r.queuedGen = r.forcedGen;
|
|
625
|
+
if (!this.queue.includes(r.repoId))
|
|
626
|
+
this.queue.push(r.repoId);
|
|
627
|
+
if (r.state !== 'indexing' && r.state !== 'failed')
|
|
628
|
+
r.state = 'changed';
|
|
629
|
+
}
|
|
630
|
+
async index(repoId) {
|
|
631
|
+
const r = this.repos.get(repoId);
|
|
632
|
+
if (r === undefined || (!r.forced && (!r.enabled || r.capped)))
|
|
633
|
+
return;
|
|
634
|
+
// Crew's own check (a domain mapping parked at a gate holds the map too); the engine re-reads active runs under
|
|
635
|
+
// its lock, so a launch between this read and the index is caught there (`held`).
|
|
636
|
+
const views = await this.deps.runViews();
|
|
637
|
+
const holds = holdsOf(views, repoId);
|
|
638
|
+
if (holds.length > 0) {
|
|
639
|
+
r.state = 'waiting-runs';
|
|
640
|
+
r.waitingOn = holds;
|
|
641
|
+
return;
|
|
642
|
+
}
|
|
643
|
+
// A press after this index was queued: poll first, so the index records the checkout it reads.
|
|
644
|
+
if (r.forced && r.forcedGen !== r.queuedGen) {
|
|
645
|
+
r.nextPollAt = this.now();
|
|
646
|
+
return;
|
|
647
|
+
}
|
|
648
|
+
// The checkout as it is NOW, read again after the index: the index is recorded as current only when the two agree,
|
|
649
|
+
// so a switch between the quiet poll and the index, or during it, is indexed again (codex r4).
|
|
650
|
+
const before = await this.sample(r);
|
|
651
|
+
if (before === null)
|
|
652
|
+
return;
|
|
653
|
+
const fp = before.fingerprint;
|
|
654
|
+
r.seenFp = fp;
|
|
655
|
+
const gen = r.forcedGen;
|
|
656
|
+
const launchesBefore = this.rec(repoId).launches ?? 0;
|
|
657
|
+
r.state = 'indexing';
|
|
658
|
+
const started = this.now();
|
|
659
|
+
try {
|
|
660
|
+
const answer = await this.deps.indexRepoGraph(repoId);
|
|
661
|
+
r.lastIndexMs = this.now() - started;
|
|
662
|
+
if (answer.outcome === 'held') {
|
|
663
|
+
r.state = 'waiting-runs';
|
|
664
|
+
const fresh = holdsOf(await this.deps.runViews(), repoId);
|
|
665
|
+
r.waitingOn = (answer.heldBy ?? []).map((runId) => fresh.find((x) => x.runId === runId) ?? { runId, reason: 'executing' });
|
|
666
|
+
return;
|
|
667
|
+
}
|
|
668
|
+
const pressServed = r.forcedGen === gen;
|
|
669
|
+
if (answer.outcome === 'no-graph') {
|
|
670
|
+
if (pressServed)
|
|
671
|
+
r.forced = false;
|
|
672
|
+
r.state = 'failed';
|
|
673
|
+
r.error = 'This repository has no code map yet.';
|
|
674
|
+
r.remedy = 'Onboard it from its page; the code map is kept current from then on.';
|
|
675
|
+
return;
|
|
676
|
+
}
|
|
677
|
+
r.indexes++;
|
|
678
|
+
r.indexFailures = 0;
|
|
679
|
+
r.indexBackoffUntil = 0;
|
|
680
|
+
r.error = null;
|
|
681
|
+
r.remedy = r.coarse ? r.remedy : null;
|
|
682
|
+
const rec = this.rec(repoId);
|
|
683
|
+
const after = await this.sample(r);
|
|
684
|
+
const same = after !== null && after.stable === before.stable;
|
|
685
|
+
if (same)
|
|
686
|
+
rec.indexedFp = fp;
|
|
687
|
+
else {
|
|
688
|
+
delete rec.indexedFp;
|
|
689
|
+
r.seenFp = after?.fingerprint ?? null;
|
|
690
|
+
r.nextPollAt = this.now();
|
|
691
|
+
}
|
|
692
|
+
// A press is served only by an index that read a checkout that held still; otherwise it stays owed, once more,
|
|
693
|
+
// even on an off or capped repo (codex r5).
|
|
694
|
+
if (pressServed)
|
|
695
|
+
r.forced = !same && !r.repairOwed;
|
|
696
|
+
r.repairOwed = !same && !r.repairOwed ? true : false;
|
|
697
|
+
rec.lastIndexedAt = this.now();
|
|
698
|
+
rec.indexedLaunches = launchesBefore;
|
|
699
|
+
this.bootOwed.delete(repoId);
|
|
700
|
+
rec.projectsOwed = true;
|
|
701
|
+
await this.save();
|
|
702
|
+
await this.refreshProjectsOf(r);
|
|
703
|
+
r.changedAt = null;
|
|
704
|
+
r.state = same ? 'current' : 'changed';
|
|
705
|
+
this.restate(r);
|
|
706
|
+
this.deps.log(`[repo-watch] ${repoId}: code map re-indexed in ${r.lastIndexMs} ms`);
|
|
707
|
+
}
|
|
708
|
+
catch (err) {
|
|
709
|
+
if (r.forcedGen === gen)
|
|
710
|
+
r.forced = false;
|
|
711
|
+
r.lastIndexMs = this.now() - started;
|
|
712
|
+
r.indexFailures++;
|
|
713
|
+
r.indexBackoffUntil = this.now() + Math.min(INDEX_BACKOFF_MAX_MS, INDEX_BACKOFF_BASE_MS * 2 ** (r.indexFailures - 1));
|
|
714
|
+
r.state = 'failed';
|
|
715
|
+
r.error = message(err).split('\n')[0] ?? 'the re-index failed';
|
|
716
|
+
r.remedy = indexRemedy(r.error);
|
|
717
|
+
this.deps.log(`[repo-watch] ${repoId}: re-index FAILED: ${r.error}`);
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
/** Refresh the repo's projects; a failure is owed (persisted) and retried, backed off, by the polls (codex r2). */
|
|
721
|
+
async refreshProjectsOf(r) {
|
|
722
|
+
const rec = this.rec(r.repoId);
|
|
723
|
+
let ok = false;
|
|
724
|
+
try {
|
|
725
|
+
ok = await this.deps.refreshProjects(r.repoId);
|
|
726
|
+
}
|
|
727
|
+
catch (err) {
|
|
728
|
+
this.deps.log(`[repo-watch] ${r.repoId}: project graph refresh failed: ${message(err)}`);
|
|
729
|
+
}
|
|
730
|
+
if (ok) {
|
|
731
|
+
delete rec.projectsOwed;
|
|
732
|
+
r.projectsRetryAt = 0;
|
|
733
|
+
}
|
|
734
|
+
else {
|
|
735
|
+
rec.projectsOwed = true;
|
|
736
|
+
r.projectsRetryAt = this.now() + INDEX_BACKOFF_BASE_MS;
|
|
737
|
+
}
|
|
738
|
+
await this.save();
|
|
739
|
+
}
|
|
740
|
+
/** One read of the checkout now (the poll's own), or `null` when git could not read it. */
|
|
741
|
+
async sample(r) {
|
|
742
|
+
try {
|
|
743
|
+
const out = await this.git(r.root, POLL_ARGS);
|
|
744
|
+
return await fingerprintOf(r.root, parsePorcelainV2(out), this.outside, this.stat, this.read, this.now);
|
|
745
|
+
}
|
|
746
|
+
catch {
|
|
747
|
+
return null;
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
/**
|
|
751
|
+
* A run on `repoId` resolved its base (`runBaseResolved`): its D8 re-indexes the repo graph at that base, so the
|
|
752
|
+
* graph no longer follows the checkout. Recorded (durably), so once nothing holds the map it is indexed again.
|
|
753
|
+
*/
|
|
754
|
+
async noteLaunch(repoId) {
|
|
755
|
+
// Counted with the watcher off too, so turning it back on does not trust a graph a launch moved (codex r2); and only
|
|
756
|
+
// once the records are loaded, so an early launch never saves over them.
|
|
757
|
+
await this.load();
|
|
758
|
+
const rec = this.rec(repoId);
|
|
759
|
+
rec.launches = (rec.launches ?? 0) + 1;
|
|
760
|
+
await this.save();
|
|
761
|
+
}
|
|
762
|
+
/** Something changed the registry (a repo onboarded): read it at the next step, now. */
|
|
763
|
+
wake() {
|
|
764
|
+
this.reposReadAt = -Infinity;
|
|
765
|
+
this.kick(0);
|
|
766
|
+
}
|
|
767
|
+
/** A person pressed Re-index now: queued at the next step, past the quiet window, the backoff, the switch and the cap;
|
|
768
|
+
* while runs hold the map the request is kept and runs when they let go. */
|
|
769
|
+
async reindexNow(repoId) {
|
|
770
|
+
await this.syncRepos(true);
|
|
771
|
+
const r = this.repos.get(repoId);
|
|
772
|
+
if (r === undefined)
|
|
773
|
+
return { queued: false, waitingOn: [], unknown: true };
|
|
774
|
+
r.forced = true;
|
|
775
|
+
r.forcedGen += 1;
|
|
776
|
+
r.indexBackoffUntil = 0;
|
|
777
|
+
r.nextPollAt = this.now();
|
|
778
|
+
const holds = holdsOf(await this.deps.runViews(), repoId);
|
|
779
|
+
if (holds.length > 0) {
|
|
780
|
+
r.state = 'waiting-runs';
|
|
781
|
+
r.waitingOn = holds;
|
|
782
|
+
this.kick(0);
|
|
783
|
+
return { queued: false, waitingOn: holds };
|
|
784
|
+
}
|
|
785
|
+
if (r.state === 'off' || r.state === 'capped')
|
|
786
|
+
r.state = 'starting';
|
|
787
|
+
this.kick(0);
|
|
788
|
+
return { queued: true, waitingOn: [] };
|
|
789
|
+
}
|
|
790
|
+
/** The per-repo switch (persisted). An unknown repo changes nothing (codex + pi r1). */
|
|
791
|
+
async setEnabled(repoId, enabled) {
|
|
792
|
+
await this.syncRepos(true);
|
|
793
|
+
const r = this.repos.get(repoId);
|
|
794
|
+
if (r === undefined)
|
|
795
|
+
return false;
|
|
796
|
+
const rec = this.rec(repoId);
|
|
797
|
+
if (enabled)
|
|
798
|
+
delete rec.enabled;
|
|
799
|
+
else
|
|
800
|
+
rec.enabled = false;
|
|
801
|
+
await this.save();
|
|
802
|
+
if (!enabled) {
|
|
803
|
+
const at = this.queue.indexOf(repoId);
|
|
804
|
+
if (at >= 0 && !r.forced)
|
|
805
|
+
this.queue.splice(at, 1);
|
|
806
|
+
}
|
|
807
|
+
await this.syncRepos(true); // re-allocate the cap among enabled repos
|
|
808
|
+
if (enabled && r.state === 'starting')
|
|
809
|
+
r.nextPollAt = this.now();
|
|
810
|
+
this.kick(0);
|
|
811
|
+
return true;
|
|
812
|
+
}
|
|
813
|
+
/** The wire status (`GET /repo-watch`). */
|
|
814
|
+
status() {
|
|
815
|
+
const repos = [...this.repos.values()].map((r) => ({
|
|
816
|
+
repoId: r.repoId,
|
|
817
|
+
state: r.state,
|
|
818
|
+
enabled: r.enabled,
|
|
819
|
+
lastIndexedAt: this.records.get(r.repoId)?.lastIndexedAt ?? null,
|
|
820
|
+
lastPolledAt: r.lastPolledAt,
|
|
821
|
+
changedAt: r.changedAt,
|
|
822
|
+
waitingOn: r.waitingOn,
|
|
823
|
+
error: r.error,
|
|
824
|
+
remedy: r.state === 'capped'
|
|
825
|
+
? `Studio keeps up to ${REPO_WATCH_CAP} repositories current. Turn another repository off to free a slot, or press Re-index now on this one after a change.`
|
|
826
|
+
: r.remedy,
|
|
827
|
+
}));
|
|
828
|
+
return { enabled: this.deps.enabled, disabledBy: this.deps.enabled ? null : 'env', cap: REPO_WATCH_CAP, covers: COVERS, repos };
|
|
829
|
+
}
|
|
830
|
+
/** `diagnostics.repoWatch`: the status plus the loop's own numbers. */
|
|
831
|
+
diagnostics() {
|
|
832
|
+
return {
|
|
833
|
+
...this.status(),
|
|
834
|
+
queue: [...this.queue],
|
|
835
|
+
watched: [...this.repos.values()].filter((r) => r.enabled && !r.capped).length,
|
|
836
|
+
perRepo: [...this.repos.values()].map((r) => ({
|
|
837
|
+
repoId: r.repoId, state: r.state, enabled: r.enabled, capped: r.capped, periodMs: pollPeriod(r.lastPollMs), lastPollMs: r.lastPollMs,
|
|
838
|
+
lastIndexMs: r.lastIndexMs, polls: r.polls, indexes: r.indexes, pollFailures: r.pollFailures, indexFailures: r.indexFailures,
|
|
839
|
+
coarse: r.coarse, forced: r.forced, nextPollInMs: Math.max(0, r.nextPollAt - this.now()),
|
|
840
|
+
})),
|
|
841
|
+
};
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
/** What "current" covers, on the wire so no surface claims more. */
|
|
845
|
+
export const COVERS = 'Symbols, files and references for what is on disk now. Clusters refresh when the repository is onboarded again.';
|
|
846
|
+
/** `WICKED_CREW_REPO_WATCH=off` (also `0`, `false`, `no`) turns the watcher off for the daemon. */
|
|
847
|
+
export function repoWatchEnabledByEnv(env = process.env) {
|
|
848
|
+
const v = (env['WICKED_CREW_REPO_WATCH'] ?? '').trim().toLowerCase();
|
|
849
|
+
return !(v === 'off' || v === '0' || v === 'false' || v === 'no');
|
|
850
|
+
}
|
|
851
|
+
//# sourceMappingURL=repo-watch.js.map
|