@phren/cli 0.1.40 → 0.1.42

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 (119) hide show
  1. package/dist/auth/profiles.js +59 -5
  2. package/dist/cli/actions.js +12 -16
  3. package/dist/cli/config-access.js +8 -1
  4. package/dist/cli/extract.d.ts +27 -1
  5. package/dist/cli/extract.js +244 -9
  6. package/dist/cli/govern.js +6 -87
  7. package/dist/cli/hooks-context.d.ts +1 -1
  8. package/dist/cli/hooks-context.js +1 -1
  9. package/dist/cli/namespaces-review.js +14 -1
  10. package/dist/cli/namespaces-utils.js +1 -1
  11. package/dist/cli/session-git.d.ts +18 -0
  12. package/dist/cli/session-git.js +47 -0
  13. package/dist/cli/session-start.js +2 -2
  14. package/dist/cli/session-stop.d.ts +11 -0
  15. package/dist/cli/session-stop.js +141 -33
  16. package/dist/cli/session-tool-hook.js +17 -5
  17. package/dist/cli-registry.d.ts +1 -1
  18. package/dist/cli-registry.js +1 -0
  19. package/dist/content/archive.js +3 -2
  20. package/dist/content/dedup.d.ts +1 -4
  21. package/dist/content/dedup.js +11 -66
  22. package/dist/content/learning.d.ts +20 -2
  23. package/dist/content/learning.js +26 -7
  24. package/dist/content/quality.d.ts +23 -0
  25. package/dist/content/quality.js +123 -0
  26. package/dist/content/secrets.d.ts +52 -0
  27. package/dist/content/secrets.js +196 -0
  28. package/dist/data/access.d.ts +56 -2
  29. package/dist/data/access.js +255 -32
  30. package/dist/data/tasks.js +46 -6
  31. package/dist/entrypoint.js +5 -1
  32. package/dist/finding/impact.js +170 -43
  33. package/dist/finding/lifecycle.d.ts +19 -2
  34. package/dist/finding/lifecycle.js +18 -5
  35. package/dist/git-worktree.d.ts +19 -0
  36. package/dist/git-worktree.js +117 -0
  37. package/dist/governance/policy.d.ts +84 -4
  38. package/dist/governance/policy.js +213 -17
  39. package/dist/governance/rbac.d.ts +8 -0
  40. package/dist/governance/rbac.js +26 -0
  41. package/dist/hooks.d.ts +20 -0
  42. package/dist/hooks.js +113 -3
  43. package/dist/index.js +5 -1
  44. package/dist/init/guard-globals.d.ts +20 -0
  45. package/dist/init/guard-globals.js +72 -6
  46. package/dist/init/init-configure.js +6 -6
  47. package/dist/init/init.js +10 -6
  48. package/dist/init/setup.d.ts +4 -3
  49. package/dist/init/setup.js +120 -16
  50. package/dist/init/store-gitignore.d.ts +29 -0
  51. package/dist/init/store-gitignore.js +48 -0
  52. package/dist/link/doctor.js +86 -20
  53. package/dist/phren-core.d.ts +35 -8
  54. package/dist/phren-core.js +35 -8
  55. package/dist/phren-paths.d.ts +90 -1
  56. package/dist/phren-paths.js +150 -5
  57. package/dist/proactivity.js +1 -1
  58. package/dist/project-config.js +3 -2
  59. package/dist/project-topics.js +13 -12
  60. package/dist/shared/data-utils.js +13 -3
  61. package/dist/shared/embedding-cache.d.ts +16 -0
  62. package/dist/shared/embedding-cache.js +24 -0
  63. package/dist/shared/fragment-graph.js +10 -0
  64. package/dist/shared/index.d.ts +6 -0
  65. package/dist/shared/index.js +523 -138
  66. package/dist/shared/ollama.d.ts +14 -2
  67. package/dist/shared/ollama.js +84 -5
  68. package/dist/shared/retrieval.d.ts +22 -1
  69. package/dist/shared/retrieval.js +30 -1
  70. package/dist/shared/search-fallback.js +15 -3
  71. package/dist/shared/vector-index.d.ts +20 -1
  72. package/dist/shared/vector-index.js +18 -4
  73. package/dist/shared.d.ts +1 -1
  74. package/dist/shared.js +1 -1
  75. package/dist/status.js +18 -1
  76. package/dist/store-registry.d.ts +22 -0
  77. package/dist/store-registry.js +36 -3
  78. package/dist/store-routing.d.ts +8 -0
  79. package/dist/store-routing.js +23 -1
  80. package/dist/task/lifecycle.js +31 -0
  81. package/dist/tools/config.js +19 -9
  82. package/dist/tools/data.js +1 -1
  83. package/dist/tools/extract-facts.js +3 -2
  84. package/dist/tools/extract.js +2 -2
  85. package/dist/tools/finding.js +20 -8
  86. package/dist/tools/graph.js +9 -1
  87. package/dist/tools/memory.js +1 -1
  88. package/dist/tools/notes.js +3 -3
  89. package/dist/tools/ops.js +19 -18
  90. package/dist/tools/search.js +2 -2
  91. package/dist/tools/session.js +2 -2
  92. package/dist/tools/tasks.js +2 -2
  93. package/dist/tools/types.d.ts +32 -2
  94. package/dist/tools/types.js +41 -8
  95. package/dist/ui/scripts.js +2 -2
  96. package/dist/ui/server.js +7 -6
  97. package/dist/utils-fts.js +3 -2
  98. package/dist/utils-paths.d.ts +1 -0
  99. package/dist/utils-paths.js +1 -1
  100. package/dist/utils.d.ts +1 -1
  101. package/dist/utils.js +1 -1
  102. package/package.json +1 -1
  103. package/dist/cli-hooks-git.d.ts +0 -50
  104. package/dist/cli-hooks-git.js +0 -288
  105. package/starter/my-api/.claude/skills/README.md +0 -7
  106. package/starter/my-api/CLAUDE.md +0 -33
  107. package/starter/my-api/FINDINGS.md +0 -9
  108. package/starter/my-api/summary.md +0 -7
  109. package/starter/my-api/tasks.md +0 -7
  110. package/starter/my-first-project/.claude/skills/README.md +0 -7
  111. package/starter/my-first-project/CLAUDE.md +0 -49
  112. package/starter/my-first-project/FINDINGS.md +0 -24
  113. package/starter/my-first-project/summary.md +0 -11
  114. package/starter/my-first-project/tasks.md +0 -25
  115. package/starter/my-frontend/.claude/skills/README.md +0 -7
  116. package/starter/my-frontend/CLAUDE.md +0 -33
  117. package/starter/my-frontend/FINDINGS.md +0 -9
  118. package/starter/my-frontend/summary.md +0 -7
  119. package/starter/my-frontend/tasks.md +0 -7
@@ -1,13 +1,121 @@
1
1
  import * as crypto from "crypto";
2
2
  import * as fs from "fs";
3
3
  import { impactLogFile } from "../shared.js";
4
- import { rotateJsonlIfLarge } from "../phren-paths.js";
4
+ import { rotateJsonlIfLarge, runtimeFile } from "../phren-paths.js";
5
5
  import { withFileLock } from "../shared/governance.js";
6
6
  import { normalizeFindingText } from "../content/metadata.js";
7
- let highImpactCache = null;
7
+ import { logger } from "../logger.js";
8
+ import { errorMessage } from "../utils.js";
9
+ /**
10
+ * Impact aggregation, and why it is not a plain memoised read.
11
+ *
12
+ * `getHighImpactFindings()` runs inside `applyTrustFilter()` on the prompt hot
13
+ * path, and `logImpact()` appends to the same file later in the *same* prompt.
14
+ * The old mtime+size cache was therefore invalidated by the very writer it was
15
+ * meant to protect: every prompt re-parsed the whole log, line by line, and at
16
+ * the log's steady-state ceiling of 2MB (13,773 lines) that cost ~9ms per
17
+ * prompt. Worse, `hook-prompt` is a fresh `node` process per prompt, so an
18
+ * in-process cache could never hit on the path that actually needed it.
19
+ *
20
+ * So the aggregate is (a) derived once, (b) persisted to a sidecar keyed by the
21
+ * log's exact [mtimeMs, size], and (c) folded forward on append rather than
22
+ * discarded — appending a record only ever increments one counter. A reader in
23
+ * the next process validates the sidecar's marker against the log and falls
24
+ * back to a full derive on any mismatch, so being wrong is impossible; the
25
+ * worst case is the work we used to do every time.
26
+ */
27
+ const IMPACT_SUMMARY_VERSION = 1;
28
+ let summaryCache = null;
8
29
  function nowIso() {
9
30
  return new Date().toISOString();
10
31
  }
32
+ function statMarker(file) {
33
+ try {
34
+ const stat = fs.statSync(file);
35
+ return { mtimeMs: stat.mtimeMs, size: stat.size };
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ }
41
+ function markersMatch(a, b) {
42
+ if (!a || !b)
43
+ return false;
44
+ return a.mtimeMs === b.mtimeMs && a.size === b.size;
45
+ }
46
+ function impactSummaryFile(phrenPath) {
47
+ return runtimeFile(phrenPath, "impact-summary.json");
48
+ }
49
+ function emptySummary() {
50
+ return { surfaceCountByFinding: new Map(), completedByFinding: new Set() };
51
+ }
52
+ function readSidecarSummary(phrenPath, marker) {
53
+ try {
54
+ const parsed = JSON.parse(fs.readFileSync(impactSummaryFile(phrenPath), "utf8"));
55
+ if (parsed?.version !== IMPACT_SUMMARY_VERSION)
56
+ return null;
57
+ if (!parsed.source || !markersMatch(parsed.source, marker))
58
+ return null;
59
+ if (!parsed.counts || typeof parsed.counts !== "object" || !Array.isArray(parsed.completed))
60
+ return null;
61
+ const surfaceCountByFinding = new Map();
62
+ for (const [findingId, count] of Object.entries(parsed.counts)) {
63
+ if (typeof count === "number" && Number.isFinite(count))
64
+ surfaceCountByFinding.set(findingId, count);
65
+ }
66
+ return {
67
+ surfaceCountByFinding,
68
+ completedByFinding: new Set(parsed.completed.filter((id) => typeof id === "string")),
69
+ };
70
+ }
71
+ catch {
72
+ return null;
73
+ }
74
+ }
75
+ function writeSidecarSummary(phrenPath, marker, summary) {
76
+ const target = impactSummaryFile(phrenPath);
77
+ const payload = {
78
+ version: IMPACT_SUMMARY_VERSION,
79
+ source: marker,
80
+ counts: Object.fromEntries(summary.surfaceCountByFinding),
81
+ completed: [...summary.completedByFinding],
82
+ };
83
+ // Atomic replace, no lock: readers validate the marker, so a lost race costs
84
+ // one re-derive and can never surface a torn or mismatched aggregate.
85
+ const tmp = `${target}.tmp-${process.pid}-${crypto.randomUUID()}`;
86
+ try {
87
+ fs.writeFileSync(tmp, JSON.stringify(payload));
88
+ fs.renameSync(tmp, target);
89
+ }
90
+ catch (err) {
91
+ logger.debug("writeSidecarSummary", errorMessage(err));
92
+ try {
93
+ fs.unlinkSync(tmp);
94
+ }
95
+ catch { /* nothing to clean up */ }
96
+ }
97
+ }
98
+ function invalidateImpactSummary(phrenPath) {
99
+ summaryCache = null;
100
+ try {
101
+ fs.unlinkSync(impactSummaryFile(phrenPath));
102
+ }
103
+ catch { /* already absent */ }
104
+ }
105
+ /** The aggregate for the log's current revision, without ever re-parsing it. Null when unavailable. */
106
+ function peekSummary(phrenPath, file, marker) {
107
+ if (summaryCache && summaryCache.file === file && markersMatch(summaryCache.marker, marker)) {
108
+ return summaryCache.summary;
109
+ }
110
+ return readSidecarSummary(phrenPath, marker);
111
+ }
112
+ function foldEntriesIntoSummary(summary, entries) {
113
+ for (const entry of entries) {
114
+ summary.surfaceCountByFinding.set(entry.findingId, (summary.surfaceCountByFinding.get(entry.findingId) ?? 0) + 1);
115
+ if (entry.taskCompleted)
116
+ summary.completedByFinding.add(entry.findingId);
117
+ }
118
+ }
11
119
  export function findingIdFromLine(line) {
12
120
  const fid = line.match(/<!--\s*fid:([a-z0-9]{8})\s*-->/i);
13
121
  if (fid?.[1])
@@ -57,41 +165,56 @@ function parseImpactLine(line) {
57
165
  return null;
58
166
  }
59
167
  }
168
+ /** The expensive path: derive the aggregate by parsing every line of the log. */
60
169
  function readImpactSummary(phrenPath) {
61
170
  const file = impactLogFile(phrenPath);
62
- const surfaceCountByFinding = new Map();
63
- const completedByFinding = new Set();
64
- if (!fs.existsSync(file)) {
65
- return {
66
- surfaceCountByFinding,
67
- completedByFinding,
68
- };
69
- }
171
+ const summary = emptySummary();
172
+ if (!fs.existsSync(file))
173
+ return summary;
70
174
  const content = fs.readFileSync(file, "utf8");
71
175
  for (const line of content.split("\n")) {
72
176
  const entry = parseImpactLine(line);
73
177
  if (!entry)
74
178
  continue;
75
- surfaceCountByFinding.set(entry.findingId, (surfaceCountByFinding.get(entry.findingId) ?? 0) + 1);
179
+ summary.surfaceCountByFinding.set(entry.findingId, (summary.surfaceCountByFinding.get(entry.findingId) ?? 0) + 1);
76
180
  if (entry.taskCompleted) {
77
- completedByFinding.add(entry.findingId);
181
+ summary.completedByFinding.add(entry.findingId);
78
182
  }
79
183
  }
80
- return {
81
- surfaceCountByFinding,
82
- completedByFinding,
83
- };
184
+ return summary;
84
185
  }
85
186
  function appendImpact(phrenPath, entries) {
86
187
  if (entries.length === 0)
87
188
  return;
88
189
  const file = impactLogFile(phrenPath);
89
190
  withFileLock(file, () => {
90
- // getHighImpactFindings re-parses this whole file on the hook hot path, so cap
91
- // it — otherwise it grows unbounded (seen at 2MB) and every prompt re-parses it.
191
+ // Cap the log. Rotation drops the oldest records, which changes the surface
192
+ // counts, so the aggregate cannot be folded across it.
193
+ const sizeBeforeRotate = statMarker(file)?.size ?? 0;
92
194
  rotateJsonlIfLarge(file);
195
+ const preAppendMarker = statMarker(file);
196
+ const rotated = (preAppendMarker?.size ?? 0) !== sizeBeforeRotate;
197
+ // An aggregate that already describes the pre-append log can absorb these
198
+ // records directly — they are exactly the delta, and appending one only
199
+ // ever increments one counter. A file that does not exist yet has an empty
200
+ // aggregate by definition.
201
+ const known = rotated
202
+ ? null
203
+ : preAppendMarker
204
+ ? peekSummary(phrenPath, file, preAppendMarker)
205
+ : emptySummary();
93
206
  const lines = entries.map((entry) => JSON.stringify(entry));
94
207
  fs.appendFileSync(file, lines.join("\n") + "\n");
208
+ const markerAfter = statMarker(file);
209
+ if (!known || !markerAfter) {
210
+ // No aggregate at hand. Drop the sidecar and let the next read rebuild
211
+ // it — deriving it here would put the whole parse on the write path.
212
+ invalidateImpactSummary(phrenPath);
213
+ return;
214
+ }
215
+ foldEntriesIntoSummary(known, entries);
216
+ summaryCache = { file, marker: markerAfter, summary: known };
217
+ writeSidecarSummary(phrenPath, markerAfter, known);
95
218
  });
96
219
  }
97
220
  export function logImpact(phrenPath, entries) {
@@ -108,37 +231,26 @@ export function logImpact(phrenPath, entries) {
108
231
  }
109
232
  export function getHighImpactFindings(phrenPath, minSurfaceCount = 3) {
110
233
  const file = impactLogFile(phrenPath);
111
- let stat = null;
112
- try {
113
- stat = fs.existsSync(file) ? fs.statSync(file) : null;
114
- }
115
- catch {
116
- stat = null;
117
- }
118
- if (!stat)
234
+ const marker = statMarker(file);
235
+ if (!marker)
119
236
  return new Set();
120
- if (highImpactCache
121
- && highImpactCache.file === file
122
- && highImpactCache.mtimeMs === stat.mtimeMs
123
- && highImpactCache.size === stat.size
124
- && highImpactCache.minSurfaceCount === minSurfaceCount) {
125
- return new Set(highImpactCache.ids);
237
+ let summary = peekSummary(phrenPath, file, marker);
238
+ if (!summary) {
239
+ summary = readImpactSummary(phrenPath);
240
+ // Persist it so the *next* prompt's process — hook-prompt is a new process
241
+ // every prompt — starts from the aggregate instead of the log.
242
+ writeSidecarSummary(phrenPath, marker, summary);
126
243
  }
127
- const summary = readImpactSummary(phrenPath);
244
+ summaryCache = { file, marker, summary };
245
+ // Derived per call: the threshold is a caller's choice, not a property of the
246
+ // aggregate, so it does not belong in the cache key.
128
247
  const ids = new Set();
129
248
  for (const [findingId, surfaceCount] of summary.surfaceCountByFinding.entries()) {
130
249
  if (surfaceCount >= minSurfaceCount && summary.completedByFinding.has(findingId)) {
131
250
  ids.add(findingId);
132
251
  }
133
252
  }
134
- highImpactCache = {
135
- file,
136
- mtimeMs: stat.mtimeMs,
137
- size: stat.size,
138
- minSurfaceCount,
139
- ids,
140
- };
141
- return new Set(ids);
253
+ return ids;
142
254
  }
143
255
  export function markImpactEntriesCompletedForSession(phrenPath, sessionId, project) {
144
256
  if (!sessionId)
@@ -149,8 +261,11 @@ export function markImpactEntriesCompletedForSession(phrenPath, sessionId, proje
149
261
  const updated = withFileLock(file, () => {
150
262
  if (!fs.existsSync(file))
151
263
  return 0;
264
+ const preMarker = statMarker(file);
265
+ const known = preMarker ? peekSummary(phrenPath, file, preMarker) : null;
152
266
  const lines = fs.readFileSync(file, "utf8").split("\n");
153
267
  let updatedCount = 0;
268
+ const flipped = new Set();
154
269
  const rewritten = lines
155
270
  .filter((line) => line.trim().length > 0)
156
271
  .map((line) => {
@@ -164,14 +279,26 @@ export function markImpactEntriesCompletedForSession(phrenPath, sessionId, proje
164
279
  if (project && entry.project !== project)
165
280
  return line;
166
281
  updatedCount += 1;
282
+ flipped.add(entry.findingId);
167
283
  return JSON.stringify({ ...entry, taskCompleted: true });
168
284
  });
169
285
  if (updatedCount > 0) {
170
286
  fs.writeFileSync(file, rewritten.join("\n") + "\n");
287
+ // This rewrite flips taskCompleted on existing records; it never adds or
288
+ // removes any, so the surface counts are untouched and the aggregate only
289
+ // gains completed ids.
290
+ const postMarker = statMarker(file);
291
+ if (known && postMarker) {
292
+ for (const findingId of flipped)
293
+ known.completedByFinding.add(findingId);
294
+ summaryCache = { file, marker: postMarker, summary: known };
295
+ writeSidecarSummary(phrenPath, postMarker, known);
296
+ }
297
+ else {
298
+ invalidateImpactSummary(phrenPath);
299
+ }
171
300
  }
172
301
  return updatedCount;
173
302
  });
174
- if (updated > 0)
175
- highImpactCache = null;
176
303
  return updated;
177
304
  }
@@ -1,8 +1,24 @@
1
1
  import { type PhrenResult } from "../phren-core.js";
2
- export declare const FINDING_TYPE_DECAY: Record<string, {
2
+ interface FindingDecayConfig {
3
3
  maxAgeDays: number;
4
4
  decayMultiplier: number;
5
- }>;
5
+ }
6
+ /**
7
+ * Decay rule per finding tag. Keyed with `satisfies Record<FindingTag, ...>`
8
+ * so this object is required to have exactly one row per tag in FINDING_TAGS
9
+ * (phren-core.ts) — no more, no less. Add a tag there and TypeScript forces a
10
+ * decay row here; remove one and the corresponding row becomes a compile
11
+ * error instead of silently-dead data.
12
+ *
13
+ * Previously this table had 9 rows against a 6-entry offered enum that
14
+ * disagreed with it in both directions: `anti-pattern`, `observation`, and
15
+ * `tooling` had rows here but nothing ever wrote those tags, while
16
+ * `tradeoff` and `architecture` were offered/writable but had no row here
17
+ * (so they never decayed and had no max-age). The exported type stays
18
+ * `Record<string, FindingDecayConfig>` so existing string-keyed lookups
19
+ * (e.g. content/citation.ts) don't need to change.
20
+ */
21
+ export declare const FINDING_TYPE_DECAY: Record<string, FindingDecayConfig>;
6
22
  export declare function extractFindingType(line: string): string | null;
7
23
  export declare const FINDING_LIFECYCLE_STATUSES: readonly ["active", "superseded", "contradicted", "stale", "invalid_citation", "retracted"];
8
24
  export type FindingLifecycleStatus = typeof FINDING_LIFECYCLE_STATUSES[number];
@@ -38,3 +54,4 @@ export declare function resolveFindingContradiction(phrenPath: string, project:
38
54
  status: FindingLifecycleStatus;
39
55
  };
40
56
  }>;
57
+ export {};
@@ -4,18 +4,31 @@ import { PhrenError, phrenErr, phrenOk } from "../phren-core.js";
4
4
  // Phren lifecycle comment prefix. No backward compat.
5
5
  const LIFECYCLE_PREFIX = "phren";
6
6
  import { withFileLock } from "../shared/governance.js";
7
- import { isValidProjectName, safeProjectPath } from "../utils.js";
7
+ import { isValidProjectName } from "../utils.js";
8
+ import { storeAwareProjectPath } from "../store-routing.js";
8
9
  import { isArchiveEnd, isArchiveStart, parseCreatedDate as parseCreatedDateMeta, parseStatusField, parseStatus, parseSupersession, parseContradiction, parseFindingId as parseFindingIdMeta, stripLifecycleMetadata, stripRelationMetadata, normalizeFindingText, } from "../content/metadata.js";
9
10
  import { FINDINGS_FILENAME } from "../data/access.js";
11
+ /**
12
+ * Decay rule per finding tag. Keyed with `satisfies Record<FindingTag, ...>`
13
+ * so this object is required to have exactly one row per tag in FINDING_TAGS
14
+ * (phren-core.ts) — no more, no less. Add a tag there and TypeScript forces a
15
+ * decay row here; remove one and the corresponding row becomes a compile
16
+ * error instead of silently-dead data.
17
+ *
18
+ * Previously this table had 9 rows against a 6-entry offered enum that
19
+ * disagreed with it in both directions: `anti-pattern`, `observation`, and
20
+ * `tooling` had rows here but nothing ever wrote those tags, while
21
+ * `tradeoff` and `architecture` were offered/writable but had no row here
22
+ * (so they never decayed and had no max-age). The exported type stays
23
+ * `Record<string, FindingDecayConfig>` so existing string-keyed lookups
24
+ * (e.g. content/citation.ts) don't need to change.
25
+ */
10
26
  export const FINDING_TYPE_DECAY = {
11
27
  'pattern': { maxAgeDays: 365, decayMultiplier: 1.0 }, // Slow decay, long-lived
12
28
  'decision': { maxAgeDays: Infinity, decayMultiplier: 1.0 }, // Never decays
13
29
  'pitfall': { maxAgeDays: 365, decayMultiplier: 1.0 }, // Slow decay
14
- 'anti-pattern': { maxAgeDays: Infinity, decayMultiplier: 1.0 }, // Never decays
15
- 'observation': { maxAgeDays: 14, decayMultiplier: 0.7 }, // Fast decay, short-lived
16
30
  'workaround': { maxAgeDays: 60, decayMultiplier: 0.85 }, // Medium decay
17
31
  'bug': { maxAgeDays: 30, decayMultiplier: 0.8 }, // Medium-fast decay
18
- 'tooling': { maxAgeDays: 180, decayMultiplier: 0.95 }, // Medium-slow decay
19
32
  'context': { maxAgeDays: 30, decayMultiplier: 0.75 }, // Fast decay (contextual facts)
20
33
  };
21
34
  export function extractFindingType(line) {
@@ -194,7 +207,7 @@ function matchFinding(lines, match) {
194
207
  function findingsPathForProject(phrenPath, project) {
195
208
  if (!isValidProjectName(project))
196
209
  return phrenErr(`Invalid project name: "${project}"`, PhrenError.INVALID_PROJECT_NAME);
197
- const projectDir = safeProjectPath(phrenPath, project);
210
+ const projectDir = storeAwareProjectPath(phrenPath, project);
198
211
  if (!projectDir)
199
212
  return phrenErr(`Invalid project name: "${project}"`, PhrenError.INVALID_PROJECT_NAME);
200
213
  if (!fs.existsSync(projectDir))
@@ -0,0 +1,19 @@
1
+ export interface WorktreeAttribution {
2
+ /** Root of the repository this worktree belongs to. */
3
+ repoRoot: string;
4
+ /** Why we concluded `dir` is a worktree — useful in debug output. */
5
+ reason: "agent-worktree-dir" | "linked-worktree";
6
+ }
7
+ /**
8
+ * If `dir` is (or lives inside) a git worktree, return the repository it belongs
9
+ * to. Returns `null` for ordinary directories, for the main working tree, and
10
+ * for git submodules — a submodule is a separate repository and *should* get its
11
+ * own project.
12
+ */
13
+ export declare function resolveWorktreeParent(dir: string): WorktreeAttribution | null;
14
+ /**
15
+ * Normalize a path for project attribution: worktrees resolve to the repository
16
+ * they came from, everything else is returned unchanged. Safe to call on any
17
+ * path — it never throws.
18
+ */
19
+ export declare function resolveRepoRootForPath(dir: string): string;
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Git worktree detection.
3
+ *
4
+ * Agent tooling (Claude Code and friends) creates throwaway worktrees under
5
+ * `<repo>/.claude/worktrees/<codename>`. Each one looks like a standalone repo
6
+ * to a naive check — it has a `.git` entry and a directory name — so phren used
7
+ * to register them as brand-new top-level projects with auto-generated
8
+ * codenames, splitting a repo's memory across directories that look like junk.
9
+ *
10
+ * These helpers map such a directory back to the repository it belongs to.
11
+ * Deliberately dependency-free (fs + path only) so every layer — project
12
+ * locator, init/setup, and the session hooks' project detection — can import it
13
+ * without creating a cycle.
14
+ */
15
+ import * as fs from "fs";
16
+ import * as path from "path";
17
+ /**
18
+ * Directory names that hold agent-managed worktrees. A `worktrees` directory
19
+ * only counts when it sits inside a dot-directory (`.claude/worktrees`,
20
+ * `.git/worktrees`, `.agent/worktrees`), so an ordinary project that happens to
21
+ * contain a `worktrees/` folder is left alone.
22
+ */
23
+ const WORKTREE_CONTAINER_NAMES = new Set(["worktrees", ".worktrees"]);
24
+ /** Marker inside a linked worktree's gitdir path: `<repo>/.git/worktrees/<name>`. */
25
+ const LINKED_WORKTREE_SEGMENT = `${path.sep}.git${path.sep}worktrees${path.sep}`;
26
+ /**
27
+ * If `dir` is (or lives inside) a git worktree, return the repository it belongs
28
+ * to. Returns `null` for ordinary directories, for the main working tree, and
29
+ * for git submodules — a submodule is a separate repository and *should* get its
30
+ * own project.
31
+ */
32
+ export function resolveWorktreeParent(dir) {
33
+ const resolved = path.resolve(dir);
34
+ const agentParent = parentFromAgentWorktreePath(resolved);
35
+ if (agentParent)
36
+ return { repoRoot: agentParent, reason: "agent-worktree-dir" };
37
+ const linkedParent = parentFromLinkedWorktree(resolved);
38
+ if (linkedParent)
39
+ return { repoRoot: linkedParent, reason: "linked-worktree" };
40
+ return null;
41
+ }
42
+ /**
43
+ * Normalize a path for project attribution: worktrees resolve to the repository
44
+ * they came from, everything else is returned unchanged. Safe to call on any
45
+ * path — it never throws.
46
+ */
47
+ export function resolveRepoRootForPath(dir) {
48
+ try {
49
+ return resolveWorktreeParent(dir)?.repoRoot ?? path.resolve(dir);
50
+ }
51
+ catch {
52
+ return path.resolve(dir);
53
+ }
54
+ }
55
+ // ── Internal helpers ─────────────────────────────────────────────────────────
56
+ /**
57
+ * Path-shape detection: `<repo>/.claude/worktrees/<name>` and friends. Handles
58
+ * the case where the worktree has already been deleted or was never a real git
59
+ * worktree, which the gitdir probe below cannot.
60
+ */
61
+ function parentFromAgentWorktreePath(resolved) {
62
+ const segments = resolved.split(path.sep);
63
+ // Scan shallowest-first so a worktree nested inside another worktree still
64
+ // attributes to the outermost real repository in a single pass.
65
+ for (let i = 1; i < segments.length; i++) {
66
+ if (!WORKTREE_CONTAINER_NAMES.has(segments[i]))
67
+ continue;
68
+ // Only trust `worktrees` when it is tucked inside a tool's dot-directory.
69
+ let j = i - 1;
70
+ if (!segments[j]?.startsWith("."))
71
+ continue;
72
+ while (j >= 1 && segments[j].startsWith("."))
73
+ j--;
74
+ if (j < 1)
75
+ continue;
76
+ return segments.slice(0, j + 1).join(path.sep) || path.sep;
77
+ }
78
+ return null;
79
+ }
80
+ /**
81
+ * Git plumbing detection, without shelling out: in a linked worktree `.git` is a
82
+ * *file* containing `gitdir: <repo>/.git/worktrees/<name>`. In the main working
83
+ * tree `.git` is a directory, and in a submodule the gitdir points at
84
+ * `.git/modules/...` instead — neither is treated as a worktree.
85
+ */
86
+ function parentFromLinkedWorktree(resolved) {
87
+ let current = resolved;
88
+ while (true) {
89
+ const parent = repoRootFromGitFile(path.join(current, ".git"));
90
+ if (parent)
91
+ return parent;
92
+ const next = path.dirname(current);
93
+ if (next === current)
94
+ return null;
95
+ current = next;
96
+ }
97
+ }
98
+ function repoRootFromGitFile(gitPath) {
99
+ let raw;
100
+ try {
101
+ if (!fs.statSync(gitPath).isFile())
102
+ return null;
103
+ raw = fs.readFileSync(gitPath, "utf8");
104
+ }
105
+ catch {
106
+ return null;
107
+ }
108
+ const match = raw.match(/^\s*gitdir:\s*(.+?)\s*$/m);
109
+ if (!match)
110
+ return null;
111
+ // Relative gitdir pointers are resolved against the directory holding `.git`.
112
+ const gitDir = path.resolve(path.dirname(gitPath), match[1].replace(/[/\\]/g, path.sep));
113
+ const idx = gitDir.indexOf(LINKED_WORKTREE_SEGMENT);
114
+ if (idx === -1)
115
+ return null; // submodule or something else — not a worktree
116
+ return gitDir.slice(0, idx);
117
+ }
@@ -28,6 +28,25 @@ export interface IndexPolicy {
28
28
  excludeGlobs: string[];
29
29
  includeHidden: boolean;
30
30
  }
31
+ /**
32
+ * Outcome of the push leg of a sync.
33
+ *
34
+ * `saved-local` means "committed, nothing to push or no remote" — a success.
35
+ * It used to double as the report for a *failed* push, which is how a store
36
+ * could go two months without syncing while every Stop hook looked healthy.
37
+ * Failures now get their own values:
38
+ *
39
+ * - `pull-failed` — the pull/rebase leg failed, so push never ran
40
+ * - `push-failed` — push was attempted and rejected
41
+ * - `unrelated-histories` — local and remote share no merge base; no amount of
42
+ * retrying will fix it, so it is called out by name
43
+ */
44
+ export type PushStatus = "saved-local" | "saved-pushed" | "no-upstream" | "pull-failed" | "push-failed" | "unrelated-histories" | "error";
45
+ export declare const PUSH_STATUSES: readonly PushStatus[];
46
+ /** Push statuses that mean the store is NOT in sync with its remote. */
47
+ export declare const FAILED_PUSH_STATUSES: ReadonlySet<PushStatus>;
48
+ export type AutoSaveStatus = "clean" | "saved-local" | "saved-pushed" | "no-upstream" | "sync-failed" | "error";
49
+ export declare const AUTO_SAVE_STATUSES: readonly AutoSaveStatus[];
31
50
  export interface RuntimeHealth {
32
51
  schemaVersion?: number;
33
52
  lastSessionStartAt?: string;
@@ -35,7 +54,7 @@ export interface RuntimeHealth {
35
54
  lastStopAt?: string;
36
55
  lastAutoSave?: {
37
56
  at: string;
38
- status: "clean" | "saved-local" | "saved-pushed" | "no-upstream" | "error";
57
+ status: AutoSaveStatus;
39
58
  detail?: string;
40
59
  };
41
60
  lastGovernance?: {
@@ -49,9 +68,17 @@ export interface RuntimeHealth {
49
68
  lastPullDetail?: string;
50
69
  lastSuccessfulPullAt?: string;
51
70
  lastPushAt?: string;
52
- lastPushStatus?: "saved-local" | "saved-pushed" | "no-upstream" | "error";
71
+ lastPushStatus?: PushStatus;
53
72
  lastPushDetail?: string;
54
73
  unsyncedCommits?: number;
74
+ /**
75
+ * Consecutive sync attempts that failed to reach the remote. Reset to 0 on
76
+ * any successful push. This is what turns "one flaky push" into "this store
77
+ * has been broken for weeks" without needing to keep a history.
78
+ */
79
+ consecutiveFailures?: number;
80
+ /** Last time a push actually reached the remote. */
81
+ lastSuccessfulPushAt?: string;
55
82
  };
56
83
  }
57
84
  export type SyncStatus = NonNullable<RuntimeHealth["lastSync"]>;
@@ -64,8 +91,28 @@ export interface BuildSyncStatusOpts {
64
91
  pullDetail?: string;
65
92
  successfulPullAt?: string;
66
93
  unsyncedCommits?: number;
94
+ consecutiveFailures?: number;
95
+ successfulPushAt?: string;
67
96
  }
68
97
  export declare function buildSyncStatus(opts: BuildSyncStatusOpts): SyncStatus;
98
+ /** Warn after this many consecutive failed syncs. */
99
+ export declare const SYNC_FAILURE_WARN_RUNS = 3;
100
+ /** ...or after this many days without a successful push, whichever comes first. */
101
+ export declare const SYNC_FAILURE_WARN_DAYS = 3;
102
+ export interface SyncOutageAssessment {
103
+ /** True when the store has been failing long enough to tell the user. */
104
+ degraded: boolean;
105
+ consecutiveFailures: number;
106
+ daysSinceSuccess: number | null;
107
+ /** One-line, user-facing explanation. Empty when not degraded. */
108
+ summary: string;
109
+ }
110
+ /**
111
+ * Decide whether a store's sync failures have gone on long enough to warrant a
112
+ * visible warning. Pure so both the Stop hook and `phren status` can ask the
113
+ * same question and get the same answer.
114
+ */
115
+ export declare function assessSyncOutage(sync: SyncStatus | undefined, nowMs?: number): SyncOutageAssessment;
69
116
  export type RetentionPolicyPatch = Partial<Omit<RetentionPolicy, "decay">> & {
70
117
  decay?: Partial<RetentionPolicy["decay"]>;
71
118
  };
@@ -111,7 +158,40 @@ export declare function normalizeQueueEntryText(raw: string, opts?: {
111
158
  text: string;
112
159
  truncated: boolean;
113
160
  }>;
114
- export declare function appendReviewQueue(phrenPath: string, project: string, section: "Review" | "Stale" | "Conflicts", entries: string[]): PhrenResult<number>;
115
- export declare function pruneDeadMemories(phrenPath: string, project?: string, dryRun?: boolean): PhrenResult<string>;
161
+ /**
162
+ * A queue entry that carries structured provenance alongside its text.
163
+ *
164
+ * `meta` is a pre-rendered run of HTML comments (e.g. `<!-- source:extract -->
165
+ * <!-- phren:cite {...} -->`) appended verbatim to the queue line. It exists so a
166
+ * queued candidate stays *promotable*: `approveQueueItem` reads it back and hands
167
+ * the same repo/commit/source provenance to the normal add-finding path, which
168
+ * makes a promoted finding indistinguishable from one added directly.
169
+ *
170
+ * Producers build the comments themselves (this module deliberately does not import
171
+ * the citation helpers, to keep governance free of a content-layer import cycle).
172
+ */
173
+ export interface ReviewQueueEntry {
174
+ text: string;
175
+ meta?: string;
176
+ }
177
+ export type ReviewQueueEntryInput = string | ReviewQueueEntry;
178
+ export declare function appendReviewQueue(phrenPath: string, project: string, section: "Review" | "Stale" | "Conflicts", entries: ReviewQueueEntryInput[]): PhrenResult<number>;
179
+ export interface PruneMemoriesResult {
180
+ /** Human-readable summary (plus dry-run detail lines), ready to print. */
181
+ message: string;
182
+ /** Entries deleted for exceeding the retention window. */
183
+ pruned: number;
184
+ /** TTL-expired entries promoted into review.md's `## Stale` section. */
185
+ ttlExpired: number;
186
+ }
187
+ /**
188
+ * Delete entries past the retention window and promote TTL-expired entries into review.md.
189
+ *
190
+ * TTL promotion lives here rather than in the CLI handler so that nightly maintenance
191
+ * (`handleBackgroundMaintenance`, which calls this directly) gets it too — previously it
192
+ * only ran on a manual `phren maintain prune`, leaving `## Stale` empty while `## Review`
193
+ * filled up.
194
+ */
195
+ export declare function pruneDeadMemories(phrenPath: string, project?: string, dryRun?: boolean): PhrenResult<PruneMemoriesResult>;
116
196
  export declare function consolidateProjectFindings(phrenPath: string, project: string, dryRun?: boolean): PhrenResult<string>;
117
197
  export {};