@ericrisco/rsc 2.1.0 → 3.0.0

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.
@@ -0,0 +1,544 @@
1
+ #!/usr/bin/env node
2
+ // Knowledge sync: `01-TOOLS/` and `02-DOCS/` stay the same on every machine of a team without anybody
3
+ // thinking about git. What you change goes up when your turn ends; what others change comes down
4
+ // before your next message.
5
+ //
6
+ // It never touches the default branch (team-safe-default D: assume it is protected). Knowledge travels
7
+ // between people through one exchange branch on the remote, `rsc/knowledge`: up to it, down from it,
8
+ // into whatever branch each person is on. It reaches the default branch inside everybody's ordinary
9
+ // pull requests — every working branch already carries it, so whichever merges first takes it there,
10
+ // and the next one carries the same content and does not conflict.
11
+ //
12
+ // On by default, and that is a decision with a price, so the price is kept small on purpose:
13
+ // - it only ever touches KNOWLEDGE paths, and never the personal profile;
14
+ // - it never pushes a commit that is not its own — your unpushed code stays unpushed;
15
+ // - every commit it makes says `[skip ci]`, so a wiki edit does not trigger a deploy;
16
+ // - the first turn says it is on and how to turn it off (`rsc knowledge-sync off`, or
17
+ // `.rsc/.no-knowledge-sync`, a PROJECT switch that travels in `.rsc.json`).
18
+ //
19
+ // Wired on its own (`knowledge-wiring.js`), on the same two lifecycle events the session memory uses —
20
+ // prompt and end of turn — but never inside the memory: the memory promises it makes no network
21
+ // request, and this exists to talk to `origin`. `rsc memory off` does not turn this off, and the other
22
+ // way round.
23
+ //
24
+ // Two speeds, because a hook should answer in seconds and a push may not:
25
+ // - what touches YOUR FILES — committing your changes, applying somebody else's — is local, fast,
26
+ // and runs inside the hook, while nobody else is editing;
27
+ // - what touches THE NETWORK — fetch, push — runs detached, and never touches the working tree or
28
+ // the index: the push is replayed on a throwaway index on top of `rsc/knowledge` (`commit-tree`),
29
+ // which is also what lets it go up from whatever branch you are on without carrying that branch.
30
+ // The cost: somebody else's change reaches you one message late.
31
+ //
32
+ // Standalone on purpose: hooks are materialized file by file under `.rsc/`, so this imports nothing
33
+ // but Node. Never throws into a hook; whatever goes wrong is said on the next message.
34
+ import { execFileSync, spawn } from 'node:child_process';
35
+ import {
36
+ closeSync, existsSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, statSync,
37
+ unlinkSync, writeFileSync,
38
+ } from 'node:fs';
39
+ import { basename, dirname, extname, isAbsolute, join, resolve } from 'node:path';
40
+ import { fileURLToPath } from 'node:url';
41
+ import { defaultBranchName, trunkClosed } from './trunk-policy.mjs';
42
+
43
+ /** What syncs on its own. Everything else is ordinary git, decided by a person. */
44
+ export const KNOWLEDGE = Object.freeze(['01-TOOLS/', '02-DOCS/wiki/', '02-DOCS/attachments/']);
45
+ /** One person's dials (`init`, `orient`): never anybody else's business. */
46
+ export const PERSONAL = Object.freeze(['02-DOCS/wiki/harness/user-profile.md']);
47
+ export const OPT_OUT = '.no-knowledge-sync';
48
+ export const SKIP_CI = '[skip ci]';
49
+ /** The exchange branch on the remote. Fixed, in every project (spec, clarify P7). */
50
+ export const KNOWLEDGE_BRANCH = 'rsc/knowledge';
51
+
52
+ const STATE = 'knowledge-sync.json';
53
+ const LOCK = 'knowledge-sync.lock';
54
+ const FETCH_EVERY_MS = 60_000;
55
+ const NET_TIMEOUT_MS = 30_000;
56
+ const LOCAL_TIMEOUT_MS = 4_000;
57
+ const LOCK_STALE_MS = 120_000;
58
+ const MAX_FILES = 200;
59
+ const KEEP_OURS = 200;
60
+
61
+ export const isKnowledge = (path) => KNOWLEDGE.some((k) => path.startsWith(k)) && !PERSONAL.includes(path);
62
+
63
+ // ------------------------------------------------------------------ git
64
+
65
+ function run(root, args, { timeout = LOCAL_TIMEOUT_MS, input, env } = {}) {
66
+ try {
67
+ const out = execFileSync('git', args, {
68
+ cwd: root, encoding: 'utf8', timeout, input, maxBuffer: 16 * 1024 * 1024,
69
+ stdio: ['pipe', 'pipe', 'pipe'],
70
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0', LC_ALL: 'C', ...env },
71
+ });
72
+ return { ok: true, status: 0, out, err: '' };
73
+ } catch (e) {
74
+ return { ok: false, status: e.status ?? -1, out: String(e.stdout || ''), err: String(e.stderr || e.message || '') };
75
+ }
76
+ }
77
+
78
+ function git(root, args, opts) {
79
+ const r = run(root, args, opts);
80
+ if (!r.ok) throw new Error(`git ${args.find((a) => !a.startsWith('-'))}: ${r.err.trim().split('\n')[0]}`);
81
+ return r.out;
82
+ }
83
+
84
+ const line = (root, args, opts) => { const r = run(root, args, opts); return r.ok ? r.out.trim() : null; };
85
+ const zlist = (out) => out.split('\0').filter(Boolean);
86
+
87
+ // One answer to "which is the default branch", shared with the guard: a copy without the local
88
+ // main/master fallback once let this module commit on a closed main the remote had not seen yet.
89
+ const defaultBranch = (root) => defaultBranchName(root);
90
+
91
+ function busy(root) {
92
+ for (const p of ['rebase-merge', 'rebase-apply', 'MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD']) {
93
+ const path = line(root, ['rev-parse', '--git-path', p]);
94
+ if (path && existsSync(isAbsolute(path) ? path : join(root, path))) return true; // absolute in a linked worktree
95
+ }
96
+ return false;
97
+ }
98
+
99
+ const blob = (root, rev, path) => line(root, ['rev-parse', '--verify', '--quiet', `${rev}:${path}`]);
100
+ const worktreeBlob = (root, path) => (existsSync(join(root, path)) ? line(root, ['hash-object', '--', path]) : null);
101
+
102
+ // ------------------------------------------------------------------ state
103
+
104
+ function readState(root) {
105
+ let s = {};
106
+ try { s = JSON.parse(readFileSync(join(root, '.rsc', STATE), 'utf8')); } catch { /* first run */ }
107
+ return { announced: false, seen: null, queue: [], ours: [], notices: [], lastFetch: 0, snap: null, ...s };
108
+ }
109
+
110
+ function writeState(root, s) {
111
+ const dir = join(root, '.rsc');
112
+ mkdirSync(dir, { recursive: true });
113
+ const tmp = join(dir, `${STATE}.tmp`);
114
+ s.ours = s.ours.slice(-KEEP_OURS);
115
+ writeFileSync(tmp, JSON.stringify(s, null, 2));
116
+ renameSync(tmp, join(dir, STATE));
117
+ }
118
+
119
+ function note(s, msg) { if (!s.notices.includes(msg)) s.notices.push(msg); }
120
+
121
+ function acquire(root) {
122
+ const path = join(root, '.rsc', LOCK);
123
+ mkdirSync(join(root, '.rsc'), { recursive: true });
124
+ try { if (Date.now() - statSync(path).mtimeMs > LOCK_STALE_MS) unlinkSync(path); } catch { /* none */ }
125
+ try { closeSync(openSync(path, 'wx')); return true; } catch { return false; }
126
+ }
127
+
128
+ function release(root) { try { unlinkSync(join(root, '.rsc', LOCK)); } catch { /* gone */ } }
129
+
130
+ /** The lock and the state live together: a body that runs without the lock never runs. */
131
+ function locked(root, body) {
132
+ if (!acquire(root)) return null;
133
+ const s = readState(root);
134
+ try { return body(s); } finally { writeState(root, s); release(root); }
135
+ }
136
+
137
+ // ------------------------------------------------------------------ text
138
+
139
+ const clean = (text, limit = 60) => {
140
+ const t = String(text).replace(/\s+/g, ' ').trim();
141
+ return t.length <= limit ? t : `${t.slice(0, limit - 1)}…`;
142
+ };
143
+
144
+ function listed(paths, max = 5) {
145
+ const shown = paths.slice(0, max).map((p) => clean(p)).join(', ');
146
+ return paths.length > max ? `${shown} y ${paths.length - max} más` : shown;
147
+ }
148
+
149
+ const authorsOf = (root, revs) => [...new Set(revs.flatMap((c) => {
150
+ const a = line(root, ['log', '-1', '--format=%an', c]);
151
+ return a ? [clean(a, 30)] : [];
152
+ }))].join(', ') || 'alguien';
153
+
154
+ // ------------------------------------------------------------------ enabled
155
+
156
+ /**
157
+ * Why sync is not running here, or null when it is. A reason and not a boolean, so `status` can say
158
+ * which of the quiet conditions applies instead of making the person guess.
159
+ */
160
+ export function inactiveReason(root) {
161
+ if (!existsSync(join(root, '.rsc.json'))) return 'no-harness';
162
+ if (existsSync(join(root, '.rsc', OPT_OUT))) return 'opted-out';
163
+ const top = line(root, ['rev-parse', '--show-toplevel']);
164
+ if (!top) return 'not-a-repo';
165
+ try { if (realpathSync(top) !== realpathSync(root)) return 'harness-not-at-repo-root'; } catch { return 'not-a-repo'; }
166
+ if (!line(root, ['remote', 'get-url', 'origin'])) return 'no-origin';
167
+ if (!KNOWLEDGE.some((k) => existsSync(join(root, k)))) return 'no-knowledge-folders';
168
+ return null;
169
+ }
170
+
171
+ // ------------------------------------------------------------------ local: your changes
172
+
173
+ function changedKnowledge(root) {
174
+ const present = KNOWLEDGE.filter((k) => existsSync(join(root, k)) || line(root, ['ls-files', '--', k]));
175
+ if (!present.length) return [];
176
+ const out = git(root, ['status', '--porcelain=v1', '-z', '--untracked-files=all', '--', ...present]);
177
+ const entries = zlist(out);
178
+ const files = [];
179
+ for (let i = 0; i < entries.length; i++) {
180
+ const e = entries[i];
181
+ files.push(e.slice(3));
182
+ if (e[0] === 'R' || e[0] === 'C') files.push(entries[++i]); // the old name of a rename follows
183
+ }
184
+ return [...new Set(files)].filter(isKnowledge);
185
+ }
186
+
187
+ function summary(files) {
188
+ const names = [...new Set(files.map((f) => basename(f, extname(f))))].sort();
189
+ return listed(names, 3);
190
+ }
191
+
192
+ /**
193
+ * Commit your knowledge changes so they can go up. Local and fast; returns the new SHA or null.
194
+ *
195
+ * On a default branch that is closed for the agent (trunk-policy), nothing is committed there: the
196
+ * commit is built on a throwaway index from HEAD plus the knowledge files and left on no branch. It
197
+ * goes up like any other; the files stay modified until the agent commits on a branch (regla A).
198
+ * Repeating it while they stay modified is a no-op upstream — the content is already there.
199
+ */
200
+ export function commitLocal(root, s) {
201
+ const branch = line(root, ['rev-parse', '--abbrev-ref', 'HEAD']);
202
+ if (branch === 'HEAD') return null; // detached
203
+ const files = changedKnowledge(root).slice(0, MAX_FILES);
204
+ if (!files.length) return null;
205
+ const message = (names) => `📝 docs(auto): ${summary(names)} ${SKIP_CI}`;
206
+ if (branch === defaultBranch(root) && trunkClosed(root)) {
207
+ const env = { GIT_INDEX_FILE: join(root, '.rsc', 'knowledge-sync.snap.index') };
208
+ try {
209
+ if (!run(root, ['read-tree', 'HEAD'], { env }).ok) return null;
210
+ git(root, ['--literal-pathspecs', 'add', '-A', '--', ...files], { env });
211
+ const tree = line(root, ['write-tree'], { env });
212
+ // Chained to the previous snapshot while HEAD has not moved, so each one carries only what
213
+ // changed since: the files stay modified on a closed trunk, and a snapshot against HEAD would
214
+ // re-offer the first version every turn and read the second as a clash (review H1).
215
+ const head = line(root, ['rev-parse', 'HEAD']);
216
+ const prev = s.snap && s.snap.head === head && line(root, ['rev-parse', '--verify', '--quiet', `${s.snap.commit}^{commit}`]) ? s.snap.commit : head;
217
+ if (!tree || tree === line(root, ['rev-parse', `${prev}^{tree}`])) return null;
218
+ const sha = git(root, ['commit-tree', tree, '-p', prev, '-F', '-'], { input: message(files) }).trim();
219
+ s.snap = { head, commit: sha };
220
+ s.queue.push(sha);
221
+ return sha;
222
+ } finally {
223
+ try { unlinkSync(env.GIT_INDEX_FILE); } catch { /* never created */ }
224
+ }
225
+ }
226
+ git(root, ['--literal-pathspecs', 'add', '-A', '--', ...files]);
227
+ const staged = zlist(git(root, ['--literal-pathspecs', 'diff', '--cached', '--name-only', '-z', '--', ...files]));
228
+ if (!staged.length) return null;
229
+ git(root, ['--literal-pathspecs', 'commit', '--quiet', '--no-verify', '--only', '-m', message(staged), '--', ...staged]);
230
+ const sha = line(root, ['rev-parse', 'HEAD']);
231
+ s.queue.push(sha);
232
+ return sha;
233
+ }
234
+
235
+ // ------------------------------------------------------------------ network: up
236
+
237
+ /**
238
+ * The tree of `base` with the change of commit `sha` applied, or null if it does not apply cleanly.
239
+ * A throwaway index under `.rsc/` and `git apply --cached`: the real index and the working tree are
240
+ * never read or written, and it works on any git (`merge-tree --merge-base` needs 2.40).
241
+ */
242
+ function replay(root, base, sha, ours = []) {
243
+ if (!line(root, ['rev-parse', '--verify', '--quiet', `${sha}^`])) return null;
244
+ const patch = run(root, ['diff-tree', '-p', '--binary', '--full-index', `${sha}^`, sha], { timeout: NET_TIMEOUT_MS });
245
+ if (!patch.ok) return null;
246
+ if (!patch.out.trim()) return line(root, ['rev-parse', `${base}^{tree}`]);
247
+ const env = { GIT_INDEX_FILE: join(root, '.rsc', 'knowledge-sync.index') };
248
+ try {
249
+ if (!run(root, ['read-tree', base], { env }).ok) return null;
250
+ // File by file: one that is already there as it should be is skipped, not read as a clash (a
251
+ // teammate's change taken uncommitted on a closed trunk comes back up in the next snapshot), and
252
+ // one real clash does not hold back the rest of the patch's reasoning.
253
+ const files = zlist(git(root, ['diff-tree', '--no-commit-id', '--name-only', '--no-renames', '-r', '-z', `${sha}^`, sha]));
254
+ for (const f of files) {
255
+ const next = blob(root, sha, f);
256
+ const there = blob(root, base, f);
257
+ if (next === there) continue;
258
+ // What is there is what this change started from, or what we ourselves put there last: ours
259
+ // to replace whole. (A snapshot from a closed trunk can start from HEAD, behind our own last
260
+ // upload — after an upgrade, or once the chain is lost.)
261
+ const last = line(root, ['log', '-1', '--format=%H', base, '--', f]);
262
+ if (there === blob(root, `${sha}^`, f) || (last && ours.includes(last))) {
263
+ const entry = next && line(root, ['ls-tree', sha, '--', f]);
264
+ const ok = next
265
+ ? run(root, ['update-index', '--add', '--cacheinfo', `${entry.split(' ')[0]},${next},${f}`], { env }).ok
266
+ : run(root, ['update-index', '--force-remove', '--', f], { env }).ok;
267
+ if (!ok) return null;
268
+ continue;
269
+ }
270
+ const one = run(root, ['diff-tree', '-p', '--binary', '--full-index', '--no-renames', `${sha}^`, sha, '--', f], { timeout: NET_TIMEOUT_MS });
271
+ if (!one.ok || !run(root, ['apply', '--cached', '-'], { env, input: one.out, timeout: NET_TIMEOUT_MS }).ok) return null;
272
+ }
273
+ return line(root, ['write-tree'], { env });
274
+ } finally {
275
+ try { unlinkSync(env.GIT_INDEX_FILE); } catch { /* never created */ }
276
+ }
277
+ }
278
+
279
+ /**
280
+ * Put the queued commits on `rsc/knowledge`. Never the default branch; never the working tree or the
281
+ * index. Each queued commit is replayed on top of the exchange branch (`replay`), which is how a
282
+ * commit made on `feat/x` goes up without `feat/x`, and how your unpushed code never leaves the
283
+ * machine. The exchange branch is born from the remote default branch the first time, and reborn the
284
+ * same way if somebody deletes it.
285
+ */
286
+ export function ship(root, s) {
287
+ const def = defaultBranch(root);
288
+ if (!def) return;
289
+ const fetched = run(root, ['fetch', '--quiet', 'origin', def], { timeout: NET_TIMEOUT_MS });
290
+ if (!fetched.ok) return; // offline: the queue goes up on a later turn
291
+ if (!s.queue.length) return;
292
+ const ref = `refs/remotes/origin/${KNOWLEDGE_BRANCH}`;
293
+
294
+ for (let attempt = 0; attempt < 2; attempt++) {
295
+ const k = run(root, ['fetch', '--quiet', 'origin', `+refs/heads/${KNOWLEDGE_BRANCH}:${ref}`], { timeout: NET_TIMEOUT_MS });
296
+ if (!k.ok && !/couldn't find remote ref/i.test(k.err)) return;
297
+ if (!k.ok) run(root, ['update-ref', '-d', ref]); // deleted upstream: reborn from the default branch
298
+ const tip = line(root, ['rev-parse', '--verify', '--quiet', ref]) || line(root, ['rev-parse', `refs/remotes/origin/${def}`]);
299
+ if (!tip) return;
300
+ let base = tip;
301
+ const built = [];
302
+ const kept = [];
303
+ for (const sha of s.queue) {
304
+ if (!line(root, ['rev-parse', '--verify', '--quiet', `${sha}^{commit}`])) continue; // rewritten away
305
+ const tree = replay(root, base, sha, s.ours);
306
+ if (tree === null) {
307
+ const files = zlist(git(root, ['diff-tree', '--no-commit-id', '--name-only', '-r', '-z', sha]));
308
+ note(s, `No he podido subir ${listed(files)}: choca con un cambio que ya está en ${KNOWLEDGE_BRANCH}. ` +
309
+ 'Tu versión sigue aquí; hay que juntarlas a mano.');
310
+ continue;
311
+ }
312
+ if (tree === line(root, ['rev-parse', `${base}^{tree}`])) { kept.push(sha); continue; } // already there
313
+ const [name, email, date, ...body] = git(root, ['log', '-1', '--format=%an%n%ae%n%aI%n%B', sha]).split('\n');
314
+ base = git(root, ['commit-tree', tree, '-p', base, '-F', '-'], {
315
+ input: body.join('\n'),
316
+ env: { GIT_AUTHOR_NAME: name, GIT_AUTHOR_EMAIL: email, GIT_AUTHOR_DATE: date },
317
+ }).trim();
318
+ built.push(base);
319
+ }
320
+ if (base === tip && line(root, ['rev-parse', '--verify', '--quiet', ref])) { s.ours.push(...kept); s.queue = []; return; }
321
+ const r = run(root, ['push', '--quiet', 'origin', `${base}:refs/heads/${KNOWLEDGE_BRANCH}`], { timeout: NET_TIMEOUT_MS });
322
+ if (r.ok) {
323
+ run(root, ['update-ref', ref, base]);
324
+ s.ours.push(...built, ...kept);
325
+ s.queue = [];
326
+ return;
327
+ }
328
+ // Somebody pushed to the exchange branch in between: look again once, then say so.
329
+ }
330
+ note(s, `No he podido subir los cambios de conocimiento a ${KNOWLEDGE_BRANCH}. ` +
331
+ 'Siguen comiteados aquí; se reintenta en el próximo turno.');
332
+ }
333
+
334
+ // ------------------------------------------------------------------ local: their changes
335
+
336
+ /**
337
+ * Apply what others put on `rsc/knowledge`, from the last fetch — no network here — into whatever
338
+ * branch you are on. Only knowledge paths are looked at: the exchange branch is born from the default
339
+ * branch, so it also carries code, and code reaches you the ordinary way. Only files you have not
340
+ * touched since; a clash is said, never forced. Never a fast-forward: that would move your local
341
+ * default branch onto a commit the remote default branch does not have.
342
+ */
343
+ export function applyIncoming(root, s) {
344
+ const said = [];
345
+ if (busy(root)) return said;
346
+ const branch = line(root, ['rev-parse', '--abbrev-ref', 'HEAD']);
347
+ if (!branch || branch === 'HEAD') return said;
348
+ const tip = line(root, ['rev-parse', '--verify', '--quiet', `refs/remotes/origin/${KNOWLEDGE_BRANCH}`]);
349
+ if (!tip) return said;
350
+ if (!s.seen || !line(root, ['rev-parse', '--verify', '--quiet', `${s.seen}^{commit}`])) {
351
+ s.seen = line(root, ['merge-base', 'HEAD', tip]) || tip;
352
+ }
353
+ if (s.seen === tip) return said;
354
+ const paths = [...KNOWLEDGE];
355
+ const theirs = git(root, ['rev-list', `${s.seen}..${tip}`, '--', ...paths]).split('\n').filter(Boolean)
356
+ .filter((c) => !s.ours.includes(c));
357
+ if (!theirs.length) { s.seen = tip; return said; }
358
+
359
+ const know = zlist(git(root, ['diff', '--name-only', '--no-renames', '-z', s.seen, tip, '--', ...paths]))
360
+ .filter(isKnowledge).slice(0, MAX_FILES);
361
+ const who = authorsOf(root, theirs);
362
+ const closed = branch === defaultBranch(root) && trunkClosed(root);
363
+ const take = [];
364
+ const clash = [];
365
+ for (const f of know) {
366
+ const incoming = blob(root, tip, f);
367
+ const mine = worktreeBlob(root, f);
368
+ if (mine === incoming) continue;
369
+ const base = blob(root, s.seen, f);
370
+ // On a closed trunk HEAD lags behind on purpose (what came in was not committed), so only the
371
+ // working tree says whether you touched it (review H2).
372
+ if (mine === base && (closed || blob(root, 'HEAD', f) === base)) take.push(f);
373
+ else clash.push(f);
374
+ }
375
+
376
+ if (take.length) {
377
+ const gone = take.filter((f) => !blob(root, tip, f));
378
+ const present = take.filter((f) => blob(root, tip, f));
379
+ if (present.length) git(root, ['--literal-pathspecs', 'checkout', tip, '--', ...present]);
380
+ if (gone.length) git(root, ['--literal-pathspecs', 'rm', '--quiet', '--', ...gone]);
381
+ // On a default branch closed for the agent nothing is committed there: the files are updated
382
+ // and travel into the next branch the agent opens (regla A).
383
+ if (!closed) {
384
+ git(root, ['--literal-pathspecs', 'commit', '--quiet', '--no-verify', '--only',
385
+ '-m', `📥 docs(auto): sync desde ${KNOWLEDGE_BRANCH} ${SKIP_CI}`, '--', ...take]);
386
+ } else {
387
+ git(root, ['--literal-pathspecs', 'reset', '--quiet', '--', ...take]); // updated, not staged
388
+ }
389
+ said.push(`📥 Traídos ${theirs.length} cambio(s) de conocimiento de ${who}: ${listed(take)}.`);
390
+ }
391
+ if (clash.length) {
392
+ said.push(`${who} cambió ${listed(clash)}, que tú también has tocado. No lo traigo solo: tu versión sigue intacta.`);
393
+ }
394
+ s.seen = tip;
395
+ return said;
396
+ }
397
+
398
+ // ------------------------------------------------------------------ hook entry points
399
+
400
+ // `RSC_KNOWLEDGE_SYNC_FOREGROUND=1` runs the network half inline: for tests, which would otherwise race
401
+ // a detached process for the lock, and for anybody debugging what the background did.
402
+ /**
403
+ * Which program runs the detached worker. Not always `process.execPath`: OpenCode loads plugins in its
404
+ * own Bun-based binary, so there `execPath` is `opencode` — which does not run scripts — and the push
405
+ * silently never happened (found end to end, not by the unit tests). Anything that is not Node gets
406
+ * `node` from the PATH, which every assistant here already needs to run the hooks.
407
+ */
408
+ export function workerRuntime(execPath = process.execPath, versions = process.versions) {
409
+ return !versions.bun && /^node(?:\.exe)?$/i.test(execPath.split(/[\\/]/).pop()) ? execPath : 'node';
410
+ }
411
+
412
+ function background(root, op) {
413
+ if (process.env.RSC_KNOWLEDGE_SYNC_FOREGROUND === '1') return work(root, op);
414
+ try {
415
+ const self = fileURLToPath(import.meta.url);
416
+ spawn(workerRuntime(), [self, op, root], { detached: true, stdio: 'ignore', windowsHide: true }).unref();
417
+ } catch { /* the next turn tries again */ }
418
+ }
419
+
420
+ const ANNOUNCE = '🔄 La sincronización del conocimiento está activa: lo que cambies en 01-TOOLS/ y 02-DOCS/ ' +
421
+ `viaja a tu equipo por la rama ${KNOWLEDGE_BRANCH} (nunca a la principal, con [skip ci]) y lo de los demás ` +
422
+ 'te llega a la rama en la que estés. Llega a la principal dentro de vuestras PRs. Para apagarla en este ' +
423
+ 'proyecto: `rsc knowledge-sync off`.';
424
+
425
+ /** UserPromptSubmit: apply what was fetched, say what happened, fetch again in the background. */
426
+ export function onRequest(root, { spawnFetch = true } = {}) {
427
+ try {
428
+ if (inactiveReason(root)) return '';
429
+ let fetchDue = false;
430
+ const said = locked(root, (s) => {
431
+ const out = [];
432
+ if (!s.announced) { out.push(ANNOUNCE); s.announced = true; }
433
+ try { out.push(...applyIncoming(root, s)); } catch (e) { out.push(`La sincronización del conocimiento falló al traer cambios: ${clean(e.message, 160)}`); }
434
+ out.push(...s.notices);
435
+ s.notices = [];
436
+ if (Date.now() - s.lastFetch > FETCH_EVERY_MS) { s.lastFetch = Date.now(); fetchDue = true; }
437
+ return out;
438
+ });
439
+ if (fetchDue && spawnFetch) background(root, 'fetch'); // after the lock is released, or it would find it taken
440
+ return (said || []).join('\n');
441
+ } catch {
442
+ return '';
443
+ }
444
+ }
445
+
446
+ /** Stop: commit your knowledge changes here, then push them in the background. */
447
+ export function onTurn(root, { spawnShip = true } = {}) {
448
+ try {
449
+ if (inactiveReason(root) || busy(root)) return;
450
+ const pending = locked(root, (s) => {
451
+ try { commitLocal(root, s); } catch (e) { note(s, `La sincronización del conocimiento no pudo comitear: ${clean(e.message, 160)}`); }
452
+ return s.queue.length;
453
+ });
454
+ if (pending && spawnShip) background(root, 'ship');
455
+ } catch { /* a hook never takes the turn down */ }
456
+ }
457
+
458
+ /** For `rsc knowledge-sync status`. */
459
+ export function knowledgeStatus(root) {
460
+ const reason = inactiveReason(root);
461
+ const s = readState(root);
462
+ return {
463
+ active: !reason,
464
+ reason,
465
+ branch: line(root, ['rev-parse', '--abbrev-ref', 'HEAD']),
466
+ defaultBranch: defaultBranch(root),
467
+ exchangeBranch: KNOWLEDGE_BRANCH,
468
+ queued: s.queue.length,
469
+ pendingNotices: s.notices.length,
470
+ lastFetch: s.lastFetch ? new Date(s.lastFetch).toISOString() : null,
471
+ paths: [...KNOWLEDGE],
472
+ neverSynced: [...PERSONAL],
473
+ };
474
+ }
475
+
476
+ // ------------------------------------------------------------------ detached worker
477
+
478
+ function isMainModule(metaUrl) {
479
+ const invoked = process.argv[1];
480
+ if (!invoked) return false;
481
+ const self = fileURLToPath(metaUrl);
482
+ try { return realpathSync(self) === realpathSync(invoked); } catch { return self === invoked; }
483
+ }
484
+
485
+ /** What the detached process does: `ship` pushes the queue, `fetch` refreshes and retries the queue. */
486
+ export function work(root, op) {
487
+ if (!root || inactiveReason(root)) return;
488
+ locked(root, (s) => {
489
+ try {
490
+ if (op === 'ship') ship(root, s);
491
+ else if (op === 'fetch') {
492
+ // What comes down comes from the exchange branch; absent upstream is not an error.
493
+ run(root, ['fetch', '--quiet', 'origin', `+refs/heads/${KNOWLEDGE_BRANCH}:refs/remotes/origin/${KNOWLEDGE_BRANCH}`],
494
+ { timeout: NET_TIMEOUT_MS });
495
+ if (s.queue.length) ship(root, s);
496
+ }
497
+ } catch (e) {
498
+ note(s, `La sincronización del conocimiento falló: ${clean(e.message, 160)}`);
499
+ }
500
+ });
501
+ }
502
+
503
+ // ------------------------------------------------------------------ the hook
504
+
505
+ /** The project is the nearest ancestor holding `.rsc.json`, as for the session memory. */
506
+ function nearestHarness(dir) {
507
+ for (let current = dir; ; current = dirname(current)) {
508
+ if (existsSync(join(current, '.rsc.json'))) return current;
509
+ if (dirname(current) === current) return dir;
510
+ }
511
+ }
512
+
513
+ const isRemote = (target, native) => (target === 'cursor' && (native?.is_background_agent === true || native?.isBackgroundAgent === true))
514
+ || process.env.RSC_REMOTE_AGENT === '1' || process.env.CURSOR_CLOUD_AGENT === '1' || process.env.CODEX_CLOUD_AGENT === '1';
515
+
516
+ /**
517
+ * One lifecycle event from an assistant. `request` = the person sent a message; `turn` = the agent
518
+ * finished. What is said goes to the PERSON (`systemMessage`, which every event accepts; Cursor's
519
+ * `user_message`), never into the model's context.
520
+ */
521
+ export function hook(target, event, native = {}) {
522
+ try {
523
+ if (isRemote(target, native)) return {};
524
+ const root = nearestHarness(resolve(native.cwd || process.env.RSC_PROJECT_CWD || process.cwd()));
525
+ if (event === 'request') {
526
+ const said = onRequest(root);
527
+ if (!said) return {};
528
+ return target === 'cursor' ? { user_message: said } : { systemMessage: said };
529
+ }
530
+ // `stop_hook_active`: this turn exists because a stop hook asked for it. Nothing new to commit.
531
+ if (event === 'turn' && !native?.stop_hook_active) onTurn(root);
532
+ } catch { /* a hook never takes the turn down */ }
533
+ return {};
534
+ }
535
+
536
+ function stdinJson() {
537
+ try { const raw = readFileSync(0, 'utf8'); return raw.trim() ? JSON.parse(raw) : {}; } catch { return {}; }
538
+ }
539
+
540
+ if (isMainModule(import.meta.url)) {
541
+ const [op, a, b] = process.argv.slice(2);
542
+ if (op === 'hook') process.stdout.write(`${JSON.stringify(hook(a, b, stdinJson()))}\n`);
543
+ else work(a, op); // detached: `ship <root>` or `fetch <root>`
544
+ }