@phren/cli 0.3.71 → 0.3.73
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.
- package/dist/bridge/agent-hooks.js +11 -1
- package/dist/bridge/browser-env.d.ts +5 -0
- package/dist/bridge/browser-env.js +110 -0
- package/dist/bridge/browser-protocol.d.ts +120 -0
- package/dist/bridge/browser-protocol.js +70 -0
- package/dist/bridge/browser-recordings.d.ts +63 -0
- package/dist/bridge/browser-recordings.js +148 -0
- package/dist/bridge/browser-registry.d.ts +64 -0
- package/dist/bridge/browser-registry.js +262 -0
- package/dist/bridge/browser-routes.d.ts +4 -0
- package/dist/bridge/browser-routes.js +39 -0
- package/dist/bridge/browser-shim/phren-playwright.cjs +184 -0
- package/dist/bridge/browser-socket.d.ts +2 -0
- package/dist/bridge/browser-socket.js +10 -0
- package/dist/bridge/browser-stream.d.ts +3 -0
- package/dist/bridge/browser-stream.js +129 -0
- package/dist/bridge/browser-watch.d.ts +12 -0
- package/dist/bridge/browser-watch.js +83 -0
- package/dist/bridge/claude-account-setup.js +3 -1
- package/dist/bridge/claude-accounts.d.ts +5 -1
- package/dist/bridge/claude-accounts.js +36 -6
- package/dist/bridge/codex-servers.d.ts +2 -0
- package/dist/bridge/codex-servers.js +1 -1
- package/dist/bridge/command.js +24 -5
- package/dist/bridge/dispatch-clone.d.ts +33 -0
- package/dist/bridge/dispatch-clone.js +176 -0
- package/dist/bridge/dispatch-command.d.ts +14 -0
- package/dist/bridge/dispatch-command.js +98 -13
- package/dist/bridge/dispatch-idempotency.d.ts +85 -0
- package/dist/bridge/dispatch-idempotency.js +235 -0
- package/dist/bridge/dispatch-returns.d.ts +6 -0
- package/dist/bridge/dispatch-returns.js +131 -1
- package/dist/bridge/dispatch-wait.d.ts +32 -0
- package/dist/bridge/dispatch-wait.js +177 -0
- package/dist/bridge/dispatch.d.ts +78 -2
- package/dist/bridge/dispatch.js +841 -25
- package/dist/bridge/dream-schedule.d.ts +133 -0
- package/dist/bridge/dream-schedule.js +322 -0
- package/dist/bridge/fanouts.js +20 -3
- package/dist/bridge/files.d.ts +1 -1
- package/dist/bridge/git-credential.d.ts +44 -0
- package/dist/bridge/git-credential.js +113 -0
- package/dist/bridge/git-host-auth.d.ts +9 -1
- package/dist/bridge/git-host-auth.js +18 -5
- package/dist/bridge/git-host-gitboy.js +8 -1
- package/dist/bridge/git-hosts.d.ts +12 -1
- package/dist/bridge/git-publish.js +3 -2
- package/dist/bridge/herdr.d.ts +4 -0
- package/dist/bridge/herdr.js +44 -9
- package/dist/bridge/install.d.ts +1 -1
- package/dist/bridge/install.js +12 -4
- package/dist/bridge/launch-brief.d.ts +11 -0
- package/dist/bridge/launch-brief.js +22 -0
- package/dist/bridge/launch-worktree.d.ts +2 -0
- package/dist/bridge/launch-worktree.js +5 -1
- package/dist/bridge/pane-status.js +1 -1
- package/dist/bridge/protocol.d.ts +7 -0
- package/dist/bridge/schedule-watch.js +13 -2
- package/dist/bridge/server-launch.d.ts +2 -0
- package/dist/bridge/server-launch.js +251 -145
- package/dist/bridge/server-routes.d.ts +3 -0
- package/dist/bridge/server-routes.js +33 -17
- package/dist/bridge/server-stream.d.ts +4 -0
- package/dist/bridge/server-stream.js +24 -5
- package/dist/bridge/server.js +35 -4
- package/dist/bridge/session-move.d.ts +10 -4
- package/dist/bridge/session-move.js +65 -34
- package/dist/bridge/simulator-stream.d.ts +2 -0
- package/dist/bridge/simulator-stream.js +2 -0
- package/dist/bridge/status-line-fast.d.ts +9 -0
- package/dist/bridge/status-line-fast.js +56 -0
- package/dist/bridge/tab-activity.d.ts +2 -0
- package/dist/bridge/tab-activity.js +15 -2
- package/dist/bridge/task-routes.d.ts +20 -16
- package/dist/bridge/task-routes.js +1 -1
- package/dist/bridge/terminal-herdr.d.ts +5 -1
- package/dist/bridge/terminal-herdr.js +67 -2
- package/dist/bridge/terminal-tmux.d.ts +2 -0
- package/dist/bridge/terminal-tmux.js +29 -7
- package/dist/bridge/terminal.d.ts +5 -1
- package/dist/bridge/transcript-claude.js +192 -112
- package/dist/bridge/transcript-preview.d.ts +2 -1
- package/dist/bridge/transcript-preview.js +85 -3
- package/dist/bridge/transcripts.js +17 -11
- package/dist/bridge/turn-records.js +16 -4
- package/dist/bridge/usage.d.ts +7 -1
- package/dist/bridge/usage.js +47 -31
- package/dist/bridge/worker-close.d.ts +15 -0
- package/dist/bridge/worker-close.js +304 -3
- package/dist/bridge/worker-identity.d.ts +51 -0
- package/dist/bridge/worker-identity.js +289 -0
- package/dist/bridge/worker-reports.js +15 -3
- package/dist/bridge-hook.mjs +39990 -36152
- package/dist/capabilities/mcp.js +1 -1
- package/dist/cli/browser-hint.d.ts +2 -0
- package/dist/cli/browser-hint.js +21 -0
- package/dist/cli/config-dreaming.d.ts +7 -0
- package/dist/cli/config-dreaming.js +72 -0
- package/dist/cli/config.js +6 -0
- package/dist/cli/dream.d.ts +59 -0
- package/dist/cli/dream.js +315 -0
- package/dist/cli/hooks-context.d.ts +2 -2
- package/dist/cli/hooks-context.js +3 -3
- package/dist/cli/hooks.js +20 -11
- package/dist/cli/namespaces-tasks.js +14 -0
- package/dist/cli-registry.js +28 -3
- package/dist/config/dreaming.d.ts +82 -0
- package/dist/config/dreaming.js +195 -0
- package/dist/config/resolve.js +11 -0
- package/dist/config/schema.d.ts +4 -4
- package/dist/config/schema.js +157 -1
- package/dist/content/citation-freshness.js +6 -0
- package/dist/content/learning.d.ts +1 -0
- package/dist/content/learning.js +2 -0
- package/dist/data/access.d.ts +1 -1
- package/dist/data/access.js +3 -1
- package/dist/data/task-contract.d.ts +5 -4
- package/dist/data/tasks.d.ts +5 -0
- package/dist/data/tasks.js +28 -2
- package/dist/dream/apply.d.ts +69 -0
- package/dist/dream/apply.js +372 -0
- package/dist/dream/budget.d.ts +78 -0
- package/dist/dream/budget.js +180 -0
- package/dist/dream/collect.d.ts +86 -0
- package/dist/dream/collect.js +449 -0
- package/dist/dream/eval/dream-adapter.d.ts +16 -0
- package/dist/dream/eval/dream-adapter.js +21 -0
- package/dist/dream/eval/fixture.d.ts +53 -0
- package/dist/dream/eval/fixture.js +172 -0
- package/dist/dream/eval/index.d.ts +40 -0
- package/dist/dream/eval/index.js +78 -0
- package/dist/dream/eval/score.d.ts +34 -0
- package/dist/dream/eval/score.js +99 -0
- package/dist/dream/eval/scripted-model.d.ts +19 -0
- package/dist/dream/eval/scripted-model.js +70 -0
- package/dist/dream/pages.d.ts +68 -0
- package/dist/dream/pages.js +220 -0
- package/dist/dream/privacy.d.ts +3 -0
- package/dist/dream/privacy.js +18 -0
- package/dist/dream/prompt.d.ts +13 -0
- package/dist/dream/prompt.js +84 -0
- package/dist/dream/run.d.ts +98 -0
- package/dist/dream/run.js +317 -0
- package/dist/dream/types.d.ts +74 -0
- package/dist/dream/types.js +4 -0
- package/dist/finding/lifecycle.d.ts +2 -2
- package/dist/finding/lifecycle.js +5 -2
- package/dist/finding/versions.d.ts +4 -0
- package/dist/finding/versions.js +28 -0
- package/dist/index.js +1 -0
- package/dist/modules/registry.js +10 -8
- package/dist/project-config.d.ts +3 -0
- package/dist/task/merge-links.d.ts +38 -0
- package/dist/task/merge-links.js +45 -0
- package/dist/task/reconcile.d.ts +39 -0
- package/dist/task/reconcile.js +201 -0
- package/dist/task/report-links.d.ts +10 -0
- package/dist/task/report-links.js +47 -0
- package/dist/tools/config.js +46 -4
- package/dist/tools/dispatch.js +2 -1
- package/dist/tools/dream.d.ts +3 -0
- package/dist/tools/dream.js +123 -0
- package/dist/tools/tasks.js +4 -1
- package/package.json +1 -1
package/dist/data/access.d.ts
CHANGED
|
@@ -84,7 +84,7 @@ export declare function removeFindings(phrenPath: string, project: string, match
|
|
|
84
84
|
removed: string[];
|
|
85
85
|
errors: string[];
|
|
86
86
|
}>;
|
|
87
|
-
export declare function editFinding(phrenPath: string, project: string, oldText: string, newText: string): PhrenResult<string>;
|
|
87
|
+
export declare function editFinding(phrenPath: string, project: string, oldText: string, newText: string, expectedFindings?: Record<string, string>): PhrenResult<string>;
|
|
88
88
|
export declare function readReviewQueue(phrenPath: string, project: string): PhrenResult<QueueItem[]>;
|
|
89
89
|
export type QueueApproveOutcome = "promoted" | "already_present" | "already_archived";
|
|
90
90
|
export interface QueueApproveResult {
|
package/dist/data/access.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// dedicated modules (data-tasks.ts, profile-store.ts, shell-state-store.ts)
|
|
3
3
|
// and owns finding/queue logic directly.
|
|
4
4
|
import * as fs from "fs";
|
|
5
|
+
import { assertFindingVersions } from "../finding/versions.js";
|
|
5
6
|
import * as path from "path";
|
|
6
7
|
import { renameOverSync } from "../phren-paths.js";
|
|
7
8
|
import * as yaml from "js-yaml";
|
|
@@ -414,7 +415,7 @@ export function removeFindings(phrenPath, project, matches) {
|
|
|
414
415
|
return phrenOk({ removed, errors });
|
|
415
416
|
});
|
|
416
417
|
}
|
|
417
|
-
export function editFinding(phrenPath, project, oldText, newText) {
|
|
418
|
+
export function editFinding(phrenPath, project, oldText, newText, expectedFindings) {
|
|
418
419
|
const ensured = ensureProject(phrenPath, project);
|
|
419
420
|
if (!ensured.ok)
|
|
420
421
|
return forwardErr(ensured);
|
|
@@ -428,6 +429,7 @@ export function editFinding(phrenPath, project, oldText, newText) {
|
|
|
428
429
|
if (!fs.existsSync(findingsPath))
|
|
429
430
|
return phrenErr(`No ${FINDINGS_FILENAME} file found for "${project}".`, PhrenError.FILE_NOT_FOUND);
|
|
430
431
|
return withSafeLock(findingsPath, () => {
|
|
432
|
+
assertFindingVersions(findingsPath, expectedFindings);
|
|
431
433
|
const lines = fs.readFileSync(findingsPath, "utf8").split("\n");
|
|
432
434
|
const needle = normalizeFindingText(oldText);
|
|
433
435
|
const bulletLines = collectFindingBulletLines(lines);
|
|
@@ -29,6 +29,10 @@ export declare function taskIdentity(phrenPath: string, doc: TaskDoc, item: Task
|
|
|
29
29
|
/** Derived, never persisted. Missing or unknown metadata blocks autonomous selection. */
|
|
30
30
|
export declare function taskReadiness(phrenPath: string, doc: TaskDoc, item: TaskItem): TaskReadiness;
|
|
31
31
|
export declare function taskView(phrenPath: string, doc: TaskDoc, item: TaskItem): {
|
|
32
|
+
responsibility: TaskResponsibility;
|
|
33
|
+
readiness: "ready" | "waiting-on-human" | "waiting-on-task";
|
|
34
|
+
prerequisites: TaskPrerequisite[];
|
|
35
|
+
identity: TaskDependency | null;
|
|
32
36
|
id: string;
|
|
33
37
|
stableId?: string;
|
|
34
38
|
identityAmbiguous?: boolean;
|
|
@@ -37,6 +41,7 @@ export declare function taskView(phrenPath: string, doc: TaskDoc, item: TaskItem
|
|
|
37
41
|
checked: boolean;
|
|
38
42
|
priority?: "high" | "medium" | "low";
|
|
39
43
|
context?: string;
|
|
44
|
+
links?: import("../task/merge-links.js").TaskLinks;
|
|
40
45
|
pinned?: boolean;
|
|
41
46
|
githubIssue?: number;
|
|
42
47
|
githubUrl?: string;
|
|
@@ -55,10 +60,6 @@ export declare function taskView(phrenPath: string, doc: TaskDoc, item: TaskItem
|
|
|
55
60
|
taskContractRecords?: string[];
|
|
56
61
|
taskContractLines?: string[];
|
|
57
62
|
opaqueContinuationLines?: string[];
|
|
58
|
-
responsibility: TaskResponsibility;
|
|
59
|
-
readiness: "ready" | "waiting-on-human" | "waiting-on-task";
|
|
60
|
-
prerequisites: TaskPrerequisite[];
|
|
61
|
-
identity: TaskDependency | null;
|
|
62
63
|
};
|
|
63
64
|
export declare function validateTaskDependencies(phrenPath: string, doc: TaskDoc, item: TaskItem, refs: TaskDependency[]): string | undefined;
|
|
64
65
|
export interface TaskFilter {
|
package/dist/data/tasks.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type TaskLinks } from "../task/merge-links.js";
|
|
1
2
|
import { type PhrenResult } from "../shared.js";
|
|
2
3
|
import { type TaskDependency, type TaskResponsibility, type TaskChange } from "./task-contract.js";
|
|
3
4
|
export type TaskSection = "Active" | "Queue" | "Done";
|
|
@@ -14,6 +15,7 @@ export interface TaskItem {
|
|
|
14
15
|
checked: boolean;
|
|
15
16
|
priority?: "high" | "medium" | "low";
|
|
16
17
|
context?: string;
|
|
18
|
+
links?: TaskLinks;
|
|
17
19
|
pinned?: boolean;
|
|
18
20
|
githubIssue?: number;
|
|
19
21
|
githubUrl?: string;
|
|
@@ -117,6 +119,9 @@ export declare function removeTasks(phrenPath: string, project: string, matches:
|
|
|
117
119
|
}>;
|
|
118
120
|
export declare function updateTask(phrenPath: string, project: string, match: string, updates: {
|
|
119
121
|
text?: string;
|
|
122
|
+
links?: TaskLinks;
|
|
123
|
+
branches?: TaskLinks["branches"];
|
|
124
|
+
prs?: TaskLinks["prs"];
|
|
120
125
|
priority?: string;
|
|
121
126
|
context?: string;
|
|
122
127
|
replace_context?: boolean;
|
package/dist/data/tasks.js
CHANGED
|
@@ -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
|
+
}
|