@phren/cli 0.1.32 → 0.1.34

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 (82) hide show
  1. package/dist/capabilities/cli.js +2 -2
  2. package/dist/cli/config-access.d.ts +1 -0
  3. package/dist/cli/config-access.js +59 -0
  4. package/dist/cli/config-llm.d.ts +1 -0
  5. package/dist/cli/config-llm.js +60 -0
  6. package/dist/cli/config-policy.d.ts +11 -0
  7. package/dist/cli/config-policy.js +328 -0
  8. package/dist/cli/config-proactivity.d.ts +15 -0
  9. package/dist/cli/config-proactivity.js +135 -0
  10. package/dist/cli/config-shared.d.ts +6 -0
  11. package/dist/cli/config-shared.js +23 -0
  12. package/dist/cli/config-synonyms.d.ts +1 -0
  13. package/dist/cli/config-synonyms.js +63 -0
  14. package/dist/cli/config.d.ts +6 -24
  15. package/dist/cli/config.js +13 -670
  16. package/dist/cli/team.js +26 -13
  17. package/dist/content/dedup.js +25 -3
  18. package/dist/content/learning.js +10 -16
  19. package/dist/finding-graph-id.d.ts +15 -0
  20. package/dist/finding-graph-id.js +58 -0
  21. package/dist/generated/memory-ui-graph.browser.js +15 -15
  22. package/dist/governance/activity.d.ts +36 -0
  23. package/dist/governance/activity.js +83 -0
  24. package/dist/governance/rbac.d.ts +17 -0
  25. package/dist/governance/rbac.js +37 -1
  26. package/dist/governance/scores.js +26 -45
  27. package/dist/index.js +32 -1
  28. package/dist/memory-ui-graph.runtime.js +15 -15
  29. package/dist/phren-paths.d.ts +6 -0
  30. package/dist/phren-paths.js +8 -0
  31. package/dist/shared/governance.d.ts +1 -0
  32. package/dist/shared/governance.js +1 -0
  33. package/dist/shared/index.d.ts +2 -0
  34. package/dist/shared/index.js +90 -17
  35. package/dist/shared/retrieval.js +25 -6
  36. package/dist/shared.d.ts +1 -1
  37. package/dist/shared.js +1 -1
  38. package/dist/telemetry.js +4 -1
  39. package/dist/tools/config.js +39 -2
  40. package/dist/tools/finding.d.ts +1 -0
  41. package/dist/tools/finding.js +40 -2
  42. package/dist/tools/search.js +28 -1
  43. package/dist/ui/data.d.ts +2 -0
  44. package/dist/ui/data.js +8 -3
  45. package/dist/ui/graph.js +2 -0
  46. package/dist/ui/page.js +45 -2
  47. package/dist/ui/scripts.d.ts +13 -0
  48. package/dist/ui/scripts.js +229 -2
  49. package/dist/ui/server.js +165 -1
  50. package/dist/ui/styles.d.ts +1 -0
  51. package/dist/ui/styles.js +38 -0
  52. package/package.json +3 -3
  53. package/dist/cli-hooks-prompt.d.ts +0 -18
  54. package/dist/cli-hooks-prompt.js +0 -359
  55. package/dist/cli-hooks-session-handlers.d.ts +0 -3
  56. package/dist/cli-hooks-session-handlers.js +0 -356
  57. package/dist/cli-hooks-stop.d.ts +0 -11
  58. package/dist/cli-hooks-stop.js +0 -584
  59. package/dist/init-bootstrap.d.ts +0 -5
  60. package/dist/init-bootstrap.js +0 -21
  61. package/dist/init-detect.d.ts +0 -8
  62. package/dist/init-detect.js +0 -38
  63. package/dist/init-env.d.ts +0 -6
  64. package/dist/init-env.js +0 -114
  65. package/dist/init-fresh.d.ts +0 -10
  66. package/dist/init-fresh.js +0 -234
  67. package/dist/init-hooks.d.ts +0 -5
  68. package/dist/init-hooks.js +0 -26
  69. package/dist/init-mcp.d.ts +0 -8
  70. package/dist/init-mcp.js +0 -65
  71. package/dist/init-modes.d.ts +0 -4
  72. package/dist/init-modes.js +0 -135
  73. package/dist/init-npm.d.ts +0 -10
  74. package/dist/init-npm.js +0 -37
  75. package/dist/init-project-local.d.ts +0 -2
  76. package/dist/init-project-local.js +0 -99
  77. package/dist/init-semantic.d.ts +0 -4
  78. package/dist/init-semantic.js +0 -48
  79. package/dist/init-types.d.ts +0 -59
  80. package/dist/init-types.js +0 -1
  81. package/dist/init-update.d.ts +0 -10
  82. package/dist/init-update.js +0 -96
@@ -1,584 +0,0 @@
1
- /**
2
- * Stop hook handler: git commit/push, background sync, auto-capture, governance.
3
- * Extracted from cli-hooks-session.ts for modularity.
4
- */
5
- import { buildHookContext, handleGuardSkip, debugLog, runtimeFile, sessionMarker, getPhrenPath, updateRuntimeHealth, buildSyncStatus, appendAuditLog, withFileLock, getWorkflowPolicy, isProjectHookEnabled, ensureLocalGitRepo, getProactivityLevelForTask, getProactivityLevelForFindings, hasExplicitFindingSignal, shouldAutoCaptureFindingsForLevel, FINDING_SENSITIVITY_CONFIG, isFeatureEnabled, errorMessage, bootstrapPhrenDotEnv, finalizeTaskSession, appendFindingJournal, homePath, } from "./cli/hooks-context.js";
6
- import * as fs from "fs";
7
- import * as path from "path";
8
- import * as os from "os";
9
- import { spawnDetachedChild } from "./shared/process.js";
10
- import { resolveSubprocessArgs as _resolveSubprocessArgs, runBestEffortGit, countUnsyncedCommits, recoverPushConflict, addTeamPathspecs, } from "./cli-hooks-git.js";
11
- import { logger } from "./logger.js";
12
- const SYNC_LOCK_STALE_MS = 10 * 60 * 1000; // 10 minutes
13
- /** Read JSON from stdin if it's not a TTY. Returns null if stdin is a TTY or parsing fails. */
14
- export function readStdinJson() {
15
- if (process.stdin.isTTY)
16
- return null;
17
- try {
18
- return JSON.parse(fs.readFileSync(0, "utf-8"));
19
- }
20
- catch (err) {
21
- logger.debug("readStdinJson", errorMessage(err));
22
- return null;
23
- }
24
- }
25
- /** Validate that a transcript path points to a safe, expected location.
26
- * Uses realpathSync to dereference symlinks, preventing traversal attacks
27
- * where a symlink inside a safe dir points outside it.
28
- */
29
- function isSafeTranscriptPath(p) {
30
- // Resolve symlinks so a link like ~/.claude/evil -> /etc/passwd is caught
31
- let normalized;
32
- try {
33
- normalized = fs.realpathSync.native(p);
34
- }
35
- catch {
36
- // If the file doesn't exist yet, fall back to lexical resolution
37
- try {
38
- normalized = fs.realpathSync.native(path.dirname(p));
39
- normalized = path.join(normalized, path.basename(p));
40
- }
41
- catch {
42
- normalized = path.resolve(p);
43
- }
44
- }
45
- const safePrefixes = [
46
- path.resolve(os.tmpdir()),
47
- path.resolve(homePath(".claude")),
48
- path.resolve(homePath(".config", "claude")),
49
- ];
50
- return safePrefixes.some(prefix => normalized.startsWith(prefix + path.sep) || normalized === prefix);
51
- }
52
- // ── Q21: Conversation memory capture ─────────────────────────────────────────
53
- const INSIGHT_KEYWORDS = [
54
- "always", "never", "important", "pitfall", "gotcha", "trick", "workaround",
55
- "careful", "caveat", "beware", "note that", "make sure",
56
- "don't forget", "remember to", "must", "avoid", "prefer",
57
- ];
58
- const INSIGHT_KEYWORD_RE = new RegExp(`\\b(${INSIGHT_KEYWORDS.join("|")})\\b`, "i");
59
- /**
60
- * Extract potential insights from conversation text using keyword heuristics.
61
- * Returns lines that contain insight-signal words and look like actionable knowledge.
62
- */
63
- export function extractConversationInsights(text) {
64
- const lines = text.split("\n").filter(l => l.trim().length > 20 && l.trim().length < 300);
65
- const insights = [];
66
- const seen = new Set();
67
- for (const line of lines) {
68
- const trimmed = line.trim();
69
- // Skip code-only lines, headers, etc.
70
- if (trimmed.startsWith("```") || trimmed.startsWith("#") || trimmed.startsWith("//"))
71
- continue;
72
- if (trimmed.startsWith("$") || trimmed.startsWith(">"))
73
- continue;
74
- if (INSIGHT_KEYWORD_RE.test(trimmed) || hasExplicitFindingSignal(trimmed)) {
75
- // Normalize for dedup
76
- const normalized = trimmed.toLowerCase().replace(/\s+/g, " ");
77
- if (!seen.has(normalized)) {
78
- seen.add(normalized);
79
- insights.push(trimmed);
80
- }
81
- }
82
- }
83
- // Cap to prevent flooding
84
- return insights.slice(0, 5);
85
- }
86
- export function filterConversationInsightsForProactivity(insights, level = getProactivityLevelForFindings(getPhrenPath())) {
87
- if (level === "high")
88
- return insights;
89
- return insights.filter((insight) => shouldAutoCaptureFindingsForLevel(level, insight));
90
- }
91
- export function getSessionCap() {
92
- if (process.env.PHREN_AUTOCAPTURE_SESSION_CAP) {
93
- return parseInt(process.env.PHREN_AUTOCAPTURE_SESSION_CAP, 10);
94
- }
95
- try {
96
- const policy = getWorkflowPolicy(getPhrenPath());
97
- const sensitivity = policy.findingSensitivity ?? "balanced";
98
- return FINDING_SENSITIVITY_CONFIG[sensitivity]?.sessionCap ?? 10;
99
- }
100
- catch {
101
- return 10;
102
- }
103
- }
104
- function scheduleBackgroundSync(phrenPathLocal) {
105
- const lockPath = runtimeFile(phrenPathLocal, "background-sync.lock");
106
- const logPath = runtimeFile(phrenPathLocal, "background-sync.log");
107
- const spawnArgs = _resolveSubprocessArgs("background-sync");
108
- if (!spawnArgs)
109
- return false;
110
- try {
111
- if (fs.existsSync(lockPath)) {
112
- const ageMs = Date.now() - fs.statSync(lockPath).mtimeMs;
113
- if (ageMs <= SYNC_LOCK_STALE_MS)
114
- return false;
115
- fs.unlinkSync(lockPath);
116
- }
117
- }
118
- catch (err) {
119
- debugLog(`scheduleBackgroundSync: lock check failed: ${errorMessage(err)}`);
120
- return false;
121
- }
122
- try {
123
- fs.writeFileSync(lockPath, JSON.stringify({ startedAt: new Date().toISOString(), pid: process.pid }) + "\n", { flag: "wx" });
124
- const logFd = fs.openSync(logPath, "a");
125
- fs.writeSync(logFd, `[${new Date().toISOString()}] spawn ${process.execPath} ${spawnArgs.join(" ")}\n`);
126
- const child = spawnDetachedChild(spawnArgs, { phrenPath: phrenPathLocal, logFd });
127
- child.unref();
128
- fs.closeSync(logFd);
129
- return true;
130
- }
131
- catch (err) {
132
- try {
133
- fs.unlinkSync(lockPath);
134
- }
135
- catch { }
136
- debugLog(`scheduleBackgroundSync: spawn failed: ${errorMessage(err)}`);
137
- return false;
138
- }
139
- }
140
- function scheduleWeeklyGovernance() {
141
- try {
142
- const lastGovPath = runtimeFile(getPhrenPath(), "last-governance.txt");
143
- const lastRun = fs.existsSync(lastGovPath) ? parseInt(fs.readFileSync(lastGovPath, "utf8"), 10) : 0;
144
- const daysSince = (Date.now() - lastRun) / 86_400_000;
145
- if (daysSince >= 7) {
146
- const spawnArgs = _resolveSubprocessArgs("background-maintenance");
147
- if (spawnArgs) {
148
- const child = spawnDetachedChild(spawnArgs, { phrenPath: getPhrenPath() });
149
- child.unref();
150
- fs.writeFileSync(lastGovPath, Date.now().toString());
151
- debugLog("hook_stop: scheduled weekly governance run");
152
- }
153
- }
154
- }
155
- catch (err) {
156
- debugLog(`hook_stop: governance scheduling failed: ${errorMessage(err)}`);
157
- }
158
- }
159
- export async function handleHookStop() {
160
- const ctx = buildHookContext();
161
- const { phrenPath, activeProject, manifest } = ctx;
162
- const now = new Date().toISOString();
163
- bootstrapPhrenDotEnv(phrenPath);
164
- if (!ctx.hooksEnabled) {
165
- handleGuardSkip(ctx, "hook_stop", "disabled", {
166
- lastStopAt: now,
167
- lastAutoSave: { at: now, status: "clean", detail: "hooks disabled by preference" },
168
- });
169
- return;
170
- }
171
- if (!ctx.toolHookEnabled) {
172
- handleGuardSkip(ctx, "hook_stop", `tool_disabled tool=${ctx.hookTool}`);
173
- return;
174
- }
175
- if (!isProjectHookEnabled(phrenPath, activeProject, "Stop")) {
176
- handleGuardSkip(ctx, "hook_stop", `project_disabled project=${activeProject}`, {
177
- lastStopAt: now,
178
- lastAutoSave: { at: now, status: "clean", detail: `hooks disabled for project ${activeProject}` },
179
- });
180
- return;
181
- }
182
- // Read stdin early — it's a stream and can only be consumed once.
183
- // Needed for auto-capture transcript_path parsing.
184
- const stdinPayload = readStdinJson();
185
- const taskSessionId = typeof stdinPayload?.session_id === "string" ? stdinPayload.session_id : undefined;
186
- const taskLevel = getProactivityLevelForTask(phrenPath);
187
- if (taskSessionId && taskLevel !== "high") {
188
- debugLog(`hook-stop task proactivity=${taskLevel}`);
189
- }
190
- // Auto-capture BEFORE git operations so captured insights get committed and pushed.
191
- // Gated behind PHREN_FEATURE_AUTO_CAPTURE=1.
192
- const findingsLevel = getProactivityLevelForFindings(phrenPath);
193
- if (isFeatureEnabled("PHREN_FEATURE_AUTO_CAPTURE", false) && findingsLevel !== "low") {
194
- try {
195
- let captureInput = process.env.PHREN_CONVERSATION_CONTEXT || "";
196
- if (!captureInput && stdinPayload?.transcript_path) {
197
- const transcriptPath = stdinPayload.transcript_path;
198
- if (!isSafeTranscriptPath(transcriptPath)) {
199
- debugLog(`auto-capture: skipping unsafe transcript_path: ${transcriptPath}`);
200
- }
201
- else if (fs.existsSync(transcriptPath)) {
202
- // Cap at last 500 lines (~50 KB) to bound memory usage for long sessions
203
- const raw = fs.readFileSync(transcriptPath, "utf-8");
204
- const allLines = raw.split("\n").filter(Boolean);
205
- const lines = allLines.length > 500 ? allLines.slice(-500) : allLines;
206
- const assistantTexts = [];
207
- for (const line of lines) {
208
- try {
209
- const msg = JSON.parse(line);
210
- if (msg.role !== "assistant")
211
- continue;
212
- if (typeof msg.content === "string")
213
- assistantTexts.push(msg.content);
214
- else if (Array.isArray(msg.content)) {
215
- for (const block of msg.content) {
216
- if (block.type === "text" && block.text)
217
- assistantTexts.push(block.text);
218
- }
219
- }
220
- }
221
- catch (err) {
222
- logger.debug("hookStop transcriptParse", errorMessage(err));
223
- }
224
- }
225
- captureInput = assistantTexts.join("\n");
226
- }
227
- }
228
- if (captureInput) {
229
- if (activeProject) {
230
- // Check session cap before extracting — same guard as PostToolUse hook
231
- let capReached = false;
232
- if (taskSessionId) {
233
- try {
234
- const capFile = sessionMarker(phrenPath, `tool-findings-${taskSessionId}`);
235
- let count = 0;
236
- if (fs.existsSync(capFile)) {
237
- count = Number.parseInt(fs.readFileSync(capFile, "utf8").trim(), 10) || 0;
238
- }
239
- const cap = getSessionCap();
240
- if (count >= cap) {
241
- debugLog(`hook-stop: session cap reached (${count}/${cap}), skipping extraction`);
242
- capReached = true;
243
- }
244
- }
245
- catch (err) {
246
- logger.debug("hookStop sessionCapCheck", errorMessage(err));
247
- }
248
- }
249
- if (!capReached) {
250
- const insights = filterConversationInsightsForProactivity(extractConversationInsights(captureInput), findingsLevel);
251
- for (const insight of insights) {
252
- appendFindingJournal(phrenPath, activeProject, `[pattern] ${insight}`, {
253
- source: "hook",
254
- sessionId: `hook-stop-${Date.now()}`,
255
- });
256
- debugLog(`auto-capture: saved insight for ${activeProject}: ${insight.slice(0, 60)}`);
257
- }
258
- }
259
- }
260
- }
261
- }
262
- catch (err) {
263
- debugLog(`auto-capture failed: ${errorMessage(err)}`);
264
- }
265
- }
266
- else if (isFeatureEnabled("PHREN_FEATURE_AUTO_CAPTURE", false)) {
267
- debugLog("auto-capture: skipped because findings proactivity is low");
268
- }
269
- // Wrap git operations in a file lock to prevent concurrent agents from fighting
270
- const gitOpLockPath = path.join(phrenPath, ".runtime", "git-op");
271
- await withFileLock(gitOpLockPath, async () => {
272
- if (manifest?.installMode === "project-local") {
273
- updateRuntimeHealth(phrenPath, {
274
- lastStopAt: now,
275
- lastAutoSave: { at: now, status: "saved-local", detail: "project-local mode writes files only" },
276
- lastSync: {
277
- lastPushAt: now,
278
- lastPushStatus: "saved-local",
279
- lastPushDetail: "project-local mode does not manage git sync",
280
- },
281
- });
282
- appendAuditLog(phrenPath, "hook_stop", "status=skipped-local");
283
- return;
284
- }
285
- const gitRepo = ensureLocalGitRepo(phrenPath);
286
- if (!gitRepo.ok) {
287
- finalizeTaskSession({
288
- phrenPath,
289
- sessionId: taskSessionId,
290
- status: "error",
291
- detail: gitRepo.detail,
292
- });
293
- updateRuntimeHealth(phrenPath, {
294
- lastStopAt: now,
295
- lastAutoSave: { at: now, status: "error", detail: gitRepo.detail },
296
- lastSync: {
297
- lastPushAt: now,
298
- lastPushStatus: "error",
299
- lastPushDetail: gitRepo.detail,
300
- },
301
- });
302
- appendAuditLog(phrenPath, "hook_stop", `status=error detail=${JSON.stringify(gitRepo.detail)}`);
303
- process.stderr.write(`phren: git repo error — ${gitRepo.detail}. Run 'phren doctor --fix' for details.\n`);
304
- return;
305
- }
306
- const status = await runBestEffortGit(["status", "--porcelain"], phrenPath);
307
- if (!status.ok) {
308
- finalizeTaskSession({
309
- phrenPath,
310
- sessionId: taskSessionId,
311
- status: "error",
312
- detail: status.error || "git status failed",
313
- });
314
- updateRuntimeHealth(phrenPath, {
315
- lastStopAt: now,
316
- lastAutoSave: { at: now, status: "error", detail: status.error || "git status failed" },
317
- lastSync: {
318
- lastPushAt: now,
319
- lastPushStatus: "error",
320
- lastPushDetail: status.error || "git status failed",
321
- },
322
- });
323
- appendAuditLog(phrenPath, "hook_stop", `status=error detail=${JSON.stringify(status.error || "git status failed")}`);
324
- process.stderr.write(`phren: git status failed — your changes may not be saved. Run 'phren doctor --fix'.\n`);
325
- return;
326
- }
327
- if (!status.output) {
328
- updateRuntimeHealth(phrenPath, {
329
- lastStopAt: now,
330
- lastAutoSave: { at: now, status: "clean", detail: "no changes" },
331
- lastSync: {
332
- lastPushAt: now,
333
- lastPushStatus: "saved-pushed",
334
- lastPushDetail: "no changes",
335
- unsyncedCommits: 0,
336
- },
337
- });
338
- appendAuditLog(phrenPath, "hook_stop", "status=clean");
339
- return;
340
- }
341
- // Stage all changes first, then unstage any sensitive files that slipped
342
- // through. Using pathspec exclusions with `git add -A` can fail when
343
- // excluded paths are also gitignored (git treats the pathspec as an error).
344
- let add = await runBestEffortGit(["add", "--sparse", "-A"], phrenPath);
345
- if (add.ok) {
346
- // Belt-and-suspenders: unstage sensitive files that .gitignore should
347
- // already block. Failures here are non-fatal (files may not exist).
348
- await runBestEffortGit(["reset", "HEAD", "--", ".env", "**/.env", "*.pem", "*.key"], phrenPath);
349
- }
350
- let commitMsg = "auto-save phren";
351
- if (add.ok) {
352
- const diff = await runBestEffortGit(["diff", "--cached", "--stat", "--no-color"], phrenPath);
353
- if (diff.ok && diff.output) {
354
- // Parse "project/file.md | 3 +++" lines into project names and file types
355
- const changes = new Map();
356
- for (const line of diff.output.split("\n")) {
357
- const m = line.match(/^\s*([^/]+)\/([^|]+)\s*\|/);
358
- if (!m)
359
- continue;
360
- const proj = m[1].trim();
361
- if (proj.startsWith("."))
362
- continue; // skip .config, .runtime, etc.
363
- const file = m[2].trim();
364
- if (!changes.has(proj))
365
- changes.set(proj, new Set());
366
- if (/findings/i.test(file))
367
- changes.get(proj).add("findings");
368
- else if (/tasks/i.test(file))
369
- changes.get(proj).add("task");
370
- else if (/CLAUDE/i.test(file))
371
- changes.get(proj).add("config");
372
- else if (/summary/i.test(file))
373
- changes.get(proj).add("summary");
374
- else if (/skill/i.test(file))
375
- changes.get(proj).add("skills");
376
- else if (/reference/i.test(file))
377
- changes.get(proj).add("reference");
378
- else
379
- changes.get(proj).add("update");
380
- }
381
- if (changes.size > 0) {
382
- const parts = [...changes.entries()].map(([proj, types]) => `${proj}(${[...types].join(",")})`);
383
- commitMsg = `phren: ${parts.join(" ")}`;
384
- }
385
- }
386
- }
387
- const commit = add.ok ? await runBestEffortGit(["commit", "-m", commitMsg], phrenPath) : { ok: false, error: add.error };
388
- if (!add.ok || !commit.ok) {
389
- finalizeTaskSession({
390
- phrenPath,
391
- sessionId: taskSessionId,
392
- status: "error",
393
- detail: add.error || commit.error || "git add/commit failed",
394
- });
395
- updateRuntimeHealth(phrenPath, {
396
- lastStopAt: now,
397
- lastAutoSave: {
398
- at: now,
399
- status: "error",
400
- detail: add.error || commit.error || "git add/commit failed",
401
- },
402
- lastSync: {
403
- lastPushAt: now,
404
- lastPushStatus: "error",
405
- lastPushDetail: add.error || commit.error || "git add/commit failed",
406
- },
407
- });
408
- appendAuditLog(phrenPath, "hook_stop", `status=error detail=${JSON.stringify(add.error || commit.error || "git add/commit failed")}`);
409
- process.stderr.write(`phren: git commit failed — ${add.error || commit.error || "unknown error"}. Changes not saved.\n`);
410
- return;
411
- }
412
- const remotes = await runBestEffortGit(["remote"], phrenPath);
413
- if (!remotes.ok || !remotes.output) {
414
- finalizeTaskSession({
415
- phrenPath,
416
- sessionId: taskSessionId,
417
- status: "saved-local",
418
- detail: "commit created; no remote configured",
419
- });
420
- const unsyncedCommits = await countUnsyncedCommits(phrenPath);
421
- updateRuntimeHealth(phrenPath, {
422
- lastStopAt: now,
423
- lastAutoSave: { at: now, status: "saved-local", detail: "commit created; no remote configured" },
424
- lastSync: {
425
- lastPushAt: now,
426
- lastPushStatus: "saved-local",
427
- lastPushDetail: "commit created; no remote configured",
428
- unsyncedCommits,
429
- },
430
- });
431
- appendAuditLog(phrenPath, "hook_stop", "status=saved-local");
432
- if (unsyncedCommits > 3) {
433
- process.stderr.write(`phren: ${unsyncedCommits} unsynced commits — no git remote configured.\n`);
434
- }
435
- return;
436
- }
437
- // Check if HEAD has an upstream tracking branch before attempting sync.
438
- // If no upstream is set but a remote exists, auto-set it to avoid silent push failures.
439
- const upstream = await runBestEffortGit(["rev-parse", "--abbrev-ref", "@{upstream}"], phrenPath);
440
- if (!upstream.ok || !upstream.output) {
441
- // Try to auto-set upstream: get current branch and set tracking to origin/<branch>
442
- const branch = await runBestEffortGit(["rev-parse", "--abbrev-ref", "HEAD"], phrenPath);
443
- if (branch.ok && branch.output) {
444
- const branchName = branch.output.trim();
445
- const setUpstream = await runBestEffortGit(["branch", "--set-upstream-to", `origin/${branchName}`, branchName], phrenPath);
446
- if (!setUpstream.ok) {
447
- // Upstream auto-set failed — log and continue to sync anyway
448
- logger.debug("hookStop", `failed to auto-set upstream for ${branchName}`);
449
- }
450
- }
451
- // Fall through to scheduleBackgroundSync instead of returning early
452
- }
453
- const unsyncedCommits = await countUnsyncedCommits(phrenPath);
454
- const scheduled = scheduleBackgroundSync(phrenPath);
455
- const syncDetail = scheduled
456
- ? "commit saved; background sync scheduled"
457
- : "commit saved; background sync already running";
458
- finalizeTaskSession({
459
- phrenPath,
460
- sessionId: taskSessionId,
461
- status: "saved-local",
462
- detail: syncDetail,
463
- });
464
- updateRuntimeHealth(phrenPath, {
465
- lastStopAt: now,
466
- lastAutoSave: { at: now, status: "saved-local", detail: syncDetail },
467
- lastSync: {
468
- lastPushAt: now,
469
- lastPushStatus: "saved-local",
470
- lastPushDetail: syncDetail,
471
- unsyncedCommits,
472
- },
473
- });
474
- appendAuditLog(phrenPath, "hook_stop", `status=saved-local detail=${JSON.stringify(syncDetail)}`);
475
- }); // end withFileLock(gitOpLockPath)
476
- // Sync non-primary stores: commit+push team stores, pull-only readonly stores
477
- try {
478
- const { getNonPrimaryStores } = await import("./store-registry.js");
479
- const otherStores = getNonPrimaryStores(phrenPath);
480
- for (const store of otherStores) {
481
- if (!fs.existsSync(store.path) || !fs.existsSync(path.join(store.path, ".git")))
482
- continue;
483
- if (store.role === "team" && store.sync !== "pull-only") {
484
- // Team stores with managed-git sync: stage team-safe files, commit, and push
485
- try {
486
- const storeStatus = await runBestEffortGit(["status", "--porcelain"], store.path);
487
- if (storeStatus.ok && storeStatus.output) {
488
- // Stage each team-safe pathspec individually — a single no-match
489
- // (e.g. no */truths.md in this store) used to abort the whole add.
490
- await addTeamPathspecs(store.path);
491
- const actor = process.env.PHREN_ACTOR || process.env.USER || "unknown";
492
- const teamCommit = await runBestEffortGit(["commit", "-m", `phren: ${actor} team sync`], store.path);
493
- if (teamCommit.ok) {
494
- // Check for remote before pushing
495
- const storeRemotes = await runBestEffortGit(["remote"], store.path);
496
- if (storeRemotes.ok && storeRemotes.output?.trim()) {
497
- const teamPush = await runBestEffortGit(["push"], store.path);
498
- if (!teamPush.ok) {
499
- // Try pull-rebase then push
500
- await runBestEffortGit(["pull", "--rebase", "--quiet"], store.path);
501
- await runBestEffortGit(["push"], store.path);
502
- }
503
- }
504
- }
505
- }
506
- }
507
- catch (err) {
508
- debugLog(`hook-stop team-store-sync ${store.name}: ${errorMessage(err)}`);
509
- }
510
- }
511
- else {
512
- // Readonly stores: pull only
513
- try {
514
- await runBestEffortGit(["pull", "--rebase", "--quiet"], store.path);
515
- }
516
- catch (err) {
517
- debugLog(`hook-stop store-pull ${store.name}: ${errorMessage(err)}`);
518
- }
519
- }
520
- }
521
- }
522
- catch {
523
- // store-registry not available or no stores — skip silently
524
- }
525
- // Auto governance scheduling (non-blocking)
526
- scheduleWeeklyGovernance();
527
- }
528
- export async function handleBackgroundSync() {
529
- const phrenPathLocal = getPhrenPath();
530
- const now = new Date().toISOString();
531
- const lockPath = runtimeFile(phrenPathLocal, "background-sync.lock");
532
- try {
533
- const remotes = await runBestEffortGit(["remote"], phrenPathLocal);
534
- if (!remotes.ok || !remotes.output) {
535
- const unsyncedCommits = await countUnsyncedCommits(phrenPathLocal);
536
- updateRuntimeHealth(phrenPathLocal, {
537
- lastAutoSave: { at: now, status: "saved-local", detail: "background sync skipped; no remote configured" },
538
- lastSync: buildSyncStatus({ now, pushStatus: "saved-local", pushDetail: "background sync skipped; no remote configured", unsyncedCommits }),
539
- });
540
- appendAuditLog(phrenPathLocal, "background_sync", "status=saved-local detail=no_remote");
541
- return;
542
- }
543
- const push = await runBestEffortGit(["push"], phrenPathLocal);
544
- if (push.ok) {
545
- updateRuntimeHealth(phrenPathLocal, {
546
- lastAutoSave: { at: now, status: "saved-pushed", detail: "commit pushed by background sync" },
547
- lastSync: buildSyncStatus({ now, pushStatus: "saved-pushed", pushDetail: "commit pushed by background sync", unsyncedCommits: 0 }),
548
- });
549
- appendAuditLog(phrenPathLocal, "background_sync", "status=saved-pushed");
550
- return;
551
- }
552
- const recovered = await recoverPushConflict(phrenPathLocal);
553
- if (recovered.ok) {
554
- updateRuntimeHealth(phrenPathLocal, {
555
- lastAutoSave: { at: now, status: "saved-pushed", detail: recovered.detail },
556
- lastSync: buildSyncStatus({ now, pushStatus: "saved-pushed", pushDetail: recovered.detail, pullAt: now, pullStatus: recovered.pullStatus, pullDetail: recovered.pullDetail, successfulPullAt: now, unsyncedCommits: 0 }),
557
- });
558
- appendAuditLog(phrenPathLocal, "background_sync", `status=saved-pushed detail=${JSON.stringify(recovered.detail)}`);
559
- return;
560
- }
561
- const unsyncedCommits = await countUnsyncedCommits(phrenPathLocal);
562
- const failDetail = recovered.detail || push.error || "background sync push failed";
563
- updateRuntimeHealth(phrenPathLocal, {
564
- lastAutoSave: { at: now, status: "saved-local", detail: failDetail },
565
- lastSync: buildSyncStatus({ now, pushStatus: "saved-local", pushDetail: failDetail, pullAt: now, pullStatus: recovered.pullStatus, pullDetail: recovered.pullDetail, unsyncedCommits }),
566
- });
567
- appendAuditLog(phrenPathLocal, "background_sync", `status=saved-local detail=${JSON.stringify(failDetail)}`);
568
- // Append to sync-warnings.jsonl so health_check and session_start can surface recent failures
569
- try {
570
- const warningsPath = runtimeFile(phrenPathLocal, "sync-warnings.jsonl");
571
- const entry = JSON.stringify({ at: now, error: failDetail, unsyncedCommits }) + "\n";
572
- fs.appendFileSync(warningsPath, entry);
573
- }
574
- catch (err) {
575
- debugLog(`background-sync: failed to write sync warning: ${errorMessage(err)}`);
576
- }
577
- }
578
- finally {
579
- try {
580
- fs.unlinkSync(lockPath);
581
- }
582
- catch { }
583
- }
584
- }
@@ -1,5 +0,0 @@
1
- import { type ProjectOwnershipMode } from "./project-config.js";
2
- /**
3
- * Bootstrap a project from an existing directory into phren.
4
- */
5
- export declare function bootstrapProject(phrenPath: string, projectPath: string, profile: string | undefined, ownership: ProjectOwnershipMode, label: string): void;
@@ -1,21 +0,0 @@
1
- /**
2
- * Bootstrap-current-project prompting and execution for init.
3
- */
4
- import { debugLog } from "./shared.js";
5
- import { bootstrapFromExisting, } from "./init/setup.js";
6
- import { log } from "./init/shared.js";
7
- /**
8
- * Bootstrap a project from an existing directory into phren.
9
- */
10
- export function bootstrapProject(phrenPath, projectPath, profile, ownership, label) {
11
- try {
12
- const created = bootstrapFromExisting(phrenPath, projectPath, {
13
- profile,
14
- ownership,
15
- });
16
- log(`\n${label} "${created.project}" (${created.ownership})`);
17
- }
18
- catch (e) {
19
- debugLog(`Bootstrap from CWD failed: ${e instanceof Error ? e.message : String(e)}`);
20
- }
21
- }
@@ -1,8 +0,0 @@
1
- import type { InitOptions } from "./init-types.js";
2
- export declare function normalizedBootstrapProjectName(projectPath: string): string;
3
- export declare function getPendingBootstrapTarget(phrenPath: string, _opts: InitOptions): {
4
- path: string;
5
- mode: "explicit" | "detected";
6
- } | null;
7
- export declare function hasInstallMarkers(phrenPath: string): boolean;
8
- export declare function resolveInitPhrenPath(opts: InitOptions): string;
@@ -1,38 +0,0 @@
1
- /**
2
- * Detection helpers for init: bootstrap target, install markers, path resolution.
3
- */
4
- import * as fs from "fs";
5
- import * as path from "path";
6
- import { expandHomePath } from "./shared.js";
7
- import { detectProjectDir, isProjectTracked } from "./init/setup.js";
8
- import { DEFAULT_PHREN_PATH } from "./init/shared.js";
9
- export function normalizedBootstrapProjectName(projectPath) {
10
- return path.basename(projectPath).toLowerCase().replace(/[^a-z0-9_-]/g, "-");
11
- }
12
- export function getPendingBootstrapTarget(phrenPath, _opts) {
13
- const cwdProject = detectProjectDir(process.cwd(), phrenPath);
14
- if (!cwdProject)
15
- return null;
16
- const projectName = normalizedBootstrapProjectName(cwdProject);
17
- if (isProjectTracked(phrenPath, projectName))
18
- return null;
19
- return { path: cwdProject, mode: "detected" };
20
- }
21
- export function hasInstallMarkers(phrenPath) {
22
- // Require at least two markers to consider this a real install.
23
- // A partial clone or failed init may create one directory but not finish.
24
- if (!fs.existsSync(phrenPath))
25
- return false;
26
- let found = 0;
27
- if (fs.existsSync(path.join(phrenPath, "machines.yaml")))
28
- found++;
29
- if (fs.existsSync(path.join(phrenPath, ".config")))
30
- found++;
31
- if (fs.existsSync(path.join(phrenPath, "global")))
32
- found++;
33
- return found >= 2;
34
- }
35
- export function resolveInitPhrenPath(opts) {
36
- const raw = opts._walkthroughStoragePath || process.env.PHREN_PATH || DEFAULT_PHREN_PATH;
37
- return path.resolve(expandHomePath(raw));
38
- }
@@ -1,6 +0,0 @@
1
- import type { InitOptions } from "./init-types.js";
2
- import { repairPreexistingInstall } from "./init/setup.js";
3
- export declare function applyOnboardingPreferences(phrenPath: string, opts: InitOptions): void;
4
- export declare function writeWalkthroughEnvDefaults(phrenPath: string, opts: InitOptions): string[];
5
- export declare function collectRepairedAssetLabels(repaired: ReturnType<typeof repairPreexistingInstall>): string[];
6
- export declare function applyProjectStorageBindings(repoRoot: string, phrenPath: string): string[];