@phren/cli 0.3.70 → 0.3.72

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 (108) hide show
  1. package/dist/bridge/browser-env.d.ts +5 -0
  2. package/dist/bridge/browser-env.js +86 -0
  3. package/dist/bridge/browser-protocol.d.ts +120 -0
  4. package/dist/bridge/browser-protocol.js +70 -0
  5. package/dist/bridge/browser-recordings.d.ts +63 -0
  6. package/dist/bridge/browser-recordings.js +148 -0
  7. package/dist/bridge/browser-registry.d.ts +64 -0
  8. package/dist/bridge/browser-registry.js +262 -0
  9. package/dist/bridge/browser-routes.d.ts +4 -0
  10. package/dist/bridge/browser-routes.js +39 -0
  11. package/dist/bridge/browser-shim/phren-playwright.cjs +184 -0
  12. package/dist/bridge/browser-socket.d.ts +2 -0
  13. package/dist/bridge/browser-socket.js +10 -0
  14. package/dist/bridge/browser-stream.d.ts +3 -0
  15. package/dist/bridge/browser-stream.js +129 -0
  16. package/dist/bridge/claude-question-dialog.js +32 -7
  17. package/dist/bridge/dispatch.d.ts +10 -0
  18. package/dist/bridge/dispatch.js +3 -1
  19. package/dist/bridge/dream-schedule.d.ts +133 -0
  20. package/dist/bridge/dream-schedule.js +322 -0
  21. package/dist/bridge/herdr.js +15 -6
  22. package/dist/bridge/install.js +4 -0
  23. package/dist/bridge/launch-brief.d.ts +11 -0
  24. package/dist/bridge/launch-brief.js +22 -0
  25. package/dist/bridge/pane-status.js +1 -1
  26. package/dist/bridge/server-routes.d.ts +3 -0
  27. package/dist/bridge/server-routes.js +15 -15
  28. package/dist/bridge/server-stream.d.ts +4 -0
  29. package/dist/bridge/server-stream.js +24 -5
  30. package/dist/bridge/server.js +23 -3
  31. package/dist/bridge/session-move.d.ts +10 -4
  32. package/dist/bridge/session-move.js +65 -34
  33. package/dist/bridge/simulator-stream.d.ts +2 -0
  34. package/dist/bridge/simulator-stream.js +2 -0
  35. package/dist/bridge/tab-activity.d.ts +2 -0
  36. package/dist/bridge/tab-activity.js +15 -2
  37. package/dist/bridge/task-routes.d.ts +20 -16
  38. package/dist/bridge/task-routes.js +1 -1
  39. package/dist/bridge/terminal-herdr.js +2 -1
  40. package/dist/bridge/terminal-tmux.js +2 -1
  41. package/dist/bridge/worker-reports.js +15 -3
  42. package/dist/bridge-hook.mjs +36819 -35219
  43. package/dist/capabilities/mcp.js +1 -1
  44. package/dist/cli/config-dreaming.d.ts +7 -0
  45. package/dist/cli/config-dreaming.js +72 -0
  46. package/dist/cli/config.js +6 -0
  47. package/dist/cli/dream.d.ts +59 -0
  48. package/dist/cli/dream.js +315 -0
  49. package/dist/cli/namespaces-tasks.js +14 -0
  50. package/dist/cli-registry.js +24 -1
  51. package/dist/config/dreaming.d.ts +82 -0
  52. package/dist/config/dreaming.js +195 -0
  53. package/dist/config/resolve.js +11 -0
  54. package/dist/config/schema.d.ts +4 -4
  55. package/dist/config/schema.js +157 -1
  56. package/dist/content/citation-freshness.js +6 -0
  57. package/dist/content/learning.d.ts +1 -0
  58. package/dist/content/learning.js +2 -0
  59. package/dist/data/access.d.ts +1 -1
  60. package/dist/data/access.js +3 -1
  61. package/dist/data/task-contract.d.ts +5 -4
  62. package/dist/data/tasks.d.ts +5 -0
  63. package/dist/data/tasks.js +28 -2
  64. package/dist/dream/apply.d.ts +69 -0
  65. package/dist/dream/apply.js +372 -0
  66. package/dist/dream/budget.d.ts +78 -0
  67. package/dist/dream/budget.js +180 -0
  68. package/dist/dream/collect.d.ts +86 -0
  69. package/dist/dream/collect.js +449 -0
  70. package/dist/dream/eval/dream-adapter.d.ts +16 -0
  71. package/dist/dream/eval/dream-adapter.js +21 -0
  72. package/dist/dream/eval/fixture.d.ts +53 -0
  73. package/dist/dream/eval/fixture.js +172 -0
  74. package/dist/dream/eval/index.d.ts +40 -0
  75. package/dist/dream/eval/index.js +78 -0
  76. package/dist/dream/eval/score.d.ts +34 -0
  77. package/dist/dream/eval/score.js +99 -0
  78. package/dist/dream/eval/scripted-model.d.ts +19 -0
  79. package/dist/dream/eval/scripted-model.js +70 -0
  80. package/dist/dream/pages.d.ts +68 -0
  81. package/dist/dream/pages.js +220 -0
  82. package/dist/dream/privacy.d.ts +3 -0
  83. package/dist/dream/privacy.js +18 -0
  84. package/dist/dream/prompt.d.ts +13 -0
  85. package/dist/dream/prompt.js +84 -0
  86. package/dist/dream/run.d.ts +98 -0
  87. package/dist/dream/run.js +317 -0
  88. package/dist/dream/types.d.ts +74 -0
  89. package/dist/dream/types.js +4 -0
  90. package/dist/finding/lifecycle.d.ts +2 -2
  91. package/dist/finding/lifecycle.js +5 -2
  92. package/dist/finding/versions.d.ts +4 -0
  93. package/dist/finding/versions.js +28 -0
  94. package/dist/index.js +1 -0
  95. package/dist/modules/registry.js +9 -7
  96. package/dist/project-config.d.ts +3 -0
  97. package/dist/task/merge-links.d.ts +38 -0
  98. package/dist/task/merge-links.js +45 -0
  99. package/dist/task/reconcile.d.ts +39 -0
  100. package/dist/task/reconcile.js +201 -0
  101. package/dist/task/report-links.d.ts +10 -0
  102. package/dist/task/report-links.js +47 -0
  103. package/dist/tools/config.js +46 -4
  104. package/dist/tools/dispatch.js +2 -1
  105. package/dist/tools/dream.d.ts +3 -0
  106. package/dist/tools/dream.js +123 -0
  107. package/dist/tools/tasks.js +4 -1
  108. package/package.json +1 -1
@@ -1,3 +1,4 @@
1
+ import { taskLinksSchema } from "../task/merge-links.js";
1
2
  import { parseTaskMetadata } from "./task-metadata.js";
2
3
  import { taskFormatStatus, taskFormatMigrationHint } from "./task-format.js";
3
4
  import { moduleEnabled } from "../modules/runtime.js";
@@ -91,6 +92,7 @@ function parseContinuation(lines, idx) {
91
92
  const taskContractLines = [];
92
93
  const opaqueContinuationLines = [];
93
94
  let context;
95
+ let links;
94
96
  let claim;
95
97
  let githubIssue;
96
98
  let githubUrl;
@@ -110,6 +112,18 @@ function parseContinuation(lines, idx) {
110
112
  linesToSkip++;
111
113
  continue;
112
114
  }
115
+ if (trimmed.startsWith("Links:")) {
116
+ // Duplicate or unsupported records stay opaque and block reconciliation.
117
+ try {
118
+ const parsed = taskLinksSchema.safeParse(JSON.parse(trimmed.slice(6).trim()));
119
+ if (parsed.success && !links) {
120
+ links = parsed.data;
121
+ linesToSkip++;
122
+ continue;
123
+ }
124
+ }
125
+ catch { /* Preserve unknown metadata verbatim. */ }
126
+ }
113
127
  if (trimmed.startsWith("Context:")) {
114
128
  context = trimmed.slice("Context:".length).trim();
115
129
  linesToSkip++;
@@ -138,7 +152,7 @@ function parseContinuation(lines, idx) {
138
152
  }
139
153
  else if (taskContractRecords.length > 1)
140
154
  taskContractRaw = taskContractRecords[0];
141
- return { context, githubIssue, githubUrl, claim, contract, taskContractRaw,
155
+ return { context, links, githubIssue, githubUrl, claim, contract, taskContractRaw,
142
156
  ...(taskContractRaw !== undefined ? { taskContractLines } : {}),
143
157
  ...(taskContractRecords.length > 1 ? { taskContractRecords } : {}),
144
158
  ...(opaqueContinuationLines.length ? { opaqueContinuationLines } : {}), linesToSkip };
@@ -287,6 +301,7 @@ export function parseTaskContent(project, taskPath, content) {
287
301
  parentFinding,
288
302
  speculative,
289
303
  context: continuation.context,
304
+ links: continuation.links,
290
305
  pinned: pinned || undefined,
291
306
  githubIssue: continuation.githubIssue,
292
307
  githubUrl: continuation.githubUrl,
@@ -328,6 +343,8 @@ function renderTask(doc) {
328
343
  out.push(` Task: ${item.taskContractRaw}`);
329
344
  else if (item.responsibility !== undefined || item.dependencies?.length || item.history?.length)
330
345
  out.push(` Task: ${JSON.stringify({ version: 1, responsibility: item.responsibility ?? "agent", dependencies: item.dependencies ?? [], history: item.history ?? [] })}`);
346
+ if (item.links)
347
+ out.push(` Links: ${JSON.stringify(item.links)}`);
331
348
  if (item.context)
332
349
  out.push(` Context: ${item.context}`);
333
350
  const githubRef = formatGitHubIssueReference(item);
@@ -721,11 +738,20 @@ export function updateTask(phrenPath, project, match, updates, graphRoot = phren
721
738
  if (!found.match)
722
739
  return taskItemNotFound(project, match);
723
740
  const item = parsed.data.items[found.match.section][found.match.index];
724
- if (expectedRevision !== undefined && (!taskFormatStatus(phrenPath).enabled
741
+ if (expectedRevision !== undefined && updates.links === undefined && (!taskFormatStatus(phrenPath).enabled
725
742
  || !taskIdentity(graphRoot, parsed.data, item) || item.taskContractRaw !== undefined || item.taskContractRecords !== undefined)) {
726
743
  return phrenErr("Task metadata is disabled, unsupported or ambiguous; preserve your draft.", PhrenError.VALIDATION_ERROR);
727
744
  }
728
745
  const changes = [];
746
+ if (updates.links !== undefined || updates.branches !== undefined || updates.prs !== undefined) {
747
+ if (item.identityAmbiguous || item.opaqueContinuationLines?.some(line => line.trim().startsWith("Links:")))
748
+ return phrenErr("Ambiguous or unsupported task links; repair before editing.", PhrenError.VALIDATION_ERROR);
749
+ const links = taskLinksSchema.safeParse(updates.links ?? { version: 1, branches: updates.branches ?? item.links?.branches ?? [], prs: updates.prs ?? item.links?.prs ?? [] });
750
+ if (!links.success)
751
+ return phrenErr("Invalid repository-qualified branch or PR links.", PhrenError.VALIDATION_ERROR);
752
+ item.links = links.data;
753
+ changes.push("private merge links updated");
754
+ }
729
755
  if (updates.responsibility !== undefined || updates.dependencies !== undefined) {
730
756
  const storeRoot = path.dirname(path.dirname(parsed.data.path));
731
757
  if (!taskFormatStatus(storeRoot).enabled)
@@ -0,0 +1,69 @@
1
+ import type { DreamChange, DreamChangeset, DreamOp } from "./types.js";
2
+ export type DreamMode = "propose" | "apply";
3
+ export type DreamOutcomeStatus = "applied" | "proposed" | "skipped" | "failed";
4
+ export interface DreamOutcome {
5
+ index: number;
6
+ op: DreamOp;
7
+ status: DreamOutcomeStatus;
8
+ detail: string;
9
+ }
10
+ /** A change validation refused, with why; `index` is its position in the model's answer. */
11
+ export interface DreamDrop {
12
+ index: number;
13
+ op: string;
14
+ reason: string;
15
+ }
16
+ export interface ApplyOptions {
17
+ mode: DreamMode;
18
+ injectBudgetKB: number;
19
+ /** The model that dreamed, for provenance. */
20
+ model?: string;
21
+ expectedFindings?: Record<string, string>;
22
+ }
23
+ export declare const PAGE_PATH: RegExp;
24
+ export declare function findingVersions(phrenPath: string, project: string): Record<string, string>;
25
+ /** The review line a person reads for one proposed change. add_finding is just the finding, so approving it adds it. */
26
+ export declare function proposalText(change: DreamChange): string;
27
+ /** Apply or propose every change in order. One change failing never stops the rest. */
28
+ export declare function applyChangeset(phrenPath: string, changeset: DreamChangeset, options: ApplyOptions): Promise<DreamOutcome[]>;
29
+ export interface DreamRecord {
30
+ changeset: DreamChangeset;
31
+ findingVersions?: Record<string, string>;
32
+ warnings?: string[];
33
+ mode: DreamMode;
34
+ model?: string;
35
+ finishedAt: string;
36
+ outcomes: DreamOutcome[];
37
+ dropped: DreamDrop[];
38
+ costUSD?: number;
39
+ }
40
+ export interface DreamCounts {
41
+ applied: number;
42
+ proposed: number;
43
+ skipped: number;
44
+ failed: number;
45
+ dropped: number;
46
+ }
47
+ export declare function countOutcomes(outcomes: DreamOutcome[], dropped: DreamDrop[]): DreamCounts;
48
+ export declare function dreamsDir(phrenPath: string, project: string): string;
49
+ export declare function lastRunFile(phrenPath: string, project: string): string;
50
+ /** dreams/<runId>.json plus one journal line. Returns the record's path. */
51
+ export declare function recordDream(phrenPath: string, project: string, record: DreamRecord): string;
52
+ export declare function appendJournal(phrenPath: string, project: string, line: string): void;
53
+ export interface DreamLastRun {
54
+ at: string;
55
+ trigger: "manual" | "scheduled";
56
+ runId: string;
57
+ startedAt: string;
58
+ finishedAt: string;
59
+ to: string;
60
+ mode: DreamMode;
61
+ status: string;
62
+ counts?: DreamCounts;
63
+ }
64
+ export declare function writeLastRun(phrenPath: string, project: string, marker: Omit<DreamLastRun, "at">): void;
65
+ export declare function readLastRun(phrenPath: string, project: string): DreamLastRun | undefined;
66
+ /** Pending structured operations; add proposals are owned by the review queue. */
67
+ export declare function pendingDreamProposals(phrenPath: string, project: string): number;
68
+ /** Apply selected zero-based indices from a stored run, never replay completed changes. */
69
+ export declare function applyDreamProposals(phrenPath: string, project: string, runId: string, only?: number[]): Promise<DreamRecord>;
@@ -0,0 +1,372 @@
1
+ // Applying a dream: each change goes through the same finding, truth, topic and review
2
+ // APIs an agent's own MCP calls use, so lifecycle history, fids, locks and citations are
3
+ // kept. Propose mode queues additions and stores other operations for dream apply.
4
+ // Either way the run is recorded in dreams/<runId>.json and dreams/journal.md.
5
+ import * as crypto from "crypto";
6
+ import * as fs from "fs";
7
+ import * as path from "path";
8
+ import { assertFindingVersions, readFindingVersions } from "../finding/versions.js";
9
+ import { sanitizeDream } from "./privacy.js";
10
+ import { isCitationLine } from "../content/metadata.js";
11
+ import { addFindingToFile, upsertCanonical } from "../content/learning.js";
12
+ import { applyFindingTypePrefix } from "../core/finding.js";
13
+ import { editFinding, readFindings } from "../data/access.js";
14
+ import { retractFinding, supersedeFinding } from "../finding/lifecycle.js";
15
+ import { withFileLock } from "../governance/locks.js";
16
+ import { appendReviewQueue } from "../governance/policy.js";
17
+ import { renameOverSync, runtimeFile } from "../phren-paths.js";
18
+ import { appendArchivedEntriesToTopicDoc, readProjectTopics, topicReferencePath } from "../project-topics.js";
19
+ import { storeAwareProjectPath } from "../store-routing.js";
20
+ import { journalFile, projectStoreDir } from "./collect.js";
21
+ import { checkPromotion } from "./budget.js";
22
+ import { writePage } from "./pages.js";
23
+ export const PAGE_PATH = /^reference\/pages\/([a-z0-9][a-z0-9-]{0,63})\.md$/;
24
+ const TRUTH_DATE = /\s*_\(added \d{4}-\d{2}-\d{2}\)_\s*$/;
25
+ const fidRef = (id) => `fid:${id.replace(/^fid:/, "")}`;
26
+ const errorText = (err) => err instanceof Error ? err.message : String(err);
27
+ function findingText(phrenPath, project, id) {
28
+ const read = readFindings(phrenPath, project);
29
+ if (!read.ok)
30
+ return undefined;
31
+ const fid = id.replace(/^fid:/, "");
32
+ return read.data.find(item => item.stableId === fid)?.text;
33
+ }
34
+ export function findingVersions(phrenPath, project) {
35
+ return readFindingVersions(path.join(projectStoreDir(phrenPath, project), "FINDINGS.md"));
36
+ }
37
+ const targetIds = (change) => change.op === "merge" ? change.findingIds : "findingId" in change ? [change.findingId] : [];
38
+ function provenance(model) {
39
+ return { source: "consolidation", tool: "dream", ...(model ? { model } : {}) };
40
+ }
41
+ function addText(phrenPath, project, text, model) {
42
+ const result = addFindingToFile(phrenPath, project, text, undefined, { provenance: provenance(model) });
43
+ if (!result.ok)
44
+ return { ok: false, detail: result.error };
45
+ return { ok: true, detail: result.data.message, ...(result.data.status === "skipped" ? { skipped: true } : {}) };
46
+ }
47
+ /**
48
+ * Replace findings with one new finding: add it as superseding the first (the add_finding
49
+ * `supersedes` citation, which keeps the old one out of dedup), then supersede the rest by fid.
50
+ * If the new text is still a near-duplicate of a saved finding, rewrite the first in place.
51
+ */
52
+ function replaceWith(phrenPath, project, ids, newText, model, expectedFindings) {
53
+ const read = readFindings(phrenPath, project);
54
+ const items = ids.map(id => read.ok ? read.data.find(f => f.stableId === id.replace(/^fid:/, "")) : undefined);
55
+ const missing = ids.filter((_, i) => !items[i]);
56
+ if (missing.length)
57
+ return { status: "failed", detail: `no finding ${missing.map(fidRef).join(", ")}` };
58
+ const added = addFindingToFile(phrenPath, project, newText, { supersedes: items[0].text }, { provenance: provenance(model), expectedFindings });
59
+ if (!added.ok)
60
+ return { status: "failed", detail: added.error };
61
+ let rest = ids;
62
+ let detail = `replaced ${ids.map(fidRef).join(", ")}`;
63
+ if (added.data.status === "skipped") {
64
+ const edited = editFinding(phrenPath, project, fidRef(ids[0]), newText, expectedFindings);
65
+ if (!edited.ok)
66
+ return { status: "failed", detail: `near-duplicate of a saved finding, and editing ${fidRef(ids[0])} failed: ${edited.error}` };
67
+ rest = ids.slice(1);
68
+ detail = `edited ${fidRef(ids[0])} in place (the new text was a near-duplicate)${rest.length ? `; superseded ${rest.map(fidRef).join(", ")}` : ""}`;
69
+ }
70
+ const errors = [];
71
+ const after = readFindings(phrenPath, project);
72
+ for (const id of rest) {
73
+ const current = after.ok ? after.data.find(f => f.stableId === id.replace(/^fid:/, "")) : undefined;
74
+ if (current?.status === "superseded")
75
+ continue;
76
+ const result = supersedeFinding(phrenPath, project, fidRef(id), newText, expectedFindings ? { [id.replace(/^fid:/, "")]: expectedFindings[id.replace(/^fid:/, "")] } : undefined);
77
+ if (!result.ok)
78
+ errors.push(`${fidRef(id)}: ${result.error}`);
79
+ }
80
+ return errors.length ? { status: "failed", detail: `${detail}; ${errors.join("; ")}` } : { status: "applied", detail };
81
+ }
82
+ function truthsPath(phrenPath, project) {
83
+ return storeAwareProjectPath(phrenPath, project, "truths.md") ?? path.join(phrenPath, project, "truths.md");
84
+ }
85
+ /** Persist a manual fragment link the way the link_findings tool does, so an index rebuild keeps it. */
86
+ function persistLink(phrenPath, project, entity) {
87
+ const file = runtimeFile(phrenPath, "manual-links.json");
88
+ withFileLock(file, () => {
89
+ let existing = [];
90
+ if (fs.existsSync(file))
91
+ existing = JSON.parse(fs.readFileSync(file, "utf8"));
92
+ const entry = { entity: entity.toLowerCase(), entityType: "fragment", sourceDoc: `${project}/FINDINGS.md`, relType: "mentions" };
93
+ if (existing.some(e => e.entity === entry.entity && e.entityType === entry.entityType && e.sourceDoc === entry.sourceDoc && e.relType === entry.relType))
94
+ return;
95
+ existing.push(entry);
96
+ const tmp = `${file}.tmp-${crypto.randomUUID()}`;
97
+ fs.writeFileSync(tmp, JSON.stringify(existing, null, 2));
98
+ renameOverSync(tmp, file);
99
+ });
100
+ }
101
+ async function applyOne(phrenPath, project, change, all, options) {
102
+ const ok = (detail) => ({ status: "applied", detail });
103
+ const fail = (detail) => ({ status: "failed", detail });
104
+ switch (change.op) {
105
+ case "add_finding": {
106
+ const added = addText(phrenPath, project, applyFindingTypePrefix(change.text, change.findingType), options.model);
107
+ if (!added.ok)
108
+ return fail(added.detail);
109
+ return added.skipped ? { status: "skipped", detail: added.detail } : ok(added.detail);
110
+ }
111
+ case "supersede":
112
+ return replaceWith(phrenPath, project, [change.findingId], change.newText, options.model, options.expectedFindings);
113
+ case "retract": {
114
+ const result = retractFinding(phrenPath, project, fidRef(change.findingId), change.reason, options.expectedFindings);
115
+ return result.ok ? ok(`retracted ${fidRef(change.findingId)}`) : fail(result.error);
116
+ }
117
+ case "edit": {
118
+ const result = editFinding(phrenPath, project, fidRef(change.findingId), change.newText, options.expectedFindings);
119
+ return result.ok ? ok(`edited ${fidRef(change.findingId)}`) : fail(result.error);
120
+ }
121
+ case "merge":
122
+ return replaceWith(phrenPath, project, change.findingIds, change.newText, options.model, options.expectedFindings);
123
+ case "move_topic": {
124
+ const topic = readProjectTopics(phrenPath, project).topics.find(t => t.slug === change.topic);
125
+ if (!topic)
126
+ return fail(`unknown topic "${change.topic}"`);
127
+ const file = topicReferencePath(phrenPath, project, topic.slug);
128
+ if (!file)
129
+ return fail(`no topic file for "${topic.slug}"`);
130
+ const source = path.join(projectStoreDir(phrenPath, project), "FINDINGS.md");
131
+ const expected = findingVersions(phrenPath, project)[change.findingId.replace(/^fid:/, "")];
132
+ return withFileLock(source, () => {
133
+ assertFindingVersions(source, options.expectedFindings);
134
+ const fid = change.findingId.replace(/^fid:/, "");
135
+ const read = readFindings(phrenPath, project);
136
+ const item = read.ok ? read.data.find(f => f.stableId === fid) : undefined;
137
+ if (!item || !expected || findingVersions(phrenPath, project)[fid] !== expected)
138
+ return fail(`finding ${fidRef(fid)} is missing or changed`);
139
+ const before = fs.readFileSync(source, "utf8");
140
+ const lines = before.split("\n");
141
+ const index = lines.findIndex(line => line.startsWith("- ") && new RegExp(`<!--\\s*fid:${fid}\\s*-->`).test(line));
142
+ if (index < 0)
143
+ return fail(`no stored bullet ${fidRef(fid)}`);
144
+ const citation = isCitationLine(lines[index + 1] ?? "") ? lines[index + 1] : undefined;
145
+ appendArchivedEntriesToTopicDoc(file, project, topic, [{ date: item.date, bullet: lines[index], ...(citation ? { citation } : {}) }]);
146
+ if (fs.readFileSync(source, "utf8") !== before)
147
+ return fail("source changed while archiving; kept source");
148
+ lines.splice(index, citation ? 2 : 1);
149
+ writeAtomic(source, lines.join("\n"));
150
+ return ok(`moved ${fidRef(fid)} to ${topic.slug}`);
151
+ });
152
+ }
153
+ case "promote_truth": {
154
+ const demoted = all.flatMap(other => other.op === "demote_truth" ? [other.truth] : []);
155
+ const check = checkPromotion(phrenPath, project, options.injectBudgetKB, change.text, demoted);
156
+ if (!check.fits) {
157
+ return fail(`would put the injected layer at ${check.bytesAfter} bytes, over its ${check.budgetBytes}-byte budget, without enough demotions in this changeset`);
158
+ }
159
+ return withFileLock(path.join(projectStoreDir(phrenPath, project), "FINDINGS.md"), () => {
160
+ assertFindingVersions(path.join(projectStoreDir(phrenPath, project), "FINDINGS.md"), options.expectedFindings);
161
+ const result = upsertCanonical(phrenPath, project, change.text);
162
+ return result.ok ? ok(result.data) : fail(result.error);
163
+ });
164
+ }
165
+ case "demote_truth": {
166
+ const file = truthsPath(phrenPath, project);
167
+ if (!fs.existsSync(file))
168
+ return fail("no such truth");
169
+ const before = fs.readFileSync(file, "utf8");
170
+ const lines = before.split("\n");
171
+ const index = lines.findIndex(line => line.startsWith("- ") && line.slice(2).replace(TRUTH_DATE, "").trim() === change.truth);
172
+ if (index < 0)
173
+ return fail("no such truth");
174
+ const added = addText(phrenPath, project, change.truth, options.model);
175
+ if (!added.ok)
176
+ return fail(`truth kept: ${added.detail}`);
177
+ return withFileLock(file, () => {
178
+ if (fs.readFileSync(file, "utf8") !== before)
179
+ return fail("truth changed while saving finding; kept truth");
180
+ lines.splice(index, 1);
181
+ writeAtomic(file, lines.join("\n"));
182
+ return ok("demoted to a finding");
183
+ });
184
+ }
185
+ case "write_page": {
186
+ const slug = PAGE_PATH.exec(change.page)?.[1];
187
+ if (!slug)
188
+ return fail(`bad page path "${change.page}"`);
189
+ const written = await writePage(phrenPath, project, slug, change.markdown, change.links);
190
+ return ok(written.brokenLinks.length ? `wrote ${slug}; broken links: ${written.brokenLinks.join(", ")}` : `wrote ${slug}`);
191
+ }
192
+ case "link": {
193
+ if (!findingText(phrenPath, project, change.findingId))
194
+ return fail(`no finding ${fidRef(change.findingId)}`);
195
+ withFileLock(path.join(projectStoreDir(phrenPath, project), "FINDINGS.md"), () => {
196
+ assertFindingVersions(path.join(projectStoreDir(phrenPath, project), "FINDINGS.md"), options.expectedFindings);
197
+ persistLink(phrenPath, project, change.entity);
198
+ });
199
+ return ok(`linked ${fidRef(change.findingId)} to ${change.entity.toLowerCase()}`);
200
+ }
201
+ }
202
+ }
203
+ const evidenceOf = (change) => "evidence" in change ? change.evidence : [];
204
+ const clean = (text, max = 200) => text.replace(/\s+/g, " ").replace(/--+/g, "-").trim().slice(0, max);
205
+ /** The review line a person reads for one proposed change. add_finding is just the finding, so approving it adds it. */
206
+ export function proposalText(change) {
207
+ const evidence = evidenceOf(change).map(e => `${e.kind} ${e.ref}`).join("; ");
208
+ const why = evidence ? ` (evidence: ${evidence})` : "";
209
+ switch (change.op) {
210
+ case "add_finding": return applyFindingTypePrefix(change.text, change.findingType);
211
+ case "supersede": return `Dream: supersede ${fidRef(change.findingId)} with "${change.newText}"${why}`;
212
+ case "retract": return `Dream: retract ${fidRef(change.findingId)}: ${change.reason}${why}`;
213
+ case "edit": return `Dream: edit ${fidRef(change.findingId)} to "${change.newText}"${why}`;
214
+ case "merge": return `Dream: merge ${change.findingIds.map(fidRef).join(", ")} into "${change.newText}"${why}`;
215
+ case "move_topic": return `Dream: move ${fidRef(change.findingId)} to topic ${change.topic}`;
216
+ case "promote_truth": return `Dream: promote ${fidRef(change.findingId)} to a truth: "${change.text}"${why}`;
217
+ case "demote_truth": return `Dream: demote truth "${change.truth}": ${change.reason}`;
218
+ case "write_page": return `Dream: write page ${change.page}${change.links.length ? ` linking ${change.links.join(", ")}` : ""}`;
219
+ case "link": return `Dream: link ${fidRef(change.findingId)} to ${change.entity}`;
220
+ }
221
+ }
222
+ function proposeOne(phrenPath, project, runId, index, change) {
223
+ if (change.op !== "add_finding")
224
+ return { status: "proposed", detail: `pending dream apply ${runId} --only ${index}` };
225
+ const refs = evidenceOf(change).map(e => clean(`${e.kind}:${e.ref}`, 80)).join("; ");
226
+ const meta = `<!-- dream:${clean(runId, 64)}#${index} op:${change.op} -->${refs ? ` <!-- evidence: ${refs} -->` : ""}`;
227
+ const result = appendReviewQueue(phrenPath, project, "Review", [{ text: proposalText(change), meta }]);
228
+ if (!result.ok)
229
+ return { status: "failed", detail: result.error };
230
+ return result.data > 0 ? { status: "proposed", detail: "queued for review" } : { status: "skipped", detail: "already in the review queue" };
231
+ }
232
+ /** Apply or propose every change in order. One change failing never stops the rest. */
233
+ export async function applyChangeset(phrenPath, changeset, options) {
234
+ const outcomes = [];
235
+ for (const [index, change] of changeset.changes.entries()) {
236
+ let result;
237
+ try {
238
+ result = options.mode === "propose"
239
+ ? proposeOne(phrenPath, changeset.project, changeset.runId, index, change)
240
+ : await applyOne(phrenPath, changeset.project, change, changeset.changes, options);
241
+ }
242
+ catch (err) {
243
+ result = { status: "failed", detail: errorText(err) };
244
+ }
245
+ outcomes.push(sanitizeDream({ index, op: change.op, ...result }));
246
+ }
247
+ return outcomes;
248
+ }
249
+ export function countOutcomes(outcomes, dropped) {
250
+ const counts = { applied: 0, proposed: 0, skipped: 0, failed: 0, dropped: dropped.length };
251
+ for (const outcome of outcomes)
252
+ counts[outcome.status]++;
253
+ return counts;
254
+ }
255
+ export function dreamsDir(phrenPath, project) {
256
+ return path.join(projectStoreDir(phrenPath, project), "dreams");
257
+ }
258
+ export function lastRunFile(phrenPath, project) {
259
+ return path.join(dreamsDir(phrenPath, project), "last-run.json");
260
+ }
261
+ function writeAtomic(file, content) {
262
+ fs.mkdirSync(path.dirname(file), { recursive: true });
263
+ const tmp = `${file}.tmp-${crypto.randomUUID()}`;
264
+ fs.writeFileSync(tmp, content);
265
+ renameOverSync(tmp, file);
266
+ }
267
+ /** dreams/<runId>.json plus one journal line. Returns the record's path. */
268
+ export function recordDream(phrenPath, project, record) {
269
+ record = sanitizeDream(record);
270
+ const dir = dreamsDir(phrenPath, project);
271
+ const file = path.join(dir, `${record.changeset.runId}.json`);
272
+ writeAtomic(file, `${JSON.stringify(record, null, 2)}\n`);
273
+ const counts = countOutcomes(record.outcomes, record.dropped);
274
+ const notes = clean(record.changeset.notes, 160);
275
+ const line = `- ${record.changeset.startedAt} ${record.changeset.runId} ${record.mode}: ${counts.applied} applied, ${counts.proposed} proposed, `
276
+ + `${counts.skipped} skipped, ${counts.failed} failed, ${counts.dropped} dropped (${record.changeset.inputs.transcripts} sessions)${notes ? ` — ${notes}` : ""}${record.warnings?.length ? ` — ${record.warnings.join("; ")}` : ""}\n`;
277
+ appendJournal(phrenPath, project, line);
278
+ return file;
279
+ }
280
+ export function appendJournal(phrenPath, project, line) {
281
+ line = sanitizeDream(line);
282
+ const journal = journalFile(phrenPath, project);
283
+ fs.mkdirSync(path.dirname(journal), { recursive: true });
284
+ withFileLock(journal, () => {
285
+ if (!fs.existsSync(journal))
286
+ fs.writeFileSync(journal, `# ${project} dream journal\n\n`);
287
+ fs.appendFileSync(journal, line);
288
+ });
289
+ }
290
+ export function writeLastRun(phrenPath, project, marker) {
291
+ writeAtomic(lastRunFile(phrenPath, project), `${JSON.stringify({ ...marker, at: marker.finishedAt }, null, 2)}\n`);
292
+ }
293
+ export function readLastRun(phrenPath, project) {
294
+ try {
295
+ const value = JSON.parse(fs.readFileSync(lastRunFile(phrenPath, project), "utf8"));
296
+ return value && typeof value.to === "string" && Number.isFinite(Date.parse(value.to)) ? value : undefined;
297
+ }
298
+ catch {
299
+ return undefined;
300
+ }
301
+ }
302
+ /** Pending structured operations; add proposals are owned by the review queue. */
303
+ export function pendingDreamProposals(phrenPath, project) {
304
+ let names;
305
+ try {
306
+ names = fs.readdirSync(dreamsDir(phrenPath, project));
307
+ }
308
+ catch {
309
+ return 0;
310
+ }
311
+ let count = 0;
312
+ for (const name of names.filter(n => n.endsWith(".json") && n !== "last-run.json")) {
313
+ try {
314
+ const record = JSON.parse(fs.readFileSync(path.join(dreamsDir(phrenPath, project), name), "utf8"));
315
+ count += record.outcomes.filter(o => o.status === "proposed" && o.op !== "add_finding").length;
316
+ }
317
+ catch { /* Not a run record. */ }
318
+ }
319
+ return count;
320
+ }
321
+ /** Apply selected zero-based indices from a stored run, never replay completed changes. */
322
+ export async function applyDreamProposals(phrenPath, project, runId, only) {
323
+ if (!/^[a-zA-Z0-9_-]+$/.test(runId))
324
+ throw new Error("Invalid dream run ID.");
325
+ if (only?.some(n => !Number.isSafeInteger(n) || n < 0))
326
+ throw new Error("Proposal indices must be nonnegative integers.");
327
+ const { dreamLockPath, readDreamConfig } = await import("./run.js");
328
+ return withFileLock(dreamLockPath(phrenPath, project), async () => {
329
+ const file = path.join(dreamsDir(phrenPath, project), `${runId}.json`);
330
+ const record = JSON.parse(fs.readFileSync(file, "utf8"));
331
+ if (record.changeset.project !== project || record.changeset.runId !== runId)
332
+ throw new Error("Dream record identity mismatch.");
333
+ if (only?.some(n => !record.changeset.changes[n]))
334
+ throw new Error("Unknown proposal index.");
335
+ const config = readDreamConfig(phrenPath, project);
336
+ // Validate all targets before our own earlier operations can modify them.
337
+ const current = findingVersions(phrenPath, project);
338
+ const eligible = new Set(record.outcomes.filter(o => o.status === "proposed" && o.op !== "add_finding" && (!only || only.includes(o.index))).map(o => o.index));
339
+ const stale = new Set([...eligible].filter(index => targetIds(record.changeset.changes[index]).some(id => {
340
+ const fid = id.replace(/^fid:/, "");
341
+ return !current[fid] || !record.findingVersions?.[fid] || current[fid] !== record.findingVersions[fid];
342
+ })));
343
+ for (const index of eligible) {
344
+ const change = record.changeset.changes[index];
345
+ let result;
346
+ if (stale.has(index))
347
+ result = { status: "failed", detail: "target finding missing or changed since the run" };
348
+ else {
349
+ const ids = targetIds(change).map(id => id.replace(/^fid:/, ""));
350
+ const selected = [...eligible].filter(i => !stale.has(i)).map(i => record.changeset.changes[i]);
351
+ try {
352
+ result = await applyOne(phrenPath, project, change, selected, {
353
+ mode: "apply", injectBudgetKB: config.injectBudgetKB, model: record.model,
354
+ expectedFindings: Object.fromEntries(ids.map(fid => [fid, current[fid]])),
355
+ });
356
+ const after = findingVersions(phrenPath, project);
357
+ for (const fid of ids)
358
+ current[fid] = after[fid];
359
+ }
360
+ catch (err) {
361
+ result = { status: "failed", detail: errorText(err) };
362
+ }
363
+ }
364
+ const outcome = sanitizeDream({ index, op: change.op, ...result });
365
+ record.outcomes = record.outcomes.map(o => o.index === index ? outcome : o);
366
+ // Checkpoint each outcome before proceeding to the next proposal.
367
+ writeAtomic(file, `${JSON.stringify(sanitizeDream(record), null, 2)}\n`);
368
+ appendJournal(phrenPath, project, `- ${new Date().toISOString()} ${runId}#${index} ${outcome.status}: ${outcome.detail}\n`);
369
+ }
370
+ return sanitizeDream(record);
371
+ });
372
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * The injected layer's size, and what to demote when it is too big.
3
+ *
4
+ * What phren puts in front of every session for a project regardless of the
5
+ * prompt is (see `shared/retrieval.ts` and `cli/hooks.ts`):
6
+ * - the whole of the project's `truths.md` (canonical rows are prepended to
7
+ * every search for the detected project), and
8
+ * - the "What phren knows" block from `summary.md`, once per session, capped
9
+ * at 520 characters by the hook.
10
+ * Everything else the hook injects is chosen by relevance and already sits
11
+ * under its own token budget. Errors in the always-on part spread to every
12
+ * session, so dreaming keeps it under `dreaming.injectBudgetKB`.
13
+ */
14
+ export interface Truth {
15
+ /** The truth as written, without the leading "- " and the "_(added …)_" stamp. */
16
+ text: string;
17
+ /** The full bullet line as stored, for an exact demote. */
18
+ line: string;
19
+ added?: string;
20
+ /** Bytes this line costs in the injected file (line plus newline). */
21
+ bytes: number;
22
+ }
23
+ export interface InjectedSize {
24
+ project: string;
25
+ /** Bytes of truths.md as stored; the hook injects the file as is. */
26
+ truthsBytes: number;
27
+ /** Bytes of the knows block as the hook injects it (after its trim). */
28
+ knowsBytes: number;
29
+ bytes: number;
30
+ kb: number;
31
+ truths: Truth[];
32
+ }
33
+ export interface DemotionCandidate extends Truth {
34
+ /** Most recent evidence that the truth was used: a lookup hit, a caller-supplied citation, or its added date. */
35
+ lastCited?: string;
36
+ }
37
+ export interface BudgetState {
38
+ project: string;
39
+ budgetBytes: number;
40
+ bytes: number;
41
+ over: boolean;
42
+ /** Bytes to free to get back under budget; 0 when under. */
43
+ excessBytes: number;
44
+ /** The shortest least-recently-cited-first prefix that, demoted, gets under budget. Empty when under. */
45
+ candidates: DemotionCandidate[];
46
+ /** Every truth, least recently cited first. */
47
+ ranking: DemotionCandidate[];
48
+ }
49
+ export interface OverBudgetOptions {
50
+ /** Extra citation dates by truth text (e.g. transcript mentions found by collect). Newer dates win. */
51
+ citedAt?: Map<string, string> | Record<string, string>;
52
+ /** Skip reading the lookup log (tests, or callers that pass citedAt themselves). */
53
+ skipLookupLog?: boolean;
54
+ }
55
+ export declare function parseTruths(content: string): Truth[];
56
+ export declare function injectedSize(store: string, project: string): InjectedSize;
57
+ export declare function rankTruths(store: string, project: string, truths: Truth[], opts?: OverBudgetOptions): DemotionCandidate[];
58
+ export declare function overBudget(store: string, project: string, budgetKB: number, opts?: OverBudgetOptions): BudgetState;
59
+ /**
60
+ * Bytes a new truth costs once `upsertCanonical` has written it: a new file is
61
+ * the header plus "- text _(added YYYY-MM-DD)_\n"; an existing one gets the
62
+ * line plus a blank-line separator inserted under "## Truths".
63
+ */
64
+ export declare function truthCost(project: string, text: string, fileExists: boolean): number;
65
+ export interface PromotionCheck {
66
+ fits: boolean;
67
+ bytesBefore: number;
68
+ bytesAfter: number;
69
+ budgetBytes: number;
70
+ }
71
+ /**
72
+ * Whether promoting `text` to a truth keeps the injected layer under budget,
73
+ * counting the truths the same changeset demotes. `apply` refuses a
74
+ * promote_truth that does not fit.
75
+ */
76
+ export declare function checkPromotion(store: string, project: string, budgetKB: number, text: string, demoted?: string[]): PromotionCheck;
77
+ /** One line for the dreaming prompt: where the injected layer stands. */
78
+ export declare function describeBudget(state: BudgetState): string;