@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,15 +1,26 @@
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
- import { errorMessage, isValidProjectName, safeProjectPath } from "../utils.js";
6
+ import { errorMessage, isValidProjectName } from "../utils.js";
7
+ import { storeAwareProjectPath } from "../store-routing.js";
7
8
  import { readProjectConfig } from "../project-config.js";
8
9
  import { getActiveProfileDefaults } from "../profile-store.js";
9
10
  import { runCustomHooks } from "../hooks.js";
10
11
  import { METADATA_REGEX, isCitationLine, isArchiveStart as isArchiveStartMeta, isArchiveEnd as isArchiveEndMeta, stripLifecycleMetadata as stripLifecycleMetadataMeta, } from "../content/metadata.js";
11
12
  /** @internal Exported for tests. */
12
13
  export const MAX_QUEUE_ENTRY_LENGTH = 500;
14
+ export const PUSH_STATUSES = [
15
+ "saved-local", "saved-pushed", "no-upstream", "pull-failed", "push-failed", "unrelated-histories", "error",
16
+ ];
17
+ /** Push statuses that mean the store is NOT in sync with its remote. */
18
+ export const FAILED_PUSH_STATUSES = new Set([
19
+ "pull-failed", "push-failed", "unrelated-histories", "error",
20
+ ]);
21
+ export const AUTO_SAVE_STATUSES = [
22
+ "clean", "saved-local", "saved-pushed", "no-upstream", "sync-failed", "error",
23
+ ];
13
24
  export function buildSyncStatus(opts) {
14
25
  return {
15
26
  ...(opts.pullAt !== undefined ? { lastPullAt: opts.pullAt } : {}),
@@ -20,6 +31,48 @@ export function buildSyncStatus(opts) {
20
31
  lastPushStatus: opts.pushStatus,
21
32
  ...(opts.pushDetail !== undefined ? { lastPushDetail: opts.pushDetail } : {}),
22
33
  ...(opts.unsyncedCommits !== undefined ? { unsyncedCommits: opts.unsyncedCommits } : {}),
34
+ ...(opts.consecutiveFailures !== undefined ? { consecutiveFailures: opts.consecutiveFailures } : {}),
35
+ ...(opts.successfulPushAt !== undefined ? { lastSuccessfulPushAt: opts.successfulPushAt } : {}),
36
+ };
37
+ }
38
+ /** Warn after this many consecutive failed syncs. */
39
+ export const SYNC_FAILURE_WARN_RUNS = 3;
40
+ /** ...or after this many days without a successful push, whichever comes first. */
41
+ export const SYNC_FAILURE_WARN_DAYS = 3;
42
+ /**
43
+ * Decide whether a store's sync failures have gone on long enough to warrant a
44
+ * visible warning. Pure so both the Stop hook and `phren status` can ask the
45
+ * same question and get the same answer.
46
+ */
47
+ export function assessSyncOutage(sync, nowMs = Date.now()) {
48
+ const consecutiveFailures = sync?.consecutiveFailures ?? 0;
49
+ const failingNow = sync?.lastPushStatus !== undefined && FAILED_PUSH_STATUSES.has(sync.lastPushStatus);
50
+ let daysSinceSuccess = null;
51
+ const successAt = sync?.lastSuccessfulPushAt;
52
+ if (successAt) {
53
+ const parsed = Date.parse(successAt);
54
+ if (!Number.isNaN(parsed))
55
+ daysSinceSuccess = (nowMs - parsed) / 86_400_000;
56
+ }
57
+ const staleTooLong = failingNow && daysSinceSuccess !== null && daysSinceSuccess >= SYNC_FAILURE_WARN_DAYS;
58
+ const degraded = (failingNow && consecutiveFailures >= SYNC_FAILURE_WARN_RUNS) || staleTooLong;
59
+ if (!degraded)
60
+ return { degraded: false, consecutiveFailures, daysSinceSuccess, summary: "" };
61
+ const parts = [];
62
+ if (consecutiveFailures > 0)
63
+ parts.push(`${consecutiveFailures} consecutive failed sync${consecutiveFailures === 1 ? "" : "s"}`);
64
+ if (daysSinceSuccess !== null)
65
+ parts.push(`last successful push ${Math.floor(daysSinceSuccess)}d ago`);
66
+ if (sync?.unsyncedCommits)
67
+ parts.push(`${sync.unsyncedCommits} unpushed commit(s)`);
68
+ const cause = sync?.lastPushStatus === "unrelated-histories"
69
+ ? "local and remote histories are unrelated — the remote was most likely re-initialized"
70
+ : (sync?.lastPushDetail || sync?.lastPullDetail || "see `phren status` for details");
71
+ return {
72
+ degraded: true,
73
+ consecutiveFailures,
74
+ daysSinceSuccess,
75
+ summary: `phren has not synced (${parts.join(", ")}): ${cause}`,
23
76
  };
24
77
  }
25
78
  export const GOVERNANCE_SCHEMA_VERSION = 1;
@@ -146,7 +199,7 @@ function normalizeRuntimeHealth(data) {
146
199
  normalized.lastPromptAt = data.lastPromptAt;
147
200
  if (typeof data.lastStopAt === "string")
148
201
  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))) {
202
+ if (isRecord(data.lastAutoSave) && typeof data.lastAutoSave.at === "string" && AUTO_SAVE_STATUSES.includes(String(data.lastAutoSave.status))) {
150
203
  normalized.lastAutoSave = {
151
204
  at: data.lastAutoSave.at,
152
205
  status: data.lastAutoSave.status,
@@ -172,12 +225,16 @@ function normalizeRuntimeHealth(data) {
172
225
  normalized.lastSync.lastSuccessfulPullAt = data.lastSync.lastSuccessfulPullAt;
173
226
  if (typeof data.lastSync.lastPushAt === "string")
174
227
  normalized.lastSync.lastPushAt = data.lastSync.lastPushAt;
175
- if (["saved-local", "saved-pushed", "no-upstream", "error"].includes(String(data.lastSync.lastPushStatus)))
228
+ if (PUSH_STATUSES.includes(String(data.lastSync.lastPushStatus)))
176
229
  normalized.lastSync.lastPushStatus = data.lastSync.lastPushStatus;
177
230
  if (typeof data.lastSync.lastPushDetail === "string")
178
231
  normalized.lastSync.lastPushDetail = data.lastSync.lastPushDetail;
179
232
  if (isFiniteNumber(data.lastSync.unsyncedCommits))
180
233
  normalized.lastSync.unsyncedCommits = data.lastSync.unsyncedCommits;
234
+ if (isFiniteNumber(data.lastSync.consecutiveFailures))
235
+ normalized.lastSync.consecutiveFailures = data.lastSync.consecutiveFailures;
236
+ if (typeof data.lastSync.lastSuccessfulPushAt === "string")
237
+ normalized.lastSync.lastSuccessfulPushAt = data.lastSync.lastSuccessfulPushAt;
181
238
  }
182
239
  return normalized;
183
240
  }
@@ -588,23 +645,51 @@ export function normalizeQueueEntryText(raw, opts = {}) {
588
645
  truncated: true,
589
646
  });
590
647
  }
648
+ /** Matches a string made up entirely of HTML comments (and whitespace). */
649
+ const QUEUE_META_ONLY_RE = /^(?:\s*<!--(?:(?!-->)[\s\S])*?-->)+\s*$/;
650
+ /** Strip every HTML comment from a line. */
651
+ function stripQueueComments(line) {
652
+ return line.replace(/<!--(?:(?!-->)[\s\S])*?-->/g, " ");
653
+ }
654
+ /**
655
+ * Identity key for queue dedup: the entry's visible text with the date prefix,
656
+ * bullet marker, and metadata comments removed. Comment-insensitive so a line
657
+ * that gained provenance metadata still dedups against the same text queued
658
+ * before metadata existed.
659
+ */
660
+ function queueDedupKey(line) {
661
+ return stripQueueComments(line.trim())
662
+ .replace(/^-\s*/, "")
663
+ .replace(/^\[\d{4}-\d{2}-\d{2}\]\s*/, "")
664
+ .replace(/\s+/g, " ")
665
+ .trim();
666
+ }
591
667
  export function appendReviewQueue(phrenPath, project, section, entries) {
592
668
  if (!isValidProjectName(project))
593
669
  return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
594
- const resolvedDir = safeProjectPath(phrenPath, project);
670
+ const resolvedDir = storeAwareProjectPath(phrenPath, project);
595
671
  if (!resolvedDir || !fs.existsSync(resolvedDir))
596
672
  return phrenErr(`Project "${project}" not found in phren.`, PhrenError.PROJECT_NOT_FOUND);
597
673
  const queuePath = path.join(resolvedDir, "review.md");
598
674
  const today = new Date().toISOString().slice(0, 10);
599
675
  const normalized = [];
600
676
  for (const entry of entries) {
601
- const sanitized = normalizeQueueEntryText(normalizeBulletForQueue(entry), { truncate: true });
677
+ const rawText = typeof entry === "string" ? entry : entry.text;
678
+ const rawMeta = typeof entry === "string" ? "" : (entry.meta ?? "");
679
+ const sanitized = normalizeQueueEntryText(normalizeBulletForQueue(rawText), { truncate: true });
602
680
  if (!sanitized.ok)
603
681
  continue;
604
682
  if (sanitized.data.truncated) {
605
683
  debugLog(`appendReviewQueue: truncated oversized queue entry for ${project}`);
606
684
  }
607
- normalized.push(sanitized.data.text);
685
+ // Metadata must be comments only and single-line — anything else would leak
686
+ // producer-controlled markup into a file humans read and agents may render.
687
+ const meta = rawMeta.replace(/[\r\n]+/g, " ").trim();
688
+ const safeMeta = meta && QUEUE_META_ONLY_RE.test(meta) ? meta : "";
689
+ if (meta && !safeMeta) {
690
+ debugLog(`appendReviewQueue: dropped non-comment queue metadata for ${project}`);
691
+ }
692
+ normalized.push({ text: sanitized.data.text, meta: safeMeta });
608
693
  }
609
694
  if (normalized.length === 0)
610
695
  return phrenOk(0);
@@ -626,14 +711,16 @@ export function appendReviewQueue(phrenPath, project, section, entries) {
626
711
  let insertAt = secIdx + 1;
627
712
  while (insertAt < lines.length && !lines[insertAt].startsWith("## "))
628
713
  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()));
714
+ // Dedup by entry text only (date prefix and metadata comments stripped) so the
715
+ // same finding isn't queued again every day.
716
+ const existingKeys = new Set(lines.filter((line) => line.trim().startsWith("- ")).map(queueDedupKey));
632
717
  const toInsert = [];
633
718
  for (const entry of normalized) {
634
- const line = `- [${today}] ${entry}`;
635
- if (!existing.has(line) && !existingTexts.has(entry.trim()))
636
- toInsert.push(line);
719
+ const key = queueDedupKey(entry.text);
720
+ if (!key || existingKeys.has(key))
721
+ continue;
722
+ existingKeys.add(key);
723
+ toInsert.push(`- [${today}] ${entry.text}${entry.meta ? ` ${entry.meta}` : ""}`);
637
724
  }
638
725
  if (!toInsert.length)
639
726
  return phrenOk(0);
@@ -642,13 +729,94 @@ export function appendReviewQueue(phrenPath, project, section, entries) {
642
729
  return phrenOk(toInsert.length);
643
730
  });
644
731
  }
732
+ /**
733
+ * Read the retrieval log once and index the most recent retrieval per document key.
734
+ * Keys match what cli-hooks-output's recordRetrieval writes: `<project>/FINDINGS.md:<type>`.
735
+ */
736
+ function lastRetrievalByDocument(phrenPath) {
737
+ const byKey = new Map();
738
+ const logPath = path.join(runtimeDir(phrenPath), "retrieval-log.jsonl");
739
+ if (!fs.existsSync(logPath))
740
+ return byKey;
741
+ try {
742
+ for (const line of fs.readFileSync(logPath, "utf8").split("\n")) {
743
+ if (!line)
744
+ continue;
745
+ let entry;
746
+ try {
747
+ entry = JSON.parse(line);
748
+ }
749
+ catch {
750
+ continue;
751
+ }
752
+ if (typeof entry.file !== "string" || typeof entry.retrievedAt !== "string")
753
+ continue;
754
+ const ts = Date.parse(entry.retrievedAt);
755
+ if (Number.isNaN(ts))
756
+ continue;
757
+ const key = `${entry.file}:${entry.section}`;
758
+ if (ts > (byKey.get(key) || 0))
759
+ byKey.set(key, ts);
760
+ }
761
+ }
762
+ catch (err) {
763
+ debugLog(`pruneDeadMemories: retrieval log unreadable: ${errorMessage(err)}`);
764
+ }
765
+ return byKey;
766
+ }
767
+ /**
768
+ * Findings past their TTL that haven't been retrieved recently, rendered for the queue.
769
+ * Entries without a `<!-- created: -->` stamp are skipped defensively.
770
+ */
771
+ function collectTtlExpiredEntries(file, project, ttlDays, lastRetrieval) {
772
+ const retrievalGraceDays = Math.floor(ttlDays / 2);
773
+ const now = Date.now();
774
+ const expired = [];
775
+ let content;
776
+ try {
777
+ content = fs.readFileSync(file, "utf8");
778
+ }
779
+ catch (err) {
780
+ debugLog(`pruneDeadMemories: ${file} unreadable for TTL scan: ${errorMessage(err)}`);
781
+ return expired;
782
+ }
783
+ for (const line of content.split("\n")) {
784
+ if (!line.startsWith("- "))
785
+ continue;
786
+ const createdMatch = line.match(/<!--\s*created:\s*(\d{4}-\d{2}-\d{2})\s*-->/);
787
+ if (!createdMatch)
788
+ continue;
789
+ const createdDate = createdMatch[1];
790
+ const createdMs = Date.parse(`${createdDate}T00:00:00Z`);
791
+ if (Number.isNaN(createdMs))
792
+ continue;
793
+ if (Math.floor((now - createdMs) / 86_400_000) <= ttlDays)
794
+ continue;
795
+ // Retrieval is logged at document level, so look up the document key rather than
796
+ // the bullet.
797
+ const retrievedAt = lastRetrieval.get(`${project}/${path.basename(file)}:findings`) || 0;
798
+ const daysSinceRetrieval = retrievedAt ? Math.floor((now - retrievedAt) / 86_400_000) : Infinity;
799
+ if (daysSinceRetrieval <= retrievalGraceDays)
800
+ continue;
801
+ expired.push(`[ttl-expired: ${createdDate}] ${line.slice(2).trim()}`);
802
+ }
803
+ return expired;
804
+ }
805
+ /**
806
+ * Delete entries past the retention window and promote TTL-expired entries into review.md.
807
+ *
808
+ * TTL promotion lives here rather than in the CLI handler so that nightly maintenance
809
+ * (`handleBackgroundMaintenance`, which calls this directly) gets it too — previously it
810
+ * only ran on a manual `phren maintain prune`, leaving `## Stale` empty while `## Review`
811
+ * filled up.
812
+ */
645
813
  export function pruneDeadMemories(phrenPath, project, dryRun) {
646
814
  const policy = getRetentionPolicy(phrenPath);
647
815
  if (project && !isValidProjectName(project))
648
816
  return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
649
817
  const dirs = project
650
818
  ? (() => {
651
- const resolvedProject = safeProjectPath(phrenPath, project);
819
+ const resolvedProject = storeAwareProjectPath(phrenPath, project);
652
820
  return resolvedProject ? [resolvedProject] : [];
653
821
  })()
654
822
  : getProjectDirs(phrenPath).filter((dir) => path.basename(dir) !== "global");
@@ -712,12 +880,40 @@ export function pruneDeadMemories(phrenPath, project, dryRun) {
712
880
  }
713
881
  });
714
882
  }
883
+ // TTL enforcement: promote entries older than ttlDays that haven't been retrieved recently.
884
+ const lastRetrieval = lastRetrievalByDocument(phrenPath);
885
+ let ttlExpired = 0;
886
+ for (const dir of dirs) {
887
+ const file = resolveFindingsPath(dir);
888
+ if (!file)
889
+ continue;
890
+ const projectName = path.basename(dir);
891
+ const expiredEntries = collectTtlExpiredEntries(file, projectName, policy.ttlDays, lastRetrieval);
892
+ if (!expiredEntries.length)
893
+ continue;
894
+ ttlExpired += expiredEntries.length;
895
+ if (dryRun) {
896
+ for (const entry of expiredEntries) {
897
+ dryRunDetails.push(`[dry-run] [${projectName}] Would move to review queue: ${entry.slice(0, 120)}`);
898
+ }
899
+ continue;
900
+ }
901
+ appendReviewQueue(phrenPath, projectName, "Stale", expiredEntries);
902
+ }
903
+ const ttlLine = ttlExpired > 0
904
+ ? `\n${dryRun ? "Would move" : "Moved"} ${ttlExpired} TTL-expired entr${ttlExpired === 1 ? "y" : "ies"} to review.md`
905
+ : "";
715
906
  if (dryRun) {
716
907
  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);
908
+ const detail = dryRunDetails.length ? `${summary}\n${dryRunDetails.join("\n")}` : summary;
909
+ return phrenOk({ message: `${detail}${ttlLine}`, pruned, ttlExpired });
718
910
  }
719
- appendAuditLog(phrenPath, "prune_memories", `project=${project || "all"} pruned=${pruned}`);
720
- return phrenOk(`Pruned ${pruned} stale memory entr${pruned === 1 ? "y" : "ies"}.`);
911
+ appendAuditLog(phrenPath, "prune_memories", `project=${project || "all"} pruned=${pruned} ttl_expired=${ttlExpired}`);
912
+ return phrenOk({
913
+ message: `Pruned ${pruned} stale memory entr${pruned === 1 ? "y" : "ies"}.${ttlLine}`,
914
+ pruned,
915
+ ttlExpired,
916
+ });
721
917
  }
722
918
  function mergeLifecycleAndIdComments(primary, fallback) {
723
919
  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)
package/dist/hooks.d.ts CHANGED
@@ -14,6 +14,26 @@ export declare function detectInstalledTools(): Set<string>;
14
14
  * re-resolves on every run) or the ~/.local/bin/phren wrapper instead.
15
15
  */
16
16
  export declare function isEphemeralNpxPath(p: string): boolean;
17
+ /**
18
+ * The local file a hook command depends on — the `~/.local/bin/phren` wrapper,
19
+ * or the script passed to `node`.
20
+ *
21
+ * Returns `null` for commands that re-resolve themselves on every run
22
+ * (`npx -y @phren/cli …`), which cannot go stale, and for commands with no
23
+ * recognisable path.
24
+ *
25
+ * Why this matters: `npm install -g @phren/cli` can move the package entry
26
+ * between versions (0.1.40 moved it from `mcp/dist/index.js` to
27
+ * `dist/index.js`). Hook commands in settings.json keep the old absolute path
28
+ * and every hook then dies with MODULE_NOT_FOUND on every prompt and every
29
+ * Stop — silently, because hook failures are not surfaced.
30
+ */
31
+ export declare function extractHookScriptPath(command: string): string | null;
32
+ /**
33
+ * Hook commands whose entrypoint no longer exists on disk. Deduplicated, so an
34
+ * upgrade that breaks all four lifecycle hooks reports one path, not four.
35
+ */
36
+ export declare function findStaleHookEntrypoints(commands: readonly string[]): string[];
17
37
  /** Shell-escape a value by wrapping in single quotes with proper escaping of embedded single quotes. */
18
38
  export declare function shellEscape(s: string): string;
19
39
  export interface LifecycleCommands {
package/dist/hooks.js CHANGED
@@ -12,6 +12,9 @@ import { PACKAGE_SPEC } from "./package-metadata.js";
12
12
  import { logger } from "./logger.js";
13
13
  import { withFileLock } from "./shared/governance.js";
14
14
  import { resolveManagementCapabilities } from "./init/management-preset.js";
15
+ // Dependency-free leaf module — hooks.ts runs in a per-PostToolUse subprocess
16
+ // and must not pull in content/dedup.ts's import graph.
17
+ import { redactSecretsForLog } from "./content/secrets.js";
15
18
  export function commandExists(cmd) {
16
19
  try {
17
20
  const whichCmd = process.platform === "win32" ? "where.exe" : "which";
@@ -77,6 +80,98 @@ function resolveCliEntryScript() {
77
80
  export function isEphemeralNpxPath(p) {
78
81
  return /(^|[/\\])_npx[/\\]/.test(p);
79
82
  }
83
+ /** Split a hook command into tokens, honouring single and double quotes. */
84
+ function tokenizeCommand(command) {
85
+ const tokens = [];
86
+ let current = "";
87
+ let quote = null;
88
+ let started = false;
89
+ for (const ch of command) {
90
+ if (quote) {
91
+ if (ch === quote)
92
+ quote = null;
93
+ else
94
+ current += ch;
95
+ continue;
96
+ }
97
+ if (ch === '"' || ch === "'") {
98
+ quote = ch;
99
+ started = true;
100
+ continue;
101
+ }
102
+ if (/\s/.test(ch)) {
103
+ if (started || current)
104
+ tokens.push(current);
105
+ current = "";
106
+ started = false;
107
+ continue;
108
+ }
109
+ current += ch;
110
+ started = true;
111
+ }
112
+ if (started || current)
113
+ tokens.push(current);
114
+ return tokens;
115
+ }
116
+ function isPathLike(token) {
117
+ return token.startsWith("/")
118
+ || token.startsWith("~/")
119
+ || token.startsWith("\\\\")
120
+ || /^[A-Za-z]:[\\/]/.test(token);
121
+ }
122
+ /**
123
+ * The local file a hook command depends on — the `~/.local/bin/phren` wrapper,
124
+ * or the script passed to `node`.
125
+ *
126
+ * Returns `null` for commands that re-resolve themselves on every run
127
+ * (`npx -y @phren/cli …`), which cannot go stale, and for commands with no
128
+ * recognisable path.
129
+ *
130
+ * Why this matters: `npm install -g @phren/cli` can move the package entry
131
+ * between versions (0.1.40 moved it from `mcp/dist/index.js` to
132
+ * `dist/index.js`). Hook commands in settings.json keep the old absolute path
133
+ * and every hook then dies with MODULE_NOT_FOUND on every prompt and every
134
+ * Stop — silently, because hook failures are not surfaced.
135
+ */
136
+ export function extractHookScriptPath(command) {
137
+ if (!command)
138
+ return null;
139
+ // `npx` re-resolves the package each run, so it is never stale.
140
+ if (/(^|\s)npx(\.cmd)?(\s|$)/.test(command))
141
+ return null;
142
+ const tokens = tokenizeCommand(command);
143
+ for (let i = 0; i < tokens.length; i++) {
144
+ const token = tokens[i];
145
+ if (!token)
146
+ continue;
147
+ // Skip shell scaffolding: `set`, `&&`, and `VAR=value` assignments.
148
+ if (token === "&&" || token === "set" || /^[A-Za-z_][A-Za-z0-9_]*=/.test(token))
149
+ continue;
150
+ if (/^node(\.exe)?$/i.test(token)) {
151
+ const next = tokens[i + 1];
152
+ return next && isPathLike(next) ? next : null;
153
+ }
154
+ if (isPathLike(token))
155
+ return token;
156
+ }
157
+ return null;
158
+ }
159
+ /**
160
+ * Hook commands whose entrypoint no longer exists on disk. Deduplicated, so an
161
+ * upgrade that breaks all four lifecycle hooks reports one path, not four.
162
+ */
163
+ export function findStaleHookEntrypoints(commands) {
164
+ const stale = new Set();
165
+ for (const command of commands) {
166
+ const scriptPath = extractHookScriptPath(command);
167
+ if (!scriptPath)
168
+ continue;
169
+ const expanded = scriptPath.startsWith("~/") ? homePath(scriptPath.slice(2)) : scriptPath;
170
+ if (!fs.existsSync(expanded))
171
+ stale.add(scriptPath);
172
+ }
173
+ return [...stale];
174
+ }
80
175
  function phrenPackageSpec() {
81
176
  return PACKAGE_SPEC;
82
177
  }
@@ -670,9 +765,24 @@ export function readCustomHooks(phrenPath) {
670
765
  return [];
671
766
  }
672
767
  }
768
+ /**
769
+ * Every path that reports a custom-hook failure funnels through here and
770
+ * through buildHookErrorMessage below, so redaction happens in one place.
771
+ *
772
+ * The composed message is the hook's own command plus the child's stderr.
773
+ * Hook commands legitimately carry inline credentials — `curl -H
774
+ * "Authorization: Bearer …"` contains none of the shell metacharacters
775
+ * validateCustomHookCommand rejects — and a failing child prints whatever it
776
+ * wants to stderr, which execFileSync appends to the thrown error's message.
777
+ * That string was going verbatim into .runtime/hook-errors.log *and* back to
778
+ * the MCP caller, i.e. into the agent's context and transcript.
779
+ */
780
+ function buildHookErrorMessage(event, command, detail) {
781
+ return redactSecretsForLog(`${event}: ${command}: ${detail}`);
782
+ }
673
783
  function appendHookErrorLog(phrenPath, event, message) {
674
784
  const logPath = runtimeFile(phrenPath, "hook-errors.log");
675
- const line = `[${new Date().toISOString()}] [${event}] ${message}\n`;
785
+ const line = `[${new Date().toISOString()}] [${event}] ${redactSecretsForLog(message)}\n`;
676
786
  try {
677
787
  withFileLock(logPath, () => {
678
788
  fs.appendFileSync(logPath, line);
@@ -771,7 +881,7 @@ export function runCustomHooks(phrenPath, event, env = {}) {
771
881
  });
772
882
  }
773
883
  catch (err) {
774
- const message = `${event}: ${hook.command}: ${errorMessage(err)}`;
884
+ const message = buildHookErrorMessage(event, hook.command, errorMessage(err));
775
885
  debugLog(`runCustomHooks: ${message}`);
776
886
  errors.push({ code: PhrenError.VALIDATION_ERROR, message });
777
887
  try {
@@ -880,7 +990,7 @@ export function runPrePromptHooks(phrenPath, stdinJson, siblingCommandsOverride)
880
990
  outputs.push(trimmed);
881
991
  }
882
992
  catch (err) {
883
- const message = `pre-prompt: ${hook.command}: ${errorMessage(err)}`;
993
+ const message = buildHookErrorMessage("pre-prompt", hook.command, errorMessage(err));
884
994
  debugLog(`runPrePromptHooks: ${message}`);
885
995
  try {
886
996
  appendHookErrorLog(phrenPath, "pre-prompt", errorMessage(err));
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import * as fs from "fs";
3
3
  import * as path from "path";
4
- import { findPhrenPathWithArg, debugLog, runtimeDir, } from "./shared.js";
4
+ import { findPhrenPathWithArg, debugLog, ensureFtsCacheRootPrivate, runtimeDir, } from "./shared.js";
5
5
  import { log as structuredLog, logger } from "./logger.js";
6
6
  import { errorMessage } from "./utils.js";
7
7
  import { printIntegratedHelp, printIntegratedVersion, resolveTopLevelInvocation, runTopLevelCommand, } from "./entrypoint.js";
@@ -70,6 +70,10 @@ async function main() {
70
70
  ]);
71
71
  const profile = resolveRuntimeProfile(phrenPath);
72
72
  cleanStaleLocks(phrenPath);
73
+ // Before buildIndex() writes the first snapshot: the FTS cache is a full
74
+ // SQLite export of the store, and on Linux it lands in a world-readable
75
+ // /tmp. A 0700 root makes it unreachable to other local accounts.
76
+ ensureFtsCacheRootPrivate();
73
77
  let db = null;
74
78
  let indexReady = false;
75
79
  let shuttingDown = false;
@@ -2,5 +2,25 @@ export interface WiringConflict {
2
2
  location: string;
3
3
  existingPath: string;
4
4
  }
5
+ /**
6
+ * A path counts as a "valid phren root" only if it currently looks like one
7
+ * — root manifest, machines.yaml, or the global skills tree. We deliberately
8
+ * tolerate partial roots so a clean `phren init` repair still works.
9
+ */
10
+ export declare function looksLikePhrenRoot(candidate: string): boolean;
11
+ /**
12
+ * True when `candidate` is a *different* phren root than the one being
13
+ * installed and still looks live. That combination is the one case where
14
+ * rewriting a global file destroys wiring someone is actually using; a stale
15
+ * root (deleted, or never a root) is exactly what init exists to repair.
16
+ */
17
+ export declare function isLiveForeignPhrenRoot(candidate: string, newPhrenPath: string): boolean;
18
+ /**
19
+ * Recover the phren root that owns a `~/.claude/CLAUDE.md` symlink, from the
20
+ * link target's shape (`<root>/global/CLAUDE.md`). Returns null when the
21
+ * target is not structured like a phren global file, i.e. it belongs to
22
+ * something that is not phren and must not be touched.
23
+ */
24
+ export declare function phrenRootFromGlobalClaudeLink(target: string): string | null;
5
25
  export declare function findConflictingGlobalWiring(newPhrenPath: string): WiringConflict[];
6
26
  export declare function assertNoGlobalWiringConflict(newPhrenPath: string, force: boolean): void;