@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
@@ -33,7 +33,7 @@ export const mcpManifest = {
33
33
  "graph.link_findings": { implemented: true, handler: "index.ts:link_findings" },
34
34
  // Config
35
35
  "config.get": { implemented: true, handler: "index.ts:get_config (supports all domains including topic)" },
36
- "config.set": { implemented: true, handler: "index.ts:set_config (proactivity, taskMode, findingSensitivity, retention, workflow, index, topic)" },
36
+ "config.set": { implemented: true, handler: "index.ts:set_config (proactivity, taskMode, findingSensitivity, retention, workflow, access, index, topic, dreaming)" },
37
37
  // Health / Sync / Session
38
38
  "health.check": { implemented: true, handler: "index.ts:health_check" },
39
39
  "health.doctor_fix": { implemented: true, handler: "index.ts:doctor_fix" },
@@ -0,0 +1,7 @@
1
+ export declare const CONFIG_DREAMING_USAGE: string;
2
+ /** `key=value` and `--key=value` arguments, as strings for {@link parseDreamingPatch}. */
3
+ export declare function parseDreamingAssignments(args: string[]): {
4
+ values: Record<string, string>;
5
+ bad: string[];
6
+ };
7
+ export declare function handleConfigDreaming(args: string[]): void;
@@ -0,0 +1,72 @@
1
+ import { getPhrenPath } from "../shared.js";
2
+ import { isValidProjectName } from "../utils.js";
3
+ import { DREAMING_KEYS, getDreamingConfig, parseDreamingPatch, updateDreamingConfig, } from "../config/dreaming.js";
4
+ import { parseProjectArg, warnIfUnregistered } from "./config-shared.js";
5
+ export const CONFIG_DREAMING_USAGE = "Usage: phren config dreaming [--project <name>] [get | set key=value ... | unset key ...]\n"
6
+ + ` keys: ${DREAMING_KEYS.join(", ")}\n`
7
+ + " e.g. phren config dreaming set enabled=true cadence=idle idleMinutes=60\n"
8
+ + " phren config dreaming --project api set mode=apply phases=correct,organize\n"
9
+ + " phren config dreaming --project api unset mode (inherit the global value again)";
10
+ /** `key=value` and `--key=value` arguments, as strings for {@link parseDreamingPatch}. */
11
+ export function parseDreamingAssignments(args) {
12
+ const values = {};
13
+ const bad = [];
14
+ for (const arg of args) {
15
+ const token = arg.startsWith("--") ? arg.slice(2) : arg;
16
+ const eq = token.indexOf("=");
17
+ if (eq <= 0) {
18
+ bad.push(arg);
19
+ continue;
20
+ }
21
+ values[token.slice(0, eq)] = token.slice(eq + 1);
22
+ }
23
+ return { values, bad };
24
+ }
25
+ export function handleConfigDreaming(args) {
26
+ const phrenPath = getPhrenPath();
27
+ const { project, rest } = parseProjectArg(args);
28
+ const action = rest[0] ?? "get";
29
+ if (project && !isValidProjectName(project)) {
30
+ console.error(`Invalid project name: "${project}"`);
31
+ process.exitCode = 1;
32
+ return;
33
+ }
34
+ const print = () => console.log(JSON.stringify({ _project: project ?? null, ...getDreamingConfig(phrenPath, project) }, null, 2));
35
+ if (action === "get")
36
+ return print();
37
+ if (action === "set") {
38
+ const { values, bad } = parseDreamingAssignments(rest.slice(1));
39
+ const parsed = parseDreamingPatch(values);
40
+ const problems = [
41
+ ...bad.map((arg) => `"${arg}" is not key=value.`),
42
+ ...parsed.unknown.map((key) => `Unknown key "${key}".`),
43
+ ...parsed.errors,
44
+ ];
45
+ if (problems.length || !Object.keys(parsed.patch).length) {
46
+ for (const line of problems)
47
+ console.error(line);
48
+ console.error(CONFIG_DREAMING_USAGE);
49
+ process.exitCode = 1;
50
+ return;
51
+ }
52
+ if (project)
53
+ warnIfUnregistered(phrenPath, project);
54
+ updateDreamingConfig(phrenPath, parsed.patch, project);
55
+ return print();
56
+ }
57
+ if (action === "unset") {
58
+ const keys = rest.slice(1);
59
+ const unknown = keys.filter((key) => !DREAMING_KEYS.includes(key));
60
+ if (!keys.length || unknown.length) {
61
+ if (unknown.length)
62
+ console.error(`Unknown key(s): ${unknown.join(", ")}`);
63
+ console.error(CONFIG_DREAMING_USAGE);
64
+ process.exitCode = 1;
65
+ return;
66
+ }
67
+ updateDreamingConfig(phrenPath, {}, project, keys);
68
+ return print();
69
+ }
70
+ console.error(CONFIG_DREAMING_USAGE);
71
+ process.exitCode = 1;
72
+ }
@@ -16,6 +16,7 @@ import { handleIndexPolicy, handleRetentionPolicy, handleWorkflowPolicy, handleC
16
16
  import { handleConfigLlm } from "./config-llm.js";
17
17
  import { handleConfigAccess } from "./config-access.js";
18
18
  import { handleConfigSynonyms } from "./config-synonyms.js";
19
+ import { handleConfigDreaming } from "./config-dreaming.js";
19
20
  // Re-export the public surface so external importers (cli-registry.ts, tools/config.ts,
20
21
  // tests) keep resolving the same names from "./cli/config.js" after the split.
21
22
  export { checkProjectInProfile, handleIndexPolicy, handleRetentionPolicy, handleWorkflowPolicy, handleConfigAccess };
@@ -153,6 +154,9 @@ export async function handleConfig(args) {
153
154
  return handleConfigLlm(rest);
154
155
  case "synonyms":
155
156
  return handleConfigSynonyms(rest);
157
+ case "dreaming":
158
+ case "dream":
159
+ return handleConfigDreaming(rest);
156
160
  default:
157
161
  console.log(`phren config - manage settings and policies
158
162
 
@@ -177,6 +181,8 @@ Subcommands:
177
181
  Finding capture level (minimal|conservative|balanced|aggressive)
178
182
  phren config access [--project <name>] [get|set --admins=...]
179
183
  Role-based access lists (admins|contributors|readers)
184
+ phren config dreaming [--project <name>] [get|set key=value ...|unset key ...]
185
+ Dreaming: offline memory reorganization (off by default)
180
186
  phren config project-ownership [mode]
181
187
  Default ownership for future project enrollments
182
188
  phren config llm [get|set model|endpoint|key]
@@ -0,0 +1,59 @@
1
+ /**
2
+ * `phren dream run|status|log|eval`: the CLI over the dream engine (dream/run.ts)
3
+ * and its outputs under `<store>/<project>/dreams/`. The MCP `dream_*` tools
4
+ * (tools/dream.ts) call the same functions.
5
+ */
6
+ import type { DreamMode } from "../config/dreaming.js";
7
+ import { type DreamStatus } from "../bridge/dream-schedule.js";
8
+ export declare const DREAM_USAGE = "phren dream - reorganize a project's memory offline (docs/dreaming.md)\n\n phren dream run [--project <p>] [--dry-run] [--apply|--propose] [--force] [--json]\n Run a dream now. --dry-run shows the changeset without writing; --apply/--propose\n override dreaming.mode; --force runs even when dreaming is off.\n phren dream apply <runId> [--project <p>] [--only <n,m,...>] [--json]\n Apply pending structured proposals by zero-based index; refuse changed targets.\n phren dream status [--project <p>] [--json]\n Enabled, cadence, last run, next eligible time and last outcome counts\n (every project when --project is omitted and the folder is not a project).\n phren dream log [--project <p>] [--limit <n>] [--json]\n The latest entries of the project's dream journal (dreams/journal.md).\n phren dream eval [--real] [--model <m>] [--json]\n Score the dream engine on the bundled fixture store (a scripted model unless --real).\n\nTurn it on with: phren config dreaming set enabled=true [cadence=nightly|idle|weekly|manual]";
9
+ export declare const DREAM_LOG_DEFAULT_LIMIT = 20;
10
+ export declare const DREAM_LOG_MAX_LIMIT = 500;
11
+ export interface DreamRunArgs {
12
+ project?: string;
13
+ dryRun: boolean;
14
+ mode?: DreamMode;
15
+ force: boolean;
16
+ scheduled: boolean;
17
+ json: boolean;
18
+ }
19
+ export interface DreamListArgs {
20
+ project?: string;
21
+ limit: number;
22
+ json: boolean;
23
+ }
24
+ export interface DreamEvalArgs {
25
+ real: boolean;
26
+ model?: string;
27
+ json: boolean;
28
+ }
29
+ type Parsed<T> = {
30
+ ok: true;
31
+ value: T;
32
+ } | {
33
+ ok: false;
34
+ error: string;
35
+ };
36
+ export declare function parseDreamRunArgs(args: string[]): Parsed<DreamRunArgs>;
37
+ export declare function parseDreamListArgs(args: string[], verb: "status" | "log"): Parsed<DreamListArgs>;
38
+ export declare function parseDreamEvalArgs(args: string[]): Parsed<DreamEvalArgs>;
39
+ /** The named project, else the one this folder belongs to. */
40
+ export declare function resolveDreamProject(phrenPath: string, project: string | undefined, profile?: string, cwd?: string): string | undefined;
41
+ export interface DreamRunOutcome {
42
+ project: string;
43
+ status: string;
44
+ result: Record<string, unknown>;
45
+ counts?: Record<string, number>;
46
+ }
47
+ /** Run one dream; the engine owns the marker inside its project lock. */
48
+ export declare function runDream(phrenPath: string, project: string, opts: {
49
+ dryRun?: boolean;
50
+ mode?: DreamMode;
51
+ force?: boolean;
52
+ trigger?: "manual" | "scheduled";
53
+ }): Promise<DreamRunOutcome>;
54
+ /** The last `limit` entries of `dreams/journal.md`, newest first. An entry is a non-blank line that is not a heading. */
55
+ export declare function readDreamJournal(phrenPath: string, project: string, limit?: number): string[];
56
+ /** Status for one project or, with none named or detected, for every project in the profile. */
57
+ export declare function dreamStatuses(phrenPath: string, project: string | undefined, profile?: string, now?: Date): DreamStatus[];
58
+ export declare function handleDreamCommand(args: string[], phrenPath: string, profile?: string): Promise<void>;
59
+ export {};
@@ -0,0 +1,315 @@
1
+ /**
2
+ * `phren dream run|status|log|eval`: the CLI over the dream engine (dream/run.ts)
3
+ * and its outputs under `<store>/<project>/dreams/`. The MCP `dream_*` tools
4
+ * (tools/dream.ts) call the same functions.
5
+ */
6
+ import * as fs from "fs";
7
+ import * as path from "path";
8
+ import { redactSecretsForLog } from "../content/secrets.js";
9
+ import { applyDreamProposals, pendingDreamProposals } from "../dream/apply.js";
10
+ import { detectProject } from "../shared/index.js";
11
+ import { isValidProjectName } from "../utils.js";
12
+ import { dreamStatus, dreamStoreProjects, dreamsDir, dreamOutcomeCounts } from "../bridge/dream-schedule.js";
13
+ import { helperFor } from "../bridge/helper.js";
14
+ import { readDreamConfig } from "../dream/run.js";
15
+ export const DREAM_USAGE = `phren dream - reorganize a project's memory offline (docs/dreaming.md)
16
+
17
+ phren dream run [--project <p>] [--dry-run] [--apply|--propose] [--force] [--json]
18
+ Run a dream now. --dry-run shows the changeset without writing; --apply/--propose
19
+ override dreaming.mode; --force runs even when dreaming is off.
20
+ phren dream apply <runId> [--project <p>] [--only <n,m,...>] [--json]
21
+ Apply pending structured proposals by zero-based index; refuse changed targets.
22
+ phren dream status [--project <p>] [--json]
23
+ Enabled, cadence, last run, next eligible time and last outcome counts
24
+ (every project when --project is omitted and the folder is not a project).
25
+ phren dream log [--project <p>] [--limit <n>] [--json]
26
+ The latest entries of the project's dream journal (dreams/journal.md).
27
+ phren dream eval [--real] [--model <m>] [--json]
28
+ Score the dream engine on the bundled fixture store (a scripted model unless --real).
29
+
30
+ Turn it on with: phren config dreaming set enabled=true [cadence=nightly|idle|weekly|manual]`;
31
+ export const DREAM_LOG_DEFAULT_LIMIT = 20;
32
+ export const DREAM_LOG_MAX_LIMIT = 500;
33
+ function takeValue(args, i, flag) {
34
+ const arg = args[i];
35
+ if (arg.startsWith(`${flag}=`))
36
+ return { value: arg.slice(flag.length + 1), skip: 0 };
37
+ const next = args[i + 1];
38
+ if (next === undefined || next.startsWith("--"))
39
+ return { skip: 0, error: `${flag} needs a value.` };
40
+ return { value: next, skip: 1 };
41
+ }
42
+ function checkProject(project) {
43
+ return project !== undefined && !isValidProjectName(project) ? `Invalid project name: "${project}".` : undefined;
44
+ }
45
+ export function parseDreamRunArgs(args) {
46
+ const out = { dryRun: false, force: false, scheduled: false, json: false };
47
+ const modes = new Set();
48
+ for (let i = 0; i < args.length; i++) {
49
+ const arg = args[i];
50
+ if (arg === "--project" || arg.startsWith("--project=")) {
51
+ const taken = takeValue(args, i, "--project");
52
+ if (taken.error)
53
+ return { ok: false, error: taken.error };
54
+ out.project = taken.value;
55
+ i += taken.skip;
56
+ }
57
+ else if (arg === "--dry-run")
58
+ out.dryRun = true;
59
+ else if (arg === "--apply")
60
+ modes.add("apply");
61
+ else if (arg === "--propose")
62
+ modes.add("propose");
63
+ else if (arg === "--force")
64
+ out.force = true;
65
+ else if (arg === "--scheduled")
66
+ out.scheduled = true;
67
+ else if (arg === "--json")
68
+ out.json = true;
69
+ else
70
+ return { ok: false, error: `Unknown argument for phren dream run: "${arg}".` };
71
+ }
72
+ if (modes.size > 1)
73
+ return { ok: false, error: "Pass --apply or --propose, not both." };
74
+ if (modes.size)
75
+ out.mode = [...modes][0];
76
+ const bad = checkProject(out.project);
77
+ return bad ? { ok: false, error: bad } : { ok: true, value: out };
78
+ }
79
+ export function parseDreamListArgs(args, verb) {
80
+ const out = { limit: DREAM_LOG_DEFAULT_LIMIT, json: false };
81
+ for (let i = 0; i < args.length; i++) {
82
+ const arg = args[i];
83
+ if (arg === "--project" || arg.startsWith("--project=")) {
84
+ const taken = takeValue(args, i, "--project");
85
+ if (taken.error)
86
+ return { ok: false, error: taken.error };
87
+ out.project = taken.value;
88
+ i += taken.skip;
89
+ }
90
+ else if (verb === "log" && (arg === "--limit" || arg.startsWith("--limit="))) {
91
+ const taken = takeValue(args, i, "--limit");
92
+ const n = Number(taken.value);
93
+ if (taken.error || !Number.isInteger(n) || n < 1 || n > DREAM_LOG_MAX_LIMIT) {
94
+ return { ok: false, error: `--limit takes a whole number from 1 to ${DREAM_LOG_MAX_LIMIT}.` };
95
+ }
96
+ out.limit = n;
97
+ i += taken.skip;
98
+ }
99
+ else if (arg === "--json")
100
+ out.json = true;
101
+ else
102
+ return { ok: false, error: `Unknown argument for phren dream ${verb}: "${arg}".` };
103
+ }
104
+ const bad = checkProject(out.project);
105
+ return bad ? { ok: false, error: bad } : { ok: true, value: out };
106
+ }
107
+ export function parseDreamEvalArgs(args) {
108
+ const out = { real: false, json: false };
109
+ for (let i = 0; i < args.length; i++) {
110
+ const arg = args[i];
111
+ if (arg === "--real")
112
+ out.real = true;
113
+ else if (arg === "--json")
114
+ out.json = true;
115
+ else if (arg === "--model" || arg.startsWith("--model=")) {
116
+ const taken = takeValue(args, i, "--model");
117
+ if (taken.error)
118
+ return { ok: false, error: taken.error };
119
+ out.model = taken.value;
120
+ i += taken.skip;
121
+ }
122
+ else
123
+ return { ok: false, error: `Unknown argument for phren dream eval: "${arg}".` };
124
+ }
125
+ return { ok: true, value: out };
126
+ }
127
+ /** The named project, else the one this folder belongs to. */
128
+ export function resolveDreamProject(phrenPath, project, profile, cwd = process.cwd()) {
129
+ return project ?? detectProject(phrenPath, cwd, profile) ?? undefined;
130
+ }
131
+ /** Run one dream; the engine owns the marker inside its project lock. */
132
+ export async function runDream(phrenPath, project, opts) {
133
+ const { dream } = await import("../dream/run.js");
134
+ // The store travels along for an engine that takes it; one that reads PHREN_PATH ignores it.
135
+ const store = { phrenPath };
136
+ const result = await dream(project, { ...store, dryRun: opts.dryRun, mode: opts.mode, force: opts.force, trigger: opts.trigger ?? "manual", now: new Date() });
137
+ const record = result && typeof result === "object" ? result : { status: "error", error: "The dream engine returned nothing." };
138
+ const status = typeof record.status === "string" ? record.status : "error";
139
+ const counts = dreamOutcomeCounts(record);
140
+ return { project, status, result: record, ...(counts ? { counts } : {}) };
141
+ }
142
+ /** The last `limit` entries of `dreams/journal.md`, newest first. An entry is a non-blank line that is not a heading. */
143
+ export function readDreamJournal(phrenPath, project, limit = DREAM_LOG_DEFAULT_LIMIT) {
144
+ const dir = dreamsDir(phrenPath, project);
145
+ if (!dir)
146
+ return [];
147
+ let text;
148
+ try {
149
+ text = fs.readFileSync(path.join(dir, "journal.md"), "utf8");
150
+ }
151
+ catch {
152
+ return [];
153
+ }
154
+ return text.split(/\r?\n/).map((line) => line.trimEnd()).filter((line) => line.trim() && !line.startsWith("#")).slice(-limit).reverse().map(redactSecretsForLog);
155
+ }
156
+ /** Status for one project or, with none named or detected, for every project in the profile. */
157
+ export function dreamStatuses(phrenPath, project, profile, now = new Date()) {
158
+ const names = project ? [project] : dreamStoreProjects(phrenPath, profile).sort();
159
+ return names.map((name) => ({ ...dreamStatus(phrenPath, name, now), runsOn: helperSummary(phrenPath, name) }));
160
+ }
161
+ /** Dreams run on the project's helper account (role helpers), never silently on another login. */
162
+ function helperSummary(phrenPath, project) {
163
+ try {
164
+ const choice = helperFor(phrenPath, project);
165
+ const model = readDreamConfig(phrenPath, project).model;
166
+ return `helper ${choice.account} · ${model || choice.model}`;
167
+ }
168
+ catch (err) {
169
+ return `no helper account, so dreams can't run yet: ${err instanceof Error ? err.message : String(err)}`;
170
+ }
171
+ }
172
+ function formatStatus(status) {
173
+ const lines = [`${status.project}: dreaming ${status.enabled ? "on" : "off"} · ${status.cadence}${status.cadence === "nightly" || status.cadence === "weekly" ? ` ${status.window}` : ""} · ${status.mode}`];
174
+ if (status.lastRun) {
175
+ const counts = status.lastOutcome ? ` (${Object.entries(status.lastOutcome).map(([k, n]) => `${k} ${n}`).join(", ")})` : "";
176
+ lines.push(` last run: ${status.lastRun.at} ${status.lastRun.status}${status.lastRun.trigger ? `, ${status.lastRun.trigger}` : ""}${counts}`);
177
+ }
178
+ else
179
+ lines.push(" last run: never");
180
+ lines.push(` next: ${status.nextEligibleAt ?? "—"} · ${status.reason}`);
181
+ lines.push(` pending proposals: ${status.pendingProposals}`);
182
+ if (status.runsOn)
183
+ lines.push(` runs on: ${status.runsOn}`);
184
+ return lines.join("\n");
185
+ }
186
+ function fail(message) {
187
+ console.error(redactSecretsForLog(message));
188
+ process.exitCode = 1;
189
+ }
190
+ export async function handleDreamCommand(args, phrenPath, profile) {
191
+ const [verb, ...rest] = args;
192
+ switch (verb) {
193
+ case "apply": {
194
+ const [runId, ...flags] = rest;
195
+ if (!runId)
196
+ return fail("Name the dream run ID.");
197
+ let only;
198
+ const listFlags = [];
199
+ for (let i = 0; i < flags.length; i++) {
200
+ if (flags[i] === "--only" || flags[i].startsWith("--only=")) {
201
+ const taken = takeValue(flags, i, "--only");
202
+ if (taken.error || !/^\d+(,\d+)*$/.test(taken.value ?? ""))
203
+ return fail("--only takes comma-separated nonnegative proposal indices.");
204
+ only = taken.value.split(",").map(Number);
205
+ i += taken.skip;
206
+ }
207
+ else
208
+ listFlags.push(flags[i]);
209
+ }
210
+ const parsed = parseDreamListArgs(listFlags, "status");
211
+ if (!parsed.ok)
212
+ return fail(parsed.error);
213
+ const project = resolveDreamProject(phrenPath, parsed.value.project, profile);
214
+ if (!project)
215
+ return fail("Name the project with --project <name>.");
216
+ try {
217
+ const record = await applyDreamProposals(phrenPath, project, runId, only);
218
+ console.log(parsed.value.json ? JSON.stringify(record, null, 2) : record.outcomes.map(o => `${o.index}: ${o.op} ${o.status} — ${o.detail}`).join("\n"));
219
+ }
220
+ catch (err) {
221
+ fail(err instanceof Error ? err.message : String(err));
222
+ }
223
+ return;
224
+ }
225
+ case "run": {
226
+ const parsed = parseDreamRunArgs(rest);
227
+ if (!parsed.ok)
228
+ return fail(`${parsed.error}\n\n${DREAM_USAGE}`);
229
+ const project = resolveDreamProject(phrenPath, parsed.value.project, profile);
230
+ if (!project)
231
+ return fail("Name the project with --project <name>; this folder is not one of your projects.");
232
+ const outcome = await runDream(phrenPath, project, { dryRun: parsed.value.dryRun, mode: parsed.value.mode, force: parsed.value.force,
233
+ trigger: parsed.value.scheduled ? "scheduled" : "manual" });
234
+ if (parsed.value.json)
235
+ console.log(JSON.stringify(outcome, null, 2));
236
+ else {
237
+ const counts = outcome.counts && Object.keys(outcome.counts).length ? ` · ${Object.entries(outcome.counts).map(([k, n]) => `${k} ${n}`).join(", ")}` : "";
238
+ const runId = typeof outcome.result.runId === "string" ? ` ${outcome.result.runId}` : "";
239
+ console.log(`Dream${runId} for ${project}: ${outcome.status}${parsed.value.dryRun ? " (dry run)" : ""}${counts}`);
240
+ if (Array.isArray(outcome.result.warnings))
241
+ for (const warning of outcome.result.warnings)
242
+ console.log(redactSecretsForLog(String(warning)));
243
+ if (outcome.status === "disabled")
244
+ console.log("Dreaming is off for this project. `phren config dreaming set enabled=true` turns it on; --force runs once anyway.");
245
+ if (outcome.status === "busy")
246
+ console.log("Another dream for this project is running.");
247
+ if (typeof outcome.result.error === "string")
248
+ console.error(outcome.result.error);
249
+ else if (outcome.status === "failed" && typeof outcome.result.message === "string")
250
+ console.error(outcome.result.message);
251
+ if (parsed.value.dryRun && outcome.result.changeset)
252
+ console.log(JSON.stringify(outcome.result.changeset, null, 2));
253
+ }
254
+ if (outcome.status === "error" || outcome.status === "failed")
255
+ process.exitCode = 1;
256
+ return;
257
+ }
258
+ case "status": {
259
+ const parsed = parseDreamListArgs(rest, "status");
260
+ if (!parsed.ok)
261
+ return fail(`${parsed.error}\n\n${DREAM_USAGE}`);
262
+ const project = resolveDreamProject(phrenPath, parsed.value.project, profile);
263
+ const statuses = dreamStatuses(phrenPath, project, profile);
264
+ if (parsed.value.json)
265
+ console.log(JSON.stringify(project ? statuses[0] : statuses, null, 2));
266
+ else
267
+ console.log(statuses.length ? statuses.map(formatStatus).join("\n\n") : "No projects.");
268
+ return;
269
+ }
270
+ case "log": {
271
+ const parsed = parseDreamListArgs(rest, "log");
272
+ if (!parsed.ok)
273
+ return fail(`${parsed.error}\n\n${DREAM_USAGE}`);
274
+ const project = resolveDreamProject(phrenPath, parsed.value.project, profile);
275
+ if (!project)
276
+ return fail("Name the project with --project <name>; this folder is not one of your projects.");
277
+ const entries = readDreamJournal(phrenPath, project, parsed.value.limit);
278
+ if (parsed.value.json)
279
+ console.log(JSON.stringify({ project, entries, pendingProposals: pendingDreamProposals(phrenPath, project) }, null, 2));
280
+ else
281
+ console.log((entries.length ? entries.join("\n") : `No dreams recorded for ${project} yet.`) + `\nPending proposals: ${pendingDreamProposals(phrenPath, project)}`);
282
+ return;
283
+ }
284
+ case "eval": {
285
+ const parsed = parseDreamEvalArgs(rest);
286
+ if (!parsed.ok)
287
+ return fail(`${parsed.error}\n\n${DREAM_USAGE}`);
288
+ // The harness lives in dream/eval/ (worker C); resolved at run time so the CLI never depends on it to build.
289
+ const specifier = "../dream/eval/index.js";
290
+ let mod;
291
+ try {
292
+ mod = await import(specifier);
293
+ }
294
+ catch {
295
+ return fail("The dream eval harness is not installed in this build.");
296
+ }
297
+ const run = (mod.runDreamEval ?? mod.default);
298
+ if (typeof run !== "function")
299
+ return fail("The dream eval harness exports no runDreamEval.");
300
+ const report = await run({ real: parsed.value.real, ...(parsed.value.model ? { model: parsed.value.model } : {}) });
301
+ console.log(parsed.value.json || typeof report !== "string" ? JSON.stringify(report, null, 2) : report);
302
+ const passed = report && typeof report === "object" ? report.passed : undefined;
303
+ if (passed === false)
304
+ process.exitCode = 1;
305
+ return;
306
+ }
307
+ case undefined:
308
+ case "help":
309
+ case "--help":
310
+ console.log(DREAM_USAGE);
311
+ return;
312
+ default:
313
+ return fail(`Unknown dream subcommand "${verb}".\n\n${DREAM_USAGE}`);
314
+ }
315
+ }
@@ -8,6 +8,7 @@ import { addTask, completeTask, updateTask, reorderTask, pinTask, removeTask, wo
8
8
  import { buildTaskIssueBody, createGithubIssueForTask, parseGithubIssueUrl, resolveProjectGithubRepo } from "../task/github.js";
9
9
  function printTaskUsage() {
10
10
  console.log("Usage:");
11
+ console.log(" phren tasks reconcile [project] [--dry-run | --apply]");
11
12
  console.log(' phren task list [profile|project] [--responsibility=human|agent] [--readiness=ready|waiting-on-human|waiting-on-task]');
12
13
  console.log(' phren task format [--json | enable --all-writers-compatible]');
13
14
  console.log(' phren task add <project> "<text>"');
@@ -45,6 +46,17 @@ export async function handleTaskNamespace(args) {
45
46
  printTaskUsage();
46
47
  return;
47
48
  }
49
+ if (subcommand === "reconcile") {
50
+ const argsRest = args.slice(1);
51
+ if (argsRest.some(arg => arg.startsWith("--") && !["--dry-run", "--apply"].includes(arg)) || argsRest.filter(arg => !arg.startsWith("--")).length > 1 || (argsRest.includes("--dry-run") && argsRest.includes("--apply")))
52
+ throw new Error("Usage: phren tasks reconcile [project] [--dry-run | --apply]");
53
+ const { reconcileTasks } = await import("../task/reconcile.js");
54
+ const result = await reconcileTasks(getPhrenPath(), { project: argsRest.find(arg => !arg.startsWith("--")), dryRun: argsRest.includes("--dry-run"), apply: argsRest.includes("--apply") });
55
+ console.log(`${result.dryRun ? "Dry run" : "Reconciled"}: ${result.checked} linked tasks checked, ${result.done} done, ${result.review} for review, ${result.linked} links imported, ${result.errors} errors (${result.requests} GitHub reads).`);
56
+ if (result.dryRun)
57
+ console.log("No tasks changed. Use --apply to enable updates for future sweeps; --dry-run always previews.");
58
+ return;
59
+ }
48
60
  if (subcommand === "list") {
49
61
  // Delegate to the cross-project task view (same as `phren tasks`)
50
62
  return handleTaskListArgs(args.slice(1), resolveRuntimeProfile(getPhrenPath()));
@@ -448,6 +460,8 @@ export async function handleTaskNamespace(args) {
448
460
  process.exit(1);
449
461
  }
450
462
  export async function handleTaskListArgs(args, defaultProfile) {
463
+ if (args[0] === "reconcile")
464
+ return handleTaskNamespace(args);
451
465
  const { handleTaskView } = await import("./ops.js");
452
466
  const { z } = await import("zod");
453
467
  const filter = z.object({ responsibility: z.enum(["human", "agent"]).optional(), readiness: z.enum(["ready", "waiting-on-human", "waiting-on-task"]).optional() }).strict().safeParse(Object.fromEntries(args.filter(a => a.startsWith("--")).map(a => a.slice(2).split("="))));
@@ -73,6 +73,12 @@ const SCHEDULE_SUBCOMMANDS = [
73
73
  { name: "run", usage: "phren schedule run <project> <id>", summary: "Run a schedule through the local Hook" },
74
74
  { name: "history", usage: "phren schedule history [project] [--id <id>] [--limit <n>]", summary: "Show local schedule runs" },
75
75
  ];
76
+ const DREAM_SUBCOMMANDS = [
77
+ { name: "run", usage: "phren dream run [--project <p>] [--dry-run] [--apply|--propose] [--force] [--json]", summary: "Run a dream now" },
78
+ { name: "status", usage: "phren dream status [--project <p>] [--json]", summary: "Enabled, cadence, last run, next eligible time" },
79
+ { name: "log", usage: "phren dream log [--project <p>] [--limit <n>] [--json]", summary: "Read the dream journal" },
80
+ { name: "eval", usage: "phren dream eval [--real] [--model <m>] [--json]", summary: "Score the dream engine on its fixture store" },
81
+ ];
76
82
  const SKILLS_SUBCOMMANDS = [
77
83
  { name: "list", usage: "phren skills list", summary: "List installed skills" },
78
84
  { name: "add", usage: "phren skills add <project> <path>", summary: "Link a skill into a project" },
@@ -133,6 +139,12 @@ const TEAM_SUBCOMMANDS = [
133
139
  ];
134
140
  // ── Registry ─────────────────────────────────────────────────────────────────
135
141
  export const REGISTRY = [
142
+ { name: "browser", topic: "setup", usage: "phren browser <env|ask>", summary: "Watch a browser or ask the owner for help", standalone: true,
143
+ subcommands: [
144
+ { name: "env", usage: "phren browser env", summary: "Print browser watching environment" },
145
+ { name: "ask", usage: 'phren browser ask "<reason>" [--browser <id>] [--timeout <s>]', summary: "Wait for owner help (900 s default); Ctrl-C cancels" },
146
+ ],
147
+ run: async (args) => { const { runBrowser } = await import("./bridge/browser-env.js"); return runBrowser(args); } },
136
148
  {
137
149
  name: "pair", topic: "setup", usage: "phren pair [--minutes <1-30>] [--port <n>] [--no-install] | phren pair --scope gitboy-read|gitboy-write --key <public-key-file|->",
138
150
  summary: "Connect your phone with a pairing QR code, or authorize a scoped key for gitboy (gitboy-read: project memory; gitboy-write: save findings)",
@@ -338,7 +350,7 @@ export const REGISTRY = [
338
350
  {
339
351
  name: "tasks",
340
352
  topic: "core",
341
- usage: "phren tasks [profile] [--responsibility=human|agent] [--readiness=ready|waiting-on-human|waiting-on-task]",
353
+ usage: "phren tasks [profile|reconcile [project] [--dry-run | --apply]] [--responsibility=human|agent] [--readiness=ready|waiting-on-human|waiting-on-task]",
342
354
  summary: "Cross-project task view",
343
355
  featured: true,
344
356
  run: async (args, ctx) => {
@@ -598,6 +610,17 @@ export const REGISTRY = [
598
610
  await handleMaintain(args);
599
611
  },
600
612
  },
613
+ {
614
+ name: "dream",
615
+ topic: "maintain",
616
+ usage: "phren dream <subcommand>",
617
+ summary: "Reorganize a project's memory offline (dreaming)",
618
+ subcommands: DREAM_SUBCOMMANDS,
619
+ run: async (args, ctx) => {
620
+ const { handleDreamCommand } = await import("./cli/dream.js");
621
+ await handleDreamCommand(args, ctx.phrenPath(), ctx.profile());
622
+ },
623
+ },
601
624
  {
602
625
  name: "consolidation-status",
603
626
  topic: "maintain",