@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
@@ -8,6 +8,7 @@ import { fileURLToPath } from "url";
8
8
  import { debugLog, errorMessage, runtimeFile, isFeatureEnabled, } from "./hooks-context.js";
9
9
  import { qualityMarkers } from "../shared.js";
10
10
  import { spawnDetachedChild } from "../shared/process.js";
11
+ import { resolveManagementCapabilities } from "../init/management-preset.js";
11
12
  import { logger } from "../logger.js";
12
13
  const SYNC_LOCK_STALE_MS = 10 * 60 * 1000; // 10 minutes
13
14
  const MAINTENANCE_LOCK_STALE_MS = 2 * 60 * 60 * 1000; // 2 hours
@@ -64,6 +65,9 @@ export function scheduleBackgroundSync(phrenPathLocal) {
64
65
  export function scheduleBackgroundMaintenance(phrenPathLocal, project) {
65
66
  if (!isFeatureEnabled("PHREN_FEATURE_DAILY_MAINTENANCE", true))
66
67
  return false;
68
+ // Lifecycle automations (daily maintenance) are off under the manual preset.
69
+ if (!resolveManagementCapabilities(phrenPathLocal).lifecycleAutomations)
70
+ return false;
67
71
  const markers = qualityMarkers(phrenPathLocal);
68
72
  if (fs.existsSync(markers.done))
69
73
  return false;
@@ -8,6 +8,24 @@ export declare function runBestEffortGit(args: string[], cwd: string): Promise<{
8
8
  output?: string;
9
9
  error?: string;
10
10
  }>;
11
+ /**
12
+ * True when local HEAD and the tracking branch share no common ancestor.
13
+ *
14
+ * This is what happens when a store's remote is re-initialized: every
15
+ * `pull --rebase` fails, the rebase is aborted, and the next commit re-enters
16
+ * the same loop forever. A generic "pull failed" sends the user chasing
17
+ * network problems, so it is worth naming — no retry will ever fix it.
18
+ *
19
+ * Returns false when there is no upstream, or when git cannot answer; callers
20
+ * treat that as "some other failure" and report the raw error instead.
21
+ */
22
+ export declare function hasUnrelatedHistories(cwd: string): Promise<boolean>;
23
+ /**
24
+ * Files phren is allowed to auto-stage in a team store. Anything not in this
25
+ * list (notably `.runtime/`, secrets, build output) is skipped on session-stop
26
+ * and `push_changes`.
27
+ */
28
+ export declare const TEAM_STORE_PATHSPECS: readonly ["*/journal/*", "*/tasks.md", "*/truths.md", "*/FINDINGS.md", "*/FINDINGS.md.bak", "*/summary.md", "*/review.md", "*/CLAUDE.md", "*/topic-config.json", "*/phren.project.yaml", "*/reference/**", "*/skills/**", "*/notes/**", ".phren-team.yaml"];
11
29
  export declare function countUnsyncedCommits(cwd: string): Promise<number>;
12
30
  export declare function recoverPushConflict(cwd: string): Promise<{
13
31
  ok: boolean;
@@ -64,6 +64,53 @@ export async function runBestEffortGit(args, cwd) {
64
64
  }
65
65
  return { ok: false, error: "git command failed" };
66
66
  }
67
+ /**
68
+ * True when local HEAD and the tracking branch share no common ancestor.
69
+ *
70
+ * This is what happens when a store's remote is re-initialized: every
71
+ * `pull --rebase` fails, the rebase is aborted, and the next commit re-enters
72
+ * the same loop forever. A generic "pull failed" sends the user chasing
73
+ * network problems, so it is worth naming — no retry will ever fix it.
74
+ *
75
+ * Returns false when there is no upstream, or when git cannot answer; callers
76
+ * treat that as "some other failure" and report the raw error instead.
77
+ */
78
+ export async function hasUnrelatedHistories(cwd) {
79
+ const upstream = await runBestEffortGit(["rev-parse", "--abbrev-ref", "@{upstream}"], cwd);
80
+ if (!upstream.ok || !upstream.output)
81
+ return false;
82
+ // Make sure we are comparing against what the remote actually has now.
83
+ await runBestEffortGit(["fetch", "--quiet"], cwd);
84
+ const localHead = await runBestEffortGit(["rev-parse", "HEAD"], cwd);
85
+ const remoteHead = await runBestEffortGit(["rev-parse", upstream.output.trim()], cwd);
86
+ if (!localHead.ok || !remoteHead.ok || !localHead.output || !remoteHead.output)
87
+ return false;
88
+ // `merge-base` exits non-zero with no output when the two commits are
89
+ // unrelated, which is exactly the signal we want.
90
+ const mergeBase = await runBestEffortGit(["merge-base", localHead.output.trim(), remoteHead.output.trim()], cwd);
91
+ return !mergeBase.ok || !mergeBase.output?.trim();
92
+ }
93
+ /**
94
+ * Files phren is allowed to auto-stage in a team store. Anything not in this
95
+ * list (notably `.runtime/`, secrets, build output) is skipped on session-stop
96
+ * and `push_changes`.
97
+ */
98
+ export const TEAM_STORE_PATHSPECS = [
99
+ "*/journal/*",
100
+ "*/tasks.md",
101
+ "*/truths.md",
102
+ "*/FINDINGS.md",
103
+ "*/FINDINGS.md.bak",
104
+ "*/summary.md",
105
+ "*/review.md",
106
+ "*/CLAUDE.md",
107
+ "*/topic-config.json",
108
+ "*/phren.project.yaml",
109
+ "*/reference/**",
110
+ "*/skills/**",
111
+ "*/notes/**",
112
+ ".phren-team.yaml",
113
+ ];
67
114
  export async function countUnsyncedCommits(cwd) {
68
115
  const upstream = await runBestEffortGit(["rev-parse", "--abbrev-ref", "@{upstream}"], cwd);
69
116
  if (!upstream.ok || !upstream.output) {
@@ -5,7 +5,7 @@
5
5
  import * as fs from "fs";
6
6
  import * as path from "path";
7
7
  import * as crypto from "crypto";
8
- import { buildHookContext, handleGuardSkip, debugLog, appendAuditLog, runtimeFile, sessionMarker, getProjectDirs, findProjectNameCaseInsensitive, updateRuntimeHealth, withFileLock, detectProject, isProjectHookEnabled, readProjectConfig, getProjectSourcePath, detectProjectDir, ensureLocalGitRepo, isProjectTracked, repairPreexistingInstall, errorMessage, resolveRuntimeProfile, } from "./hooks-context.js";
8
+ import { buildHookContext, handleGuardSkip, debugLog, appendAuditLog, runtimeFile, sessionMarker, getProjectDirs, findProjectNameCaseInsensitive, projectSlugFromPath, updateRuntimeHealth, withFileLock, detectProject, isProjectHookEnabled, readProjectConfig, getProjectSourcePath, detectProjectDir, ensureLocalGitRepo, isProjectTracked, repairPreexistingInstall, errorMessage, resolveRuntimeProfile, } from "./hooks-context.js";
9
9
  import { TASKS_FILENAME } from "../data/tasks.js";
10
10
  import { FINDINGS_FILENAME } from "../data/access.js";
11
11
  import { readInstallPreferences } from "../init/preferences.js";
@@ -44,7 +44,7 @@ export function getUntrackedProjectNotice(phrenPath, cwd) {
44
44
  return null;
45
45
  if (detectProject(phrenPath, projectDir, activeProfile))
46
46
  return null;
47
- const projectName = path.basename(projectDir).toLowerCase().replace(/[^a-z0-9_-]/g, "-");
47
+ const projectName = projectSlugFromPath(projectDir);
48
48
  if (isProjectTracked(phrenPath, projectName, activeProfile)) {
49
49
  const trackedName = getProjectDirs(phrenPath, activeProfile)
50
50
  .map((dir) => path.basename(dir))
@@ -1,8 +1,19 @@
1
+ import { type PushStatus, type SyncStatus } from "../shared/governance.js";
1
2
  /**
2
3
  * Extract potential insights from conversation text using keyword heuristics.
3
4
  * Returns lines that contain insight-signal words and look like actionable knowledge.
4
5
  */
5
6
  export declare function extractConversationInsights(text: string): string[];
6
7
  export declare function filterConversationInsightsForProactivity(insights: string[], level?: "high" | "medium" | "low"): string[];
8
+ /**
9
+ * Build the `lastSync` patch for a sync attempt, carrying the failure streak
10
+ * forward. Success resets the counter and stamps `lastSuccessfulPushAt`;
11
+ * failure increments it. Without this the runtime health file only ever showed
12
+ * the most recent attempt, so "failed once" and "failed for two months" looked
13
+ * identical.
14
+ */
15
+ export declare function nextSyncStatus(previous: SyncStatus | undefined, patch: Omit<SyncStatus, "consecutiveFailures" | "lastSuccessfulPushAt"> & {
16
+ lastPushStatus: PushStatus;
17
+ }, now: string): SyncStatus;
7
18
  export declare function handleHookStop(): Promise<void>;
8
19
  export declare function handleBackgroundSync(): Promise<void>;
@@ -5,11 +5,13 @@
5
5
  import * as fs from "fs";
6
6
  import * as path from "path";
7
7
  import * as os from "os";
8
- import { buildHookContext, handleGuardSkip, debugLog, appendAuditLog, runtimeFile, sessionMarker, getPhrenPath, updateRuntimeHealth, withFileLock, getWorkflowPolicy, getProactivityLevelForTask, getProactivityLevelForFindings, hasExplicitFindingSignal, shouldAutoCaptureFindingsForLevel, FINDING_SENSITIVITY_CONFIG, isFeatureEnabled, errorMessage, homePath, isProjectHookEnabled, ensureLocalGitRepo, bootstrapPhrenDotEnv, finalizeTaskSession, appendFindingJournal, buildSyncStatus, } from "./hooks-context.js";
8
+ import { buildHookContext, handleGuardSkip, debugLog, appendAuditLog, runtimeFile, sessionMarker, getPhrenPath, updateRuntimeHealth, withFileLock, getWorkflowPolicy, getProactivityLevelForTask, getProactivityLevelForFindings, hasExplicitFindingSignal, shouldAutoCaptureFindingsForLevel, FINDING_SENSITIVITY_CONFIG, isFeatureEnabled, errorMessage, homePath, isProjectHookEnabled, ensureLocalGitRepo, bootstrapPhrenDotEnv, finalizeTaskSession, appendFindingJournal, } from "./hooks-context.js";
9
9
  import { logger } from "../logger.js";
10
- import { runBestEffortGit, countUnsyncedCommits, recoverPushConflict, } from "./session-git.js";
10
+ import { runBestEffortGit, countUnsyncedCommits, recoverPushConflict, hasUnrelatedHistories, } from "./session-git.js";
11
+ import { assessSyncOutage, getRuntimeHealth, } from "../shared/governance.js";
11
12
  import { resolveSubprocessArgs, scheduleBackgroundSync, } from "./session-background.js";
12
13
  import { spawnDetachedChild } from "../shared/process.js";
14
+ import { resolveManagementCapabilities } from "../init/management-preset.js";
13
15
  // ── Utility ─────────────────────────────────────────────────────────────────
14
16
  /** Read JSON from stdin if it's not a TTY. Returns null if stdin is a TTY or parsing fails. */
15
17
  function readStdinJson() {
@@ -84,6 +86,75 @@ export function filterConversationInsightsForProactivity(insights, level = getPr
84
86
  return insights;
85
87
  return insights.filter((insight) => shouldAutoCaptureFindingsForLevel(level, insight));
86
88
  }
89
+ // ── Sync failure accounting ─────────────────────────────────────────────────
90
+ const SYNC_WARN_MARKER = "sync-outage-warned-v1";
91
+ /** Re-warn at most once a day, so a broken store nags without spamming. */
92
+ const SYNC_WARN_INTERVAL_MS = 86_400_000;
93
+ /**
94
+ * Build the `lastSync` patch for a sync attempt, carrying the failure streak
95
+ * forward. Success resets the counter and stamps `lastSuccessfulPushAt`;
96
+ * failure increments it. Without this the runtime health file only ever showed
97
+ * the most recent attempt, so "failed once" and "failed for two months" looked
98
+ * identical.
99
+ */
100
+ export function nextSyncStatus(previous, patch, now) {
101
+ const failed = ["pull-failed", "push-failed", "unrelated-histories", "error"].includes(patch.lastPushStatus);
102
+ if (failed) {
103
+ return {
104
+ ...patch,
105
+ consecutiveFailures: (previous?.consecutiveFailures ?? 0) + 1,
106
+ ...(previous?.lastSuccessfulPushAt ? { lastSuccessfulPushAt: previous.lastSuccessfulPushAt } : {}),
107
+ };
108
+ }
109
+ const reachedRemote = patch.lastPushStatus === "saved-pushed";
110
+ return {
111
+ ...patch,
112
+ consecutiveFailures: 0,
113
+ ...(reachedRemote
114
+ ? { lastSuccessfulPushAt: now }
115
+ : previous?.lastSuccessfulPushAt
116
+ ? { lastSuccessfulPushAt: previous.lastSuccessfulPushAt }
117
+ : {}),
118
+ };
119
+ }
120
+ /**
121
+ * Tell the user, on stdout, that their store has stopped syncing. The Stop hook
122
+ * is the only place that runs on every turn, so silence here is what let a
123
+ * two-month outage go unnoticed. Rate-limited via a marker file.
124
+ */
125
+ function warnIfSyncDegraded(phrenPath) {
126
+ try {
127
+ const assessment = assessSyncOutage(getRuntimeHealth(phrenPath).lastSync);
128
+ if (!assessment.degraded)
129
+ return;
130
+ const markerPath = sessionMarker(phrenPath, SYNC_WARN_MARKER);
131
+ try {
132
+ const lastWarned = Date.parse(fs.readFileSync(markerPath, "utf8").trim());
133
+ if (!Number.isNaN(lastWarned) && Date.now() - lastWarned < SYNC_WARN_INTERVAL_MS)
134
+ return;
135
+ }
136
+ catch {
137
+ // No marker yet (or unreadable) — warn.
138
+ }
139
+ process.stdout.write([
140
+ "<phren-notice>",
141
+ assessment.summary,
142
+ `Your findings and tasks are safe on disk in ${phrenPath}, but they are not reaching the remote.`,
143
+ `Diagnose with: phren status (then: cd ${phrenPath} && git pull --rebase)`,
144
+ "<phren-notice>",
145
+ "",
146
+ ].join("\n"));
147
+ try {
148
+ fs.writeFileSync(markerPath, `${new Date().toISOString()}\n`);
149
+ }
150
+ catch (err) {
151
+ debugLog(`sync-outage marker write failed: ${errorMessage(err)}`);
152
+ }
153
+ }
154
+ catch (err) {
155
+ debugLog(`sync-outage check failed: ${errorMessage(err)}`);
156
+ }
157
+ }
87
158
  // ── Session cap helper ──────────────────────────────────────────────────────
88
159
  function getSessionCap() {
89
160
  if (process.env.PHREN_AUTOCAPTURE_SESSION_CAP) {
@@ -225,6 +296,21 @@ export async function handleHookStop() {
225
296
  appendAuditLog(phrenPath, "hook_stop", "status=skipped-local");
226
297
  return;
227
298
  }
299
+ // Under the manual preset lifecycle automations are off: never auto commit or
300
+ // push the store, even if a stale Stop hook fires. Files on disk are the record.
301
+ if (!resolveManagementCapabilities(phrenPath).lifecycleAutomations) {
302
+ updateRuntimeHealth(phrenPath, {
303
+ lastStopAt: now,
304
+ lastAutoSave: { at: now, status: "saved-local", detail: "manual preset: auto-commit disabled" },
305
+ lastSync: {
306
+ lastPushAt: now,
307
+ lastPushStatus: "saved-local",
308
+ lastPushDetail: "manual preset does not auto-commit or push",
309
+ },
310
+ });
311
+ appendAuditLog(phrenPath, "hook_stop", "status=skipped-manual-preset");
312
+ return;
313
+ }
228
314
  const gitRepo = ensureLocalGitRepo(phrenPath);
229
315
  if (!gitRepo.ok) {
230
316
  finalizeTaskSession({
@@ -266,17 +352,24 @@ export async function handleHookStop() {
266
352
  return;
267
353
  }
268
354
  if (!status.output) {
355
+ // A clean working tree says nothing about whether the store is in sync.
356
+ // Reporting "saved-pushed / no changes" here was the core lie: it
357
+ // overwrote a real `pull-failed` from the previous run every single turn,
358
+ // so the failure never accumulated and the user never saw it.
359
+ const previousSync = getRuntimeHealth(phrenPath).lastSync;
360
+ const pending = await countUnsyncedCommits(phrenPath);
361
+ const inSync = pending === 0;
362
+ const detail = inSync ? "no changes" : `no changes; ${pending} commit(s) still unpushed`;
269
363
  updateRuntimeHealth(phrenPath, {
270
364
  lastStopAt: now,
271
- lastAutoSave: { at: now, status: "clean", detail: "no changes" },
272
- lastSync: {
273
- lastPushAt: now,
274
- lastPushStatus: "saved-pushed",
275
- lastPushDetail: "no changes",
276
- unsyncedCommits: 0,
277
- },
365
+ lastAutoSave: { at: now, status: inSync ? "clean" : "sync-failed", detail },
366
+ lastSync: inSync
367
+ ? { ...previousSync, lastPushAt: now, lastPushDetail: detail, unsyncedCommits: 0 }
368
+ : { ...previousSync, lastPushAt: now, lastPushDetail: detail, unsyncedCommits: pending },
278
369
  });
279
- appendAuditLog(phrenPath, "hook_stop", "status=clean");
370
+ appendAuditLog(phrenPath, "hook_stop", `status=${inSync ? "clean" : "clean-unsynced"} pending=${pending}`);
371
+ if (!inSync)
372
+ warnIfSyncDegraded(phrenPath);
280
373
  return;
281
374
  }
282
375
  // Stage all changes first, then unstage any sensitive files that slipped
@@ -286,7 +379,11 @@ export async function handleHookStop() {
286
379
  if (add.ok) {
287
380
  // Belt-and-suspenders: unstage sensitive files that .gitignore should
288
381
  // already block. Failures here are non-fatal (files may not exist).
289
- await runBestEffortGit(["reset", "HEAD", "--", ".env", "**/.env", "*.pem", "*.key"], phrenPath);
382
+ // .config/auth-profiles.json is the legacy path for auth/profiles.ts's
383
+ // credential store (API keys, OpenAI Codex OAuth tokens) — it now lives
384
+ // in .runtime/ (never staged by `-A`, since that directory is
385
+ // gitignored), but this still protects a store from before that move.
386
+ await runBestEffortGit(["reset", "HEAD", "--", ".env", "**/.env", "*.pem", "*.key", ".config/auth-profiles.json"], phrenPath);
290
387
  }
291
388
  let commitMsg = "auto-save phren";
292
389
  if (add.ok) {
@@ -382,17 +479,22 @@ export async function handleHookStop() {
382
479
  status: "saved-local",
383
480
  detail: syncDetail,
384
481
  });
482
+ // The push has been handed to the background sync and has not happened yet,
483
+ // so only the push *detail* is updated here — the status, failure streak and
484
+ // last-success timestamp are left for whoever actually talks to the remote.
485
+ const priorSync = getRuntimeHealth(phrenPath).lastSync;
385
486
  updateRuntimeHealth(phrenPath, {
386
487
  lastStopAt: now,
387
488
  lastAutoSave: { at: now, status: "saved-local", detail: syncDetail },
388
489
  lastSync: {
490
+ ...priorSync,
389
491
  lastPushAt: now,
390
- lastPushStatus: "saved-local",
391
492
  lastPushDetail: syncDetail,
392
493
  unsyncedCommits,
393
494
  },
394
495
  });
395
496
  appendAuditLog(phrenPath, "hook_stop", `status=saved-local detail=${JSON.stringify(syncDetail)}`);
497
+ warnIfSyncDegraded(phrenPath);
396
498
  }); // end withFileLock(gitOpLockPath)
397
499
  // Auto governance scheduling (non-blocking)
398
500
  scheduleWeeklyGovernance();
@@ -403,41 +505,63 @@ export async function handleBackgroundSync() {
403
505
  const now = new Date().toISOString();
404
506
  const lockPath = runtimeFile(phrenPathLocal, "background-sync.lock");
405
507
  try {
508
+ const previousSync = getRuntimeHealth(phrenPathLocal).lastSync;
509
+ const record = (autoSaveStatus, patch, detail) => {
510
+ updateRuntimeHealth(phrenPathLocal, {
511
+ lastAutoSave: { at: now, status: autoSaveStatus, detail },
512
+ lastSync: nextSyncStatus(previousSync, patch, now),
513
+ });
514
+ appendAuditLog(phrenPathLocal, "background_sync", `status=${patch.lastPushStatus} detail=${JSON.stringify(detail)}`);
515
+ };
406
516
  const remotes = await runBestEffortGit(["remote"], phrenPathLocal);
407
517
  if (!remotes.ok || !remotes.output) {
408
518
  const unsyncedCommits = await countUnsyncedCommits(phrenPathLocal);
409
- updateRuntimeHealth(phrenPathLocal, {
410
- lastAutoSave: { at: now, status: "saved-local", detail: "background sync skipped; no remote configured" },
411
- lastSync: buildSyncStatus({ now, pushStatus: "saved-local", pushDetail: "background sync skipped; no remote configured", unsyncedCommits }),
412
- });
413
- appendAuditLog(phrenPathLocal, "background_sync", "status=saved-local detail=no_remote");
519
+ const detail = "background sync skipped; no remote configured";
520
+ record("saved-local", { lastPushAt: now, lastPushStatus: "saved-local", lastPushDetail: detail, unsyncedCommits }, detail);
414
521
  return;
415
522
  }
416
523
  const push = await runBestEffortGit(["push"], phrenPathLocal);
417
524
  if (push.ok) {
418
- updateRuntimeHealth(phrenPathLocal, {
419
- lastAutoSave: { at: now, status: "saved-pushed", detail: "commit pushed by background sync" },
420
- lastSync: buildSyncStatus({ now, pushStatus: "saved-pushed", pushDetail: "commit pushed by background sync", unsyncedCommits: 0 }),
421
- });
422
- appendAuditLog(phrenPathLocal, "background_sync", "status=saved-pushed");
525
+ const detail = "commit pushed by background sync";
526
+ record("saved-pushed", { lastPushAt: now, lastPushStatus: "saved-pushed", lastPushDetail: detail, unsyncedCommits: 0 }, detail);
423
527
  return;
424
528
  }
425
529
  const recovered = await recoverPushConflict(phrenPathLocal);
426
530
  if (recovered.ok) {
427
- updateRuntimeHealth(phrenPathLocal, {
428
- lastAutoSave: { at: now, status: "saved-pushed", detail: recovered.detail },
429
- lastSync: buildSyncStatus({ now, pushStatus: "saved-pushed", pushDetail: recovered.detail, pullAt: now, pullStatus: recovered.pullStatus, pullDetail: recovered.pullDetail, successfulPullAt: now, unsyncedCommits: 0 }),
430
- });
431
- appendAuditLog(phrenPathLocal, "background_sync", `status=saved-pushed detail=${JSON.stringify(recovered.detail)}`);
531
+ record("saved-pushed", {
532
+ lastPushAt: now,
533
+ lastPushStatus: "saved-pushed",
534
+ lastPushDetail: recovered.detail,
535
+ lastPullAt: now,
536
+ lastPullStatus: recovered.pullStatus,
537
+ lastPullDetail: recovered.pullDetail,
538
+ lastSuccessfulPullAt: now,
539
+ unsyncedCommits: 0,
540
+ }, recovered.detail);
432
541
  return;
433
542
  }
543
+ // The push leg genuinely failed. Report *which* leg failed instead of the
544
+ // old success-shaped "saved-local", and name the unrelated-histories case
545
+ // specifically — no retry will ever clear it, so a generic "pull failed"
546
+ // would send the user chasing the wrong problem.
434
547
  const unsyncedCommits = await countUnsyncedCommits(phrenPathLocal);
435
- const failDetail = recovered.detail || push.error || "background sync push failed";
436
- updateRuntimeHealth(phrenPathLocal, {
437
- lastAutoSave: { at: now, status: "saved-local", detail: failDetail },
438
- lastSync: buildSyncStatus({ now, pushStatus: "saved-local", pushDetail: failDetail, pullAt: now, pullStatus: recovered.pullStatus, pullDetail: recovered.pullDetail, unsyncedCommits }),
439
- });
440
- appendAuditLog(phrenPathLocal, "background_sync", `status=saved-local detail=${JSON.stringify(failDetail)}`);
548
+ const unrelated = recovered.pullStatus === "error" && await hasUnrelatedHistories(phrenPathLocal);
549
+ const pushStatus = unrelated
550
+ ? "unrelated-histories"
551
+ : recovered.pullStatus === "error" ? "pull-failed" : "push-failed";
552
+ const failDetail = unrelated
553
+ ? `local and remote histories are unrelated (no merge base) — the remote was most likely re-initialized. ` +
554
+ `Reconcile manually: cd ${phrenPathLocal} && git fetch && git log --oneline origin/HEAD`
555
+ : (recovered.detail || push.error || "background sync push failed");
556
+ record("sync-failed", {
557
+ lastPushAt: now,
558
+ lastPushStatus: pushStatus,
559
+ lastPushDetail: failDetail,
560
+ lastPullAt: now,
561
+ lastPullStatus: recovered.pullStatus,
562
+ lastPullDetail: recovered.pullDetail,
563
+ unsyncedCommits,
564
+ }, failDetail);
441
565
  }
442
566
  finally {
443
567
  try {
@@ -6,6 +6,7 @@ import * as fs from "fs";
6
6
  import * as path from "path";
7
7
  import { buildHookContext, debugLog, appendAuditLog, runtimeFile, sessionMarker, getPhrenPath, getWorkflowPolicy, appendReviewQueue, getProactivityLevelForFindings, FINDING_SENSITIVITY_CONFIG, isProjectHookEnabled, errorMessage, detectProject, } from "./hooks-context.js";
8
8
  import { logger } from "../logger.js";
9
+ import { findingQualityReason } from "../content/quality.js";
9
10
  import { rotateJsonlIfLarge } from "../phren-paths.js";
10
11
  import { buildIndex, queryRows, } from "../shared/index.js";
11
12
  import { filterTaskByPriority } from "../shared/retrieval.js";
@@ -210,10 +211,12 @@ export async function handleHookTool() {
210
211
  }
211
212
  }
212
213
  // Negative lookahead `(?!\(|\[)` rejects markdown link/reference patterns:
213
- // [Architecture](#architecture) ← TOC anchor, content was being captured as "(#architecture)"
214
- // [bug][1] ← markdown reference link, content was being captured as "[1]"
215
- // produced garbage review-queue entries like "[architecture] (#architecture)".
216
- const EXPLICIT_TAG_PATTERN = /\[(pitfall|decision|pattern|tradeoff|architecture|bug)\](?!\(|\[)\s*(.+)/i;
214
+ // [Pattern](#pattern) ← TOC anchor, content was being captured as "(#pattern)"
215
+ // [bug][1] ← markdown reference link, content was being captured as "[1]"
216
+ // produced garbage review-queue entries like "[pattern] (#pattern)".
217
+ // Tag list mirrors FINDING_TAGS (phren-core.ts): everything phren can write,
218
+ // offered or auto-detected, not just the smaller offered FINDING_TYPES set.
219
+ const EXPLICIT_TAG_PATTERN = /\[(pitfall|decision|pattern|bug|workaround|context)\](?!\(|\[)\s*(.+)/i;
217
220
  export function filterToolFindingsForProactivity(candidates, level = getProactivityLevelForFindings(getPhrenPath())) {
218
221
  if (level === "high")
219
222
  return candidates;
@@ -304,7 +307,16 @@ export function extractToolFindings(toolName, input, responseStr, toolResponse)
304
307
  }
305
308
  }
306
309
  }
307
- return candidates;
310
+ // Single quality gate for everything this hook scrapes. Explicit [tag] matches are not
311
+ // exempt: the tag scraper happily matched phren's own prompt text and code fragments
312
+ // like `[pattern] ");` and queued them for review.
313
+ return candidates.filter((candidate) => {
314
+ const reason = findingQualityReason(candidate.text);
315
+ if (!reason)
316
+ return true;
317
+ debugLog(`extractToolFindings: rejected (${reason}): ${candidate.text.slice(0, 80)}`);
318
+ return false;
319
+ });
308
320
  }
309
321
  // ── Context hook handler ────────────────────────────────────────────────────
310
322
  function readStdinJson() {
@@ -14,4 +14,6 @@ export declare function runStatusCommand(_args: string[]): Promise<number>;
14
14
  export declare function runVerifyCommand(_args: string[]): Promise<number>;
15
15
  export declare function runMcpModeCommand(args: string[]): Promise<number>;
16
16
  export declare function runHooksModeCommand(args: string[]): Promise<number>;
17
+ export declare function runPresetCommand(args: string[]): Promise<number>;
18
+ export declare function runSnippetCommand(_args: string[]): Promise<number>;
17
19
  export declare function runLinkRemovedNotice(_args: string[]): Promise<number>;
@@ -79,6 +79,7 @@ export async function runAddCommand(args) {
79
79
  }
80
80
  export async function runInitCommand(args) {
81
81
  const { parseMcpMode, runInit } = await import("./init/init.js");
82
+ const { parseManagementPreset, MANAGEMENT_PRESETS } = await import("./init/management-preset.js");
82
83
  const machineIdx = args.indexOf("--machine");
83
84
  const profileIdx = args.indexOf("--profile");
84
85
  const mcpIdx = args.indexOf("--mcp");
@@ -118,6 +119,18 @@ export async function runInitCommand(args) {
118
119
  console.error(`Invalid --task-proactivity value "${taskArg}". Use one of: high, medium, low.`);
119
120
  return 1;
120
121
  }
122
+ const presetArg = getOptionValue(args, "--preset") ?? getOptionValue(args, "--management");
123
+ const managementPreset = parseManagementPreset(presetArg);
124
+ if (presetArg && !managementPreset) {
125
+ console.error(`Invalid --preset value "${presetArg}". Use one of: ${MANAGEMENT_PRESETS.join(", ")}`);
126
+ return 1;
127
+ }
128
+ const hooksMode = parseMcpMode(getOptionValue(args, "--hooks") ?? "");
129
+ const hooksArg = getOptionValue(args, "--hooks");
130
+ if (hooksArg && !hooksMode) {
131
+ console.error(`Invalid --hooks value "${hooksArg}". Use "on" or "off".`);
132
+ return 1;
133
+ }
121
134
  const cloneUrl = getOptionValue(args, "--clone-url");
122
135
  try {
123
136
  await runInit({
@@ -125,7 +138,9 @@ export async function runInitCommand(args) {
125
138
  machine: machineIdx !== -1 ? args[machineIdx + 1] : undefined,
126
139
  profile: profileIdx !== -1 ? args[profileIdx + 1] : undefined,
127
140
  mcp: mcpMode,
141
+ hooks: hooksMode,
128
142
  projectOwnershipDefault: ownershipMode,
143
+ managementPreset,
129
144
  taskMode,
130
145
  findingsProactivity,
131
146
  taskProactivity,
@@ -198,6 +213,31 @@ export async function runHooksModeCommand(args) {
198
213
  return 1;
199
214
  }
200
215
  }
216
+ export async function runPresetCommand(args) {
217
+ const { runPreset } = await import("./init/init.js");
218
+ const positional = args.filter((a) => !a.startsWith("-"));
219
+ const yes = args.includes("--yes") || args.includes("-y");
220
+ try {
221
+ await runPreset(positional[0], { yes });
222
+ return 0;
223
+ }
224
+ catch (err) {
225
+ console.error(errorMessage(err));
226
+ return 1;
227
+ }
228
+ }
229
+ export async function runSnippetCommand(_args) {
230
+ const { printSelfWiringSnippet } = await import("./init/init.js");
231
+ const phrenPath = findPhrenPath() || defaultPhrenPath();
232
+ try {
233
+ printSelfWiringSnippet(phrenPath);
234
+ return 0;
235
+ }
236
+ catch (err) {
237
+ console.error(errorMessage(err));
238
+ return 1;
239
+ }
240
+ }
201
241
  export async function runLinkRemovedNotice(_args) {
202
242
  console.error("`phren link` has been removed. Use `phren init` instead.");
203
243
  return 1;
@@ -35,7 +35,7 @@ export interface Command {
35
35
  hidden?: boolean;
36
36
  run: RunFn;
37
37
  }
38
- export declare const ENV_HELP = "Environment variables:\n PHREN_PATH Override phren directory (default: ~/.phren)\n PHREN_PROFILE Active profile name\n PHREN_DEBUG Enable debug logging (set to 1)\n\n Embeddings:\n PHREN_OLLAMA_URL Ollama base URL (default: http://localhost:11434, 'off' to disable)\n PHREN_EMBEDDING_API_URL OpenAI-compatible /embeddings endpoint\n PHREN_EMBEDDING_API_KEY API key for embedding endpoint\n PHREN_EMBEDDING_MODEL Embedding model (default: nomic-embed-text)\n\n Context injection:\n PHREN_CONTEXT_TOKEN_BUDGET Max tokens injected per prompt (default: 550)\n PHREN_MAX_INJECT_TOKENS Hard cap on total injected tokens (default: 2000)\n PHREN_HOOK_TIMEOUT_MS Hook subprocess timeout in ms (default: 14000)\n\n Feature flags:\n PHREN_FEATURE_AUTO_EXTRACT=0 Disable auto memory extraction\n PHREN_FEATURE_AUTO_CAPTURE=1 Extract insights from conversations\n PHREN_FEATURE_SEMANTIC_DEDUP=1 LLM-based dedup on add_finding\n PHREN_FEATURE_HYBRID_SEARCH=0 Disable TF-IDF cosine fallback\n\n Run 'phren help all' to see everything.\n";
38
+ export declare const ENV_HELP = "Environment variables:\n PHREN_PATH Override phren directory (default: ~/.phren)\n PHREN_PROFILE Active profile name\n PHREN_DEBUG Enable debug logging (set to 1)\n\n Embeddings:\n PHREN_OLLAMA_URL Ollama base URL (default: http://localhost:11434, 'off' to disable)\n PHREN_EMBEDDING_API_URL OpenAI-compatible /embeddings endpoint\n PHREN_EMBEDDING_API_KEY API key for embedding endpoint\n PHREN_EMBEDDING_MODEL Embedding model (default: nomic-embed-text)\n\n Context injection:\n PHREN_CONTEXT_TOKEN_BUDGET Max tokens injected per prompt (default: 550)\n PHREN_MAX_INJECT_TOKENS Hard cap on total injected tokens (default: 2000)\n PHREN_HOOK_TIMEOUT_MS Hook subprocess timeout in ms (default: 14000)\n\n Feature flags:\n PHREN_FEATURE_TOOL_HOOK=0 Skip the PostToolUse subprocess (perf)\n PHREN_FEATURE_AUTO_EXTRACT=0 Disable auto memory extraction\n PHREN_FEATURE_AUTO_CAPTURE=1 Extract insights from conversations\n PHREN_FEATURE_SEMANTIC_DEDUP=1 LLM-based dedup on add_finding\n PHREN_FEATURE_HYBRID_SEARCH=0 Disable TF-IDF cosine fallback\n\n Run 'phren help all' to see everything.\n";
39
39
  export declare const DOC_TOPICS: Record<string, string>;
40
40
  export declare const REGISTRY: Command[];
41
41
  export declare function lookupCommand(name: string): Command | undefined;
@@ -43,6 +43,7 @@ export const ENV_HELP = `Environment variables:
43
43
  PHREN_HOOK_TIMEOUT_MS Hook subprocess timeout in ms (default: 14000)
44
44
 
45
45
  Feature flags:
46
+ PHREN_FEATURE_TOOL_HOOK=0 Skip the PostToolUse subprocess (perf)
46
47
  PHREN_FEATURE_AUTO_EXTRACT=0 Disable auto memory extraction
47
48
  PHREN_FEATURE_AUTO_CAPTURE=1 Extract insights from conversations
48
49
  PHREN_FEATURE_SEMANTIC_DEDUP=1 LLM-based dedup on add_finding
@@ -117,7 +118,7 @@ export const REGISTRY = [
117
118
  {
118
119
  name: "init",
119
120
  topic: "setup",
120
- usage: "phren init [--mode shared|project-local] [--machine <n>] [--profile <n>] [--dry-run] [-y]",
121
+ usage: "phren init [--preset managed|assisted|manual] [--mode shared|project-local] [--machine <n>] [--profile <n>] [--dry-run] [-y]",
121
122
  cheatUsage: "phren init",
122
123
  summary: "Set up phren",
123
124
  featured: true,
@@ -456,6 +457,20 @@ export const REGISTRY = [
456
457
  summary: "Toggle hook execution",
457
458
  run: native("runHooksModeCommand"),
458
459
  },
460
+ {
461
+ name: "preset",
462
+ topic: "setup",
463
+ usage: "phren preset [status|managed|assisted|manual] [-y]",
464
+ summary: "Set the management preset (how much phren wires up)",
465
+ run: native("runPresetCommand"),
466
+ },
467
+ {
468
+ name: "snippet",
469
+ topic: "setup",
470
+ usage: "phren snippet",
471
+ summary: "Print the self-wiring snippet for assisted/manual presets",
472
+ run: native("runSnippetCommand"),
473
+ },
459
474
  {
460
475
  name: "verify",
461
476
  topic: "setup",
@@ -25,10 +25,7 @@ export declare function normalizeObservationTags(text: string): {
25
25
  text: string;
26
26
  warning?: string;
27
27
  };
28
- /**
29
- * Scan text for secrets and PII patterns. Returns the type of secret found, or null if clean.
30
- */
31
- export declare function scanForSecrets(text: string): string | null;
28
+ export { looksLikePlaceholderSecret, scanForSecrets, redactSecretsForLog } from "./secrets.js";
32
29
  /**
33
30
  * Resolve coreferences in learning text by replacing vague pronouns with concrete names.
34
31
  */