@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
@@ -7,8 +7,8 @@ import { PROACTIVITY_LEVELS, } from "../proactivity.js";
7
7
  import { writeGovernanceInstallPreferences, } from "../init/preferences.js";
8
8
  import { FINDING_SENSITIVITY_CONFIG, buildProactivitySnapshot, checkProjectInProfile } from "../cli/config.js";
9
9
  import { readProjectConfig, updateProjectConfigOverrides, } from "../project-config.js";
10
- import { isValidProjectName, safeProjectPath } from "../utils.js";
11
- import { ACCESS_ROLE_KEYS, setAccessRoles } from "../governance/rbac.js";
10
+ import { errorMessage, isValidProjectName, safeProjectPath } from "../utils.js";
11
+ import { ACCESS_ROLE_KEYS, ACL_LOCKOUT_HINT, permissionDeniedError, setAccessRoles } from "../governance/rbac.js";
12
12
  import { readProjectTopics, writeProjectTopics, } from "../project-topics.js";
13
13
  import { buildConfigView } from "../config/resolve.js";
14
14
  import { getConfigField, CONFIG_DOMAINS } from "../config/schema.js";
@@ -101,7 +101,7 @@ async function handleGetConfig(ctx, { domain, project }) {
101
101
  let resolvedPhrenPath = phrenPath;
102
102
  let resolvedProject = project;
103
103
  try {
104
- const resolved = resolveStoreForProject(ctx, project);
104
+ const resolved = resolveStoreForProject(ctx, project, "read");
105
105
  resolvedPhrenPath = resolved.phrenPath;
106
106
  resolvedProject = resolved.project;
107
107
  }
@@ -454,6 +454,11 @@ async function handleSetConfig(ctx, { domain, settings, project }) {
454
454
  }
455
455
  // ── access ────────────────────────────────────────────────────
456
456
  case "access": {
457
+ // Rewriting the ACL is admin-only. Without this an actor the ACL denies
458
+ // every mutating action could still add itself to `admins` here.
459
+ const accessDenied = permissionDeniedError(phrenPath, "manage_config", project);
460
+ if (accessDenied)
461
+ return mcpResponse({ ok: false, error: `${accessDenied} ${ACL_LOCKOUT_HINT}` });
457
462
  const patch = {};
458
463
  let touched = false;
459
464
  for (const key of ACCESS_ROLE_KEYS) {
@@ -515,15 +520,19 @@ async function handleSetConfig(ctx, { domain, settings, project }) {
515
520
  const err = validateProject(project);
516
521
  if (err)
517
522
  return mcpResponse({ ok: false, error: err });
518
- // Resolve store-qualified project names for team stores
519
- let topicPhrenPath = phrenPath;
520
- let topicProject = project;
523
+ // Resolve store-qualified project names for team stores. This branch
524
+ // writes topic-config.json, so a failed resolution must surface instead
525
+ // of quietly writing into the primary store.
526
+ let topicPhrenPath;
527
+ let topicProject;
521
528
  try {
522
529
  const resolved = resolveStoreForProject(ctx, project);
523
530
  topicPhrenPath = resolved.phrenPath;
524
531
  topicProject = resolved.project;
525
532
  }
526
- catch { /* fall back to primary */ }
533
+ catch (err) {
534
+ return mcpResponse({ ok: false, error: errorMessage(err) });
535
+ }
527
536
  const projectDir = safeProjectPath(topicPhrenPath, topicProject);
528
537
  if (!projectDir || !fs.existsSync(projectDir)) {
529
538
  return mcpResponse({ ok: false, error: `Project "${topicProject}" not found in phren.` });
@@ -40,7 +40,7 @@ export function register(server, ctx) {
40
40
  let resolvedPhrenPath;
41
41
  let project;
42
42
  try {
43
- const resolved = resolveStoreForProject(ctx, projectInput);
43
+ const resolved = resolveStoreForProject(ctx, projectInput, "read");
44
44
  resolvedPhrenPath = resolved.phrenPath;
45
45
  project = resolved.project;
46
46
  }
@@ -15,7 +15,7 @@ Rules:
15
15
  - Do NOT extract obvious facts or things any developer would know
16
16
  - Do NOT extract credentials, API keys, or personal information
17
17
  - Each finding must be self-contained (understandable without seeing the source text)
18
- - Prefix each finding with its type in brackets: [decision], [pitfall], [pattern], [tradeoff], [bug], or [architecture]
18
+ - Prefix each finding with its type in brackets: [decision], [pitfall], [pattern], [bug], or [workaround]
19
19
  - Maximum 10 findings
20
20
  - If nothing is worth extracting, return []
21
21
  - Return ONLY the JSON array, no explanation, no markdown
@@ -45,7 +45,7 @@ export function register(server, ctx) {
45
45
  title: "◆ phren · auto-extract findings",
46
46
  description: "Use a local Ollama LLM to automatically extract non-obvious findings from text. " +
47
47
  "Pass conversation snippets, code review notes, error logs, or any engineering text. " +
48
- "The model identifies patterns, pitfalls, decisions, and bugs worth remembering. " +
48
+ "The model identifies patterns, pitfalls, decisions, bugs, and workarounds worth remembering. " +
49
49
  "Requires Ollama running locally. Set PHREN_EXTRACT_MODEL env var to choose model (default: llama3.2). " +
50
50
  "Set PHREN_OLLAMA_URL=off to disable.",
51
51
  inputSchema: z.object({
@@ -17,7 +17,7 @@ import { appendChildFinding, editFinding as editFindingCore, readFindings, FINDI
17
17
  import { getActiveTaskForSession } from "../task/lifecycle.js";
18
18
  import { isInactiveFindingLine, supersedeFinding, retractFinding as retractFindingLifecycle, resolveFindingContradiction, } from "../finding/lifecycle.js";
19
19
  import { permissionDeniedError } from "../governance/rbac.js";
20
- import { TEAM_STORE_PATHSPECS } from "../cli-hooks-git.js";
20
+ import { TEAM_STORE_PATHSPECS } from "../cli/session-git.js";
21
21
  const JACCARD_MAYBE_LOW = 0.25;
22
22
  const JACCARD_MAYBE_HIGH = 0.40; // above this isDuplicateFinding already catches it
23
23
  function findJaccardCandidates(phrenPath, project, finding) {
@@ -382,7 +382,7 @@ async function handleGetContradictions(ctx, { project, finding_text }) {
382
382
  // Build project list from all stores (primary + team)
383
383
  let projectsWithPaths;
384
384
  if (project) {
385
- const resolved = resolveStoreForProject(ctx, project);
385
+ const resolved = resolveStoreForProject(ctx, project, "read");
386
386
  projectsWithPaths = [{ project: resolved.project, storePath: resolved.phrenPath }];
387
387
  }
388
388
  else {
@@ -516,6 +516,17 @@ async function handlePushChanges(ctx, { message }) {
516
516
  runCustomHooks(phrenPath, "pre-save");
517
517
  // Stage all files including untracked (new project dirs, first FINDINGS.md, etc.)
518
518
  runGit(["add", "--sparse", "-A"]);
519
+ // Belt-and-suspenders: unstage sensitive files that .gitignore should
520
+ // already block (mirrors the same defensive reset in cli/session-stop.ts's
521
+ // auto-save). .config/auth-profiles.json is the legacy path for
522
+ // auth/profiles.ts's credential store (API keys, OpenAI Codex OAuth
523
+ // tokens) — this catches a store where the file was already tracked
524
+ // before it was gitignored, so a later token refresh doesn't get
525
+ // re-staged and pushed. Failures here are non-fatal (files may not exist).
526
+ try {
527
+ runGit(["reset", "HEAD", "--", ".env", "**/.env", "*.pem", "*.key", ".config/auth-profiles.json"]);
528
+ }
529
+ catch { /* best effort */ }
519
530
  runGit(["commit", "-m", commitMsg]);
520
531
  let hasRemote = false;
521
532
  try {
@@ -679,7 +690,7 @@ export function register(server, ctx) {
679
690
  sessionId: z.string().optional().describe("Optional session ID from session_start. Pass this if you want session metrics to include this write."),
680
691
  findingType: z.enum(FINDING_TYPES)
681
692
  .optional()
682
- .describe("Classify this finding: 'decision' (architectural choice with rationale), 'pitfall' (bug or failure mode to avoid), 'pattern' (reusable approach that works well), 'tradeoff' (deliberate compromise), 'architecture' (structural design note), 'bug' (confirmed defect or failure)."),
693
+ .describe("Classify this finding: 'decision' (architectural choice with rationale), 'pitfall' (bug or failure mode to avoid), 'pattern' (reusable approach that works well), 'bug' (confirmed defect or failure)."),
683
694
  scope: z.string().optional().describe("Optional memory scope label. Defaults to 'shared'. Example: 'researcher' or 'builder'."),
684
695
  }),
685
696
  }, (params) => handleAddFinding(ctx, params));
@@ -7,6 +7,14 @@ import { queryDocBySourceKey, queryRows, queryFragmentLinks, queryCrossProjectFr
7
7
  import { runtimeFile } from "../shared.js";
8
8
  import { withFileLock } from "../shared/governance.js";
9
9
  import { logger } from "../logger.js";
10
+ // NOTE on naming: titles/descriptions below all say "fragment" (the entity ->
11
+ // fragment rename, CHANGELOG 0.0.5), but the actual input schema key on
12
+ // get_related_docs, link_findings, and cross_project_fragments is still
13
+ // `entity` / `entity_type` — renaming it is a breaking change to a live MCP
14
+ // tool contract, plus link_findings persists that same shape to
15
+ // .runtime/manual-links.json (read back in shared/index.ts), so it is not a
16
+ // same-PR-safe rename. Left as-is; flagged for a product decision rather than
17
+ // changed unilaterally.
10
18
  export function register(server, ctx) {
11
19
  // ── search_fragments ──────────────────────────────────────────────────
12
20
  server.registerTool("search_fragments", {
@@ -88,7 +96,7 @@ export function register(server, ctx) {
88
96
  const docProject = doc.split("/")[0];
89
97
  let docPhrenPath = ctx.phrenPath;
90
98
  try {
91
- docPhrenPath = resolveStoreForProject(ctx, docProject).phrenPath;
99
+ docPhrenPath = resolveStoreForProject(ctx, docProject, "read").phrenPath;
92
100
  }
93
101
  catch { /* fall back to primary */ }
94
102
  const docRow = queryDocBySourceKey(db, docPhrenPath, doc);
@@ -47,7 +47,7 @@ export function register(server, ctx) {
47
47
  let phrenPath;
48
48
  let project;
49
49
  try {
50
- const resolved = resolveStoreForProject(ctx, projectInput);
50
+ const resolved = resolveStoreForProject(ctx, projectInput, "read");
51
51
  phrenPath = resolved.phrenPath;
52
52
  project = resolved.project;
53
53
  }
@@ -6,9 +6,9 @@ import { addNote, editNote, listNotes, removeNote } from "../data/notes.js";
6
6
  import { promoteNote } from "../core/note.js";
7
7
  import { permissionDeniedError } from "../governance/rbac.js";
8
8
  import { mcpResponse, resolveStoreForProject } from "./types.js";
9
- function resolve(ctx, projectInput) {
9
+ function resolve(ctx, projectInput, mode = "write") {
10
10
  try {
11
- return { ok: true, value: resolveStoreForProject(ctx, projectInput) };
11
+ return { ok: true, value: resolveStoreForProject(ctx, projectInput, mode) };
12
12
  }
13
13
  catch (err) {
14
14
  return { ok: false, error: err instanceof Error ? err.message : String(err) };
@@ -38,7 +38,7 @@ export function register(server, ctx) {
38
38
  limit: z.number().int().min(1).max(500).optional().describe("Maximum notes to return. Defaults to 100."),
39
39
  }),
40
40
  }, async ({ project: projectInput, date, limit }) => {
41
- const target = resolve(ctx, projectInput);
41
+ const target = resolve(ctx, projectInput, "read");
42
42
  if (!target.ok)
43
43
  return mcpResponse({ ok: false, error: target.error });
44
44
  const { phrenPath, project } = target.value;
package/dist/tools/ops.js CHANGED
@@ -1,8 +1,8 @@
1
- import { mcpResponse } from "./types.js";
1
+ import { mcpResponse, resolveStoreForProject } from "./types.js";
2
2
  import { z } from "zod";
3
3
  import * as fs from "fs";
4
4
  import * as path from "path";
5
- import { runtimeFile, getProjectDirs } from "../shared.js";
5
+ import { runtimeFile, getProjectDirs, projectSlugFromPath } from "../shared.js";
6
6
  import { findFtsCacheForPath } from "../shared/index.js";
7
7
  import { isValidProjectName, errorMessage } from "../utils.js";
8
8
  import { readReviewQueue, readReviewQueueAcrossProjects, approveQueueItem, rejectQueueItem, editQueueItem } from "../data/access.js";
@@ -10,11 +10,11 @@ import { addProjectFromPath } from "../core/project.js";
10
10
  import { PROJECT_OWNERSHIP_MODES, parseProjectOwnershipMode } from "../project-config.js";
11
11
  import { resolveRuntimeProfile } from "../runtime-profile.js";
12
12
  import { getMachineName } from "../machine-identity.js";
13
- import { resolveAllStores } from "../store-registry.js";
13
+ import { resolveAllStores, describeUnavailableStore } from "../store-registry.js";
14
14
  import { getProjectConsolidationStatus, CONSOLIDATION_ENTRY_THRESHOLD } from "../content/validate.js";
15
15
  import { logger } from "../logger.js";
16
16
  import { getRuntimeHealth } from "../governance/policy.js";
17
- import { countUnsyncedCommits } from "../cli-hooks-git.js";
17
+ import { countUnsyncedCommits } from "../cli/session-git.js";
18
18
  // ── Handlers ─────────────────────────────────────────────────────────────────
19
19
  async function handleAddProject(ctx, { path: targetPath, profile: requestedProfile, ownership, store: storeName }) {
20
20
  const { phrenPath, profile, withWriteQueue } = ctx;
@@ -23,6 +23,7 @@ async function handleAddProject(ctx, { path: targetPath, profile: requestedProfi
23
23
  // Resolve the target store path: explicit store > auto-route by project claim > primary
24
24
  let targetPhrenPath = phrenPath;
25
25
  let storeRole = "primary";
26
+ const projectName = targetPath ? projectSlugFromPath(targetPath) : undefined;
26
27
  if (storeName) {
27
28
  const stores = resolveAllStores(phrenPath);
28
29
  const store = stores.find((s) => s.name === storeName);
@@ -32,23 +33,23 @@ async function handleAddProject(ctx, { path: targetPath, profile: requestedProfi
32
33
  if (store.role === "readonly") {
33
34
  return mcpResponse({ ok: false, error: `Store "${storeName}" is read-only` });
34
35
  }
36
+ if (store.available === false) {
37
+ return mcpResponse({ ok: false, error: describeUnavailableStore(store) });
38
+ }
35
39
  targetPhrenPath = store.path;
36
40
  storeRole = store.role;
37
41
  }
38
- else {
39
- // Check if any non-primary writable store claims this project
40
- const projectName = targetPath
41
- ? path.basename(path.resolve(targetPath)).toLowerCase().replace(/[^a-z0-9_-]/g, "-")
42
- : undefined;
43
- if (projectName) {
44
- const stores = resolveAllStores(phrenPath);
45
- for (const store of stores) {
46
- if (store.role !== "readonly" && store.role !== "primary" && store.projects?.includes(projectName)) {
47
- targetPhrenPath = store.path;
48
- storeRole = store.role;
49
- break;
50
- }
51
- }
42
+ else if (projectName) {
43
+ // Same rule as every other write: a store that claims this project but
44
+ // is not attached here must fail, never fall through to the primary
45
+ // store — that is what copied work projects into the personal store.
46
+ try {
47
+ const resolved = resolveStoreForProject(ctx, projectName);
48
+ targetPhrenPath = resolved.phrenPath;
49
+ storeRole = resolved.storeRole;
50
+ }
51
+ catch (err) {
52
+ return mcpResponse({ ok: false, error: errorMessage(err) });
52
53
  }
53
54
  }
54
55
  const added = addProjectFromPath(phrenPath, targetPath, requestedProfile || profile || undefined, parseProjectOwnershipMode(ownership) ?? undefined, { writeToPath: targetPhrenPath });
@@ -643,7 +643,7 @@ async function handleListProjects(ctx, { page, page_size }) {
643
643
  async function handleGetFindings(ctx, { project, limit, include_superseded, include_history, status }) {
644
644
  if (!isValidProjectName(project))
645
645
  return mcpResponse({ ok: false, error: `Invalid project name: "${project}"` });
646
- const resolved = resolveStoreForProject(ctx, project);
646
+ const resolved = resolveStoreForProject(ctx, project, "read");
647
647
  const { phrenPath } = resolved;
648
648
  const includeHistory = include_history ?? include_superseded ?? false;
649
649
  // Always read with archive so we can compute historyCount without a second read
@@ -763,7 +763,7 @@ export function register(server, ctx) {
763
763
  .describe("Filter by document type: claude, findings, reference, summary, task, skill"),
764
764
  tag: z.preprocess(value => typeof value === "string" ? value.toLowerCase() : value, z.enum(FINDING_TAGS))
765
765
  .optional()
766
- .describe("Filter findings by type tag: decision, pitfall, pattern, tradeoff, architecture, bug."),
766
+ .describe("Filter findings by type tag: decision, pitfall, pattern, bug, workaround, context."),
767
767
  since: z.string().optional().describe('Filter findings by creation date. Formats: "7d" (last 7 days), "30d" (last 30 days), "YYYY-MM" (since start of month), "YYYY-MM-DD" (since date).'),
768
768
  status: z.enum(FINDING_LIFECYCLE_STATUSES).optional().describe("Filter findings by lifecycle status: active, superseded, contradicted, stale, invalid_citation, or retracted."),
769
769
  include_history: z.boolean().optional().describe("When true, include historical findings (superseded/retracted). Default false."),
@@ -410,7 +410,7 @@ export function register(server, ctx) {
410
410
  if (activeProject && isValidProjectName(activeProject)) {
411
411
  const projectStorePath = (() => {
412
412
  try {
413
- return resolveStoreForProject(ctx, activeProject).phrenPath;
413
+ return resolveStoreForProject(ctx, activeProject, "read").phrenPath;
414
414
  }
415
415
  catch {
416
416
  return phrenPath;
@@ -572,7 +572,7 @@ export function register(server, ctx) {
572
572
  if (!endedState.project)
573
573
  return phrenPath;
574
574
  try {
575
- return resolveStoreForProject(ctx, endedState.project).phrenPath;
575
+ return resolveStoreForProject(ctx, endedState.project, "read").phrenPath;
576
576
  }
577
577
  catch {
578
578
  return phrenPath;
@@ -109,7 +109,7 @@ export function register(server, ctx) {
109
109
  return mcpResponse({ ok: false, error: "Provide `project` when looking up a single item." });
110
110
  if (!isValidProjectName(project))
111
111
  return mcpResponse({ ok: false, error: `Invalid project name: "${project}"` });
112
- const resolvedPath = resolveStoreForProject(ctx, project).phrenPath;
112
+ const resolvedPath = resolveStoreForProject(ctx, project, "read").phrenPath;
113
113
  const result = readTasks(resolvedPath, project);
114
114
  if (!result.ok)
115
115
  return mcpResponse({ ok: false, error: result.error });
@@ -142,7 +142,7 @@ export function register(server, ctx) {
142
142
  if (project) {
143
143
  if (!isValidProjectName(project))
144
144
  return mcpResponse({ ok: false, error: `Invalid project name: "${project}"` });
145
- const resolvedPath = resolveStoreForProject(ctx, project).phrenPath;
145
+ const resolvedPath = resolveStoreForProject(ctx, project, "read").phrenPath;
146
146
  const result = readTasks(resolvedPath, project);
147
147
  if (!result.ok)
148
148
  return mcpResponse({ ok: false, error: result.error });
@@ -1,4 +1,5 @@
1
1
  import type { SqlJsDatabase } from "../shared/index.js";
2
+ import { type StoreEntry } from "../store-registry.js";
2
3
  export interface McpContext {
3
4
  phrenPath: string;
4
5
  profile: string;
@@ -12,12 +13,41 @@ export interface McpContext {
12
13
  }[];
13
14
  }>;
14
15
  }
16
+ /**
17
+ * How the caller intends to use the resolved store.
18
+ *
19
+ * - `"write"` (default) — the resolution must be exact. If a store claims the
20
+ * project but is not attached on this machine, resolution **fails loudly**
21
+ * rather than silently redirecting the write somewhere else.
22
+ * - `"read"` — the caller only reads. Missing team stores degrade to the
23
+ * primary store so search/list surfaces keep working offline; nothing leaves
24
+ * the machine, so a wrong answer here is a gap, not a leak.
25
+ *
26
+ * Defaulting to `"write"` is deliberate: an unclassified call site should get
27
+ * the safe behavior, not the lossy one.
28
+ */
29
+ export type StoreAccessMode = "read" | "write";
30
+ /**
31
+ * Error raised when a project is claimed by a store that is declared in
32
+ * stores.yaml but has no directory on this machine. Distinct class so callers
33
+ * can special-case it if they ever want to offer an interactive fix.
34
+ */
35
+ export declare class StoreUnavailableError extends Error {
36
+ readonly storeName: string;
37
+ readonly storePath: string;
38
+ constructor(store: StoreEntry, project: string);
39
+ }
15
40
  /**
16
41
  * Resolve the effective phrenPath and bare project name for a project input.
17
42
  * Handles store-qualified names ("store/project") by routing to the correct store.
18
- * Returns the primary store path for bare names.
43
+ * Returns the primary store path for bare names that no store claims.
44
+ *
45
+ * Note on the bare-name path: a store that claims the project but is missing
46
+ * locally used to fall through to the primary store, which quietly relocated
47
+ * team-store projects into the user's personal store. That fallback is gone for
48
+ * writes — see {@link StoreAccessMode}.
19
49
  */
20
- export declare function resolveStoreForProject(ctx: McpContext, projectInput: string): {
50
+ export declare function resolveStoreForProject(ctx: McpContext, projectInput: string, mode?: StoreAccessMode): {
21
51
  phrenPath: string;
22
52
  project: string;
23
53
  storeRole: string;
@@ -1,26 +1,54 @@
1
1
  import { parseStoreQualified } from "../store-routing.js";
2
- import { resolveAllStores } from "../store-registry.js";
2
+ import { describeUnavailableStore, resolveAllStores } from "../store-registry.js";
3
+ import { logger } from "../logger.js";
4
+ /**
5
+ * Error raised when a project is claimed by a store that is declared in
6
+ * stores.yaml but has no directory on this machine. Distinct class so callers
7
+ * can special-case it if they ever want to offer an interactive fix.
8
+ */
9
+ export class StoreUnavailableError extends Error {
10
+ storeName;
11
+ storePath;
12
+ constructor(store, project) {
13
+ super(`Refusing to write "${project}": it belongs to a store that is not available here. ` +
14
+ `${describeUnavailableStore(store)} ` +
15
+ `Writing it to the primary store instead would copy ${store.role}-store data into your personal store, ` +
16
+ `so phren stopped instead. Re-run once the store is attached, or use "phren team unsubscribe ${store.name} ${project}" ` +
17
+ `if this project should no longer live there.`);
18
+ this.name = "StoreUnavailableError";
19
+ this.storeName = store.name;
20
+ this.storePath = store.path;
21
+ }
22
+ }
3
23
  /**
4
24
  * Resolve the effective phrenPath and bare project name for a project input.
5
25
  * Handles store-qualified names ("store/project") by routing to the correct store.
6
- * Returns the primary store path for bare names.
26
+ * Returns the primary store path for bare names that no store claims.
27
+ *
28
+ * Note on the bare-name path: a store that claims the project but is missing
29
+ * locally used to fall through to the primary store, which quietly relocated
30
+ * team-store projects into the user's personal store. That fallback is gone for
31
+ * writes — see {@link StoreAccessMode}.
7
32
  */
8
- export function resolveStoreForProject(ctx, projectInput) {
33
+ export function resolveStoreForProject(ctx, projectInput, mode = "write") {
9
34
  const { storeName, projectName } = parseStoreQualified(projectInput);
35
+ const stores = resolveAllStores(ctx.phrenPath);
10
36
  if (!storeName) {
11
37
  // Check if any non-readonly store claims this project via projects[] array.
12
38
  // This enables automatic write routing: once a project is claimed by a team
13
39
  // store (via `phren team add-project`), writes go there without needing the
14
40
  // store-qualified prefix.
15
- const stores = resolveAllStores(ctx.phrenPath);
16
- for (const store of stores) {
17
- if (store.role !== "readonly" && store.role !== "primary" && store.projects?.includes(projectName)) {
18
- return { phrenPath: store.path, project: projectName, storeRole: store.role };
41
+ const claiming = stores.find((s) => s.role !== "readonly" && s.role !== "primary" && s.projects?.includes(projectName));
42
+ if (claiming) {
43
+ if (claiming.available !== false) {
44
+ return { phrenPath: claiming.path, project: projectName, storeRole: claiming.role };
19
45
  }
46
+ if (mode === "write")
47
+ throw new StoreUnavailableError(claiming, projectName);
48
+ logger.debug("store-routing", `read for "${projectName}" fell back to primary: ${describeUnavailableStore(claiming)}`);
20
49
  }
21
50
  return { phrenPath: ctx.phrenPath, project: projectName, storeRole: "primary" };
22
51
  }
23
- const stores = resolveAllStores(ctx.phrenPath);
24
52
  const store = stores.find((s) => s.name === storeName);
25
53
  if (!store) {
26
54
  throw new Error(`Store "${storeName}" not found`);
@@ -28,6 +56,11 @@ export function resolveStoreForProject(ctx, projectInput) {
28
56
  if (store.role === "readonly") {
29
57
  throw new Error(`Store "${storeName}" is read-only`);
30
58
  }
59
+ // An explicitly named store has no defensible fallback — the caller asked for
60
+ // that store by name, so say it isn't here rather than answering from another.
61
+ if (store.available === false) {
62
+ throw new StoreUnavailableError(store, projectName);
63
+ }
31
64
  return { phrenPath: store.path, project: projectName, storeRole: store.role };
32
65
  }
33
66
  /**
@@ -319,10 +319,10 @@ export function renderNotesEnhancementScript() {
319
319
  if (!confirm('Remove this note?')) return;
320
320
  request(project, 'DELETE', { note: note }, function() { loadNotes(false); });
321
321
  } else if (action === 'promote') {
322
- var findingType = prompt('Finding type (optional): decision, pitfall, pattern, tradeoff, architecture, bug', '');
322
+ var findingType = prompt('Finding type (optional): decision, pitfall, pattern, bug', '');
323
323
  if (findingType === null) return;
324
324
  findingType = findingType.trim().toLowerCase();
325
- var valid = ['', 'decision', 'pitfall', 'pattern', 'tradeoff', 'architecture', 'bug'];
325
+ var valid = ['', 'decision', 'pitfall', 'pattern', 'bug'];
326
326
  if (valid.indexOf(findingType) === -1) { alert('Unknown finding type.'); return; }
327
327
  request(project, 'POST', { action: 'promote', note: note, finding_type: findingType }, function() { loadNotes(false); });
328
328
  }
package/dist/ui/server.js CHANGED
@@ -986,6 +986,11 @@ function handlePostSettingsAccess(req, res, url, ctx) {
986
986
  }
987
987
  if (!Object.keys(patch).length)
988
988
  return jsonErr(res, "Provide at least one of: admins, contributors, readers");
989
+ // Rewriting the ACL is admin-only — otherwise a denied actor could POST
990
+ // itself into `admins` here and undo every other check on this server.
991
+ const denied = permissionDeniedError(ctx.phrenPath, "manage_config", project || undefined);
992
+ if (denied)
993
+ return jsonErr(res, denied, 403);
989
994
  try {
990
995
  const written = setAccessRoles(ctx.phrenPath, patch, project || undefined);
991
996
  jsonOk(res, { ok: true, access: written });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/cli",
3
- "version": "0.1.39",
3
+ "version": "0.1.41",
4
4
  "description": "Knowledge layer for AI agents — CLI, MCP server, and data layer",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,50 +0,0 @@
1
- import type { SelectedSnippet } from "./shared/retrieval.js";
2
- export interface GitContext {
3
- branch: string;
4
- changedFiles: Set<string>;
5
- }
6
- export declare function getGitContext(cwd?: string): GitContext | null;
7
- export interface SessionMetric {
8
- prompts: number;
9
- keys: Record<string, number>;
10
- lastChangedCount: number;
11
- lastKeys: string[];
12
- lastSeen?: string;
13
- }
14
- export declare function parseSessionMetrics(phrenPathLocal: string): Record<string, SessionMetric>;
15
- export declare function writeSessionMetrics(phrenPathLocal: string, data: Record<string, SessionMetric>): void;
16
- export declare function updateSessionMetrics(phrenPathLocal: string, updater: (data: Record<string, SessionMetric>) => void): void;
17
- export declare function trackSessionMetrics(phrenPathLocal: string, sessionId: string, selected: SelectedSnippet[]): void;
18
- export declare function isTransientGitError(message: string): boolean;
19
- export declare function shouldRetryGitCommand(args: string[]): boolean;
20
- export declare function runBestEffortGit(args: string[], cwd: string): Promise<{
21
- ok: boolean;
22
- output?: string;
23
- error?: string;
24
- }>;
25
- /**
26
- * Files phren is allowed to auto-stage in a team store. Anything not in this
27
- * list (notably `.runtime/`, secrets, build output) is skipped on session-stop
28
- * and `push_changes`.
29
- */
30
- 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"];
31
- /**
32
- * Stage each team pathspec individually so a single no-match (e.g. a store
33
- * with no `truths.md` anywhere) doesn't abort the entire `git add` and strand
34
- * every other change. Errors are swallowed by `runBestEffortGit` already.
35
- *
36
- * Returns the number of pathspecs that staged successfully — useful for
37
- * telemetry, not gating.
38
- */
39
- export declare function addTeamPathspecs(cwd: string): Promise<number>;
40
- export declare function countUnsyncedCommits(cwd: string): Promise<number>;
41
- export declare function isMergeableMarkdown(relPath: string): boolean;
42
- export declare function snapshotLocalMergeableFiles(cwd: string): Promise<Map<string, string>>;
43
- export declare function reconcileMergeableFiles(cwd: string, snapshots: Map<string, string>): Promise<boolean>;
44
- export declare function recoverPushConflict(cwd: string): Promise<{
45
- ok: boolean;
46
- detail: string;
47
- pullStatus: "ok" | "error";
48
- pullDetail: string;
49
- }>;
50
- export declare function resolveSubprocessArgs(command: string): string[] | null;