liteagents 2.24.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.
Files changed (39) hide show
  1. package/CHANGELOG.md +121 -0
  2. package/README.md +27 -11
  3. package/installer/cli.js +36 -3
  4. package/installer/installation-engine.js +8 -0
  5. package/package.json +2 -2
  6. package/packages/ampcode/AGENT.md +1 -2
  7. package/packages/ampcode/agents/orchestrator.md +2 -2
  8. package/packages/ampcode/commands/refactor.md +8 -2
  9. package/packages/ampcode/commands/remember/stub-check.cjs +197 -0
  10. package/packages/ampcode/commands/remember/sync-rules.cjs +169 -0
  11. package/packages/ampcode/commands/remember/version-check.cjs +214 -0
  12. package/packages/ampcode/commands/remember.md +78 -10
  13. package/packages/claude/CLAUDE.md +1 -2
  14. package/packages/claude/agents/orchestrator.md +2 -2
  15. package/packages/claude/commands/refactor.md +8 -2
  16. package/packages/claude/commands/remember/stub-check.cjs +197 -0
  17. package/packages/claude/commands/remember/sync-rules.cjs +169 -0
  18. package/packages/claude/commands/remember/version-check.cjs +214 -0
  19. package/packages/claude/commands/remember.md +78 -10
  20. package/packages/droid/AGENTS.md +1 -2
  21. package/packages/droid/commands/refactor.md +8 -2
  22. package/packages/droid/commands/remember/stub-check.cjs +197 -0
  23. package/packages/droid/commands/remember/sync-rules.cjs +169 -0
  24. package/packages/droid/commands/remember/version-check.cjs +214 -0
  25. package/packages/droid/commands/remember.md +78 -10
  26. package/packages/droid/droids/orchestrator.md +2 -2
  27. package/packages/opencode/AGENTS.md +1 -2
  28. package/packages/opencode/agent/orchestrator.md +2 -2
  29. package/packages/opencode/command/refactor.md +8 -2
  30. package/packages/opencode/command/remember/stub-check.cjs +197 -0
  31. package/packages/opencode/command/remember/sync-rules.cjs +169 -0
  32. package/packages/opencode/command/remember/version-check.cjs +214 -0
  33. package/packages/opencode/command/remember.md +78 -10
  34. package/packages/opencode/opencode.jsonc +0 -10
  35. package/packages/subagentic-manual.md +15 -15
  36. package/packages/ampcode/agents/context-builder.md +0 -144
  37. package/packages/claude/agents/context-builder.md +0 -145
  38. package/packages/droid/droids/context-builder.md +0 -144
  39. package/packages/opencode/agent/context-builder.md +0 -148
@@ -38,6 +38,26 @@ Reads all raw material (`.claude/stash/*.md` + `.claude/remember/friction/antige
38
38
  - **Locate `friction.cjs`** — it is bundled next to this command at `remember/friction.cjs`
39
39
  (the same directory as `remember.md`, whether installed or run from the package). If it
40
40
  exists nowhere, skip to step 1 (stash-only) and tell the user friction.cjs is missing.
41
+ - **Check for a newer liteagents** (best-effort, one line, never blocking) — bundled
42
+ beside `friction.cjs` as `remember/version-check.cjs`. Call it by its **absolute
43
+ path**, exactly as step 7 calls `docs-builder.cjs`: the cwd here is the target repo,
44
+ not this package, so a cwd-relative path fails everywhere except the liteagents repo
45
+ itself.
46
+ ```bash
47
+ node ~/.claude/commands/remember/version-check.cjs
48
+ ```
49
+ **If that path does not exist, use the directory you just resolved for
50
+ `friction.cjs`** — the two ship side by side, so that directory is correct for a
51
+ non-default install and when running from a checkout, where the path above would
52
+ point at the installed copy instead of the one under test.
53
+ It prints one advice line if the installed version is behind the registry, and prints
54
+ nothing otherwise. It exits 0 on every path, caches the registry answer for 24h, and
55
+ is bounded to ~2s, so it cannot stall this run. If it prints a line, relay it verbatim
56
+ in your final report; never act on it and never run the install yourself.
57
+ - **If the script is missing from both locations, say so** — one line, same rule as step
58
+ 7's "applicable but could not run". A failed *check* (offline, registry down, timeout)
59
+ stays silent by design: it is a once-a-day nudge, not a result anyone is waiting on. A
60
+ missing *script* means the install is incomplete, which is worth a word.
41
61
  - **Resolve the global sessions root** — probe this list top-to-bottom, use the first that
42
62
  exists and contains `.jsonl` files directly, or one level down in per-project
43
63
  subdirectories (friction.cjs scans exactly those two levels, not a deep recursive walk).
@@ -72,11 +92,26 @@ Reads all raw material (`.claude/stash/*.md` + `.claude/remember/friction/antige
72
92
  fresh output). **Move only those pipeline files** — anything else in `.claude/memory/`
73
93
  (e.g. user-owned rule files) stays where it is. Remove the old dirs only if empty, update the managed MEMORY section in CLAUDE.md to
74
94
  the new reference (step 5), and tell the user exactly what moved.
75
- - **Bootstrap `AGENT_RULES.md` (one-time, silent-if-present).** If
76
- `.claude/remember/AGENT_RULES.md` does not exist, copy it from the bundled template next
77
- to this command (`remember/AGENT_RULES.md`, same directory as `friction.cjs`). If it
78
- already exists, leave it untouched — never overwrite, even if the bundled template
79
- changes in a later version; it becomes user-owned the moment it lands in the project.
95
+ - **Sync `AGENT_RULES.md` from the installed template** — run the bundled script, which
96
+ does the whole decision itself. Call it by **absolute path**, for the same reason as
97
+ `version-check.cjs` in step 0: the cwd is the target repo, not this package.
98
+ ```bash
99
+ node ~/.claude/commands/remember/sync-rules.cjs
100
+ ```
101
+ It compares `.claude/remember/AGENT_RULES.md` against the template shipped beside it
102
+ and takes one of three actions: **absent** — copies it in; **identical** — does
103
+ nothing at all, no write and no output; **differs** — moves the old body to
104
+ `AGENT_RULES.md.bak` and copies the new one in, reporting both. Relay whatever it
105
+ prints in the step-8 report; it is silent when nothing changed.
106
+
107
+ **This replaced a bootstrap-once rule that never refreshed**, which left a measured 35
108
+ repos many releases behind. The rules doc is a shipped standards document, so it is
109
+ kept current rather than frozen on first write — nothing is destroyed, because a
110
+ differing body is always preserved in the backup first.
111
+
112
+ The comparison is a byte compare done *by the script*, never by you: a model-performed
113
+ copy can re-wrap a line or drop a trailing newline, and the file would then differ
114
+ forever, backing up on every single run.
80
115
  - Read all `.claude/stash/*.md` files in the current project
81
116
  - Read friction output written in step 0: `.claude/remember/friction/antigen_clusters.json` (preferred) or `.claude/remember/friction/antigen_review.md` (fallback). On the fallback path, step 4c does NO counting — merge quotes into
82
117
  matching entries only; never change `sessions`, `last_seen`, or `recurred_while_hot` (the
@@ -88,7 +123,11 @@ Reads all raw material (`.claude/stash/*.md` + `.claude/remember/friction/antige
88
123
  length-gate debt on `.claude/remember/MEMORY.md`. Steps 4-5 (friction → ledger count →
89
124
  Antigens render) are stash-independent and still run whenever friction produced output
90
125
  (see step 4's own guard). If there is also no friction
91
- output, report "nothing to consolidate" and stop after step 1.
126
+ output, report "nothing to consolidate" and stop after step 1 — **but run
127
+ step 5's `stub-check.cjs` before you stop.** The stub shape does not depend on
128
+ there being anything to consolidate, and skipping it on quiet runs is exactly
129
+ how a repo with nothing to remember stays broken forever. `sync-rules.cjs`
130
+ already ran above, for the same reason.
92
131
 
93
132
  2. **Extract from unprocessed stashes** (up to 5 stashes per agent, as few agents as possible — see Guardrails)
94
133
  - Each agent reads its batch of stashes together and calls the mid-tier model (see Guardrails) to extract:
@@ -387,11 +426,32 @@ Reads all raw material (`.claude/stash/*.md` + `.claude/remember/friction/antige
387
426
  Users trim this section deliberately (a pointer-only variant is common), and rewriting
388
427
  it silently re-adds text they removed, on every single run, forever. Observed in the
389
428
  field: a run restored the inline rules into a CLAUDE.md whose owner had cut them, and
390
- the edit had to be reverted by hand. This matches how `AGENT_RULES.md` itself is
391
- handled bootstrapped once, never overwritten after.
429
+ the edit had to be reverted by hand. Note this no longer matches how `AGENT_RULES.md`
430
+ itself is handled: `sync-rules.cjs` refreshes that file every run, because it is a
431
+ shipped standards document with a backup behind it. This section is prose the user
432
+ owns, with nothing behind it — so it stays bootstrap-once.
392
433
  - If an existing pair is present but its **path pointer** is missing or wrong, that is
393
434
  load-bearing: **report it and stop**, do not silently rewrite the section around it.
394
435
 
436
+ - **Then assert the stub SHAPE mechanically** — run the bundled script by **absolute
437
+ path**, for the same reason as steps 0 and 1:
438
+ ```bash
439
+ node ~/.claude/commands/remember/stub-check.cjs
440
+ ```
441
+ It edits only *inside* the marker pairs, and only the mechanism: a MEMORY include that
442
+ is not `@.claude/remember/MEMORY.md` is repaired, and an `@`-include of
443
+ `AGENT_RULES.md` is demoted to a plain pointer. Prose inside the blocks is user-owned
444
+ and is never touched, which is why the bootstrap-once rule above still holds. It will
445
+ **not** repoint a MEMORY include at a file that does not exist — an un-migrated
446
+ `.claude/memory/` repo has a live MEMORY.md at the old path, and breaking a working
447
+ include to satisfy a naming convention is worse than reporting it. Silent when the
448
+ shape is already current; relay whatever it prints in the step-8 report.
449
+
450
+ Measured 2026-09-03: 21 of 37 local repos still carried the pre-v2.19 `@`-include of
451
+ `AGENT_RULES.md`, hot-loading ~300 lines into every session. A shape rule checked by
452
+ asking you to look is a rule that drifts back; this one is a byte-level assertion done
453
+ by the script, never by you.
454
+
395
455
  ```markdown
396
456
  # Project Memory
397
457
  > Auto-generated by /remember. Do not edit manually.
@@ -535,7 +595,14 @@ Reads all raw material (`.claude/stash/*.md` + `.claude/remember/friction/antige
535
595
  ledger: ag-003 "don't commit per change" RECURRED while hot (2/2) → rephrased, attempt 2
536
596
  ledger: ag-002 "literal scoped ask" ESCALATED → Fact; 2 phrasings failed. Hook or accept?
537
597
  ```
538
- - If AGENT_RULES.md was bootstrapped this run, say so (one line)
598
+ - Relay verbatim whatever `version-check.cjs` (step 0), `sync-rules.cjs` (step 1), and
599
+ `stub-check.cjs` (step 5) printed. Never re-word or summarize them: they are the
600
+ record of a file that was written or a version gap, and a paraphrase of "your body
601
+ was backed up to AGENT_RULES.md.bak" can lose the filename the user needs.
602
+ - Each is silent when nothing changed, so silence is the normal case and there is
603
+ nothing to invent — never report an action that produced no output.
604
+ - Never a silent write: if any of the three wrote or moved a file and you did not
605
+ relay its line, that is a defect.
539
606
  - If step 7 ran the auto re-index, say so and name the regenerated files
540
607
  (`docs/index.md`, plus `docs/log.md` if touched) so they are staged with this run
541
608
  - Confirm MEMORY.md and CLAUDE.md updated
@@ -543,7 +610,8 @@ Reads all raw material (`.claude/stash/*.md` + `.claude/remember/friction/antige
543
610
  **File locations (all project-local — two dirs: `/stash` owns `.claude/stash/`, `/remember` owns `.claude/remember/`)**
544
611
  - Stash files: `.claude/stash/*.md`
545
612
  - Memory file: `.claude/remember/MEMORY.md` (single source of truth, referenced as `@.claude/remember/MEMORY.md`)
546
- - Rules template: `.claude/remember/AGENT_RULES.md` (bootstrapped once from the bundled package template on first `/remember` run, never overwritten again user-owned after that; referenced by a plain path pointer, not `@`-referenced — see step 5)
613
+ - Rules template: `.claude/remember/AGENT_RULES.md` (refreshed from the bundled package template every `/remember` run by `sync-rules.cjs`; a differing body is backed up first, not silently overwritten — referenced by a plain path pointer, not `@`-referenced — see step 5)
614
+ - Rules backup: `.claude/remember/AGENT_RULES.md.bak` (written by `sync-rules.cjs` only when the existing body differs from the template; a single file, overwritten each time it fires — not timestamped)
547
615
  - Antigen ledger: `.claude/remember/ledger.json` (per-rule evidence trail: class, status, attempts/rejected-buffer, recurrence-while-hot)
548
616
  - Consolidation report: `.claude/remember/report.md` (latest step-8 report, overwritten each run)
549
617
  - Processed manifest: `.claude/remember/.processed`
@@ -6,7 +6,7 @@ Droid is a lightweight CLI tool that provides workflow automation commands.
6
6
 
7
7
  These subagents are available when using Claude Code CLI. Droid can reference them but doesn't implement them directly.
8
8
 
9
- ### Subagents (11 total)
9
+ ### Subagents (10 total)
10
10
 
11
11
  | ID | Title | When To Use |
12
12
  |---|---|---|
@@ -14,7 +14,6 @@ These subagents are available when using Claude Code CLI. Droid can reference th
14
14
  | 2-generate-tasks | 2-Generate Tasks | Detailed Planning - use to break down the PRD into a granular, actionable task list |
15
15
  | 3-process-task-list | 3-Process Task List | Iterative Implementation - use to guide the AI to tackle one task at a time, allowing you to review and approve each change |
16
16
  | code-developer | Full Stack Developer | Use for code implementation, debugging, refactoring, and development best practices |
17
- | context-builder | Context Initializer | Use to initialize project context for new/existing projects, discover and organize documentation, create AGENTS.md and KNOWLEDGE_BASE.md for optimal token-efficient memory |
18
17
  | feature-planner | Product Manager | Use for creating epics and user stories, prioritization, backlog navigation, story refinement, and retrospectives |
19
18
  | market-researcher | Business Analyst | Use for market research, brainstorming, competitive analysis, project briefs, and initial project discovery |
20
19
  | orchestrator | Master Orchestrator | Use for workflow coordination, multi-agent tasks, role switching guidance, and when unsure which specialist to consult |
@@ -72,8 +72,14 @@ refactor and how to close each item.
72
72
  behaviour change is not a refactor — leave the bullet, note it in the report.
73
73
  5. Run the tests as described below. Then report: **fixed / dropped / left**
74
74
  with the reason per left item, and the remaining bullet count.
75
- 6. Say plainly: **commit, then run `/branch-review`** on this branch — ledger
76
- mode is a fixer, not a review, and its diff gets the ordinary gate.
75
+ 6. **Hand it back; do not chain it.** Say plainly: **commit, then run
76
+ `/branch-review`** on this branch — ledger mode is a fixer, not a review,
77
+ and its diff gets the ordinary gate. That is a sentence you *say*, not a
78
+ sequence you *run*. They are two separate calls and both are the user's:
79
+ an answer of "commit", "yes" or "go" authorizes the commit and nothing
80
+ after it. Never start `/branch-review` off the back of it. Observed in the
81
+ field: a run chained the review onto the owner's "commit" and the owner
82
+ objected.
77
83
 
78
84
  ## Goals
79
85
  - Reduce complexity
@@ -0,0 +1,197 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * stub-check.cjs — asserts the two managed blocks in the tool config carry the
6
+ * CURRENT stub shape, and repairs the shape when it is wrong.
7
+ *
8
+ * Shape, not content. The blocks' prose is user-owned — step 5 writes it once
9
+ * and never re-imposes it, because users trim it deliberately. What this script
10
+ * touches is only the mechanism:
11
+ *
12
+ * MEMORY block @<PROJECT_DIR>/remember/MEMORY.md — an @-include.
13
+ * A bare `@MEMORY.md` resolves relative to the file that
14
+ * contains it, so in a repo root it names a file that does
15
+ * not exist and hot memory silently never loads.
16
+ *
17
+ * AGENT_RULES block <PROJECT_DIR>/remember/AGENT_RULES.md — a PLAIN pointer.
18
+ * v2.19 demoted it from an @-include on purpose: it is a
19
+ * standards guide to consult when building something new,
20
+ * not hot context, and @-including it loads ~300 lines into
21
+ * every session. Measured 2026-09-03: 21 of 37 local repos
22
+ * still carried the pre-v2.19 @-include.
23
+ *
24
+ * Two deliberate limits:
25
+ *
26
+ * - It only edits INSIDE a marker pair. A pointer elsewhere in the config is
27
+ * the user's prose and is left alone.
28
+ * - It never repoints the MEMORY include at a file that does not exist. An
29
+ * un-migrated `.factory/memory/` repo has a live MEMORY.md at the old path;
30
+ * rewriting it to the new one would break a working include to satisfy a
31
+ * naming convention. That case is reported, not repaired.
32
+ *
33
+ * Missing marker pairs are not this script's business — step 5 creates them.
34
+ */
35
+
36
+ const fs = require('fs');
37
+ const path = require('path');
38
+
39
+ // The ONE pair of lines that differs across packages.
40
+ const PROJECT_DIR = '.factory';
41
+ const CONFIG_FILE = 'AGENTS.md';
42
+
43
+ const MEM = { start: '<!-- MEMORY:START -->', end: '<!-- MEMORY:END -->' };
44
+ const RULES = { start: '<!-- AGENT_RULES:START -->', end: '<!-- AGENT_RULES:END -->' };
45
+
46
+ const MEMORY_REL = `${PROJECT_DIR}/remember/MEMORY.md`;
47
+ const RULES_REL = `${PROJECT_DIR}/remember/AGENT_RULES.md`;
48
+
49
+ /** lstat, not existsSync: existsSync follows links, so a DANGLING link reads
50
+ * as absent and gets walked straight past. */
51
+ function lexists(p) {
52
+ try { fs.lstatSync(p); return true; } catch (e) { return false; }
53
+ }
54
+
55
+ /**
56
+ * True when writing to `target` would land outside `repo`.
57
+ *
58
+ * There are two ways out and a guard on only one of them is false safety:
59
+ * `target` may itself be a symlink — including a dangling one, which reads as
60
+ * "the file is absent" and is still followed on write — or any parent
61
+ * directory may be a link pointing elsewhere. This runs across a whole fleet
62
+ * of repos, so a relative link only has to reach a sibling checkout.
63
+ */
64
+ function escapesRepo(repo, target) {
65
+ let root;
66
+ try { root = fs.realpathSync(repo); } catch (e) { return true; }
67
+
68
+ // Walk up to the deepest ancestor that exists; anything below it cannot be
69
+ // a link yet, so only the existing part needs resolving.
70
+ const tail = [];
71
+ let dir = path.dirname(target);
72
+ while (!lexists(dir)) {
73
+ tail.unshift(path.basename(dir));
74
+ const up = path.dirname(dir);
75
+ if (up === dir) return true; // walked off the filesystem root
76
+ dir = up;
77
+ }
78
+
79
+ let resolved;
80
+ try { resolved = path.join(fs.realpathSync(dir), ...tail, path.basename(target)); }
81
+ catch (e) { return true; } // an ancestor is a dangling link
82
+
83
+ // The last component can be a link even when every directory above it is
84
+ // clean — that is the dangling-file case.
85
+ try { if (fs.lstatSync(resolved).isSymbolicLink()) return true; } catch (e) { /* absent: fine */ }
86
+
87
+ return resolved !== root && !resolved.startsWith(root + path.sep);
88
+ }
89
+
90
+ /** Index range of the lines strictly between a marker pair, or null. */
91
+ function blockRange(lines, markers) {
92
+ const s = lines.findIndex((l) => l.trim() === markers.start);
93
+ if (s === -1) return null;
94
+ const e = lines.findIndex((l, i) => i > s && l.trim() === markers.end);
95
+ if (e === -1) return null;
96
+ return { from: s + 1, to: e }; // [from, to)
97
+ }
98
+
99
+ /**
100
+ * @returns {{fixes:string[], notes:string[], changed:boolean}}
101
+ * fixes — repairs written to disk
102
+ * notes — wrong shapes deliberately left alone, with the reason
103
+ */
104
+ function check(repo) {
105
+ const config = path.join(repo, CONFIG_FILE);
106
+ const fixes = [];
107
+ const notes = [];
108
+
109
+ // Checked before the read, not just before the write: a repair decided
110
+ // from a followed link is already the wrong decision.
111
+ if (escapesRepo(repo, config)) {
112
+ return { fixes, notes: [`${CONFIG_FILE} not checked: it leaves the repo via a symlink`], changed: false };
113
+ }
114
+
115
+ let text;
116
+ try { text = fs.readFileSync(config, 'utf8'); } catch (e) {
117
+ return { fixes, notes, changed: false }; // no config: step 5 will create one
118
+ }
119
+
120
+ const lines = text.split('\n');
121
+ let changed = false;
122
+
123
+ // ── MEMORY block: must be an @-include naming the explicit path ────────────
124
+ const mem = blockRange(lines, MEM);
125
+ if (mem) {
126
+ const i = lines.findIndex(
127
+ (l, n) => n >= mem.from && n < mem.to && /^@\S*MEMORY\.md\s*$/.test(l.trim()));
128
+ if (i === -1) {
129
+ notes.push(`${CONFIG_FILE}: MEMORY block has no @-include — hot memory does not load`);
130
+ } else {
131
+ const want = `@${MEMORY_REL}`;
132
+ const have = lines[i].trim();
133
+ if (have !== want) {
134
+ if (fs.existsSync(path.join(repo, MEMORY_REL))) {
135
+ lines[i] = want;
136
+ changed = true;
137
+ fixes.push(`${CONFIG_FILE}: MEMORY include repaired, ${have} → ${want}`);
138
+ } else {
139
+ // The old path may be the only one with a file behind it.
140
+ notes.push(
141
+ `${CONFIG_FILE}: MEMORY include is ${have}, not ${want} — left as is, `
142
+ + `${MEMORY_REL} does not exist yet`);
143
+ }
144
+ }
145
+ }
146
+ }
147
+
148
+ // ── AGENT_RULES block: must be a PLAIN pointer, never an @-include ─────────
149
+ const rules = blockRange(lines, RULES);
150
+ if (rules) {
151
+ const i = lines.findIndex(
152
+ (l, n) => n >= rules.from && n < rules.to && /^@\S*AGENT_RULES\.md\s*$/.test(l.trim()));
153
+ if (i !== -1) {
154
+ // Demote in place. The path is kept as written — only the @ is dropped,
155
+ // because the @ is the defect and the path may be a deliberate variant.
156
+ const had = lines[i].trim();
157
+ lines[i] = had.slice(1);
158
+ changed = true;
159
+ fixes.push(
160
+ `${CONFIG_FILE}: AGENT_RULES pointer demoted from an @-include (${had} → ${had.slice(1)}) `
161
+ + `— it is a standards guide, not hot context`);
162
+ } else {
163
+ const hasPointer = lines
164
+ .slice(rules.from, rules.to)
165
+ .some((l) => /AGENT_RULES\.md/.test(l));
166
+ if (!hasPointer) {
167
+ notes.push(`${CONFIG_FILE}: AGENT_RULES block has no path pointer — nothing points at the rules`);
168
+ }
169
+ }
170
+ }
171
+
172
+ if (changed) {
173
+ try {
174
+ fs.writeFileSync(config, lines.join('\n'));
175
+ } catch (e) {
176
+ return { fixes: [], notes: [`${CONFIG_FILE} not repaired: ${e.message}`], changed: false };
177
+ }
178
+ }
179
+
180
+ return { fixes, notes, changed };
181
+ }
182
+
183
+ function main() {
184
+ const repo = process.argv[2] || process.cwd();
185
+ const r = check(repo);
186
+ for (const line of r.fixes) process.stdout.write(`${line}\n`);
187
+ for (const line of r.notes) process.stdout.write(`${line}\n`);
188
+ // Silent when the shape is already current — the common case.
189
+ }
190
+
191
+ if (require.main === module) {
192
+ // A passenger on /remember, like version-check.cjs and sync-rules.cjs: it
193
+ // never gets to fail the run it rides in.
194
+ try { main(); } catch (e) { /* silent */ }
195
+ }
196
+
197
+ module.exports = { check, PROJECT_DIR, CONFIG_FILE, MEMORY_REL, RULES_REL };
@@ -0,0 +1,169 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * sync-rules.cjs — keeps a repo's AGENT_RULES.md current with the installed
6
+ * template, without ever destroying what was there.
7
+ *
8
+ * Run every /remember, from the target repo. Before this existed, the rules
9
+ * were bootstrapped once and never refreshed, so a measured 35 local repos
10
+ * drifted to a body many releases old and three hand sweeps failed to hold.
11
+ *
12
+ * Three outcomes, decided by a byte compare — not a stored hash, because the
13
+ * only question is "am I about to change this file?", which any careful copy
14
+ * asks anyway:
15
+ *
16
+ * absent copy it in and say so
17
+ * identical do nothing at all: no write, no backup, no output
18
+ * differs move the old body aside, copy the new one in, say so loudly
19
+ *
20
+ * THE BACKUP IS A SINGLE FILE and is overwritten on each differing run. A
21
+ * customised file therefore survives exactly one update: fold your changes
22
+ * into the new AGENT_RULES.md before the next release, or the next sync
23
+ * replaces the backup with a vanilla body. This is a deliberate trade — see
24
+ * docs/product/agent-rules-freshness-prd.md §5 — chosen over accumulating
25
+ * timestamped backups.
26
+ */
27
+
28
+ const fs = require('fs');
29
+ const path = require('path');
30
+
31
+ // Per-kit PROJECT dir. NOTE this is not always the global config dir: amp
32
+ // installs to ~/.config/amp but writes .amp/ in a repo, and opencode likewise.
33
+ // This is the ONE line that differs across packages.
34
+ const PROJECT_DIR = '.factory';
35
+
36
+ const RULES = 'AGENT_RULES.md';
37
+ const BACKUP = 'AGENT_RULES.md.bak'; // keeps the origin name; not .md, so doc tooling ignores it
38
+
39
+ /** lstat, not existsSync: existsSync follows links, so a DANGLING link reads
40
+ * as absent and gets walked straight past. */
41
+ function lexists(p) {
42
+ try { fs.lstatSync(p); return true; } catch (e) { return false; }
43
+ }
44
+
45
+ /**
46
+ * True when writing to `target` would land outside `repo`.
47
+ *
48
+ * There are two ways out and a guard on only one of them is false safety:
49
+ * `target` may itself be a symlink — including a dangling one, which reads as
50
+ * "the file is absent" and is still followed on write — or any parent
51
+ * directory may be a link pointing elsewhere. This runs across a whole fleet
52
+ * of repos, so a relative link only has to reach a sibling checkout.
53
+ */
54
+ function escapesRepo(repo, target) {
55
+ let root;
56
+ try { root = fs.realpathSync(repo); } catch (e) { return true; }
57
+
58
+ // Walk up to the deepest ancestor that exists; anything below it cannot be
59
+ // a link yet, so only the existing part needs resolving.
60
+ const tail = [];
61
+ let dir = path.dirname(target);
62
+ while (!lexists(dir)) {
63
+ tail.unshift(path.basename(dir));
64
+ const up = path.dirname(dir);
65
+ if (up === dir) return true; // walked off the filesystem root
66
+ dir = up;
67
+ }
68
+
69
+ let resolved;
70
+ try { resolved = path.join(fs.realpathSync(dir), ...tail, path.basename(target)); }
71
+ catch (e) { return true; } // an ancestor is a dangling link
72
+
73
+ // The last component can be a link even when every directory above it is
74
+ // clean — that is the dangling-file case.
75
+ try { if (fs.lstatSync(resolved).isSymbolicLink()) return true; } catch (e) { /* absent: fine */ }
76
+
77
+ return resolved !== root && !resolved.startsWith(root + path.sep);
78
+ }
79
+
80
+ function templatePath() {
81
+ // Ships beside this script, so no path guessing and no dependence on where
82
+ // the kit was installed.
83
+ return path.join(__dirname, RULES);
84
+ }
85
+
86
+ function targetPath(repo) {
87
+ return path.join(repo, PROJECT_DIR, 'remember', RULES);
88
+ }
89
+
90
+ /**
91
+ * @returns {{action:string, detail?:string}} action is one of:
92
+ * 'no-template' | 'bootstrapped' | 'unchanged' | 'updated' | 'failed'
93
+ */
94
+ function sync(repo) {
95
+ const tpl = templatePath();
96
+ let template;
97
+ try {
98
+ template = fs.readFileSync(tpl);
99
+ } catch (e) {
100
+ return { action: 'no-template', detail: tpl };
101
+ }
102
+
103
+ const target = targetPath(repo);
104
+ if (escapesRepo(repo, target)) return { action: 'escapes', detail: target };
105
+
106
+ let current = null;
107
+ try { current = fs.readFileSync(target); } catch (e) { /* absent */ }
108
+
109
+ // Byte compare. No normalisation on either side: the copy below is a plain
110
+ // byte write, so a mismatch here means the content really differs.
111
+ if (current && current.equals(template)) return { action: 'unchanged' };
112
+
113
+ try {
114
+ fs.mkdirSync(path.dirname(target), { recursive: true });
115
+ if (current) {
116
+ // Single backup, overwritten. rename() is atomic on the same filesystem
117
+ // and cannot leave a half-written backup the way copy+truncate could.
118
+ fs.renameSync(target, path.join(path.dirname(target), BACKUP));
119
+ }
120
+ fs.writeFileSync(target, template);
121
+ } catch (e) {
122
+ return { action: 'failed', detail: e.message };
123
+ }
124
+
125
+ return current ? { action: 'updated' } : { action: 'bootstrapped' };
126
+ }
127
+
128
+ function main() {
129
+ const repo = process.argv[2] || process.cwd();
130
+ const r = sync(repo);
131
+ const rel = path.join(PROJECT_DIR, 'remember', RULES);
132
+
133
+ switch (r.action) {
134
+ case 'unchanged':
135
+ break; // silent: nothing happened
136
+ case 'bootstrapped':
137
+ process.stdout.write(`${rel} created from the installed template\n`);
138
+ break;
139
+ case 'updated':
140
+ process.stdout.write(
141
+ `${rel} updated from the installed template `
142
+ + `(previous body kept as ${BACKUP} — fold your changes in before the `
143
+ + `next release, it is a single file and the next update replaces it)\n`);
144
+ break;
145
+ case 'escapes':
146
+ // Loud, never repaired: the path is under the repo but does not stay
147
+ // there, so any write lands somewhere the run was not invited.
148
+ process.stdout.write(
149
+ `${rel} not synced: it leaves the repo via a symlink — refusing to `
150
+ + `write through it\n`);
151
+ break;
152
+ case 'no-template':
153
+ // Loud: this means the install is incomplete, not that nothing changed.
154
+ process.stdout.write(
155
+ `AGENT_RULES.md not synced: no template beside this script (${r.detail})\n`);
156
+ break;
157
+ case 'failed':
158
+ process.stdout.write(`AGENT_RULES.md not synced: ${r.detail}\n`);
159
+ break;
160
+ }
161
+ }
162
+
163
+ if (require.main === module) {
164
+ // A passenger on /remember, like version-check.cjs: it never gets to fail
165
+ // the run it rides in.
166
+ try { main(); } catch (e) { /* silent */ }
167
+ }
168
+
169
+ module.exports = { sync, PROJECT_DIR, RULES, BACKUP };