fapony 0.1.3 → 0.2.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 (51) hide show
  1. package/README.md +111 -46
  2. package/fapony.ts +35 -2
  3. package/package.json +3 -2
  4. package/skill/move-to-done/SKILL.md +18 -28
  5. package/skill/plan-with-pony/SKILL.md +8 -3
  6. package/src/analyze.ts +175 -5
  7. package/src/conventions-seed.ts +3 -3
  8. package/src/db/defaults.ts +13 -5
  9. package/src/db/getters.ts +11 -9
  10. package/src/db/load.ts +2 -2
  11. package/src/db/store.ts +0 -75
  12. package/src/db/types.ts +2 -4
  13. package/src/debt.ts +176 -36
  14. package/src/digest/collect.ts +19 -2
  15. package/src/digest/text.ts +25 -0
  16. package/src/hook.ts +665 -24
  17. package/src/init-mem.ts +123 -37
  18. package/src/init.ts +57 -39
  19. package/src/install/claude.ts +44 -8
  20. package/src/install/codex.ts +105 -13
  21. package/src/install/opencode.ts +169 -5
  22. package/src/install.ts +2 -1
  23. package/src/lint-baseline.ts +3 -8
  24. package/src/mcp/evidence.ts +15 -3
  25. package/src/mcp/tools/index.ts +97 -185
  26. package/src/mcp/tools/mem.ts +153 -11
  27. package/src/mcp/transport.ts +5 -13
  28. package/src/mem/commands/read.ts +448 -0
  29. package/src/mem/commands/where.ts +56 -0
  30. package/{templates → src}/mem/commands/write.ts +12 -5
  31. package/src/mem/index.ts +144 -0
  32. package/src/mem/store.ts +350 -0
  33. package/src/memory.ts +238 -40
  34. package/src/plan-seed.ts +26 -6
  35. package/src/review-seed.ts +19 -0
  36. package/src/setup.ts +7 -8
  37. package/src/stats/data.ts +40 -104
  38. package/src/stats/format.ts +8 -9
  39. package/src/stats/index.ts +0 -1
  40. package/templates/PLAN.md +1 -0
  41. package/src/mcp/tools/context.ts +0 -66
  42. package/src/mcp/tools/plans.ts +0 -255
  43. package/src/mcp/tools/stats.ts +0 -96
  44. package/templates/mem/commands/read.ts +0 -194
  45. package/templates/mem/commands/selftest.ts +0 -450
  46. package/templates/mem/mem.ts +0 -68
  47. package/templates/mem/store.ts +0 -285
  48. /package/{templates → src}/mem/commands/plan.ts +0 -0
  49. /package/{templates → src}/mem/commands/rotate.ts +0 -0
  50. /package/{templates → src}/mem/render.ts +0 -0
  51. /package/{templates → src}/mem/selectors.ts +0 -0
@@ -0,0 +1,350 @@
1
+ // store.ts — types + config + read/write primitives for the append-only memory log
2
+ //
3
+ // Moved from templates/mem/store.ts (2026-09-19) as part of PLAN-agent-one-call chunk 1.
4
+ // The template was copied into every repo via `fapony init-mem`; now fapony owns the code
5
+ // and calls it directly via `fapony mem <sub>`. Path resolution is no longer based on
6
+ // import.meta.dir — initStore() receives the worktree explicitly from the CLI dispatch.
7
+
8
+ import { createHash } from "node:crypto";
9
+ import {
10
+ appendFileSync,
11
+ existsSync,
12
+ mkdirSync,
13
+ readdirSync,
14
+ readFileSync,
15
+ } from "node:fs";
16
+ import { hostname, networkInterfaces } from "node:os";
17
+ import { basename, dirname, join, relative } from "node:path";
18
+ import { CONFIG_FILENAME, DEFAULT_MEM_DIR, FAPONY_DIR } from "../db/index.js";
19
+ import { whereMemDir } from "../memory.js";
20
+
21
+ // --- types ---
22
+
23
+ type WorkKind = "next" | "bug" | "decision" | "note" | "hold";
24
+
25
+ type WorkRow = {
26
+ ts: string;
27
+ agent: string;
28
+ id: string;
29
+ kind: WorkKind;
30
+ text: string;
31
+ spec?: string;
32
+ files?: string[];
33
+ };
34
+
35
+ type CloseRow = {
36
+ ts: string;
37
+ agent: string;
38
+ kind: "close";
39
+ ref: string;
40
+ text: string;
41
+ };
42
+
43
+ type ClaimRow = {
44
+ ts: string;
45
+ agent: string;
46
+ kind: "claim";
47
+ ref: string;
48
+ };
49
+
50
+ type ReleaseRow = {
51
+ ts: string;
52
+ agent: string;
53
+ kind: "release";
54
+ ref: string;
55
+ text?: string;
56
+ };
57
+
58
+ type SyncedRow = {
59
+ ts: string;
60
+ agent: string;
61
+ kind: "synced";
62
+ spec: string;
63
+ };
64
+
65
+ type LogRow = WorkRow | CloseRow | ClaimRow | ReleaseRow | SyncedRow;
66
+
67
+ // --- identity ---
68
+ //
69
+ // `agent` goes in every row, `person` names the file. Both used to end in
70
+ // "unknown", which is not a fallback: two machines with no git and no $USER
71
+ // wrote the same filename and their rows interleaved with no way to tell them
72
+ // apart. Generic OS accounts collide the same way — `admin`/`user`/`owner` are
73
+ // what a fresh install offers, so treat them as absent rather than as a name.
74
+ // git user.email is unique by construction; the machine tag is the last resort,
75
+ // hashed because this file is committed and a raw MAC address is not ours to
76
+ // publish. user.email is only spawned when the cheap sources fail — initStore
77
+ // sits on the mem_add hot path (git config ≈ 12ms).
78
+
79
+ const GENERIC_NAMES = new Set([
80
+ "admin",
81
+ "user",
82
+ "owner",
83
+ "root",
84
+ "ubuntu",
85
+ "ec2-user",
86
+ "vagrant",
87
+ "dev",
88
+ "developer",
89
+ "node",
90
+ "unknown",
91
+ ]);
92
+
93
+ const usable = (v: string | null | undefined): string | null => {
94
+ const s = (v ?? "").trim();
95
+ return s && !GENERIC_NAMES.has(s.toLowerCase()) ? s : null;
96
+ };
97
+
98
+ // `env: process.env` is not redundant: Bun.spawnSync snapshots the environment
99
+ // at startup, so a variable set at runtime (GIT_CONFIG_GLOBAL in a test, MEM_*
100
+ // set by a wrapper) never reaches the child without passing it explicitly.
101
+ const gitConfig = (key: string, cwd: string): string | null =>
102
+ Bun.spawnSync(["git", "config", key], { cwd, env: process.env })
103
+ .stdout.toString()
104
+ .trim() || null;
105
+
106
+ function machineSeed(): string {
107
+ try {
108
+ const id = readFileSync("/etc/machine-id", "utf8").trim();
109
+ if (id) return id;
110
+ } catch {
111
+ // no /etc/machine-id (macOS) — fall through to the interface list
112
+ }
113
+ for (const ifaces of Object.values(networkInterfaces()))
114
+ for (const i of ifaces ?? [])
115
+ if (!i.internal && i.mac && i.mac !== "00:00:00:00:00:00") return i.mac;
116
+ return hostname();
117
+ }
118
+
119
+ const machineTag = (): string =>
120
+ `m-${createHash("sha256").update(machineSeed()).digest("hex").slice(0, 8)}`;
121
+
122
+ const slug = (v: string): string =>
123
+ v
124
+ .toLowerCase()
125
+ .replace(/[^a-z0-9._-]+/g, "-")
126
+ .replace(/^-+|-+$/g, "");
127
+
128
+ // --- mutable state (populated by initStore) ---
129
+
130
+ let root = "";
131
+ let dir = "";
132
+ let planDir = "";
133
+ let doneDir = "";
134
+ let agent = "";
135
+ let person = "";
136
+ let LOG = "";
137
+ let memCmd = "";
138
+ let planBase = "";
139
+ let app = "";
140
+ // Non-empty when the resolver found two or more app-scoped mem dirs and no
141
+ // single one at/above cwd — a write must die rather than start a third log.
142
+ let blockWrite = "";
143
+
144
+ // --- init ---
145
+
146
+ /**
147
+ * Initialize the store for a given worktree. Must be called before using any
148
+ * export. The CLI dispatch layer calls this with the resolved worktree path.
149
+ *
150
+ * `overrideMemDir` (from --mem-dir flag) skips resolution entirely.
151
+ * Otherwise whereMemDir() walks up from cwd — the same dir the reader
152
+ * (src/memory.ts) uses, so writer and reader cannot drift apart.
153
+ */
154
+ export function initStore(worktree: string, overrideMemDir?: string): void {
155
+ root = Bun.spawnSync(["git", "rev-parse", "--show-toplevel"], {
156
+ cwd: worktree,
157
+ })
158
+ .stdout.toString()
159
+ .trim();
160
+ if (!root) root = worktree;
161
+
162
+ // An explicit --mem-dir is a promise: never silently fall back to the
163
+ // default when the path is wrong, or the row lands in a log nobody reads.
164
+ if (overrideMemDir && !existsSync(overrideMemDir)) {
165
+ throw new Error(`--mem-dir path does not exist: ${overrideMemDir}`);
166
+ }
167
+
168
+ // Resolution and the CLI's `mem where` share one function, so the path a row
169
+ // is written to is the path `mem where` reports.
170
+ blockWrite = "";
171
+ const resolved = whereMemDir(worktree, overrideMemDir);
172
+ if (resolved.step === "ambiguous") {
173
+ const list = (resolved.candidates ?? []).map((c) => ` ${c}`).join("\n");
174
+ blockWrite =
175
+ `two or more .fapony/.memory dirs under ${root} — refusing to guess:\n` +
176
+ `${list}\ncd into one, set paths.memDir, or pass --mem-dir`;
177
+ }
178
+ dir = resolved.dir ?? join(root, DEFAULT_MEM_DIR);
179
+
180
+ // planBase: the .fapony dir — plan/done/conventions live here.
181
+ // Derive from dir by going up from .fapony/.memory → .fapony
182
+ planBase = dirname(dir);
183
+
184
+ // app name for display — the directory containing .fapony
185
+ app = dirname(planBase);
186
+
187
+ // Read fapony.config.json
188
+ const configDir =
189
+ planBase === `${root}/${FAPONY_DIR}` ? root : dirname(planBase);
190
+ const configPaths = ((): Record<string, string> => {
191
+ try {
192
+ const raw = readFileSync(`${configDir}/${CONFIG_FILENAME}`, "utf8");
193
+ return (JSON.parse(raw)?.paths ?? {}) as Record<string, string>;
194
+ } catch {
195
+ return {};
196
+ }
197
+ })();
198
+ const fromConfig = (key: string): string | null =>
199
+ typeof configPaths[key] === "string"
200
+ ? join(configDir, configPaths[key])
201
+ : null;
202
+
203
+ planDir = `${planBase}/plan`;
204
+
205
+ // done/ sits beside plan/ (same depth, relative links survive)
206
+ doneDir =
207
+ fromConfig("doneDir") ??
208
+ (!existsSync(`${planBase}/done`) && existsSync(`${planDir}/done`)
209
+ ? `${planDir}/done`
210
+ : `${planBase}/done`);
211
+
212
+ let emailCache: string | null | undefined;
213
+ const email = (): string | null =>
214
+ emailCache !== undefined
215
+ ? emailCache
216
+ : (emailCache = gitConfig("user.email", root));
217
+
218
+ agent =
219
+ process.env.MEM_AGENT?.trim() ||
220
+ usable(process.env.USER) ||
221
+ usable(email()) ||
222
+ machineTag();
223
+
224
+ // filename = *person*, not client — naming by MEM_AGENT would collide
225
+ person = slug(
226
+ usable(gitConfig("user.name", root)) ||
227
+ usable(process.env.USER) ||
228
+ usable(email()) ||
229
+ machineTag(),
230
+ );
231
+
232
+ LOG = `${dir}/log.${person}.jsonl`;
233
+ memCmd = `fapony mem`;
234
+ }
235
+
236
+ // --- log file helpers ---
237
+
238
+ const isLogFile = (f: string): boolean =>
239
+ f === "log.jsonl" ||
240
+ (/^log\.[A-Za-z0-9._-]+\.jsonl$/.test(f) &&
241
+ !/^log\.\d{4}-\d{2}-\d{2}\.jsonl$/.test(f));
242
+
243
+ const listLogs = (match: (f: string) => boolean): string[] =>
244
+ existsSync(dir)
245
+ ? readdirSync(dir)
246
+ .filter(match)
247
+ .sort()
248
+ .map((f) => join(dir, f))
249
+ : [];
250
+
251
+ const logFiles = (): string[] => listLogs(isLogFile);
252
+
253
+ const archivedFiles = (): string[] =>
254
+ listLogs((f) => /^log\.\d{4}-\d{2}-\d{2}\.jsonl$/.test(f));
255
+
256
+ // --- core ---
257
+
258
+ const parseLog = (f: string): LogRow[] =>
259
+ readFileSync(f, "utf8")
260
+ .split("\n")
261
+ .filter(Boolean)
262
+ .flatMap((l: string, i: number) => {
263
+ try {
264
+ return [JSON.parse(l) as LogRow];
265
+ } catch {
266
+ console.error(`[mem] skipped ${basename(f)} line ${i + 1} (bad JSON)`);
267
+ return [];
268
+ }
269
+ });
270
+
271
+ const byTs = (a: LogRow, b: LogRow) => a.ts.localeCompare(b.ts);
272
+
273
+ // The live view: what `rotate` counts and what open-work commands read. It must
274
+ // stay archive-free or rotate re-imports the rows it just moved out and never
275
+ // gets under its own threshold.
276
+ const rows = (): LogRow[] => logFiles().flatMap(parseLog).sort(byTs);
277
+
278
+ // The recall view: rotated rows included. A bug closed six months ago is exactly
279
+ // what `find` exists to surface — rotate shrinks the live file, it does not
280
+ // decide what is still worth remembering.
281
+ const allRows = (): LogRow[] =>
282
+ [...logFiles(), ...archivedFiles()].flatMap(parseLog).sort(byTs);
283
+
284
+ function put(r: Omit<WorkRow, "ts" | "agent">): void;
285
+ function put(r: Omit<CloseRow, "ts" | "agent">): void;
286
+ function put(r: Omit<ClaimRow, "ts" | "agent">): void;
287
+ function put(r: Omit<ReleaseRow, "ts" | "agent">): void;
288
+ function put(r: Omit<SyncedRow, "ts" | "agent">): void;
289
+ function put(
290
+ r:
291
+ | Omit<WorkRow, "ts" | "agent">
292
+ | Omit<CloseRow, "ts" | "agent">
293
+ | Omit<ClaimRow, "ts" | "agent">
294
+ | Omit<ReleaseRow, "ts" | "agent">
295
+ | Omit<SyncedRow, "ts" | "agent">,
296
+ ) {
297
+ if (blockWrite) throw new Error(blockWrite);
298
+ mkdirSync(dir, { recursive: true });
299
+ appendFileSync(
300
+ LOG,
301
+ `${JSON.stringify({ ts: new Date().toISOString(), agent, ...r })}\n`,
302
+ );
303
+ }
304
+
305
+ function nextId(all: LogRow[]): string {
306
+ const used = new Set(all.map((r) => ("id" in r ? r.id : "")));
307
+ let base = Date.now();
308
+ let id = base.toString(36);
309
+ while (used.has(id)) {
310
+ id = base.toString(36) + Math.random().toString(36).slice(2, 4);
311
+ base++;
312
+ }
313
+ return id;
314
+ }
315
+
316
+ const appendRaw = (path: string, r: LogRow): void =>
317
+ appendFileSync(path, `${JSON.stringify(r)}\n`);
318
+
319
+ const rel = (p: string) => relative(root, p) || ".";
320
+
321
+ const KINDS: WorkKind[] = ["next", "bug", "decision", "note", "hold"];
322
+
323
+ export type {
324
+ ClaimRow,
325
+ CloseRow,
326
+ LogRow,
327
+ ReleaseRow,
328
+ SyncedRow,
329
+ WorkKind,
330
+ WorkRow,
331
+ };
332
+ export {
333
+ agent,
334
+ allRows,
335
+ app,
336
+ appendRaw,
337
+ dir,
338
+ doneDir,
339
+ KINDS,
340
+ LOG,
341
+ memCmd,
342
+ nextId,
343
+ person,
344
+ planBase,
345
+ planDir,
346
+ put,
347
+ rel,
348
+ root,
349
+ rows,
350
+ };
package/src/memory.ts CHANGED
@@ -3,37 +3,42 @@
3
3
  // ponytail: dedupe close-command logic that was copy-pasted in run.ts + stop.ts
4
4
 
5
5
  import { execSync } from "node:child_process";
6
- import { existsSync, readdirSync, readFileSync } from "node:fs";
7
- import { basename, join } from "node:path";
8
- import {
9
- type Config,
10
- DEFAULT_MEMORY_ENTRY,
11
- memoryEntry,
12
- safetyDeny,
13
- } from "./db/index.js";
6
+ import { existsSync, readdirSync, readFileSync, realpathSync } from "node:fs";
7
+ import { dirname, isAbsolute, join, resolve } from "node:path";
8
+ import { CONFIG_FILENAME, DEFAULT_MEM_DIR, FAPONY_DIR } from "./db/defaults.js";
9
+ import { type Config, loadConfig, safetyDeny } from "./db/index.js";
14
10
  import { assertSafe } from "./safety.js";
15
11
  import { templateArgs } from "./util.js";
16
12
 
17
- /** Default memory commands — matches templates/mem/mem.ts CLI. */
13
+ /** Default memory commands — built into fapony via `fapony mem <sub>`. */
18
14
  export const DEFAULT_MEMORY: Config["memory"] = {
19
- claim: ["bun", DEFAULT_MEMORY_ENTRY, "claim", "{id}"],
20
- close: ["bun", DEFAULT_MEMORY_ENTRY, "close", "{id}", "{msg}"],
21
- add: ["bun", DEFAULT_MEMORY_ENTRY, "add", "{kind}", "{text}"],
22
- kickoff: ["bun", DEFAULT_MEMORY_ENTRY, "kickoff"],
15
+ claim: ["fapony", "mem", "claim", "{id}"],
16
+ close: ["fapony", "mem", "close", "{id}", "{msg}"],
17
+ add: ["fapony", "mem", "add", "{kind}", "{text}"],
18
+ kickoff: ["fapony", "mem", "kickoff"],
23
19
  };
24
20
 
25
21
  /**
26
22
  * Returns the effective memory config:
27
23
  * - explicit config.memory wins if set
28
- * - fallback: config.memory === null + <memoryEntry> exists → DEFAULT_MEMORY
24
+ * - fallback: a mem log dir exists (any `.fapony/.memory/`) → DEFAULT_MEMORY
29
25
  * - otherwise null (no memory)
26
+ *
27
+ * Since PLAN-agent-one-call the code is built into fapony (`fapony mem`), so the
28
+ * old gate on `.fapony/.memory/mem.ts` no longer means anything — that file is
29
+ * not scaffolded and `init-mem` deletes it. Gate on the dir the writer needs.
30
30
  */
31
31
  export function resolveMemoryConfig(
32
32
  config: Config,
33
33
  worktree: string,
34
34
  ): Config["memory"] {
35
35
  if (config.memory) return config.memory;
36
- if (existsSync(join(worktree, memoryEntry(config)))) return DEFAULT_MEMORY;
36
+ // A real log is not required for wiring: `fapony init` scaffolds an empty
37
+ // `.fapony/.memory/` and the writer creates the first log there. Resolution
38
+ // proper (above) still skips empty dirs, so it cannot pick the wrong one.
39
+ if (resolveMemDir(worktree) || walkUpForMemDir(worktree, true)) {
40
+ return DEFAULT_MEMORY;
41
+ }
37
42
  return null;
38
43
  }
39
44
 
@@ -125,36 +130,227 @@ interface RawMemRow {
125
130
  }
126
131
 
127
132
  /**
128
- * The app's own .fapony/ dir for a worktree root — the same monorepo guess
129
- * resolveMemDir makes (templates/mem/store.ts is the mirror). Conventions
130
- * live beside the mem log (SPEC-convention-debt §2.1), so both resolvers must
131
- * guess identically; the guess is shared here so they cannot drift.
133
+ * A directory is a mem dir only when it holds a `log.jsonl` or a named
134
+ * `log.<person>.jsonl` (rotated `log.YYYY-MM-DD.jsonl` archives count too).
135
+ * A `.fapony/.memory/` scaffolded empty by `fapony init` is not a candidate —
136
+ * otherwise it would shadow an ancestor that holds the real log (SPEC §1).
132
137
  */
133
- export function resolveAppFaponyDir(worktree: string): string {
134
- const app = process.env.MEM_APP ?? basename(worktree).replace(/^wt-/, "");
135
- const appBase = ["apps", "packages", "services"]
136
- .map((d) => join(worktree, d, app))
137
- .find((p) => existsSync(p));
138
- return appBase ? join(appBase, ".fapony") : join(worktree, ".fapony");
138
+ function hasMemLogs(dir: string): boolean {
139
+ try {
140
+ return readdirSync(dir).some(
141
+ (f) => f === "log.jsonl" || /^log\.[A-Za-z0-9._-]+\.jsonl$/.test(f),
142
+ );
143
+ } catch {
144
+ return false;
145
+ }
146
+ }
147
+
148
+ /** Physical path (symlinks resolved) so start and repo root compare like with
149
+ * like; falls back to a lexical resolve when the path does not exist yet. */
150
+ function physical(p: string): string {
151
+ try {
152
+ return realpathSync(p);
153
+ } catch {
154
+ return resolve(p);
155
+ }
156
+ }
157
+
158
+ /** `git rev-parse --show-toplevel` from a directory, or null outside a repo. */
159
+ function gitRootOf(fromDir: string): string | null {
160
+ try {
161
+ const root = execSync("git rev-parse --show-toplevel", {
162
+ cwd: fromDir,
163
+ encoding: "utf-8",
164
+ stdio: ["pipe", "pipe", "pipe"],
165
+ }).trim();
166
+ return root || null;
167
+ } catch {
168
+ return null;
169
+ }
139
170
  }
140
171
 
141
172
  /**
142
- * Locate the memory dir for a worktree root, mirroring templates/mem/store.ts:
143
- * in a monorepo the log lives under `<apps|packages|services>/<app>/.fapony/.memory`
144
- * (app guessed from the dir name, `wt-` prefix stripped; MEM_APP overrides), not
145
- * at the git root. Single repos fall back to the root-relative layout.
173
+ * The lexical ancestor of `fromDir` that is the git repo root, or null outside
174
+ * a repo. `git rev-parse` returns a physical path (it resolves /var → /private/
175
+ * var on macOS), so the walk compares `physical(dir)` against it and returns the
176
+ * path in the caller's own lexical form — the returned dir must match what the
177
+ * caller passed in, not a canonicalized stranger.
146
178
  */
147
- export function resolveMemDir(worktree: string): string | null {
148
- const base = resolveAppFaponyDir(worktree);
149
-
150
- const legacyDir = join(base, "..", ".memory");
151
- const newDir = join(base, ".memory");
179
+ function repoRootOf(fromDir: string): string | null {
180
+ const start = resolve(fromDir);
181
+ const gitRoot = gitRootOf(start);
182
+ if (!gitRoot) return null;
183
+ const physicalRoot = physical(gitRoot);
184
+ let dir = start;
185
+ while (true) {
186
+ if (physical(dir) === physicalRoot) return dir;
187
+ const parent = dirname(dir);
188
+ if (parent === dir) return null;
189
+ dir = parent;
190
+ }
191
+ }
152
192
 
153
- if (existsSync(join(legacyDir, "log.jsonl"))) return legacyDir;
154
- if (existsSync(newDir)) return newDir;
193
+ /**
194
+ * Locate the nearest `.fapony/.memory/` by walking up from `fromDir`.
195
+ *
196
+ * The walk stops at the git repo root (SPEC §1) — a mem dir in a parent
197
+ * checkout is never ours. Outside a repo it stops at the filesystem root.
198
+ * `acceptEmpty` is for the default-wiring check, which only needs the dir the
199
+ * writer will use (log or not); the resolver itself requires a real log.
200
+ */
201
+ function walkUpForMemDir(fromDir: string, acceptEmpty: boolean): string | null {
202
+ const start = resolve(fromDir);
203
+ const boundary = repoRootOf(start) ?? "/";
204
+ let dir = start;
205
+ while (true) {
206
+ const candidate = join(dir, DEFAULT_MEM_DIR);
207
+ if (existsSync(candidate) && (acceptEmpty || hasMemLogs(candidate))) {
208
+ return candidate;
209
+ }
210
+ if (dir === boundary) break;
211
+ const parent = dirname(dir);
212
+ if (parent === dir) break;
213
+ dir = parent;
214
+ }
155
215
  return null;
156
216
  }
157
217
 
218
+ export interface MemDirResult {
219
+ dir: string | null;
220
+ step: "flag" | "config" | "walk-up" | "repo-root" | "ambiguous" | "none";
221
+ /** For step "ambiguous" — the sibling `.fapony/.memory/` dirs that hold logs. */
222
+ candidates?: string[];
223
+ }
224
+
225
+ // Dirs that never hold a project mem log and are expensive to walk.
226
+ const SCAN_SKIP = new Set([
227
+ "node_modules",
228
+ ".git",
229
+ "dist",
230
+ "build",
231
+ "coverage",
232
+ "vendor",
233
+ "out",
234
+ "target",
235
+ ".next",
236
+ ".turbo",
237
+ ".cache",
238
+ ]);
239
+
240
+ /**
241
+ * Every `.fapony/.memory/` under `root` that holds a real log, bounded to a
242
+ * shallow walk. Used only to detect the ambiguous monorepo layout (SPEC §1
243
+ * fail example): if two or more app-scoped logs exist and nothing at/above cwd
244
+ * holds one, the caller must refuse rather than start a third log at the root.
245
+ */
246
+ function findMemDirsUnder(root: string): string[] {
247
+ const found: string[] = [];
248
+ const walk = (dir: string, depth: number): void => {
249
+ if (depth > 5) return;
250
+ let entries: import("node:fs").Dirent[];
251
+ try {
252
+ entries = readdirSync(dir, { withFileTypes: true });
253
+ } catch {
254
+ return;
255
+ }
256
+ for (const e of entries) {
257
+ if (!e.isDirectory()) continue;
258
+ if (e.name === FAPONY_DIR) {
259
+ const candidate = join(dir, DEFAULT_MEM_DIR);
260
+ if (hasMemLogs(candidate)) found.push(candidate);
261
+ continue;
262
+ }
263
+ if (e.name.startsWith(".") || SCAN_SKIP.has(e.name)) continue;
264
+ walk(join(dir, e.name), depth + 1);
265
+ }
266
+ };
267
+ walk(root, 0);
268
+ return found;
269
+ }
270
+
271
+ /**
272
+ * The single resolver: returns the mem dir and which step won.
273
+ *
274
+ * Resolution order (SPEC §1):
275
+ * 1. `--mem-dir <path>` (wins over everything)
276
+ * 2. `paths.memDir` in the **repo-root** `fapony.config.json` (relative to root)
277
+ * 3. walk up from cwd for the first `.fapony/.memory/` that holds a real log
278
+ * 4. `<repo root>/.fapony/.memory/`
279
+ *
280
+ * `.memory/` (outside `.fapony/`) and the monorepo app-guess (`wt-<app>`,
281
+ * `MEM_APP`) are both dead — they are not in the order and never return.
282
+ */
283
+ function resolveMemDirFrom(
284
+ fromDir: string,
285
+ explicitOverride?: string,
286
+ ): MemDirResult {
287
+ // Step 1: --mem-dir flag
288
+ if (explicitOverride) {
289
+ return {
290
+ dir: existsSync(explicitOverride) ? resolve(explicitOverride) : null,
291
+ step: "flag",
292
+ };
293
+ }
294
+
295
+ const cwd = resolve(fromDir);
296
+ const root = repoRootOf(cwd);
297
+
298
+ // Step 2: paths.memDir in the repo-root config (FAPONY_CONFIG is not a
299
+ // path source here — spec §1 pins this to fapony.config.json)
300
+ const configDir = root ?? cwd;
301
+ try {
302
+ const configPath = join(configDir, CONFIG_FILENAME);
303
+ if (existsSync(configPath)) {
304
+ const config = loadConfig(configPath);
305
+ if (config?.paths?.memDir) {
306
+ const absCfg = isAbsolute(config.paths.memDir)
307
+ ? config.paths.memDir
308
+ : join(configDir, config.paths.memDir);
309
+ if (existsSync(absCfg)) return { dir: absCfg, step: "config" };
310
+ }
311
+ }
312
+ } catch {
313
+ // no config or unreadable — continue
314
+ }
315
+
316
+ // Step 3: walk up from cwd, only a dir with a real log counts
317
+ const walked = walkUpForMemDir(cwd, false);
318
+ if (walked) return { dir: walked, step: "walk-up" };
319
+
320
+ // Guard (SPEC §1 fail example): nothing at/above cwd holds a log, but the repo
321
+ // has two or more app-scoped ones — refuse instead of silently creating a
322
+ // third log at the root that no app-scoped reader will ever see.
323
+ if (root) {
324
+ const candidates = findMemDirsUnder(root);
325
+ if (candidates.length >= 2) {
326
+ return { dir: null, step: "ambiguous", candidates };
327
+ }
328
+ }
329
+
330
+ // Step 4: <repo root>/.fapony/.memory/ — where a new log is created
331
+ if (root) {
332
+ const rootDir = join(root, DEFAULT_MEM_DIR);
333
+ if (existsSync(rootDir)) return { dir: rootDir, step: "repo-root" };
334
+ }
335
+
336
+ return { dir: null, step: "none" };
337
+ }
338
+
339
+ export function resolveMemDir(
340
+ worktree?: string,
341
+ explicitOverride?: string,
342
+ ): string | null {
343
+ return resolveMemDirFrom(worktree ?? process.cwd(), explicitOverride).dir;
344
+ }
345
+
346
+ /** Resolve and report which step won — for `fapony mem where`. */
347
+ export function whereMemDir(
348
+ fromDir?: string,
349
+ explicitOverride?: string,
350
+ ): MemDirResult {
351
+ return resolveMemDirFrom(fromDir ?? process.cwd(), explicitOverride);
352
+ }
353
+
158
354
  /**
159
355
  * Read every `log*.jsonl` row under the worktree's memory dir, newest first.
160
356
  * `sinceIso` (exclusive) drops older rows; omit it to read the whole log.
@@ -168,11 +364,13 @@ export function readMemLog(
168
364
  const dir = resolveMemDir(worktree);
169
365
  if (!dir) return { rows: [], skipped: 0, filesFound: 0 };
170
366
 
171
- // read every log*.jsonl (excluding rotated files log.YYYY-MM-DD.jsonl)
367
+ // Every log*.jsonl, rotated archives (log.YYYY-MM-DD.jsonl) included. They
368
+ // used to be excluded, which meant the day a repo crossed the rotate
369
+ // threshold mem_find silently forgot everything already closed — the rows
370
+ // most worth recalling. Rotate exists to keep the live file small, not to
371
+ // decide what is still remembered.
172
372
  const isLogFile = (f: string): boolean =>
173
- f === "log.jsonl" ||
174
- (/^log\.[A-Za-z0-9._-]+\.jsonl$/.test(f) &&
175
- !/^log\.\d{4}-\d{2}-\d{2}\.jsonl$/.test(f));
373
+ f === "log.jsonl" || /^log\.[A-Za-z0-9._-]+\.jsonl$/.test(f);
176
374
 
177
375
  let files: string[];
178
376
  try {