@phren/cli 0.1.40 → 0.1.41

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 (105) hide show
  1. package/dist/auth/profiles.js +59 -5
  2. package/dist/cli/actions.js +11 -3
  3. package/dist/cli/config-access.js +8 -1
  4. package/dist/cli/extract.d.ts +27 -1
  5. package/dist/cli/extract.js +243 -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/session-git.d.ts +18 -0
  11. package/dist/cli/session-git.js +47 -0
  12. package/dist/cli/session-start.js +2 -2
  13. package/dist/cli/session-stop.d.ts +11 -0
  14. package/dist/cli/session-stop.js +141 -33
  15. package/dist/cli/session-tool-hook.js +17 -5
  16. package/dist/cli-registry.d.ts +1 -1
  17. package/dist/cli-registry.js +1 -0
  18. package/dist/content/dedup.d.ts +1 -4
  19. package/dist/content/dedup.js +7 -63
  20. package/dist/content/learning.d.ts +20 -2
  21. package/dist/content/learning.js +21 -3
  22. package/dist/content/quality.d.ts +23 -0
  23. package/dist/content/quality.js +123 -0
  24. package/dist/content/secrets.d.ts +52 -0
  25. package/dist/content/secrets.js +193 -0
  26. package/dist/data/access.d.ts +56 -2
  27. package/dist/data/access.js +246 -24
  28. package/dist/entrypoint.js +5 -1
  29. package/dist/finding/impact.js +170 -43
  30. package/dist/finding/lifecycle.d.ts +19 -2
  31. package/dist/finding/lifecycle.js +15 -3
  32. package/dist/git-worktree.d.ts +19 -0
  33. package/dist/git-worktree.js +117 -0
  34. package/dist/governance/policy.d.ts +84 -4
  35. package/dist/governance/policy.js +209 -14
  36. package/dist/governance/rbac.d.ts +8 -0
  37. package/dist/governance/rbac.js +26 -0
  38. package/dist/hooks.d.ts +20 -0
  39. package/dist/hooks.js +113 -3
  40. package/dist/index.js +5 -1
  41. package/dist/init/guard-globals.d.ts +20 -0
  42. package/dist/init/guard-globals.js +72 -6
  43. package/dist/init/init-configure.js +6 -6
  44. package/dist/init/init.js +10 -6
  45. package/dist/init/setup.d.ts +4 -3
  46. package/dist/init/setup.js +120 -16
  47. package/dist/init/store-gitignore.d.ts +29 -0
  48. package/dist/init/store-gitignore.js +48 -0
  49. package/dist/link/doctor.js +86 -20
  50. package/dist/phren-core.d.ts +35 -8
  51. package/dist/phren-core.js +35 -8
  52. package/dist/phren-paths.d.ts +90 -1
  53. package/dist/phren-paths.js +150 -5
  54. package/dist/proactivity.js +1 -1
  55. package/dist/shared/embedding-cache.d.ts +16 -0
  56. package/dist/shared/embedding-cache.js +24 -0
  57. package/dist/shared/fragment-graph.js +10 -0
  58. package/dist/shared/index.d.ts +6 -0
  59. package/dist/shared/index.js +523 -138
  60. package/dist/shared/ollama.d.ts +14 -2
  61. package/dist/shared/ollama.js +84 -5
  62. package/dist/shared/retrieval.d.ts +22 -1
  63. package/dist/shared/retrieval.js +30 -1
  64. package/dist/shared/search-fallback.js +15 -3
  65. package/dist/shared/vector-index.d.ts +20 -1
  66. package/dist/shared/vector-index.js +18 -4
  67. package/dist/shared.d.ts +1 -1
  68. package/dist/shared.js +1 -1
  69. package/dist/status.js +18 -1
  70. package/dist/store-registry.d.ts +22 -0
  71. package/dist/store-registry.js +36 -3
  72. package/dist/task/lifecycle.js +31 -0
  73. package/dist/tools/config.js +16 -7
  74. package/dist/tools/data.js +1 -1
  75. package/dist/tools/extract.js +2 -2
  76. package/dist/tools/finding.js +14 -3
  77. package/dist/tools/graph.js +9 -1
  78. package/dist/tools/memory.js +1 -1
  79. package/dist/tools/notes.js +3 -3
  80. package/dist/tools/ops.js +19 -18
  81. package/dist/tools/search.js +2 -2
  82. package/dist/tools/session.js +2 -2
  83. package/dist/tools/tasks.js +2 -2
  84. package/dist/tools/types.d.ts +32 -2
  85. package/dist/tools/types.js +41 -8
  86. package/dist/ui/scripts.js +2 -2
  87. package/dist/ui/server.js +5 -0
  88. package/package.json +1 -1
  89. package/dist/cli-hooks-git.d.ts +0 -50
  90. package/dist/cli-hooks-git.js +0 -288
  91. package/starter/my-api/.claude/skills/README.md +0 -7
  92. package/starter/my-api/CLAUDE.md +0 -33
  93. package/starter/my-api/FINDINGS.md +0 -9
  94. package/starter/my-api/summary.md +0 -7
  95. package/starter/my-api/tasks.md +0 -7
  96. package/starter/my-first-project/.claude/skills/README.md +0 -7
  97. package/starter/my-first-project/CLAUDE.md +0 -49
  98. package/starter/my-first-project/FINDINGS.md +0 -24
  99. package/starter/my-first-project/summary.md +0 -11
  100. package/starter/my-first-project/tasks.md +0 -25
  101. package/starter/my-frontend/.claude/skills/README.md +0 -7
  102. package/starter/my-frontend/CLAUDE.md +0 -33
  103. package/starter/my-frontend/FINDINGS.md +0 -9
  104. package/starter/my-frontend/summary.md +0 -7
  105. package/starter/my-frontend/tasks.md +0 -7
@@ -7,15 +7,27 @@ import { withFileLock } from "../shared/governance.js";
7
7
  import { isValidProjectName, safeProjectPath } from "../utils.js";
8
8
  import { isArchiveEnd, isArchiveStart, parseCreatedDate as parseCreatedDateMeta, parseStatusField, parseStatus, parseSupersession, parseContradiction, parseFindingId as parseFindingIdMeta, stripLifecycleMetadata, stripRelationMetadata, normalizeFindingText, } from "../content/metadata.js";
9
9
  import { FINDINGS_FILENAME } from "../data/access.js";
10
+ /**
11
+ * Decay rule per finding tag. Keyed with `satisfies Record<FindingTag, ...>`
12
+ * so this object is required to have exactly one row per tag in FINDING_TAGS
13
+ * (phren-core.ts) — no more, no less. Add a tag there and TypeScript forces a
14
+ * decay row here; remove one and the corresponding row becomes a compile
15
+ * error instead of silently-dead data.
16
+ *
17
+ * Previously this table had 9 rows against a 6-entry offered enum that
18
+ * disagreed with it in both directions: `anti-pattern`, `observation`, and
19
+ * `tooling` had rows here but nothing ever wrote those tags, while
20
+ * `tradeoff` and `architecture` were offered/writable but had no row here
21
+ * (so they never decayed and had no max-age). The exported type stays
22
+ * `Record<string, FindingDecayConfig>` so existing string-keyed lookups
23
+ * (e.g. content/citation.ts) don't need to change.
24
+ */
10
25
  export const FINDING_TYPE_DECAY = {
11
26
  'pattern': { maxAgeDays: 365, decayMultiplier: 1.0 }, // Slow decay, long-lived
12
27
  'decision': { maxAgeDays: Infinity, decayMultiplier: 1.0 }, // Never decays
13
28
  '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
29
  'workaround': { maxAgeDays: 60, decayMultiplier: 0.85 }, // Medium decay
17
30
  'bug': { maxAgeDays: 30, decayMultiplier: 0.8 }, // Medium-fast decay
18
- 'tooling': { maxAgeDays: 180, decayMultiplier: 0.95 }, // Medium-slow decay
19
31
  'context': { maxAgeDays: 30, decayMultiplier: 0.75 }, // Fast decay (contextual facts)
20
32
  };
21
33
  export function extractFindingType(line) {
@@ -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 {};
@@ -1,7 +1,7 @@
1
1
  import * as crypto from "crypto";
2
2
  import * as fs from "fs";
3
3
  import * as path from "path";
4
- import { appendAuditLog, debugLog, getProjectDirs, isRecord, runtimeHealthFile, withDefaults, phrenErr, PhrenError, phrenOk, resolveFindingsPath } from "../shared.js";
4
+ import { appendAuditLog, debugLog, getProjectDirs, isRecord, runtimeDir, runtimeHealthFile, withDefaults, phrenErr, PhrenError, phrenOk, resolveFindingsPath } from "../shared.js";
5
5
  import { withFileLock, isFiniteNumber, hasValidSchemaVersion } from "../shared/governance.js";
6
6
  import { errorMessage, isValidProjectName, safeProjectPath } from "../utils.js";
7
7
  import { readProjectConfig } from "../project-config.js";
@@ -10,6 +10,16 @@ import { runCustomHooks } from "../hooks.js";
10
10
  import { METADATA_REGEX, isCitationLine, isArchiveStart as isArchiveStartMeta, isArchiveEnd as isArchiveEndMeta, stripLifecycleMetadata as stripLifecycleMetadataMeta, } from "../content/metadata.js";
11
11
  /** @internal Exported for tests. */
12
12
  export const MAX_QUEUE_ENTRY_LENGTH = 500;
13
+ export const PUSH_STATUSES = [
14
+ "saved-local", "saved-pushed", "no-upstream", "pull-failed", "push-failed", "unrelated-histories", "error",
15
+ ];
16
+ /** Push statuses that mean the store is NOT in sync with its remote. */
17
+ export const FAILED_PUSH_STATUSES = new Set([
18
+ "pull-failed", "push-failed", "unrelated-histories", "error",
19
+ ]);
20
+ export const AUTO_SAVE_STATUSES = [
21
+ "clean", "saved-local", "saved-pushed", "no-upstream", "sync-failed", "error",
22
+ ];
13
23
  export function buildSyncStatus(opts) {
14
24
  return {
15
25
  ...(opts.pullAt !== undefined ? { lastPullAt: opts.pullAt } : {}),
@@ -20,6 +30,48 @@ export function buildSyncStatus(opts) {
20
30
  lastPushStatus: opts.pushStatus,
21
31
  ...(opts.pushDetail !== undefined ? { lastPushDetail: opts.pushDetail } : {}),
22
32
  ...(opts.unsyncedCommits !== undefined ? { unsyncedCommits: opts.unsyncedCommits } : {}),
33
+ ...(opts.consecutiveFailures !== undefined ? { consecutiveFailures: opts.consecutiveFailures } : {}),
34
+ ...(opts.successfulPushAt !== undefined ? { lastSuccessfulPushAt: opts.successfulPushAt } : {}),
35
+ };
36
+ }
37
+ /** Warn after this many consecutive failed syncs. */
38
+ export const SYNC_FAILURE_WARN_RUNS = 3;
39
+ /** ...or after this many days without a successful push, whichever comes first. */
40
+ export const SYNC_FAILURE_WARN_DAYS = 3;
41
+ /**
42
+ * Decide whether a store's sync failures have gone on long enough to warrant a
43
+ * visible warning. Pure so both the Stop hook and `phren status` can ask the
44
+ * same question and get the same answer.
45
+ */
46
+ export function assessSyncOutage(sync, nowMs = Date.now()) {
47
+ const consecutiveFailures = sync?.consecutiveFailures ?? 0;
48
+ const failingNow = sync?.lastPushStatus !== undefined && FAILED_PUSH_STATUSES.has(sync.lastPushStatus);
49
+ let daysSinceSuccess = null;
50
+ const successAt = sync?.lastSuccessfulPushAt;
51
+ if (successAt) {
52
+ const parsed = Date.parse(successAt);
53
+ if (!Number.isNaN(parsed))
54
+ daysSinceSuccess = (nowMs - parsed) / 86_400_000;
55
+ }
56
+ const staleTooLong = failingNow && daysSinceSuccess !== null && daysSinceSuccess >= SYNC_FAILURE_WARN_DAYS;
57
+ const degraded = (failingNow && consecutiveFailures >= SYNC_FAILURE_WARN_RUNS) || staleTooLong;
58
+ if (!degraded)
59
+ return { degraded: false, consecutiveFailures, daysSinceSuccess, summary: "" };
60
+ const parts = [];
61
+ if (consecutiveFailures > 0)
62
+ parts.push(`${consecutiveFailures} consecutive failed sync${consecutiveFailures === 1 ? "" : "s"}`);
63
+ if (daysSinceSuccess !== null)
64
+ parts.push(`last successful push ${Math.floor(daysSinceSuccess)}d ago`);
65
+ if (sync?.unsyncedCommits)
66
+ parts.push(`${sync.unsyncedCommits} unpushed commit(s)`);
67
+ const cause = sync?.lastPushStatus === "unrelated-histories"
68
+ ? "local and remote histories are unrelated — the remote was most likely re-initialized"
69
+ : (sync?.lastPushDetail || sync?.lastPullDetail || "see `phren status` for details");
70
+ return {
71
+ degraded: true,
72
+ consecutiveFailures,
73
+ daysSinceSuccess,
74
+ summary: `phren has not synced (${parts.join(", ")}): ${cause}`,
23
75
  };
24
76
  }
25
77
  export const GOVERNANCE_SCHEMA_VERSION = 1;
@@ -146,7 +198,7 @@ function normalizeRuntimeHealth(data) {
146
198
  normalized.lastPromptAt = data.lastPromptAt;
147
199
  if (typeof data.lastStopAt === "string")
148
200
  normalized.lastStopAt = data.lastStopAt;
149
- if (isRecord(data.lastAutoSave) && typeof data.lastAutoSave.at === "string" && ["clean", "saved-local", "saved-pushed", "no-upstream", "error"].includes(String(data.lastAutoSave.status))) {
201
+ if (isRecord(data.lastAutoSave) && typeof data.lastAutoSave.at === "string" && AUTO_SAVE_STATUSES.includes(String(data.lastAutoSave.status))) {
150
202
  normalized.lastAutoSave = {
151
203
  at: data.lastAutoSave.at,
152
204
  status: data.lastAutoSave.status,
@@ -172,12 +224,16 @@ function normalizeRuntimeHealth(data) {
172
224
  normalized.lastSync.lastSuccessfulPullAt = data.lastSync.lastSuccessfulPullAt;
173
225
  if (typeof data.lastSync.lastPushAt === "string")
174
226
  normalized.lastSync.lastPushAt = data.lastSync.lastPushAt;
175
- if (["saved-local", "saved-pushed", "no-upstream", "error"].includes(String(data.lastSync.lastPushStatus)))
227
+ if (PUSH_STATUSES.includes(String(data.lastSync.lastPushStatus)))
176
228
  normalized.lastSync.lastPushStatus = data.lastSync.lastPushStatus;
177
229
  if (typeof data.lastSync.lastPushDetail === "string")
178
230
  normalized.lastSync.lastPushDetail = data.lastSync.lastPushDetail;
179
231
  if (isFiniteNumber(data.lastSync.unsyncedCommits))
180
232
  normalized.lastSync.unsyncedCommits = data.lastSync.unsyncedCommits;
233
+ if (isFiniteNumber(data.lastSync.consecutiveFailures))
234
+ normalized.lastSync.consecutiveFailures = data.lastSync.consecutiveFailures;
235
+ if (typeof data.lastSync.lastSuccessfulPushAt === "string")
236
+ normalized.lastSync.lastSuccessfulPushAt = data.lastSync.lastSuccessfulPushAt;
181
237
  }
182
238
  return normalized;
183
239
  }
@@ -588,6 +644,25 @@ export function normalizeQueueEntryText(raw, opts = {}) {
588
644
  truncated: true,
589
645
  });
590
646
  }
647
+ /** Matches a string made up entirely of HTML comments (and whitespace). */
648
+ const QUEUE_META_ONLY_RE = /^(?:\s*<!--(?:(?!-->)[\s\S])*?-->)+\s*$/;
649
+ /** Strip every HTML comment from a line. */
650
+ function stripQueueComments(line) {
651
+ return line.replace(/<!--(?:(?!-->)[\s\S])*?-->/g, " ");
652
+ }
653
+ /**
654
+ * Identity key for queue dedup: the entry's visible text with the date prefix,
655
+ * bullet marker, and metadata comments removed. Comment-insensitive so a line
656
+ * that gained provenance metadata still dedups against the same text queued
657
+ * before metadata existed.
658
+ */
659
+ function queueDedupKey(line) {
660
+ return stripQueueComments(line.trim())
661
+ .replace(/^-\s*/, "")
662
+ .replace(/^\[\d{4}-\d{2}-\d{2}\]\s*/, "")
663
+ .replace(/\s+/g, " ")
664
+ .trim();
665
+ }
591
666
  export function appendReviewQueue(phrenPath, project, section, entries) {
592
667
  if (!isValidProjectName(project))
593
668
  return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
@@ -598,13 +673,22 @@ export function appendReviewQueue(phrenPath, project, section, entries) {
598
673
  const today = new Date().toISOString().slice(0, 10);
599
674
  const normalized = [];
600
675
  for (const entry of entries) {
601
- const sanitized = normalizeQueueEntryText(normalizeBulletForQueue(entry), { truncate: true });
676
+ const rawText = typeof entry === "string" ? entry : entry.text;
677
+ const rawMeta = typeof entry === "string" ? "" : (entry.meta ?? "");
678
+ const sanitized = normalizeQueueEntryText(normalizeBulletForQueue(rawText), { truncate: true });
602
679
  if (!sanitized.ok)
603
680
  continue;
604
681
  if (sanitized.data.truncated) {
605
682
  debugLog(`appendReviewQueue: truncated oversized queue entry for ${project}`);
606
683
  }
607
- normalized.push(sanitized.data.text);
684
+ // Metadata must be comments only and single-line — anything else would leak
685
+ // producer-controlled markup into a file humans read and agents may render.
686
+ const meta = rawMeta.replace(/[\r\n]+/g, " ").trim();
687
+ const safeMeta = meta && QUEUE_META_ONLY_RE.test(meta) ? meta : "";
688
+ if (meta && !safeMeta) {
689
+ debugLog(`appendReviewQueue: dropped non-comment queue metadata for ${project}`);
690
+ }
691
+ normalized.push({ text: sanitized.data.text, meta: safeMeta });
608
692
  }
609
693
  if (normalized.length === 0)
610
694
  return phrenOk(0);
@@ -626,14 +710,16 @@ export function appendReviewQueue(phrenPath, project, section, entries) {
626
710
  let insertAt = secIdx + 1;
627
711
  while (insertAt < lines.length && !lines[insertAt].startsWith("## "))
628
712
  insertAt++;
629
- const existing = new Set(lines.map((line) => line.trim()));
630
- // Dedup by entry text only (strip leading date prefix) so the same finding isn't added every day.
631
- const existingTexts = new Set(lines.map((line) => line.trim().replace(/^-\s*\[\d{4}-\d{2}-\d{2}\]\s*/, "").trim()));
713
+ // Dedup by entry text only (date prefix and metadata comments stripped) so the
714
+ // same finding isn't queued again every day.
715
+ const existingKeys = new Set(lines.filter((line) => line.trim().startsWith("- ")).map(queueDedupKey));
632
716
  const toInsert = [];
633
717
  for (const entry of normalized) {
634
- const line = `- [${today}] ${entry}`;
635
- if (!existing.has(line) && !existingTexts.has(entry.trim()))
636
- toInsert.push(line);
718
+ const key = queueDedupKey(entry.text);
719
+ if (!key || existingKeys.has(key))
720
+ continue;
721
+ existingKeys.add(key);
722
+ toInsert.push(`- [${today}] ${entry.text}${entry.meta ? ` ${entry.meta}` : ""}`);
637
723
  }
638
724
  if (!toInsert.length)
639
725
  return phrenOk(0);
@@ -642,6 +728,87 @@ export function appendReviewQueue(phrenPath, project, section, entries) {
642
728
  return phrenOk(toInsert.length);
643
729
  });
644
730
  }
731
+ /**
732
+ * Read the retrieval log once and index the most recent retrieval per document key.
733
+ * Keys match what cli-hooks-output's recordRetrieval writes: `<project>/FINDINGS.md:<type>`.
734
+ */
735
+ function lastRetrievalByDocument(phrenPath) {
736
+ const byKey = new Map();
737
+ const logPath = path.join(runtimeDir(phrenPath), "retrieval-log.jsonl");
738
+ if (!fs.existsSync(logPath))
739
+ return byKey;
740
+ try {
741
+ for (const line of fs.readFileSync(logPath, "utf8").split("\n")) {
742
+ if (!line)
743
+ continue;
744
+ let entry;
745
+ try {
746
+ entry = JSON.parse(line);
747
+ }
748
+ catch {
749
+ continue;
750
+ }
751
+ if (typeof entry.file !== "string" || typeof entry.retrievedAt !== "string")
752
+ continue;
753
+ const ts = Date.parse(entry.retrievedAt);
754
+ if (Number.isNaN(ts))
755
+ continue;
756
+ const key = `${entry.file}:${entry.section}`;
757
+ if (ts > (byKey.get(key) || 0))
758
+ byKey.set(key, ts);
759
+ }
760
+ }
761
+ catch (err) {
762
+ debugLog(`pruneDeadMemories: retrieval log unreadable: ${errorMessage(err)}`);
763
+ }
764
+ return byKey;
765
+ }
766
+ /**
767
+ * Findings past their TTL that haven't been retrieved recently, rendered for the queue.
768
+ * Entries without a `<!-- created: -->` stamp are skipped defensively.
769
+ */
770
+ function collectTtlExpiredEntries(file, project, ttlDays, lastRetrieval) {
771
+ const retrievalGraceDays = Math.floor(ttlDays / 2);
772
+ const now = Date.now();
773
+ const expired = [];
774
+ let content;
775
+ try {
776
+ content = fs.readFileSync(file, "utf8");
777
+ }
778
+ catch (err) {
779
+ debugLog(`pruneDeadMemories: ${file} unreadable for TTL scan: ${errorMessage(err)}`);
780
+ return expired;
781
+ }
782
+ for (const line of content.split("\n")) {
783
+ if (!line.startsWith("- "))
784
+ continue;
785
+ const createdMatch = line.match(/<!--\s*created:\s*(\d{4}-\d{2}-\d{2})\s*-->/);
786
+ if (!createdMatch)
787
+ continue;
788
+ const createdDate = createdMatch[1];
789
+ const createdMs = Date.parse(`${createdDate}T00:00:00Z`);
790
+ if (Number.isNaN(createdMs))
791
+ continue;
792
+ if (Math.floor((now - createdMs) / 86_400_000) <= ttlDays)
793
+ continue;
794
+ // Retrieval is logged at document level, so look up the document key rather than
795
+ // the bullet.
796
+ const retrievedAt = lastRetrieval.get(`${project}/${path.basename(file)}:findings`) || 0;
797
+ const daysSinceRetrieval = retrievedAt ? Math.floor((now - retrievedAt) / 86_400_000) : Infinity;
798
+ if (daysSinceRetrieval <= retrievalGraceDays)
799
+ continue;
800
+ expired.push(`[ttl-expired: ${createdDate}] ${line.slice(2).trim()}`);
801
+ }
802
+ return expired;
803
+ }
804
+ /**
805
+ * Delete entries past the retention window and promote TTL-expired entries into review.md.
806
+ *
807
+ * TTL promotion lives here rather than in the CLI handler so that nightly maintenance
808
+ * (`handleBackgroundMaintenance`, which calls this directly) gets it too — previously it
809
+ * only ran on a manual `phren maintain prune`, leaving `## Stale` empty while `## Review`
810
+ * filled up.
811
+ */
645
812
  export function pruneDeadMemories(phrenPath, project, dryRun) {
646
813
  const policy = getRetentionPolicy(phrenPath);
647
814
  if (project && !isValidProjectName(project))
@@ -712,12 +879,40 @@ export function pruneDeadMemories(phrenPath, project, dryRun) {
712
879
  }
713
880
  });
714
881
  }
882
+ // TTL enforcement: promote entries older than ttlDays that haven't been retrieved recently.
883
+ const lastRetrieval = lastRetrievalByDocument(phrenPath);
884
+ let ttlExpired = 0;
885
+ for (const dir of dirs) {
886
+ const file = resolveFindingsPath(dir);
887
+ if (!file)
888
+ continue;
889
+ const projectName = path.basename(dir);
890
+ const expiredEntries = collectTtlExpiredEntries(file, projectName, policy.ttlDays, lastRetrieval);
891
+ if (!expiredEntries.length)
892
+ continue;
893
+ ttlExpired += expiredEntries.length;
894
+ if (dryRun) {
895
+ for (const entry of expiredEntries) {
896
+ dryRunDetails.push(`[dry-run] [${projectName}] Would move to review queue: ${entry.slice(0, 120)}`);
897
+ }
898
+ continue;
899
+ }
900
+ appendReviewQueue(phrenPath, projectName, "Stale", expiredEntries);
901
+ }
902
+ const ttlLine = ttlExpired > 0
903
+ ? `\n${dryRun ? "Would move" : "Moved"} ${ttlExpired} TTL-expired entr${ttlExpired === 1 ? "y" : "ies"} to review.md`
904
+ : "";
715
905
  if (dryRun) {
716
906
  const summary = `[dry-run] Would prune ${pruned} stale memory entr${pruned === 1 ? "y" : "ies"}.`;
717
- return phrenOk(dryRunDetails.length ? `${summary}\n${dryRunDetails.join("\n")}` : summary);
907
+ const detail = dryRunDetails.length ? `${summary}\n${dryRunDetails.join("\n")}` : summary;
908
+ return phrenOk({ message: `${detail}${ttlLine}`, pruned, ttlExpired });
718
909
  }
719
- appendAuditLog(phrenPath, "prune_memories", `project=${project || "all"} pruned=${pruned}`);
720
- return phrenOk(`Pruned ${pruned} stale memory entr${pruned === 1 ? "y" : "ies"}.`);
910
+ appendAuditLog(phrenPath, "prune_memories", `project=${project || "all"} pruned=${pruned} ttl_expired=${ttlExpired}`);
911
+ return phrenOk({
912
+ message: `Pruned ${pruned} stale memory entr${pruned === 1 ? "y" : "ies"}.${ttlLine}`,
913
+ pruned,
914
+ ttlExpired,
915
+ });
721
916
  }
722
917
  function mergeLifecycleAndIdComments(primary, fallback) {
723
918
  const extract = (line, pattern) => line.match(pattern)?.[0];
@@ -17,6 +17,14 @@
17
17
  * The actor is read from the PHREN_ACTOR env var (falls back to open if unset).
18
18
  */
19
19
  type RbacAction = "add_finding" | "remove_finding" | "edit_finding" | "complete_task" | "add_task" | "remove_task" | "update_task" | "pin_task" | "add_note" | "edit_note" | "remove_note" | "promote_note" | "manage_config";
20
+ /**
21
+ * Appended to every ACL-write denial. The natural way to lock yourself out is
22
+ * to run the very first `phren config access set --admins=someone-else`: that
23
+ * turns open mode off and, because you are not in any list, every later edit
24
+ * is denied. Recovery is a text edit, so say so rather than leaving the user
25
+ * to guess.
26
+ */
27
+ export declare const ACL_LOCKOUT_HINT = "Editing access control requires the `admins` role. To recover, edit `.config/access-control.json` in the store directly.";
20
28
  export declare const ACCESS_ROLE_KEYS: readonly ["admins", "contributors", "readers"];
21
29
  export type AccessRole = (typeof ACCESS_ROLE_KEYS)[number];
22
30
  export type AccessRolePatch = Partial<Record<AccessRole, string[]>>;
@@ -45,6 +45,14 @@ function normalizeStringArray(value) {
45
45
  return [];
46
46
  return value.filter((item) => typeof item === "string" && item.trim().length > 0);
47
47
  }
48
+ /**
49
+ * Appended to every ACL-write denial. The natural way to lock yourself out is
50
+ * to run the very first `phren config access set --admins=someone-else`: that
51
+ * turns open mode off and, because you are not in any list, every later edit
52
+ * is denied. Recovery is a text edit, so say so rather than leaving the user
53
+ * to guess.
54
+ */
55
+ export const ACL_LOCKOUT_HINT = "Editing access control requires the `admins` role. To recover, edit `.config/access-control.json` in the store directly.";
48
56
  export const ACCESS_ROLE_KEYS = ["admins", "contributors", "readers"];
49
57
  /**
50
58
  * Single source of truth for writing access-control role lists. Writes to the
@@ -56,6 +64,24 @@ export const ACCESS_ROLE_KEYS = ["admins", "contributors", "readers"];
56
64
  * the two paths can never diverge.
57
65
  */
58
66
  export function setAccessRoles(phrenPath, patch, project) {
67
+ // The ACL is the one object whose own write has to be gated by itself.
68
+ // Without this, `manage_config` was a role that existed in the table and was
69
+ // never checked anywhere, so any actor the ACL denied `add_finding` could
70
+ // call `set_config { action: "access", admins: ["me"] }` and promote itself
71
+ // to admin — the ACL was a suggestion, not a boundary.
72
+ //
73
+ // This is the choke point for all three write surfaces (MCP set_config, the
74
+ // web UI's POST /api/settings/access, and `phren config access set`); each
75
+ // also checks up front so it can return its own error shape. Belt and
76
+ // braces on purpose: the call-site checks give good errors, this one is what
77
+ // a future fourth caller cannot forget.
78
+ //
79
+ // Bootstrapping still works: with no ACL configured anywhere, checkPermission
80
+ // returns open mode, so the first `setAccessRoles` that creates the ACL is
81
+ // always allowed.
82
+ const denied = permissionDeniedError(phrenPath, "manage_config", project);
83
+ if (denied)
84
+ throw new Error(`${denied} ${ACL_LOCKOUT_HINT}`);
59
85
  const clean = {};
60
86
  for (const key of ACCESS_ROLE_KEYS) {
61
87
  if (patch[key] !== undefined)