fapony 0.6.2 → 0.7.1

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 (63) hide show
  1. package/README.md +144 -156
  2. package/package.json +5 -6
  3. package/skill/define-convention/SKILL.md +3 -3
  4. package/skill/lookup-before-edit/SKILL.md +2 -1
  5. package/skill/move-to-done/SKILL.md +18 -22
  6. package/skill/plan-with-pony/SKILL.md +4 -4
  7. package/skill/review-pony/SKILL.md +10 -12
  8. package/src/adapters/cli.ts +11 -52
  9. package/src/adapters/hooks/index.ts +0 -67
  10. package/src/adapters/hooks/mv-guard.ts +2 -2
  11. package/src/analyze/discover.ts +1 -1
  12. package/src/analyze/index.ts +0 -1
  13. package/src/commands.ts +8 -39
  14. package/src/core/config.ts +0 -6
  15. package/src/core/fapony-dir.ts +71 -0
  16. package/src/core/hook-helpers.ts +1 -2
  17. package/src/debt/load.ts +3 -5
  18. package/src/debt/promotion.ts +2 -2
  19. package/src/debt/scan.ts +1 -1
  20. package/src/digest/collect.ts +6 -7
  21. package/src/fael.ts +139 -0
  22. package/src/hook.ts +1 -81
  23. package/src/init.ts +30 -90
  24. package/src/install/antigravity.ts +8 -99
  25. package/src/install/claude.ts +66 -200
  26. package/src/install/codex.ts +6 -170
  27. package/src/install/detect.ts +4 -14
  28. package/src/install/opencode.ts +50 -486
  29. package/src/install/types.ts +1 -39
  30. package/src/install/zcode.ts +5 -91
  31. package/src/install.ts +9 -35
  32. package/src/memory.ts +10 -69
  33. package/src/plan/index.ts +34 -0
  34. package/src/plan/next.ts +181 -0
  35. package/src/plan/store.ts +41 -0
  36. package/src/{mem/commands/plan.ts → plan/sweep.ts} +66 -46
  37. package/src/seed/plan-seed.ts +10 -9
  38. package/src/setup.ts +4 -22
  39. package/src/update.ts +1 -1
  40. package/templates/PLAN.md +1 -1
  41. package/src/adapters/hooks/bug-markers.ts +0 -60
  42. package/src/adapters/hooks/context-data.ts +0 -139
  43. package/src/adapters/hooks/edit-hint.ts +0 -215
  44. package/src/adapters/hooks/read-hint.ts +0 -410
  45. package/src/adapters/hooks/session-start.ts +0 -112
  46. package/src/adapters/hooks/stop.ts +0 -768
  47. package/src/adapters/mcp/tools/index.ts +0 -149
  48. package/src/adapters/mcp/tools/mem.ts +0 -252
  49. package/src/adapters/mcp/transport.ts +0 -147
  50. package/src/analyze/cache.ts +0 -162
  51. package/src/core/mem-log.ts +0 -375
  52. package/src/init-mem.ts +0 -143
  53. package/src/install/cursor.ts +0 -167
  54. package/src/install/utils.ts +0 -29
  55. package/src/mem/commands/read.ts +0 -738
  56. package/src/mem/commands/rotate.ts +0 -59
  57. package/src/mem/commands/where.ts +0 -56
  58. package/src/mem/commands/write.ts +0 -273
  59. package/src/mem/engine.ts +0 -315
  60. package/src/mem/index.ts +0 -201
  61. package/src/mem/render.ts +0 -66
  62. package/src/mem/selectors.ts +0 -160
  63. package/src/mem/store.ts +0 -356
@@ -1,162 +0,0 @@
1
- // src/analyze/cache.ts — session-scoped graph cache.
2
- //
3
- // buildGraph is cheap on this repo (~50ms/150 files) but the Edit hint calls it
4
- // on every Edit — and a Claude Code PreToolUse hook is a *fresh process per
5
- // tool call*, so an in-process cache alone never survives to the next edit. The
6
- // graph is therefore mirrored to <faponyDir>/graph-cache/<key>.json:
7
- // - auto-build: every build is written through, best-effort (never blocks)
8
- // - auto-invalidate: a fingerprint over the source-file set (rel path + size
9
- // + mtimeMs) is stored beside the graph; a mismatch means rebuild
10
- // - cost: the cache file is only stat-ed when there is one to validate, so a
11
- // first-ever call pays build + write; later calls pay a walk + stat + parse,
12
- // well under a rebuild on any repo large enough for this to matter
13
- // Everything here is derived state — an unreadable, corrupt, stale or
14
- // unwritable cache falls back to a live build and no code path trusts it.
15
-
16
- import {
17
- existsSync,
18
- mkdirSync,
19
- readFileSync,
20
- renameSync,
21
- statSync,
22
- writeFileSync,
23
- } from "node:fs";
24
- import { join, resolve } from "node:path";
25
-
26
- import { faponyDir } from "../core/config.js";
27
- import { collectSourceFiles } from "./discover.js";
28
- import { buildGraph } from "./graph.js";
29
- import type { ImportGraph } from "./types.js";
30
-
31
- const GRAPH_CACHE_VERSION = 1;
32
- const GRAPH_CACHE_DIR = "graph-cache";
33
-
34
- interface SerializedGraph {
35
- v: number;
36
- fp: string;
37
- files: string[];
38
- deps: Record<string, string[]>;
39
- dependents: Record<string, string[]>;
40
- unresolved: number;
41
- external: number;
42
- barrels: string[];
43
- }
44
-
45
- let _graphCache: { dir: string; fp: string; graph: ImportGraph } | null = null;
46
-
47
- /** Drop the in-process graph cache (tests simulate a fresh hook process). */
48
- export function resetGraphCache(): void {
49
- _graphCache = null;
50
- }
51
-
52
- /** Absolute path of a worktree's graph-cache file — may not exist. */
53
- export function graphCachePath(dir: string): string {
54
- const abs = resolve(dir);
55
- const slug = abs.replace(/[^A-Za-z0-9]+/g, "-").slice(0, 60);
56
- return join(
57
- faponyDir(),
58
- GRAPH_CACHE_DIR,
59
- `${slug}-${Bun.hash(abs).toString(36)}.json`,
60
- );
61
- }
62
-
63
- // The graph changes only when the set of source files or their bytes change —
64
- // size/mtime/ctime catch that without reading any file. ctime rides the same
65
- // stat call for free and cannot be forged like mtime can (only the system
66
- // moves it), so an mtime-preserving rewrite still invalidates.
67
- function graphFingerprint(absDir: string): string {
68
- const parts: string[] = [];
69
- for (const rel of collectSourceFiles(absDir)) {
70
- try {
71
- const st = statSync(join(absDir, rel));
72
- parts.push(
73
- `${rel}\u0000${st.size}\u0000${st.mtimeMs}\u0000${st.ctimeMs}`,
74
- );
75
- } catch {
76
- parts.push(`${rel}\u0000?\u0000?\u0000?`);
77
- }
78
- }
79
- return Bun.hash(parts.join("\n")).toString(36);
80
- }
81
-
82
- function serializeGraph(graph: ImportGraph, fp: string): SerializedGraph {
83
- const rec = (m: Map<string, Set<string>>): Record<string, string[]> => {
84
- const out: Record<string, string[]> = {};
85
- for (const [k, v] of m) out[k] = [...v];
86
- return out;
87
- };
88
- return {
89
- v: GRAPH_CACHE_VERSION,
90
- fp,
91
- files: graph.files,
92
- deps: rec(graph.deps),
93
- dependents: rec(graph.dependents),
94
- unresolved: graph.unresolved,
95
- external: graph.external,
96
- barrels: [...graph.barrels],
97
- };
98
- }
99
-
100
- function hydrateGraph(c: SerializedGraph): ImportGraph {
101
- const toMap = (r: Record<string, string[]>): Map<string, Set<string>> => {
102
- const m = new Map<string, Set<string>>();
103
- for (const [k, v] of Object.entries(r)) m.set(k, new Set(v));
104
- return m;
105
- };
106
- return {
107
- files: c.files,
108
- deps: toMap(c.deps),
109
- dependents: toMap(c.dependents),
110
- unresolved: c.unresolved,
111
- external: c.external,
112
- barrels: new Set(c.barrels),
113
- };
114
- }
115
-
116
- function readCachedGraph(path: string, fp: string): ImportGraph | null {
117
- try {
118
- const cached = JSON.parse(readFileSync(path, "utf-8")) as SerializedGraph;
119
- if (cached.v !== GRAPH_CACHE_VERSION || cached.fp !== fp) return null;
120
- return hydrateGraph(cached);
121
- } catch {
122
- return null;
123
- }
124
- }
125
-
126
- function writeCachedGraph(path: string, graph: ImportGraph, fp: string): void {
127
- try {
128
- if (!existsSync(join(faponyDir(), GRAPH_CACHE_DIR))) {
129
- mkdirSync(join(faponyDir(), GRAPH_CACHE_DIR), { recursive: true });
130
- }
131
- // pid-suffixed temp + rename: a reader never sees a half-written file even
132
- // when two hook processes race.
133
- const tmp = `${path}.${process.pid}.tmp`;
134
- writeFileSync(tmp, JSON.stringify(serializeGraph(graph, fp)), "utf-8");
135
- renameSync(tmp, path);
136
- } catch {
137
- // best-effort — a cache that cannot be written must not break the caller
138
- }
139
- }
140
-
141
- export function buildGraphCached(dir: string): ImportGraph {
142
- const abs = resolve(dir);
143
- // One walk per call: the fingerprint doubles as the in-process validity
144
- // check, so a same-process second call after an edit rebuilds instead of
145
- // serving the stale graph. A drift between this fp and the built graph
146
- // self-heals — the next call recomputes and rebuilds again.
147
- const fp = graphFingerprint(abs);
148
- if (_graphCache?.dir === abs && _graphCache.fp === fp)
149
- return _graphCache.graph;
150
- const path = graphCachePath(abs);
151
- if (existsSync(path)) {
152
- const cached = readCachedGraph(path, fp);
153
- if (cached) {
154
- _graphCache = { dir: abs, fp, graph: cached };
155
- return cached;
156
- }
157
- }
158
- const graph = buildGraph(abs);
159
- _graphCache = { dir: abs, fp, graph };
160
- writeCachedGraph(path, graph, fp);
161
- return graph;
162
- }
@@ -1,375 +0,0 @@
1
- // src/core/mem-log.ts — mem-log reader: directory discovery + JSONL parsing (pure, no feature imports)
2
- //
3
- // Extracted from src/memory.ts (PLAN-lib-layer chunk 2b). Shell adapter
4
- // helpers (closeMemory, kickoffMemory, claimMemory) stay in memory.ts.
5
-
6
- import { existsSync, readdirSync, readFileSync, realpathSync } from "node:fs";
7
- import { dirname, isAbsolute, join, resolve } from "node:path";
8
- import {
9
- CONFIG_FILENAME,
10
- DEFAULT_MEM_DIR,
11
- FAPONY_DIR,
12
- loadConfig,
13
- } from "./config.js";
14
-
15
- export interface MemRow {
16
- ts: string;
17
- agent: string;
18
- kind: string;
19
- text: string;
20
- spec?: string;
21
- id?: string;
22
- ref?: string;
23
- /** Files the row is about — written by `mem add --files` (PLAN-convention-debt chunk 3). */
24
- files?: string[];
25
- /** Problem identity, distinct from kind (action) and files[] (place) — written by `mem add --key` (PLAN-mem-keys chunk 1). */
26
- key?: string;
27
- /** Row schema version: 2 = may carry `key`; absent = v:1 legacy row, read as-is. */
28
- v?: number;
29
- }
30
-
31
- /** One mem-row text budget for any hint/seed surface that shows a row (was context-data's private const). */
32
- export const MEM_TEXT_MAX = 120;
33
-
34
- /**
35
- * The only accepted shape of a mem row `key` — problem identity, not action
36
- * (kind) and not place (files[]). Lives here in core so CLI and MCP validate
37
- * through one regex (PLAN-unify-mem-engine: one engine, both surfaces).
38
- */
39
- export const KEY_RE = /^[a-z0-9-]{3,40}$/;
40
-
41
- interface RawMemRow {
42
- ts?: string;
43
- agent?: string;
44
- kind?: string;
45
- text?: string;
46
- spec?: string;
47
- id?: string;
48
- ref?: string;
49
- files?: unknown;
50
- key?: unknown;
51
- v?: unknown;
52
- }
53
-
54
- /**
55
- * A directory is a mem dir only when it holds a `log.jsonl` or a named
56
- * `log.<person>.jsonl` (rotated `log.YYYY-MM-DD.jsonl` archives count too).
57
- * A `.fapony/.memory/` scaffolded empty by `fapony init` is not a candidate —
58
- * otherwise it would shadow an ancestor that holds the real log (SPEC §1).
59
- */
60
- function hasMemLogs(dir: string): boolean {
61
- try {
62
- return readdirSync(dir).some(
63
- (f) => f === "log.jsonl" || /^log\.[A-Za-z0-9._-]+\.jsonl$/.test(f),
64
- );
65
- } catch {
66
- return false;
67
- }
68
- }
69
-
70
- /** Physical path (symlinks resolved) so start and repo root compare like with
71
- * like; falls back to a lexical resolve when the path does not exist yet. */
72
- function physical(p: string): string {
73
- try {
74
- return realpathSync(p);
75
- } catch {
76
- return resolve(p);
77
- }
78
- }
79
-
80
- /** `git rev-parse --show-toplevel` from a directory, or null outside a repo. */
81
- function gitRootOf(fromDir: string): string | null {
82
- try {
83
- const { execSync } =
84
- require("node:child_process") as typeof import("node:child_process");
85
- const root = execSync("git rev-parse --show-toplevel", {
86
- cwd: fromDir,
87
- encoding: "utf-8",
88
- stdio: ["pipe", "pipe", "pipe"],
89
- }).trim();
90
- return root || null;
91
- } catch {
92
- return null;
93
- }
94
- }
95
-
96
- /**
97
- * The lexical ancestor of `fromDir` that is the git repo root, or null outside
98
- * a repo. `git rev-parse` returns a physical path (it resolves /var → /private/
99
- * var on macOS), so the walk compares `physical(dir)` against it and returns the
100
- * path in the caller's own lexical form — the returned dir must match what the
101
- * caller passed in, not a canonicalized stranger.
102
- */
103
- function repoRootOf(fromDir: string): string | null {
104
- const start = resolve(fromDir);
105
- const gitRoot = gitRootOf(start);
106
- if (!gitRoot) return null;
107
- const physicalRoot = physical(gitRoot);
108
- let dir = start;
109
- while (true) {
110
- if (physical(dir) === physicalRoot) return dir;
111
- const parent = dirname(dir);
112
- if (parent === dir) return null;
113
- dir = parent;
114
- }
115
- }
116
-
117
- /**
118
- * Locate the nearest `.fapony/.memory/` by walking up from `fromDir`.
119
- *
120
- * The walk stops at the git repo root (SPEC §1) — a mem dir in a parent
121
- * checkout is never ours. Outside a repo it stops at the filesystem root.
122
- * `acceptEmpty` is for the default-wiring check, which only needs the dir the
123
- * writer will use (log or not); the resolver itself requires a real log.
124
- */
125
- export function walkUpForMemDir(
126
- fromDir: string,
127
- acceptEmpty: boolean,
128
- ): string | null {
129
- const start = resolve(fromDir);
130
- const boundary = repoRootOf(start) ?? "/";
131
- let dir = start;
132
- while (true) {
133
- const candidate = join(dir, DEFAULT_MEM_DIR);
134
- if (existsSync(candidate) && (acceptEmpty || hasMemLogs(candidate))) {
135
- return candidate;
136
- }
137
- if (dir === boundary) break;
138
- const parent = dirname(dir);
139
- if (parent === dir) break;
140
- dir = parent;
141
- }
142
- return null;
143
- }
144
-
145
- export interface MemDirResult {
146
- dir: string | null;
147
- step: "flag" | "config" | "walk-up" | "repo-root" | "ambiguous" | "none";
148
- candidates?: string[];
149
- }
150
-
151
- // Dirs that never hold a project mem log and are expensive to walk.
152
- const SCAN_SKIP = new Set([
153
- "node_modules",
154
- ".git",
155
- "dist",
156
- "build",
157
- "coverage",
158
- "vendor",
159
- "out",
160
- "target",
161
- ".next",
162
- ".turbo",
163
- ".cache",
164
- ]);
165
-
166
- /**
167
- * Every `.fapony/.memory/` under `root` that holds a real log, bounded to a
168
- * shallow walk. Used only to detect the ambiguous monorepo layout (SPEC §1
169
- * fail example): if two or more app-scoped logs exist and nothing at/above cwd
170
- * holds one, the caller must refuse rather than start a third log at the root.
171
- */
172
- function findMemDirsUnder(root: string): string[] {
173
- const found: string[] = [];
174
- const walk = (dir: string, depth: number): void => {
175
- if (depth > 5) return;
176
- let entries: import("node:fs").Dirent[];
177
- try {
178
- entries = readdirSync(dir, { withFileTypes: true });
179
- } catch {
180
- return;
181
- }
182
- for (const e of entries) {
183
- if (!e.isDirectory()) continue;
184
- if (e.name === FAPONY_DIR) {
185
- const candidate = join(dir, DEFAULT_MEM_DIR);
186
- if (hasMemLogs(candidate)) found.push(candidate);
187
- continue;
188
- }
189
- if (e.name.startsWith(".") || SCAN_SKIP.has(e.name)) continue;
190
- walk(join(dir, e.name), depth + 1);
191
- }
192
- };
193
- walk(root, 0);
194
- return found;
195
- }
196
-
197
- /**
198
- * The single resolver: returns the mem dir and which step won.
199
- *
200
- * Resolution order (SPEC §1):
201
- * 1. `--mem-dir <path>` (wins over everything)
202
- * 2. `paths.memDir` in the **repo-root** `fapony.config.json` (relative to root)
203
- * 3. walk up from cwd for the first `.fapony/.memory/` that holds a real log
204
- * 4. `<repo root>/.fapony/.memory/`
205
- */
206
- function resolveMemDirFrom(
207
- fromDir: string,
208
- explicitOverride?: string,
209
- ): MemDirResult {
210
- // Step 1: --mem-dir flag
211
- if (explicitOverride) {
212
- return {
213
- dir: existsSync(explicitOverride) ? resolve(explicitOverride) : null,
214
- step: "flag",
215
- };
216
- }
217
-
218
- const cwd = resolve(fromDir);
219
- const root = repoRootOf(cwd);
220
-
221
- // Step 2: paths.memDir in the repo-root config
222
- const configDir = root ?? cwd;
223
- try {
224
- const configPath = join(configDir, CONFIG_FILENAME);
225
- if (existsSync(configPath)) {
226
- const config = loadConfig(configPath);
227
- if (config?.paths?.memDir) {
228
- const absCfg = isAbsolute(config.paths.memDir)
229
- ? config.paths.memDir
230
- : join(configDir, config.paths.memDir);
231
- if (existsSync(absCfg)) return { dir: absCfg, step: "config" };
232
- }
233
- }
234
- } catch {
235
- // no config or unreadable — continue
236
- }
237
-
238
- // Step 3: walk up from cwd, only a dir with a real log counts
239
- const walked = walkUpForMemDir(cwd, false);
240
- if (walked) return { dir: walked, step: "walk-up" };
241
-
242
- // Guard (SPEC §1 fail example)
243
- const candidates = root ? findMemDirsUnder(root) : [];
244
- if (candidates.length >= 2) {
245
- return { dir: null, step: "ambiguous", candidates };
246
- }
247
- const outOfScope = candidates.length ? { candidates } : {};
248
-
249
- // Step 4: <repo root>/.fapony/.memory/
250
- if (root) {
251
- const rootDir = join(root, DEFAULT_MEM_DIR);
252
- if (existsSync(rootDir)) {
253
- return { dir: rootDir, step: "repo-root", ...outOfScope };
254
- }
255
- }
256
-
257
- return { dir: null, step: "none", ...outOfScope };
258
- }
259
-
260
- export function resolveMemDir(
261
- worktree?: string,
262
- explicitOverride?: string,
263
- ): string | null {
264
- return resolveMemDirFrom(worktree ?? process.cwd(), explicitOverride).dir;
265
- }
266
-
267
- /** Resolve and report which step won — for `fapony mem where`. */
268
- export function whereMemDir(
269
- fromDir?: string,
270
- explicitOverride?: string,
271
- ): MemDirResult {
272
- return resolveMemDirFrom(fromDir ?? process.cwd(), explicitOverride);
273
- }
274
-
275
- /**
276
- * Read every `log*.jsonl` row under the worktree's memory dir, newest first.
277
- * `sinceIso` (exclusive) drops older rows; omit it to read the whole log.
278
- * Malformed/unreadable rows are counted, never thrown — a corrupt line must
279
- * not take down the caller.
280
- */
281
- export function readMemLog(
282
- worktree: string,
283
- sinceIso?: string,
284
- ): { rows: MemRow[]; skipped: number; filesFound: number } {
285
- const dir = resolveMemDir(worktree);
286
- if (!dir) return { rows: [], skipped: 0, filesFound: 0 };
287
-
288
- const isLogFile = (f: string): boolean =>
289
- f === "log.jsonl" || /^log\.[A-Za-z0-9._-]+\.jsonl$/.test(f);
290
-
291
- let files: string[];
292
- try {
293
- files = readdirSync(dir)
294
- .filter(isLogFile)
295
- .sort()
296
- .map((f) => join(dir, f));
297
- } catch {
298
- return { rows: [], skipped: 0, filesFound: 0 };
299
- }
300
-
301
- if (files.length === 0) return { rows: [], skipped: 0, filesFound: 0 };
302
-
303
- let skipped = 0;
304
- const all: MemRow[] = [];
305
-
306
- for (const file of files) {
307
- let raw: string;
308
- try {
309
- raw = readFileSync(file, "utf-8");
310
- } catch {
311
- continue;
312
- }
313
- const lines = raw.split("\n").filter(Boolean);
314
- for (const line of lines) {
315
- let parsed: RawMemRow;
316
- try {
317
- parsed = JSON.parse(line) as RawMemRow;
318
- } catch {
319
- skipped++;
320
- continue;
321
- }
322
- if (!parsed.ts || !parsed.kind) {
323
- skipped++;
324
- continue;
325
- }
326
- if (sinceIso && parsed.ts < sinceIso) continue;
327
- all.push({
328
- ts: parsed.ts,
329
- agent: parsed.agent ?? "unknown",
330
- kind: parsed.kind,
331
- text: parsed.text ?? "",
332
- spec: parsed.spec,
333
- id: parsed.id,
334
- ref: parsed.ref,
335
- ...(Array.isArray(parsed.files)
336
- ? { files: parsed.files.filter((f) => typeof f === "string") }
337
- : {}),
338
- ...(typeof parsed.key === "string" ? { key: parsed.key } : {}),
339
- ...(typeof parsed.v === "number" ? { v: parsed.v } : {}),
340
- });
341
- }
342
- }
343
-
344
- all.sort((a, b) => b.ts.localeCompare(a.ts)); // newest first
345
- return { rows: all, skipped, filesFound: files.length };
346
- }
347
-
348
- /**
349
- * Decisions for the pre-edit context summary — newest first, capped at `limit`.
350
- */
351
- export function readRecentMemDecisions(
352
- worktree: string,
353
- limit: number,
354
- keywords?: string[],
355
- ): MemRow[] {
356
- let decisions: MemRow[];
357
- try {
358
- decisions = readMemLog(worktree).rows.filter((r) => r.kind === "decision");
359
- } catch {
360
- return [];
361
- }
362
- if (decisions.length === 0) return [];
363
-
364
- const kws = (keywords ?? [])
365
- .map((k) => k.toLowerCase())
366
- .filter((k) => k.length > 0);
367
- if (kws.length > 0) {
368
- const hits = decisions.filter((r) => {
369
- const hay = `${r.text}\n${r.spec ?? ""}`.toLowerCase();
370
- return kws.some((k) => hay.includes(k));
371
- });
372
- if (hits.length > 0) return hits.slice(0, limit);
373
- }
374
- return decisions.slice(0, limit);
375
- }
package/src/init-mem.ts DELETED
@@ -1,143 +0,0 @@
1
- // src/init-mem.ts — cleanup old .memory/ directories and warn about stale call sites.
2
- //
3
- // Before PLAN-agent-one-call, this file scaffolded templates/mem/ into every repo.
4
- // Now fapony owns the mem code (src/mem/) and calls it directly via `fapony mem`.
5
- // This command's new job: delete legacy .memory/ dirs + warn about package.json refs.
6
-
7
- import { existsSync, readdirSync, readFileSync, rmSync } from "node:fs";
8
- import { join } from "node:path";
9
- import { DEFAULT_MEM_DIR, FAPONY_DIR, loadConfig } from "./core/config.js";
10
- import { walkDir } from "./util.js";
11
-
12
- export function cmdInitMem(args: string[]): void {
13
- const force = args.includes("--force");
14
- const worktreeKey = args.find((x) => !x.startsWith("-"));
15
- const config = loadConfig();
16
-
17
- // no key given = the repo you are standing in
18
- const worktree = worktreeKey ? config.worktrees[worktreeKey] : process.cwd();
19
- if (!worktree) {
20
- console.error(`unknown worktree key: ${worktreeKey}`);
21
- console.error(`available: ${Object.keys(config.worktrees).join(", ")}`);
22
- process.exit(1);
23
- }
24
-
25
- const gitRoot = Bun.spawnSync(["git", "rev-parse", "--show-toplevel"], {
26
- cwd: worktree,
27
- })
28
- .stdout.toString()
29
- .trim();
30
- const root = gitRoot || worktree;
31
-
32
- // 1) Find and delete .memory/ directories (legacy layout)
33
- const memoryDirs = walkDir(root, {
34
- includeDotDirs: [FAPONY_DIR],
35
- predicate: (dir) => existsSync(join(dir, ".memory")),
36
- }).map((dir) => join(dir, ".memory"));
37
-
38
- // Legacy filenames that may live alongside live logs inside .fapony/.memory/
39
- const LEGACY_MEM_FILENAMES = [
40
- "mem.ts",
41
- "store.ts",
42
- "selectors.ts",
43
- "render.ts",
44
- ];
45
-
46
- if (memoryDirs.length === 0) {
47
- console.log("no legacy .memory/ directories found — already clean");
48
- } else {
49
- let removed = 0;
50
- let kept = 0;
51
- for (const d of memoryDirs) {
52
- // Any log*.jsonl is history — includes log.<person>.jsonl (the standard
53
- // filename) and rotated log.YYYY-MM-DD.jsonl, not just log.jsonl.
54
- let logs: string[] = [];
55
- try {
56
- logs = readdirSync(d).filter(
57
- (f) => f === "log.jsonl" || /^log\..*\.jsonl$/.test(f),
58
- );
59
- } catch {
60
- // unreadable dir — fall through and remove
61
- }
62
- // Inside .fapony/.memory/: remove known legacy .ts files while keeping
63
- // live logs. The keep-if-logs guard would preserve the whole directory,
64
- // but legacy scaffolding (mem.ts, store.ts, ...) is dead code that
65
- // should not linger beside the active log.
66
- const isFaponyMemory =
67
- d.endsWith(`/${FAPONY_DIR}/.memory`) || d === `${FAPONY_DIR}/.memory`;
68
- if (isFaponyMemory && logs.length > 0) {
69
- let legacyRemoved = 0;
70
- let commandsRemoved = 0;
71
- for (const name of LEGACY_MEM_FILENAMES) {
72
- const fp = join(d, name);
73
- if (existsSync(fp)) {
74
- rmSync(fp);
75
- legacyRemoved++;
76
- }
77
- }
78
- const commandsDir = join(d, "commands");
79
- if (existsSync(commandsDir)) {
80
- rmSync(commandsDir, { recursive: true, force: true });
81
- commandsRemoved++;
82
- }
83
- if (legacyRemoved || commandsRemoved) {
84
- console.log(
85
- `cleaned ${d} — removed ${legacyRemoved} legacy file(s)${
86
- commandsRemoved ? " + commands/" : ""
87
- } (kept ${logs.length} log file(s): ${logs.join(", ")})`,
88
- );
89
- } else {
90
- console.log(`${d} — already clean (logs: ${logs.join(", ")})`);
91
- }
92
- kept++;
93
- continue;
94
- }
95
- if (logs.length > 0 && !force) {
96
- console.log(
97
- `keeping ${d} — has ${logs.length} log file(s): ${logs.join(", ")}`,
98
- );
99
- console.log(
100
- ` move them under ${DEFAULT_MEM_DIR}/, or re-run with --force to delete`,
101
- );
102
- kept++;
103
- continue;
104
- }
105
- console.log(
106
- `deleting ${d}${logs.length > 0 ? ` (--force: ${logs.length} log file(s))` : ""}`,
107
- );
108
- rmSync(d, { recursive: true, force: true });
109
- removed++;
110
- }
111
- console.log(
112
- `\nremoved ${removed} legacy .memory/ director${removed === 1 ? "y" : "ies"}${
113
- kept > 0
114
- ? ` · kept ${kept} with logs — move them under ${DEFAULT_MEM_DIR}/, then re-run`
115
- : ""
116
- }`,
117
- );
118
- }
119
-
120
- // 2) Warn about package.json call sites still referencing .memory/mem.ts
121
- for (const dir of walkDir(root)) {
122
- const pkg = join(dir, "package.json");
123
- if (!existsSync(pkg)) continue;
124
- try {
125
- const raw = readFileSync(pkg, "utf8");
126
- if (raw.includes(".memory/mem.ts")) {
127
- console.log(`\n⚠ ${pkg} still references .memory/mem.ts`);
128
- console.log(
129
- ` update to: "fapony mem <sub>" (e.g. "fapony mem add", "fapony mem close")`,
130
- );
131
- }
132
- } catch {
133
- // ignore
134
- }
135
- }
136
-
137
- console.log("\nmem commands are now built into fapony:");
138
- console.log(' fapony mem add <kind> "<text>" --files <files>');
139
- console.log(' fapony mem close <id> "<text>"');
140
- console.log(" fapony mem find <word>");
141
- console.log(" fapony mem kickoff [id|spec.md]");
142
- console.log(" fapony mem done | stale");
143
- }