@phren/cli 0.1.40 → 0.1.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/dist/auth/profiles.js +59 -5
  2. package/dist/cli/actions.js +12 -16
  3. package/dist/cli/config-access.js +8 -1
  4. package/dist/cli/extract.d.ts +27 -1
  5. package/dist/cli/extract.js +244 -9
  6. package/dist/cli/govern.js +6 -87
  7. package/dist/cli/hooks-context.d.ts +1 -1
  8. package/dist/cli/hooks-context.js +1 -1
  9. package/dist/cli/namespaces-review.js +14 -1
  10. package/dist/cli/namespaces-utils.js +1 -1
  11. package/dist/cli/session-git.d.ts +18 -0
  12. package/dist/cli/session-git.js +47 -0
  13. package/dist/cli/session-start.js +2 -2
  14. package/dist/cli/session-stop.d.ts +11 -0
  15. package/dist/cli/session-stop.js +141 -33
  16. package/dist/cli/session-tool-hook.js +17 -5
  17. package/dist/cli-registry.d.ts +1 -1
  18. package/dist/cli-registry.js +1 -0
  19. package/dist/content/archive.js +3 -2
  20. package/dist/content/dedup.d.ts +1 -4
  21. package/dist/content/dedup.js +11 -66
  22. package/dist/content/learning.d.ts +20 -2
  23. package/dist/content/learning.js +26 -7
  24. package/dist/content/quality.d.ts +23 -0
  25. package/dist/content/quality.js +123 -0
  26. package/dist/content/secrets.d.ts +52 -0
  27. package/dist/content/secrets.js +196 -0
  28. package/dist/data/access.d.ts +56 -2
  29. package/dist/data/access.js +255 -32
  30. package/dist/data/tasks.js +46 -6
  31. package/dist/entrypoint.js +5 -1
  32. package/dist/finding/impact.js +170 -43
  33. package/dist/finding/lifecycle.d.ts +19 -2
  34. package/dist/finding/lifecycle.js +18 -5
  35. package/dist/git-worktree.d.ts +19 -0
  36. package/dist/git-worktree.js +117 -0
  37. package/dist/governance/policy.d.ts +84 -4
  38. package/dist/governance/policy.js +213 -17
  39. package/dist/governance/rbac.d.ts +8 -0
  40. package/dist/governance/rbac.js +26 -0
  41. package/dist/hooks.d.ts +20 -0
  42. package/dist/hooks.js +113 -3
  43. package/dist/index.js +5 -1
  44. package/dist/init/guard-globals.d.ts +20 -0
  45. package/dist/init/guard-globals.js +72 -6
  46. package/dist/init/init-configure.js +6 -6
  47. package/dist/init/init.js +10 -6
  48. package/dist/init/setup.d.ts +4 -3
  49. package/dist/init/setup.js +120 -16
  50. package/dist/init/store-gitignore.d.ts +29 -0
  51. package/dist/init/store-gitignore.js +48 -0
  52. package/dist/link/doctor.js +86 -20
  53. package/dist/phren-core.d.ts +35 -8
  54. package/dist/phren-core.js +35 -8
  55. package/dist/phren-paths.d.ts +90 -1
  56. package/dist/phren-paths.js +150 -5
  57. package/dist/proactivity.js +1 -1
  58. package/dist/project-config.js +3 -2
  59. package/dist/project-topics.js +13 -12
  60. package/dist/shared/data-utils.js +13 -3
  61. package/dist/shared/embedding-cache.d.ts +16 -0
  62. package/dist/shared/embedding-cache.js +24 -0
  63. package/dist/shared/fragment-graph.js +10 -0
  64. package/dist/shared/index.d.ts +6 -0
  65. package/dist/shared/index.js +523 -138
  66. package/dist/shared/ollama.d.ts +14 -2
  67. package/dist/shared/ollama.js +84 -5
  68. package/dist/shared/retrieval.d.ts +22 -1
  69. package/dist/shared/retrieval.js +30 -1
  70. package/dist/shared/search-fallback.js +15 -3
  71. package/dist/shared/vector-index.d.ts +20 -1
  72. package/dist/shared/vector-index.js +18 -4
  73. package/dist/shared.d.ts +1 -1
  74. package/dist/shared.js +1 -1
  75. package/dist/status.js +18 -1
  76. package/dist/store-registry.d.ts +22 -0
  77. package/dist/store-registry.js +36 -3
  78. package/dist/store-routing.d.ts +8 -0
  79. package/dist/store-routing.js +23 -1
  80. package/dist/task/lifecycle.js +31 -0
  81. package/dist/tools/config.js +19 -9
  82. package/dist/tools/data.js +1 -1
  83. package/dist/tools/extract-facts.js +3 -2
  84. package/dist/tools/extract.js +2 -2
  85. package/dist/tools/finding.js +20 -8
  86. package/dist/tools/graph.js +9 -1
  87. package/dist/tools/memory.js +1 -1
  88. package/dist/tools/notes.js +3 -3
  89. package/dist/tools/ops.js +19 -18
  90. package/dist/tools/search.js +2 -2
  91. package/dist/tools/session.js +2 -2
  92. package/dist/tools/tasks.js +2 -2
  93. package/dist/tools/types.d.ts +32 -2
  94. package/dist/tools/types.js +41 -8
  95. package/dist/ui/scripts.js +2 -2
  96. package/dist/ui/server.js +7 -6
  97. package/dist/utils-fts.js +3 -2
  98. package/dist/utils-paths.d.ts +1 -0
  99. package/dist/utils-paths.js +1 -1
  100. package/dist/utils.d.ts +1 -1
  101. package/dist/utils.js +1 -1
  102. package/package.json +1 -1
  103. package/dist/cli-hooks-git.d.ts +0 -50
  104. package/dist/cli-hooks-git.js +0 -288
  105. package/starter/my-api/.claude/skills/README.md +0 -7
  106. package/starter/my-api/CLAUDE.md +0 -33
  107. package/starter/my-api/FINDINGS.md +0 -9
  108. package/starter/my-api/summary.md +0 -7
  109. package/starter/my-api/tasks.md +0 -7
  110. package/starter/my-first-project/.claude/skills/README.md +0 -7
  111. package/starter/my-first-project/CLAUDE.md +0 -49
  112. package/starter/my-first-project/FINDINGS.md +0 -24
  113. package/starter/my-first-project/summary.md +0 -11
  114. package/starter/my-first-project/tasks.md +0 -25
  115. package/starter/my-frontend/.claude/skills/README.md +0 -7
  116. package/starter/my-frontend/CLAUDE.md +0 -33
  117. package/starter/my-frontend/FINDINGS.md +0 -9
  118. package/starter/my-frontend/summary.md +0 -7
  119. package/starter/my-frontend/tasks.md +0 -7
@@ -4,14 +4,14 @@
4
4
  import * as fs from "fs";
5
5
  import * as path from "path";
6
6
  import * as yaml from "js-yaml";
7
- import { phrenErr, PhrenError, phrenOk, forwardErr, getProjectDirs, isRecord, } from "../shared.js";
7
+ import { appendAuditLog, phrenErr, PhrenError, phrenOk, forwardErr, getProjectDirs, isRecord, } from "../shared.js";
8
8
  import { normalizeQueueEntryText, } from "../shared/governance.js";
9
9
  import { addFindingToFile, } from "../shared/content.js";
10
- import { isValidProjectName, queueFilePath, safeProjectPath } from "../utils.js";
10
+ import { isValidProjectName, QUEUE_FILENAME, safeProjectPath } from "../utils.js";
11
11
  import { parseCitationComment, parseScopeComment, parseSourceComment, } from "../content/citation.js";
12
12
  import { parseFindingLifecycle, } from "../finding/lifecycle.js";
13
13
  import { METADATA_REGEX, isCitationLine, isArchiveStart, isArchiveEnd, parseFindingId, parseAllContradictions, stripComments, normalizeFindingText, } from "../content/metadata.js";
14
- import { withSafeLock, ensureProject } from "../shared/data-utils.js";
14
+ import { withSafeLock, ensureProject, walkDirectory } from "../shared/data-utils.js";
15
15
  import { getNonPrimaryStores, getStoreProjectDirs } from "../store-registry.js";
16
16
  export { readTasks, readTasksAcrossProjects, resolveTaskItem, addTask, addTasks, completeTasks, completeTask, removeTask, removeTasks, updateTask, linkTaskIssue, pinTask, unpinTask, workNextTask, tidyDoneTasks, taskMarkdown, appendChildFinding, promoteTask, TASKS_FILENAME, TASK_FILE_ALIASES, canonicalTaskFilePath, resolveTaskFilePath, isTaskFileName, } from "./tasks.js";
17
17
  export { addProjectToProfile, listMachines, listProfiles, listProjectCards, removeProjectFromProfile, setMachineProfile, } from "../profile-store.js";
@@ -303,7 +303,7 @@ export function removeFinding(phrenPath, project, match) {
303
303
  if (!ensured.ok)
304
304
  return forwardErr(ensured);
305
305
  const findingsPath = path.resolve(path.join(ensured.data, FINDINGS_FILENAME));
306
- if (!findingsPath.startsWith(phrenPath + path.sep) && findingsPath !== phrenPath) {
306
+ if (!findingsPath.startsWith(path.resolve(ensured.data) + path.sep)) {
307
307
  return phrenErr(`${FINDINGS_FILENAME} path escapes phren store`, PhrenError.VALIDATION_ERROR);
308
308
  }
309
309
  const filePath = findingsPath;
@@ -340,7 +340,7 @@ export function removeFindings(phrenPath, project, matches) {
340
340
  if (!ensured.ok)
341
341
  return forwardErr(ensured);
342
342
  const findingsPath = path.resolve(path.join(ensured.data, FINDINGS_FILENAME));
343
- if (!findingsPath.startsWith(phrenPath + path.sep) && findingsPath !== phrenPath) {
343
+ if (!findingsPath.startsWith(path.resolve(ensured.data) + path.sep)) {
344
344
  return phrenErr(`${FINDINGS_FILENAME} path escapes phren store`, PhrenError.VALIDATION_ERROR);
345
345
  }
346
346
  if (!fs.existsSync(findingsPath))
@@ -394,7 +394,7 @@ export function editFinding(phrenPath, project, oldText, newText) {
394
394
  if (!newTextTrimmed)
395
395
  return phrenErr("New finding text cannot be empty.", PhrenError.EMPTY_INPUT);
396
396
  const findingsPath = path.resolve(path.join(ensured.data, FINDINGS_FILENAME));
397
- if (!findingsPath.startsWith(phrenPath + path.sep) && findingsPath !== phrenPath) {
397
+ if (!findingsPath.startsWith(path.resolve(ensured.data) + path.sep)) {
398
398
  return phrenErr(`${FINDINGS_FILENAME} path escapes phren store`, PhrenError.VALIDATION_ERROR);
399
399
  }
400
400
  if (!fs.existsSync(findingsPath))
@@ -432,15 +432,15 @@ export function editFinding(phrenPath, project, oldText, newText) {
432
432
  return phrenOk(`Updated finding in ${project}`);
433
433
  });
434
434
  }
435
- // Use shared queueFilePath from utils.ts; alias for local brevity.
436
- const queuePath = queueFilePath;
435
+ // Queue paths derive from the store-resolved project dir (ensureProject),
436
+ // so secondary-store projects hit their own store's review.md.
437
+ const queuePath = (projectDir) => path.join(projectDir, QUEUE_FILENAME);
437
438
  function parseQueueLine(line) {
438
439
  const parsed = line.match(/^- \[(\d{4}-\d{2}-\d{2})\]\s*(.+)$/);
439
440
  const rawText = parsed ? parsed[2] : line.replace(/^-\s+/, "").trim();
440
441
  const confidence = rawText.match(/\[confidence\s+([01](?:\.\d+)?)\]/i);
441
442
  const source = parseSourceComment(line);
442
- let machine = source?.machine;
443
- let model = source?.model;
443
+ const citation = parseCitationComment(line);
444
444
  // Strip the confidence marker from the canonical text so it doesn't pollute FINDINGS.md
445
445
  const sanitized = normalizeQueueEntryText(rawText.replace(/\s*\[confidence\s+[01](?:\.\d+)?\]/gi, "").trim(), { truncate: true });
446
446
  const text = sanitized.ok ? sanitized.data.text : "";
@@ -448,15 +448,17 @@ function parseQueueLine(line) {
448
448
  date: parsed?.[1],
449
449
  text,
450
450
  confidence: confidence ? Number.parseFloat(confidence[1]) : undefined,
451
- machine,
452
- model,
451
+ machine: source?.machine,
452
+ model: source?.model,
453
+ provenance: source ?? undefined,
454
+ citation: citation ?? undefined,
453
455
  };
454
456
  }
455
457
  export function readReviewQueue(phrenPath, project) {
456
458
  const ensured = ensureProject(phrenPath, project);
457
459
  if (!ensured.ok)
458
460
  return forwardErr(ensured);
459
- const file = queuePath(phrenPath, project);
461
+ const file = queuePath(ensured.data);
460
462
  if (!fs.existsSync(file))
461
463
  return phrenOk([]);
462
464
  const lines = fs.readFileSync(file, "utf8").split("\n");
@@ -505,7 +507,7 @@ function withQueueLineOp(phrenPath, project, lineText, op) {
505
507
  const ensured = ensureProject(phrenPath, project);
506
508
  if (!ensured.ok)
507
509
  return forwardErr(ensured);
508
- const file = queuePath(phrenPath, project);
510
+ const file = queuePath(ensured.data);
509
511
  if (!fs.existsSync(file))
510
512
  return phrenErr(`No review queue found for "${project}".`, PhrenError.FILE_NOT_FOUND);
511
513
  return withSafeLock(file, () => {
@@ -522,31 +524,252 @@ function writeQueueLines(file, lines) {
522
524
  fs.writeFileSync(tmp, content);
523
525
  fs.renameSync(tmp, file);
524
526
  }
525
- /** Remove a queue item's line from review.md (finding stays in FINDINGS.md). */
526
- export function approveQueueItem(phrenPath, project, lineText) {
527
+ /**
528
+ * Read-only lookup of a queue line. Returns the *stored* line (not the caller's
529
+ * approximation of it) so callers can read metadata comments the caller never had.
530
+ *
531
+ * Approve and reject both resolve the line first, act on FINDINGS.md second, and
532
+ * dequeue last. Dequeuing first — the old order — meant a failed content operation
533
+ * still destroyed the queue entry, which is how "approve" became a silent discard.
534
+ */
535
+ function locateQueueLine(phrenPath, project, lineText) {
536
+ const ensured = ensureProject(phrenPath, project);
537
+ if (!ensured.ok)
538
+ return forwardErr(ensured);
539
+ const file = queuePath(ensured.data);
540
+ if (!fs.existsSync(file))
541
+ return phrenErr(`No review queue found for "${project}".`, PhrenError.FILE_NOT_FOUND);
542
+ const lines = fs.readFileSync(file, "utf8").split("\n");
543
+ const idx = lines.findIndex((l) => l.trim() === lineText.trim());
544
+ if (idx === -1)
545
+ return phrenErr(`Queue item not found in "${project}".`, PhrenError.NOT_FOUND);
546
+ return phrenOk(lines[idx]);
547
+ }
548
+ /** Drop a queue line from review.md. */
549
+ function dequeueLine(phrenPath, project, lineText) {
527
550
  return withQueueLineOp(phrenPath, project, lineText, (lines, idx, file) => {
528
551
  lines.splice(idx, 1);
529
552
  writeQueueLines(file, lines);
530
- return phrenOk(`Approved queue item in ${project}`);
553
+ return phrenOk(undefined);
531
554
  });
532
555
  }
533
- /** Remove a queue item from review.md AND remove the corresponding finding from FINDINGS.md. */
534
- export function rejectQueueItem(phrenPath, project, lineText) {
535
- const lockResult = withQueueLineOp(phrenPath, project, lineText, (lines, idx, file) => {
536
- lines.splice(idx, 1);
537
- writeQueueLines(file, lines);
538
- return phrenOk("ok");
539
- });
540
- if (!lockResult.ok)
541
- return lockResult;
542
- const parsed = parseQueueLine(lineText);
543
- if (parsed.text) {
544
- const removeResult = removeFinding(phrenPath, project, parsed.text);
545
- if (!removeResult.ok) {
546
- return phrenOk(`Rejected queue item from ${project} (note: finding not found in FINDINGS.md — may have already been removed)`);
556
+ /** Does this text already exist as a live (non-archived) bullet in FINDINGS.md? */
557
+ function existsAsLiveFinding(phrenPath, project, text) {
558
+ const dir = safeProjectPath(phrenPath, project);
559
+ if (!dir)
560
+ return false;
561
+ const findingsPath = path.join(dir, FINDINGS_FILENAME);
562
+ if (!fs.existsSync(findingsPath))
563
+ return false;
564
+ const lines = fs.readFileSync(findingsPath, "utf8").split("\n");
565
+ const active = collectFindingBulletLines(lines).filter(({ archived }) => !archived);
566
+ const match = findMatchingFindingBullet(active, normalizeFindingText(text), text);
567
+ // "ambiguous" means several bullets matched — it is still present, just not uniquely
568
+ // addressable, so approve must not write yet another copy.
569
+ return match.kind === "found" || match.kind === "ambiguous";
570
+ }
571
+ /**
572
+ * Find a queue item's content in the project's `reference/` tier.
573
+ *
574
+ * `autoArchiveToReference` moves findings out of FINDINGS.md into
575
+ * `reference/topics/*.md` once a project exceeds the findings cap, without touching
576
+ * the review queue lines that point at them. Those queue items are the reason
577
+ * approve and reject used to be no-ops, so both verbs have to look here.
578
+ */
579
+ function findArchivedReferenceMatches(phrenPath, project, text) {
580
+ const referenceDir = safeProjectPath(phrenPath, project, "reference");
581
+ if (!referenceDir || !fs.existsSync(referenceDir))
582
+ return [];
583
+ const needle = normalizeFindingText(text);
584
+ if (!needle)
585
+ return [];
586
+ const topicsDir = path.join(referenceDir, "topics") + path.sep;
587
+ const exact = [];
588
+ const partial = [];
589
+ for (const filePath of walkDirectory(referenceDir)) {
590
+ const lines = fs.readFileSync(filePath, "utf8").split("\n");
591
+ for (let i = 0; i < lines.length; i++) {
592
+ if (!lines[i].startsWith("- "))
593
+ continue;
594
+ const normalized = normalizeFindingText(lines[i]);
595
+ if (!normalized)
596
+ continue;
597
+ const hit = {
598
+ file: filePath,
599
+ autoArchived: filePath.startsWith(topicsDir),
600
+ idx: i,
601
+ line: lines[i],
602
+ };
603
+ if (normalized === needle)
604
+ exact.push(hit);
605
+ else if (normalized.includes(needle))
606
+ partial.push(hit);
547
607
  }
548
608
  }
549
- return phrenOk(`Rejected and removed queue item from ${project}`);
609
+ return exact.length > 0 ? exact : partial;
610
+ }
611
+ /** Bullet content of archived matches, ignoring metadata — used to detect true ambiguity. */
612
+ function archivedMatchesAreIdentical(matches) {
613
+ const first = bulletContentKey(matches[0].line);
614
+ return matches.every(({ line }) => bulletContentKey(line) === first);
615
+ }
616
+ /**
617
+ * Approve a queue item: make it real, then dequeue.
618
+ *
619
+ * Three outcomes, because a queue line can point at three different realities:
620
+ *
621
+ * - `promoted` — the text is not in FINDINGS.md, so approving *writes* it. This is the
622
+ * case for every extraction candidate that scored below `autoAcceptThreshold`:
623
+ * extraction queues those without ever adding them, so the old "just splice the line
624
+ * out" behaviour silently discarded them. Promotion goes through `addFindingToFile`,
625
+ * the same path a direct add uses, so dedup, fid assignment, citation metadata, and
626
+ * the findings-cap auto-archive all behave identically.
627
+ * - `already_present` — the text is already a live finding (govern queues existing
628
+ * findings for Stale/Conflicts review). Approving means "keep it"; just dequeue.
629
+ * - `already_archived` — the content only exists in `reference/topics/`, because
630
+ * auto-archive moved it after it was queued. It is still live for retrieval, so the
631
+ * archive is left untouched and the item is dequeued.
632
+ */
633
+ export function approveQueueItemDetailed(phrenPath, project, lineText) {
634
+ const located = locateQueueLine(phrenPath, project, lineText);
635
+ if (!located.ok)
636
+ return forwardErr(located);
637
+ const parsed = parseQueueLine(located.data);
638
+ const text = parsed.text;
639
+ if (!text) {
640
+ // Nothing usable to promote — dequeue so the malformed line stops blocking the queue.
641
+ const dequeued = dequeueLine(phrenPath, project, lineText);
642
+ if (!dequeued.ok)
643
+ return forwardErr(dequeued);
644
+ appendAuditLog(phrenPath, "review_approve", `project=${project} outcome=empty`);
645
+ return phrenOk({
646
+ outcome: "already_present",
647
+ message: `Approved queue item in ${project} (empty entry, nothing to promote)`,
648
+ text: "",
649
+ });
650
+ }
651
+ const finish = (outcome, message) => {
652
+ const dequeued = dequeueLine(phrenPath, project, lineText);
653
+ if (!dequeued.ok)
654
+ return forwardErr(dequeued);
655
+ appendAuditLog(phrenPath, "review_approve", `project=${project} outcome=${outcome}`);
656
+ return phrenOk({ outcome, message, text });
657
+ };
658
+ if (existsAsLiveFinding(phrenPath, project, text)) {
659
+ return finish("already_present", `Approved queue item in ${project} (already in ${FINDINGS_FILENAME}; kept as-is)`);
660
+ }
661
+ const archived = findArchivedReferenceMatches(phrenPath, project, text);
662
+ if (archived.length > 0) {
663
+ return finish("already_archived", `Approved queue item in ${project} (already archived to ${path.basename(archived[0].file)}; still available for retrieval, archive left untouched)`);
664
+ }
665
+ // Not anywhere: this queue line IS the only copy. Write it as a finding, preserving
666
+ // the entry's type tag (carried in the text) and its capture provenance.
667
+ const citationInput = parsed.citation
668
+ ? {
669
+ ...(parsed.citation.repo ? { repo: parsed.citation.repo } : {}),
670
+ ...(parsed.citation.file ? { file: parsed.citation.file } : {}),
671
+ ...(parsed.citation.line !== undefined ? { line: parsed.citation.line } : {}),
672
+ ...(parsed.citation.commit ? { commit: parsed.citation.commit } : {}),
673
+ }
674
+ : undefined;
675
+ // The queue entry's own date is the day the observation was captured; the finding is
676
+ // written today, so keep the original date as an explicit annotation rather than
677
+ // losing it.
678
+ const extraAnnotations = parsed.date ? [`<!-- phren:queued "${parsed.date}" -->`] : undefined;
679
+ const added = addFindingToFile(phrenPath, project, text, citationInput, {
680
+ ...(parsed.provenance ? { provenance: parsed.provenance } : {}),
681
+ ...(parsed.provenance?.session_id ? { sessionId: parsed.provenance.session_id } : {}),
682
+ ...(extraAnnotations ? { extraAnnotations } : {}),
683
+ });
684
+ if (!added.ok)
685
+ return forwardErr(added);
686
+ // A fuzzy-dedup skip means an equivalent finding already exists — the item is
687
+ // effectively already present, not newly promoted.
688
+ if (added.data.status === "skipped") {
689
+ return finish("already_present", `Approved queue item in ${project} (equivalent finding already in ${FINDINGS_FILENAME}; not duplicated)`);
690
+ }
691
+ return finish("promoted", `Approved and promoted queue item to ${FINDINGS_FILENAME} in ${project}`);
692
+ }
693
+ /** Remove a queue item's line from review.md, promoting it to a finding when needed. */
694
+ export function approveQueueItem(phrenPath, project, lineText) {
695
+ const result = approveQueueItemDetailed(phrenPath, project, lineText);
696
+ return result.ok ? phrenOk(result.data.message) : result;
697
+ }
698
+ /**
699
+ * Reject a queue item: destroy the content wherever it actually lives, then dequeue.
700
+ *
701
+ * Rejection removes from the live FINDINGS.md tier *and* from `reference/topics/*.md`,
702
+ * because auto-archive moves findings there without reconciling their queue lines and
703
+ * archived content is still injected into agent prompts. Leaving it would make reject a
704
+ * lie — the hosts tell users rejection removes the finding permanently.
705
+ *
706
+ * Two situations deliberately do NOT succeed quietly:
707
+ * - the content sits in a FINDINGS.md archive block (`<details>` / `phren:archive`),
708
+ * which the rest of the codebase treats as read-only history; and
709
+ * - several *different* bullets match, so deleting one would be a guess.
710
+ *
711
+ * Both return an error and leave the queue line in place, so the user sees the problem
712
+ * instead of a success message over undeleted content.
713
+ */
714
+ export function rejectQueueItemDetailed(phrenPath, project, lineText) {
715
+ const located = locateQueueLine(phrenPath, project, lineText);
716
+ if (!located.ok)
717
+ return forwardErr(located);
718
+ const parsed = parseQueueLine(located.data);
719
+ const text = parsed.text;
720
+ const finish = (outcome, message) => {
721
+ const dequeued = dequeueLine(phrenPath, project, lineText);
722
+ if (!dequeued.ok)
723
+ return forwardErr(dequeued);
724
+ appendAuditLog(phrenPath, "review_reject", `project=${project} outcome=${outcome}`);
725
+ return phrenOk({ outcome, message, text });
726
+ };
727
+ if (!text)
728
+ return finish("discarded", `Rejected queue item from ${project} (empty entry)`);
729
+ const removed = removeFinding(phrenPath, project, text);
730
+ if (removed.ok) {
731
+ return finish("removed", `Rejected and removed finding from ${FINDINGS_FILENAME} in ${project}`);
732
+ }
733
+ // Anything other than "it isn't there" is a real problem — an ambiguous match, a
734
+ // read-only FINDINGS.md archive block, a lock timeout. Surface it and keep the queue
735
+ // line so the user can act on it, rather than reporting success over live content.
736
+ if (removed.code !== PhrenError.NOT_FOUND && removed.code !== PhrenError.FILE_NOT_FOUND) {
737
+ return forwardErr(removed);
738
+ }
739
+ const matches = findArchivedReferenceMatches(phrenPath, project, text);
740
+ if (matches.length === 0) {
741
+ return finish("discarded", `Rejected and discarded queue item from ${project} (candidate was never added to ${FINDINGS_FILENAME}; nothing to remove)`);
742
+ }
743
+ const external = matches.filter((match) => !match.autoArchived);
744
+ if (external.length > 0) {
745
+ return phrenErr(`Cannot reject: "${text.slice(0, 60)}" lives in ${path.relative(phrenPath, external[0].file)}, which phren does not auto-manage. Remove it there, then reject again.`, PhrenError.VALIDATION_ERROR);
746
+ }
747
+ if (matches.length > 1 && !archivedMatchesAreIdentical(matches)) {
748
+ return phrenErr(`Cannot reject: "${text.slice(0, 60)}" matches ${matches.length} different archived entries. Remove the right one manually, then reject again.`, PhrenError.AMBIGUOUS_MATCH);
749
+ }
750
+ const target = matches[0];
751
+ const purge = withSafeLock(target.file, () => {
752
+ const lines = fs.readFileSync(target.file, "utf8").split("\n");
753
+ // Re-resolve under the lock — the file may have moved since the scan.
754
+ const idx = lines[target.idx] === target.line ? target.idx : lines.indexOf(target.line);
755
+ if (idx === -1)
756
+ return phrenErr(`Archived entry vanished from ${path.basename(target.file)} before it could be removed.`, PhrenError.NOT_FOUND);
757
+ const removeCount = isCitationLine(lines[idx + 1] || "") ? 2 : 1;
758
+ lines.splice(idx, removeCount);
759
+ const normalized = lines.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
760
+ const tmp = `${target.file}.tmp.${process.pid}`;
761
+ fs.writeFileSync(tmp, normalized);
762
+ fs.renameSync(tmp, target.file);
763
+ return phrenOk(undefined);
764
+ });
765
+ if (!purge.ok)
766
+ return forwardErr(purge);
767
+ return finish("removed_from_archive", `Rejected and removed archived finding from reference/topics/${path.basename(target.file)} in ${project}`);
768
+ }
769
+ /** Remove a queue item from review.md AND the corresponding finding wherever it lives. */
770
+ export function rejectQueueItem(phrenPath, project, lineText) {
771
+ const result = rejectQueueItemDetailed(phrenPath, project, lineText);
772
+ return result.ok ? phrenOk(result.data.message) : result;
550
773
  }
551
774
  /** Edit a queue item's text in review.md and the corresponding finding in FINDINGS.md. */
552
775
  export function editQueueItem(phrenPath, project, lineText, newText) {
@@ -3,9 +3,9 @@ import * as path from "path";
3
3
  import { randomBytes, randomUUID } from "crypto";
4
4
  import { phrenErr, PhrenError, phrenOk, forwardErr, getProjectDirs, } from "../shared.js";
5
5
  import { validateTaskFormat } from "../shared/content.js";
6
- import { safeProjectPath } from "../utils.js";
7
6
  import { withSafeLock, ensureProject } from "../shared/data-utils.js";
8
7
  import { getNonPrimaryStores, getStoreProjectDirs } from "../store-registry.js";
8
+ import { storeAwareProjectPath } from "../store-routing.js";
9
9
  const ACTIVE_HEADINGS = new Set(["active", "in progress", "in-progress", "current", "wip"]);
10
10
  const QUEUE_HEADINGS = new Set(["queue", "queued", "task", "todo", "upcoming", "next"]);
11
11
  const DONE_HEADINGS = new Set(["done", "completed", "finished", "archived"]);
@@ -166,10 +166,9 @@ export function applyGravity(items) {
166
166
  });
167
167
  }
168
168
  export function canonicalTaskFilePath(phrenPath, project) {
169
- const resolved = safeProjectPath(phrenPath, project);
170
- if (!resolved)
171
- return null;
172
- return path.join(resolved, TASKS_FILENAME);
169
+ // Store-aware: locks and writes must target the owning store's file, not a
170
+ // phantom primary-store path.
171
+ return storeAwareProjectPath(phrenPath, project, TASKS_FILENAME);
173
172
  }
174
173
  export function isTaskFileName(filename) {
175
174
  return filename.toLowerCase() === TASKS_FILENAME;
@@ -480,6 +479,9 @@ export function completeTasks(phrenPath, project, matches) {
480
479
  const bPath = canonicalTaskFilePath(phrenPath, project);
481
480
  if (!bPath)
482
481
  return phrenErr(`Project name "${project}" is not valid.`, PhrenError.INVALID_PROJECT_NAME);
482
+ const preCheck = ensureProject(phrenPath, project);
483
+ if (!preCheck.ok)
484
+ return forwardErr(preCheck);
483
485
  return withSafeLock(bPath, () => {
484
486
  const parsed = readTasks(phrenPath, project);
485
487
  if (!parsed.ok)
@@ -506,6 +508,9 @@ export function completeTask(phrenPath, project, match) {
506
508
  const bPath = canonicalTaskFilePath(phrenPath, project);
507
509
  if (!bPath)
508
510
  return phrenErr(`Project name "${project}" is not valid.`, PhrenError.INVALID_PROJECT_NAME);
511
+ const preCheck = ensureProject(phrenPath, project);
512
+ if (!preCheck.ok)
513
+ return forwardErr(preCheck);
509
514
  return withSafeLock(bPath, () => {
510
515
  const parsed = readTasks(phrenPath, project);
511
516
  if (!parsed.ok)
@@ -527,6 +532,9 @@ export function removeTask(phrenPath, project, match) {
527
532
  const bPath = canonicalTaskFilePath(phrenPath, project);
528
533
  if (!bPath)
529
534
  return phrenErr(`Project name "${project}" is not valid.`, PhrenError.INVALID_PROJECT_NAME);
535
+ const preCheck = ensureProject(phrenPath, project);
536
+ if (!preCheck.ok)
537
+ return forwardErr(preCheck);
530
538
  return withSafeLock(bPath, () => {
531
539
  const parsed = readTasks(phrenPath, project);
532
540
  if (!parsed.ok)
@@ -545,6 +553,9 @@ export function removeTasks(phrenPath, project, matches) {
545
553
  const bPath = canonicalTaskFilePath(phrenPath, project);
546
554
  if (!bPath)
547
555
  return phrenErr(`Project name "${project}" is not valid.`, PhrenError.INVALID_PROJECT_NAME);
556
+ const preCheck = ensureProject(phrenPath, project);
557
+ if (!preCheck.ok)
558
+ return forwardErr(preCheck);
548
559
  return withSafeLock(bPath, () => {
549
560
  const parsed = readTasks(phrenPath, project);
550
561
  if (!parsed.ok)
@@ -568,6 +579,9 @@ export function updateTask(phrenPath, project, match, updates) {
568
579
  const bPath = canonicalTaskFilePath(phrenPath, project);
569
580
  if (!bPath)
570
581
  return phrenErr(`Project name "${project}" is not valid.`, PhrenError.INVALID_PROJECT_NAME);
582
+ const preCheck = ensureProject(phrenPath, project);
583
+ if (!preCheck.ok)
584
+ return forwardErr(preCheck);
571
585
  return withSafeLock(bPath, () => {
572
586
  const parsed = readTasks(phrenPath, project);
573
587
  if (!parsed.ok)
@@ -648,6 +662,9 @@ export function pinTask(phrenPath, project, match) {
648
662
  const bPath = canonicalTaskFilePath(phrenPath, project);
649
663
  if (!bPath)
650
664
  return phrenErr(`Project name "${project}" is not valid.`, PhrenError.INVALID_PROJECT_NAME);
665
+ const preCheck = ensureProject(phrenPath, project);
666
+ if (!preCheck.ok)
667
+ return forwardErr(preCheck);
651
668
  return withSafeLock(bPath, () => {
652
669
  const parsed = readTasks(phrenPath, project);
653
670
  if (!parsed.ok)
@@ -673,6 +690,9 @@ export function unpinTask(phrenPath, project, match) {
673
690
  const bPath = canonicalTaskFilePath(phrenPath, project);
674
691
  if (!bPath)
675
692
  return phrenErr(`Project name "${project}" is not valid.`, PhrenError.INVALID_PROJECT_NAME);
693
+ const preCheck = ensureProject(phrenPath, project);
694
+ if (!preCheck.ok)
695
+ return forwardErr(preCheck);
676
696
  return withSafeLock(bPath, () => {
677
697
  const parsed = readTasks(phrenPath, project);
678
698
  if (!parsed.ok)
@@ -695,6 +715,9 @@ export function reorderTask(phrenPath, project, match, targetRank) {
695
715
  const bPath = canonicalTaskFilePath(phrenPath, project);
696
716
  if (!bPath)
697
717
  return phrenErr(`Project name "${project}" is not valid.`, PhrenError.INVALID_PROJECT_NAME);
718
+ const preCheck = ensureProject(phrenPath, project);
719
+ if (!preCheck.ok)
720
+ return forwardErr(preCheck);
698
721
  return withSafeLock(bPath, () => {
699
722
  const parsed = readTasks(phrenPath, project);
700
723
  if (!parsed.ok)
@@ -732,6 +755,9 @@ export function appendChildFinding(phrenPath, project, match, findingId) {
732
755
  const bPath = canonicalTaskFilePath(phrenPath, project);
733
756
  if (!bPath)
734
757
  return phrenErr(`Project name "${project}" is not valid.`, PhrenError.INVALID_PROJECT_NAME);
758
+ const preCheck = ensureProject(phrenPath, project);
759
+ if (!preCheck.ok)
760
+ return forwardErr(preCheck);
735
761
  return withSafeLock(bPath, () => {
736
762
  const parsed = readTasks(phrenPath, project);
737
763
  if (!parsed.ok)
@@ -752,6 +778,9 @@ export function promoteTask(phrenPath, project, match, moveToActive) {
752
778
  const bPath = canonicalTaskFilePath(phrenPath, project);
753
779
  if (!bPath)
754
780
  return phrenErr(`Project name "${project}" is not valid.`, PhrenError.INVALID_PROJECT_NAME);
781
+ const preCheck = ensureProject(phrenPath, project);
782
+ if (!preCheck.ok)
783
+ return forwardErr(preCheck);
755
784
  return withSafeLock(bPath, () => {
756
785
  const parsed = readTasks(phrenPath, project);
757
786
  if (!parsed.ok)
@@ -777,6 +806,9 @@ export function workNextTask(phrenPath, project) {
777
806
  const bPath = canonicalTaskFilePath(phrenPath, project);
778
807
  if (!bPath)
779
808
  return phrenErr(`Project name "${project}" is not valid.`, PhrenError.INVALID_PROJECT_NAME);
809
+ const preCheck = ensureProject(phrenPath, project);
810
+ if (!preCheck.ok)
811
+ return forwardErr(preCheck);
780
812
  return withSafeLock(bPath, () => {
781
813
  const parsed = readTasks(phrenPath, project);
782
814
  if (!parsed.ok)
@@ -802,6 +834,9 @@ export function tidyDoneTasks(phrenPath, project, keep = 30, dryRun) {
802
834
  const bPath = canonicalTaskFilePath(phrenPath, project);
803
835
  if (!bPath)
804
836
  return phrenErr(`Project name "${project}" is not valid.`, PhrenError.INVALID_PROJECT_NAME);
837
+ const preCheck = ensureProject(phrenPath, project);
838
+ if (!preCheck.ok)
839
+ return forwardErr(preCheck);
805
840
  return withSafeLock(bPath, () => {
806
841
  const parsed = readTasks(phrenPath, project);
807
842
  if (!parsed.ok)
@@ -815,7 +850,9 @@ export function tidyDoneTasks(phrenPath, project, keep = 30, dryRun) {
815
850
  return phrenOk(`[dry-run] Would archive ${archived.length} done item(s) for ${project}, keeping ${safeKeep}.`);
816
851
  }
817
852
  parsed.data.items.Done = parsed.data.items.Done.slice(0, safeKeep);
818
- const archiveFile = taskArchivePath(phrenPath, project);
853
+ // Archive into the store that owns the tasks file (bPath = <store>/<project>/tasks.md),
854
+ // so secondary-store task history never lands in the primary store's .config.
855
+ const archiveFile = taskArchivePath(path.dirname(path.dirname(bPath)), project);
819
856
  fs.mkdirSync(path.dirname(archiveFile), { recursive: true });
820
857
  const stamp = new Date().toISOString();
821
858
  const lines = archived.map((item) => `- [x] ${item.line}${item.context ? `\n Context: ${item.context}` : ""}`);
@@ -835,6 +872,9 @@ export function linkTaskIssue(phrenPath, project, match, link) {
835
872
  const bPath = canonicalTaskFilePath(phrenPath, project);
836
873
  if (!bPath)
837
874
  return phrenErr(`Project name "${project}" is not valid.`, PhrenError.INVALID_PROJECT_NAME);
875
+ const preCheck = ensureProject(phrenPath, project);
876
+ if (!preCheck.ok)
877
+ return forwardErr(preCheck);
838
878
  return withSafeLock(bPath, () => {
839
879
  const parsed = readTasks(phrenPath, project);
840
880
  if (!parsed.ok)
@@ -2,7 +2,7 @@ import * as fs from "fs";
2
2
  import * as path from "path";
3
3
  import { errorMessage } from "./utils.js";
4
4
  import { logger } from "./logger.js";
5
- import { defaultPhrenPath, expandHomePath, getPhrenPath, readRootManifest, } from "./shared.js";
5
+ import { defaultPhrenPath, ensureFtsCacheRootPrivate, expandHomePath, getPhrenPath, readRootManifest, } from "./shared.js";
6
6
  import { resolveRuntimeProfile } from "./runtime-profile.js";
7
7
  import { VERSION } from "./package-metadata.js";
8
8
  import { TOPIC_ORDER, helpTopicNames, lookupCommand, } from "./cli-registry.js";
@@ -127,6 +127,10 @@ export async function runTopLevelCommand(argv, opts = {}) {
127
127
  const cmd = lookupCommand(argvCommand);
128
128
  if (!cmd)
129
129
  return false;
130
+ // Any command can end up building or reading the FTS snapshot cache, which
131
+ // is a SQLite export of the whole store landing in os.tmpdir() — /tmp (1777)
132
+ // on Linux and WSL. Harden the per-user cache root before the command runs.
133
+ ensureFtsCacheRootPrivate();
130
134
  // Intercept before any handler runs - in particular before namespace
131
135
  // handlers that used to print their own per-subcommand help text.
132
136
  if (argv.includes("--help") || argv.includes("-h")) {