@phren/cli 0.1.39 → 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 (124) 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-background.js +4 -0
  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 +157 -33
  16. package/dist/cli/session-tool-hook.js +17 -5
  17. package/dist/cli-handlers.d.ts +2 -0
  18. package/dist/cli-handlers.js +40 -0
  19. package/dist/cli-registry.d.ts +1 -1
  20. package/dist/cli-registry.js +16 -1
  21. package/dist/content/dedup.d.ts +1 -4
  22. package/dist/content/dedup.js +7 -63
  23. package/dist/content/learning.d.ts +20 -2
  24. package/dist/content/learning.js +21 -3
  25. package/dist/content/quality.d.ts +23 -0
  26. package/dist/content/quality.js +123 -0
  27. package/dist/content/secrets.d.ts +52 -0
  28. package/dist/content/secrets.js +193 -0
  29. package/dist/data/access.d.ts +56 -2
  30. package/dist/data/access.js +246 -24
  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 +15 -3
  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 +209 -14
  39. package/dist/governance/rbac.d.ts +8 -0
  40. package/dist/governance/rbac.js +26 -0
  41. package/dist/hooks.d.ts +26 -0
  42. package/dist/hooks.js +119 -6
  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.d.ts +7 -2
  47. package/dist/init/init-configure.js +42 -16
  48. package/dist/init/init-preset.d.ts +3 -0
  49. package/dist/init/init-preset.js +122 -0
  50. package/dist/init/init-uninstall.js +9 -0
  51. package/dist/init/init-walkthrough.d.ts +2 -0
  52. package/dist/init/init-walkthrough.js +42 -17
  53. package/dist/init/init.d.ts +5 -0
  54. package/dist/init/init.js +71 -19
  55. package/dist/init/management-preset.d.ts +42 -0
  56. package/dist/init/management-preset.js +122 -0
  57. package/dist/init/preferences.d.ts +17 -0
  58. package/dist/init/preferences.js +3 -0
  59. package/dist/init/self-wiring.d.ts +5 -0
  60. package/dist/init/self-wiring.js +52 -0
  61. package/dist/init/setup.d.ts +9 -4
  62. package/dist/init/setup.js +139 -23
  63. package/dist/init/store-gitignore.d.ts +29 -0
  64. package/dist/init/store-gitignore.js +48 -0
  65. package/dist/init/teardown.d.ts +15 -0
  66. package/dist/init/teardown.js +241 -0
  67. package/dist/link/doctor.js +127 -34
  68. package/dist/link/link.js +49 -26
  69. package/dist/phren-core.d.ts +35 -8
  70. package/dist/phren-core.js +35 -8
  71. package/dist/phren-paths.d.ts +90 -1
  72. package/dist/phren-paths.js +150 -5
  73. package/dist/proactivity.js +1 -1
  74. package/dist/shared/embedding-cache.d.ts +16 -0
  75. package/dist/shared/embedding-cache.js +24 -0
  76. package/dist/shared/fragment-graph.js +10 -0
  77. package/dist/shared/index.d.ts +6 -0
  78. package/dist/shared/index.js +523 -138
  79. package/dist/shared/ollama.d.ts +14 -2
  80. package/dist/shared/ollama.js +84 -5
  81. package/dist/shared/retrieval.d.ts +22 -1
  82. package/dist/shared/retrieval.js +30 -1
  83. package/dist/shared/search-fallback.js +15 -3
  84. package/dist/shared/vector-index.d.ts +20 -1
  85. package/dist/shared/vector-index.js +18 -4
  86. package/dist/shared.d.ts +1 -1
  87. package/dist/shared.js +1 -1
  88. package/dist/status.js +31 -2
  89. package/dist/store-registry.d.ts +22 -0
  90. package/dist/store-registry.js +36 -3
  91. package/dist/task/lifecycle.js +31 -0
  92. package/dist/tools/config.js +16 -7
  93. package/dist/tools/data.js +1 -1
  94. package/dist/tools/extract.js +2 -2
  95. package/dist/tools/finding.js +14 -3
  96. package/dist/tools/graph.js +9 -1
  97. package/dist/tools/memory.js +1 -1
  98. package/dist/tools/notes.js +3 -3
  99. package/dist/tools/ops.js +19 -18
  100. package/dist/tools/search.js +2 -2
  101. package/dist/tools/session.js +2 -2
  102. package/dist/tools/tasks.js +2 -2
  103. package/dist/tools/types.d.ts +32 -2
  104. package/dist/tools/types.js +41 -8
  105. package/dist/ui/scripts.js +2 -2
  106. package/dist/ui/server.js +5 -0
  107. package/package.json +1 -1
  108. package/dist/cli-hooks-git.d.ts +0 -50
  109. package/dist/cli-hooks-git.js +0 -288
  110. package/starter/my-api/.claude/skills/README.md +0 -7
  111. package/starter/my-api/CLAUDE.md +0 -33
  112. package/starter/my-api/FINDINGS.md +0 -9
  113. package/starter/my-api/summary.md +0 -7
  114. package/starter/my-api/tasks.md +0 -7
  115. package/starter/my-first-project/.claude/skills/README.md +0 -7
  116. package/starter/my-first-project/CLAUDE.md +0 -49
  117. package/starter/my-first-project/FINDINGS.md +0 -24
  118. package/starter/my-first-project/summary.md +0 -11
  119. package/starter/my-first-project/tasks.md +0 -25
  120. package/starter/my-frontend/.claude/skills/README.md +0 -7
  121. package/starter/my-frontend/CLAUDE.md +0 -33
  122. package/starter/my-frontend/FINDINGS.md +0 -9
  123. package/starter/my-frontend/summary.md +0 -7
  124. package/starter/my-frontend/tasks.md +0 -7
@@ -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)
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 {
@@ -115,5 +135,11 @@ export declare function runPrePromptHooks(phrenPath: string, stdinJson: string,
115
135
  export interface HookConfigOptions {
116
136
  tools?: Set<string>;
117
137
  allTools?: boolean;
138
+ /**
139
+ * Whether to install ~/.local/bin session wrappers. Defaults to the current
140
+ * management preset's `installWrappers` capability. Assisted/manual presets
141
+ * skip wrappers (hooks fall back to node/npx invocation).
142
+ */
143
+ installWrappers?: boolean;
118
144
  }
119
145
  export declare function configureAllHooks(phrenPath: string, options?: HookConfigOptions): string[];
package/dist/hooks.js CHANGED
@@ -11,6 +11,10 @@ import { hookConfigPath } from "./provider-adapters.js";
11
11
  import { PACKAGE_SPEC } from "./package-metadata.js";
12
12
  import { logger } from "./logger.js";
13
13
  import { withFileLock } from "./shared/governance.js";
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";
14
18
  export function commandExists(cmd) {
15
19
  try {
16
20
  const whichCmd = process.platform === "win32" ? "where.exe" : "which";
@@ -76,6 +80,98 @@ function resolveCliEntryScript() {
76
80
  export function isEphemeralNpxPath(p) {
77
81
  return /(^|[/\\])_npx[/\\]/.test(p);
78
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
+ }
79
175
  function phrenPackageSpec() {
80
176
  return PACKAGE_SPEC;
81
177
  }
@@ -669,9 +765,24 @@ export function readCustomHooks(phrenPath) {
669
765
  return [];
670
766
  }
671
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
+ }
672
783
  function appendHookErrorLog(phrenPath, event, message) {
673
784
  const logPath = runtimeFile(phrenPath, "hook-errors.log");
674
- const line = `[${new Date().toISOString()}] [${event}] ${message}\n`;
785
+ const line = `[${new Date().toISOString()}] [${event}] ${redactSecretsForLog(message)}\n`;
675
786
  try {
676
787
  withFileLock(logPath, () => {
677
788
  fs.appendFileSync(logPath, line);
@@ -770,7 +881,7 @@ export function runCustomHooks(phrenPath, event, env = {}) {
770
881
  });
771
882
  }
772
883
  catch (err) {
773
- const message = `${event}: ${hook.command}: ${errorMessage(err)}`;
884
+ const message = buildHookErrorMessage(event, hook.command, errorMessage(err));
774
885
  debugLog(`runCustomHooks: ${message}`);
775
886
  errors.push({ code: PhrenError.VALIDATION_ERROR, message });
776
887
  try {
@@ -879,7 +990,7 @@ export function runPrePromptHooks(phrenPath, stdinJson, siblingCommandsOverride)
879
990
  outputs.push(trimmed);
880
991
  }
881
992
  catch (err) {
882
- const message = `pre-prompt: ${hook.command}: ${errorMessage(err)}`;
993
+ const message = buildHookErrorMessage("pre-prompt", hook.command, errorMessage(err));
883
994
  debugLog(`runPrePromptHooks: ${message}`);
884
995
  try {
885
996
  appendHookErrorLog(phrenPath, "pre-prompt", errorMessage(err));
@@ -898,6 +1009,8 @@ export function configureAllHooks(phrenPath, options = {}) {
898
1009
  : options.allTools
899
1010
  ? new Set(["copilot", "cursor", "codex"])
900
1011
  : detectInstalledTools();
1012
+ const installWrappers = options.installWrappers
1013
+ ?? resolveManagementCapabilities(phrenPath).installWrappers;
901
1014
  const lifecycle = buildLifecycleCommands(phrenPath);
902
1015
  // ── GitHub Copilot CLI (user-level: ~/.github/hooks/phren.json) ──────────
903
1016
  if (detected.has("copilot")) {
@@ -927,7 +1040,7 @@ export function configureAllHooks(phrenPath, options = {}) {
927
1040
  catch (err) {
928
1041
  console.warn(`configureAllHooks: copilot hook config failed: ${errorMessage(err)}`);
929
1042
  }
930
- if (isToolHookEnabled(phrenPath, "copilot"))
1043
+ if (installWrappers && isToolHookEnabled(phrenPath, "copilot"))
931
1044
  installSessionWrapper("copilot", phrenPath);
932
1045
  }
933
1046
  // ── Cursor (user-level: ~/.cursor/hooks.json) ────────────────────────────
@@ -959,7 +1072,7 @@ export function configureAllHooks(phrenPath, options = {}) {
959
1072
  catch (err) {
960
1073
  console.warn(`configureAllHooks: cursor hook config failed: ${errorMessage(err)}`);
961
1074
  }
962
- if (isToolHookEnabled(phrenPath, "cursor"))
1075
+ if (installWrappers && isToolHookEnabled(phrenPath, "cursor"))
963
1076
  installSessionWrapper("cursor", phrenPath);
964
1077
  }
965
1078
  // ── Codex (codex.json in phren path) ─────────────────────────────────────
@@ -990,7 +1103,7 @@ export function configureAllHooks(phrenPath, options = {}) {
990
1103
  catch (err) {
991
1104
  console.warn(`configureAllHooks: codex hook config failed: ${errorMessage(err)}`);
992
1105
  }
993
- if (isToolHookEnabled(phrenPath, "codex"))
1106
+ if (installWrappers && isToolHookEnabled(phrenPath, "codex"))
994
1107
  installSessionWrapper("codex", phrenPath);
995
1108
  }
996
1109
  return configured;
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;