@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.
Files changed (164) hide show
  1. package/dist/bridge/agent-hooks.js +11 -1
  2. package/dist/bridge/browser-env.d.ts +5 -0
  3. package/dist/bridge/browser-env.js +110 -0
  4. package/dist/bridge/browser-protocol.d.ts +120 -0
  5. package/dist/bridge/browser-protocol.js +70 -0
  6. package/dist/bridge/browser-recordings.d.ts +63 -0
  7. package/dist/bridge/browser-recordings.js +148 -0
  8. package/dist/bridge/browser-registry.d.ts +64 -0
  9. package/dist/bridge/browser-registry.js +262 -0
  10. package/dist/bridge/browser-routes.d.ts +4 -0
  11. package/dist/bridge/browser-routes.js +39 -0
  12. package/dist/bridge/browser-shim/phren-playwright.cjs +184 -0
  13. package/dist/bridge/browser-socket.d.ts +2 -0
  14. package/dist/bridge/browser-socket.js +10 -0
  15. package/dist/bridge/browser-stream.d.ts +3 -0
  16. package/dist/bridge/browser-stream.js +129 -0
  17. package/dist/bridge/browser-watch.d.ts +12 -0
  18. package/dist/bridge/browser-watch.js +83 -0
  19. package/dist/bridge/claude-account-setup.js +3 -1
  20. package/dist/bridge/claude-accounts.d.ts +5 -1
  21. package/dist/bridge/claude-accounts.js +36 -6
  22. package/dist/bridge/codex-servers.d.ts +2 -0
  23. package/dist/bridge/codex-servers.js +1 -1
  24. package/dist/bridge/command.js +24 -5
  25. package/dist/bridge/dispatch-clone.d.ts +33 -0
  26. package/dist/bridge/dispatch-clone.js +176 -0
  27. package/dist/bridge/dispatch-command.d.ts +14 -0
  28. package/dist/bridge/dispatch-command.js +98 -13
  29. package/dist/bridge/dispatch-idempotency.d.ts +85 -0
  30. package/dist/bridge/dispatch-idempotency.js +235 -0
  31. package/dist/bridge/dispatch-returns.d.ts +6 -0
  32. package/dist/bridge/dispatch-returns.js +131 -1
  33. package/dist/bridge/dispatch-wait.d.ts +32 -0
  34. package/dist/bridge/dispatch-wait.js +177 -0
  35. package/dist/bridge/dispatch.d.ts +78 -2
  36. package/dist/bridge/dispatch.js +841 -25
  37. package/dist/bridge/dream-schedule.d.ts +133 -0
  38. package/dist/bridge/dream-schedule.js +322 -0
  39. package/dist/bridge/fanouts.js +20 -3
  40. package/dist/bridge/files.d.ts +1 -1
  41. package/dist/bridge/git-credential.d.ts +44 -0
  42. package/dist/bridge/git-credential.js +113 -0
  43. package/dist/bridge/git-host-auth.d.ts +9 -1
  44. package/dist/bridge/git-host-auth.js +18 -5
  45. package/dist/bridge/git-host-gitboy.js +8 -1
  46. package/dist/bridge/git-hosts.d.ts +12 -1
  47. package/dist/bridge/git-publish.js +3 -2
  48. package/dist/bridge/herdr.d.ts +4 -0
  49. package/dist/bridge/herdr.js +44 -9
  50. package/dist/bridge/install.d.ts +1 -1
  51. package/dist/bridge/install.js +12 -4
  52. package/dist/bridge/launch-brief.d.ts +11 -0
  53. package/dist/bridge/launch-brief.js +22 -0
  54. package/dist/bridge/launch-worktree.d.ts +2 -0
  55. package/dist/bridge/launch-worktree.js +5 -1
  56. package/dist/bridge/pane-status.js +1 -1
  57. package/dist/bridge/protocol.d.ts +7 -0
  58. package/dist/bridge/schedule-watch.js +13 -2
  59. package/dist/bridge/server-launch.d.ts +2 -0
  60. package/dist/bridge/server-launch.js +251 -145
  61. package/dist/bridge/server-routes.d.ts +3 -0
  62. package/dist/bridge/server-routes.js +33 -17
  63. package/dist/bridge/server-stream.d.ts +4 -0
  64. package/dist/bridge/server-stream.js +24 -5
  65. package/dist/bridge/server.js +35 -4
  66. package/dist/bridge/session-move.d.ts +10 -4
  67. package/dist/bridge/session-move.js +65 -34
  68. package/dist/bridge/simulator-stream.d.ts +2 -0
  69. package/dist/bridge/simulator-stream.js +2 -0
  70. package/dist/bridge/status-line-fast.d.ts +9 -0
  71. package/dist/bridge/status-line-fast.js +56 -0
  72. package/dist/bridge/tab-activity.d.ts +2 -0
  73. package/dist/bridge/tab-activity.js +15 -2
  74. package/dist/bridge/task-routes.d.ts +20 -16
  75. package/dist/bridge/task-routes.js +1 -1
  76. package/dist/bridge/terminal-herdr.d.ts +5 -1
  77. package/dist/bridge/terminal-herdr.js +67 -2
  78. package/dist/bridge/terminal-tmux.d.ts +2 -0
  79. package/dist/bridge/terminal-tmux.js +29 -7
  80. package/dist/bridge/terminal.d.ts +5 -1
  81. package/dist/bridge/transcript-claude.js +192 -112
  82. package/dist/bridge/transcript-preview.d.ts +2 -1
  83. package/dist/bridge/transcript-preview.js +85 -3
  84. package/dist/bridge/transcripts.js +17 -11
  85. package/dist/bridge/turn-records.js +16 -4
  86. package/dist/bridge/usage.d.ts +7 -1
  87. package/dist/bridge/usage.js +47 -31
  88. package/dist/bridge/worker-close.d.ts +15 -0
  89. package/dist/bridge/worker-close.js +304 -3
  90. package/dist/bridge/worker-identity.d.ts +51 -0
  91. package/dist/bridge/worker-identity.js +289 -0
  92. package/dist/bridge/worker-reports.js +15 -3
  93. package/dist/bridge-hook.mjs +39990 -36152
  94. package/dist/capabilities/mcp.js +1 -1
  95. package/dist/cli/browser-hint.d.ts +2 -0
  96. package/dist/cli/browser-hint.js +21 -0
  97. package/dist/cli/config-dreaming.d.ts +7 -0
  98. package/dist/cli/config-dreaming.js +72 -0
  99. package/dist/cli/config.js +6 -0
  100. package/dist/cli/dream.d.ts +59 -0
  101. package/dist/cli/dream.js +315 -0
  102. package/dist/cli/hooks-context.d.ts +2 -2
  103. package/dist/cli/hooks-context.js +3 -3
  104. package/dist/cli/hooks.js +20 -11
  105. package/dist/cli/namespaces-tasks.js +14 -0
  106. package/dist/cli-registry.js +28 -3
  107. package/dist/config/dreaming.d.ts +82 -0
  108. package/dist/config/dreaming.js +195 -0
  109. package/dist/config/resolve.js +11 -0
  110. package/dist/config/schema.d.ts +4 -4
  111. package/dist/config/schema.js +157 -1
  112. package/dist/content/citation-freshness.js +6 -0
  113. package/dist/content/learning.d.ts +1 -0
  114. package/dist/content/learning.js +2 -0
  115. package/dist/data/access.d.ts +1 -1
  116. package/dist/data/access.js +3 -1
  117. package/dist/data/task-contract.d.ts +5 -4
  118. package/dist/data/tasks.d.ts +5 -0
  119. package/dist/data/tasks.js +28 -2
  120. package/dist/dream/apply.d.ts +69 -0
  121. package/dist/dream/apply.js +372 -0
  122. package/dist/dream/budget.d.ts +78 -0
  123. package/dist/dream/budget.js +180 -0
  124. package/dist/dream/collect.d.ts +86 -0
  125. package/dist/dream/collect.js +449 -0
  126. package/dist/dream/eval/dream-adapter.d.ts +16 -0
  127. package/dist/dream/eval/dream-adapter.js +21 -0
  128. package/dist/dream/eval/fixture.d.ts +53 -0
  129. package/dist/dream/eval/fixture.js +172 -0
  130. package/dist/dream/eval/index.d.ts +40 -0
  131. package/dist/dream/eval/index.js +78 -0
  132. package/dist/dream/eval/score.d.ts +34 -0
  133. package/dist/dream/eval/score.js +99 -0
  134. package/dist/dream/eval/scripted-model.d.ts +19 -0
  135. package/dist/dream/eval/scripted-model.js +70 -0
  136. package/dist/dream/pages.d.ts +68 -0
  137. package/dist/dream/pages.js +220 -0
  138. package/dist/dream/privacy.d.ts +3 -0
  139. package/dist/dream/privacy.js +18 -0
  140. package/dist/dream/prompt.d.ts +13 -0
  141. package/dist/dream/prompt.js +84 -0
  142. package/dist/dream/run.d.ts +98 -0
  143. package/dist/dream/run.js +317 -0
  144. package/dist/dream/types.d.ts +74 -0
  145. package/dist/dream/types.js +4 -0
  146. package/dist/finding/lifecycle.d.ts +2 -2
  147. package/dist/finding/lifecycle.js +5 -2
  148. package/dist/finding/versions.d.ts +4 -0
  149. package/dist/finding/versions.js +28 -0
  150. package/dist/index.js +1 -0
  151. package/dist/modules/registry.js +10 -8
  152. package/dist/project-config.d.ts +3 -0
  153. package/dist/task/merge-links.d.ts +38 -0
  154. package/dist/task/merge-links.js +45 -0
  155. package/dist/task/reconcile.d.ts +39 -0
  156. package/dist/task/reconcile.js +201 -0
  157. package/dist/task/report-links.d.ts +10 -0
  158. package/dist/task/report-links.js +47 -0
  159. package/dist/tools/config.js +46 -4
  160. package/dist/tools/dispatch.js +2 -1
  161. package/dist/tools/dream.d.ts +3 -0
  162. package/dist/tools/dream.js +123 -0
  163. package/dist/tools/tasks.js +4 -1
  164. package/package.json +1 -1
@@ -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 [--session <name>] [--json | --fish]", summary: 'Start Playwright after eval "$(phren browser env)"; see Bun preload guidance in output' },
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)",
@@ -143,7 +155,7 @@ export const REGISTRY = [
143
155
  },
144
156
  },
145
157
  {
146
- name: "bridge", topic: "setup", usage: "phren bridge <install|status|doctor|update|rollback|uninstall|enroll-computer|accounts|discover|link|fanouts archive|git-host|speech-key set|speech-voice|speech-model|speech-region>",
158
+ name: "bridge", topic: "setup", usage: "phren bridge <install|status|doctor|update|rollback|uninstall|enroll-computer|accounts|discover|link|fanouts archive|git-host|git-credential|speech-key set|speech-voice|speech-model|speech-region>",
147
159
  summary: "Install Phren Hook and enroll phone or computer connections",
148
160
  subcommands: [
149
161
  { name: "enroll-computer", usage: "phren bridge enroll-computer <name> [--accept <public-key-file>]", summary: "Print or accept a restricted computer dispatch key" },
@@ -164,9 +176,11 @@ export const REGISTRY = [
164
176
  },
165
177
  },
166
178
  {
167
- name: "dispatch", topic: "core", usage: "phren dispatch <computer|anywhere> <project> --label <label> --prompt <brief> [--harness codex|claude|opencode|copilot] [--model <model>] [--effort <effort>] [--account <id>] [--permission-mode <mode>] [--keep-open]",
179
+ name: "dispatch", topic: "core", usage: "phren dispatch <computer|anywhere|local> <project> --prompt <brief> | --prompt-file <path|-> [--harness codex|claude|opencode|copilot] [--label <label>] [--idempotency-key <key>] [--worktree [--branch <name>]] [--model <model>] [--effort <effort>] [--account <id>] [--permission-mode <mode>] [--keep-open]",
168
180
  summary: "Dispatch a worker brief through Phren Hook",
169
181
  subcommands: [{ name: "status", usage: "phren dispatch status", summary: "List local dispatch receipts" },
182
+ { name: "wait", usage: "phren dispatch wait <dispatch-id> [--timeout <seconds>] [--json] [--follow]", summary: "Follow one local dispatch to its end as NDJSON; exits 0 done, 1 failed or gone, 124 timeout" },
183
+ { name: "close", usage: "phren dispatch close <dispatch-id> | phren dispatch close --idempotency-key <key>", summary: "Cancel a running local dispatch by id or idempotency key: stop its agent and close its pane" },
170
184
  { name: "returns", usage: "phren dispatch returns [--watch [--json] [--consume]]", summary: "List unread worker returns (done, needs you, blocked, gone) and mark them read; --watch prints them as they land until Ctrl-C, leaving them unread unless --consume" },
171
185
  { name: "sessions", usage: "phren dispatch sessions", summary: "List live agent sessions on this and every enrolled computer" },
172
186
  { name: "usage", usage: "phren dispatch usage [--json]", summary: "Show agent usage on this and every enrolled computer, merged by account" },
@@ -338,7 +352,7 @@ export const REGISTRY = [
338
352
  {
339
353
  name: "tasks",
340
354
  topic: "core",
341
- usage: "phren tasks [profile] [--responsibility=human|agent] [--readiness=ready|waiting-on-human|waiting-on-task]",
355
+ usage: "phren tasks [profile|reconcile [project] [--dry-run | --apply]] [--responsibility=human|agent] [--readiness=ready|waiting-on-human|waiting-on-task]",
342
356
  summary: "Cross-project task view",
343
357
  featured: true,
344
358
  run: async (args, ctx) => {
@@ -598,6 +612,17 @@ export const REGISTRY = [
598
612
  await handleMaintain(args);
599
613
  },
600
614
  },
615
+ {
616
+ name: "dream",
617
+ topic: "maintain",
618
+ usage: "phren dream <subcommand>",
619
+ summary: "Reorganize a project's memory offline (dreaming)",
620
+ subcommands: DREAM_SUBCOMMANDS,
621
+ run: async (args, ctx) => {
622
+ const { handleDreamCommand } = await import("./cli/dream.js");
623
+ await handleDreamCommand(args, ctx.phrenPath(), ctx.profile());
624
+ },
625
+ },
601
626
  {
602
627
  name: "consolidation-status",
603
628
  topic: "maintain",
@@ -0,0 +1,82 @@
1
+ /**
2
+ * The `dreaming` config domain: the offline pass that reorganizes a project's
3
+ * memory between sessions (docs/dreaming.md). Off by default.
4
+ *
5
+ * Global values live in `.config/dreaming.json`; a project overrides any of
6
+ * them under `config.dreaming` in its `phren.project.yaml`. Reads are lenient
7
+ * (an invalid value falls back to the level below it); writes validate and say
8
+ * why a value was refused.
9
+ */
10
+ export declare const DREAM_MODES: readonly ["propose", "apply"];
11
+ export type DreamMode = typeof DREAM_MODES[number];
12
+ export declare const DREAM_CADENCES: readonly ["nightly", "idle", "weekly", "manual"];
13
+ export type DreamCadence = typeof DREAM_CADENCES[number];
14
+ export declare const DREAM_PHASES: readonly ["capture", "correct", "organize", "prune"];
15
+ export type DreamPhase = typeof DREAM_PHASES[number];
16
+ export interface DreamingConfig {
17
+ enabled: boolean;
18
+ mode: DreamMode;
19
+ cadence: DreamCadence;
20
+ /** `HH:MM-HH:MM` local time; may wrap midnight (`22:00-02:00`). */
21
+ window: string;
22
+ idleMinutes: number;
23
+ lookbackHours: number;
24
+ maxChanges: number;
25
+ injectBudgetKB: number;
26
+ phases: DreamPhase[];
27
+ /** Empty means the project's helper model. */
28
+ model: string;
29
+ }
30
+ export declare const DEFAULT_DREAMING_CONFIG: Readonly<DreamingConfig>;
31
+ /** Inclusive ranges for the numeric keys; the schema descriptors share them. */
32
+ export declare const DREAMING_RANGES: {
33
+ readonly idleMinutes: {
34
+ readonly min: 5;
35
+ readonly max: 1440;
36
+ readonly step: 5;
37
+ };
38
+ readonly lookbackHours: {
39
+ readonly min: 1;
40
+ readonly max: 720;
41
+ readonly step: 1;
42
+ };
43
+ readonly maxChanges: {
44
+ readonly min: 1;
45
+ readonly max: 200;
46
+ readonly step: 1;
47
+ };
48
+ readonly injectBudgetKB: {
49
+ readonly min: 1;
50
+ readonly max: 256;
51
+ readonly step: 1;
52
+ };
53
+ };
54
+ export declare const DREAMING_KEYS: Array<keyof DreamingConfig>;
55
+ /** Minutes after local midnight for each end of a `HH:MM-HH:MM` window, or null when malformed. */
56
+ export declare function parseDreamWindow(window: string): {
57
+ start: number;
58
+ end: number;
59
+ } | null;
60
+ /** True when `date`'s local time of day falls inside the window (start inclusive, end exclusive). */
61
+ export declare function insideDreamWindow(window: string, date: Date): boolean;
62
+ export interface DreamingPatchResult {
63
+ patch: Partial<DreamingConfig>;
64
+ /** One sentence per refused key. */
65
+ errors: string[];
66
+ /** Keys that are not dreaming settings. */
67
+ unknown: string[];
68
+ }
69
+ /** Validate a user-supplied partial config. Values may be strings (CLI) or typed (MCP, JSON). */
70
+ export declare function parseDreamingPatch(raw: unknown): DreamingPatchResult;
71
+ /** The valid keys of a stored object; anything malformed is dropped so the level below shows through. */
72
+ export declare function normalizeDreamingLevel(raw: unknown): Partial<DreamingConfig>;
73
+ export declare function globalDreamingPath(phrenPath: string): string;
74
+ export declare function readGlobalDreaming(phrenPath: string): Partial<DreamingConfig>;
75
+ export declare function readProjectDreaming(phrenPath: string, project: string): Partial<DreamingConfig>;
76
+ /** The effective dreaming config: defaults, then the global file, then the project's override. */
77
+ export declare function getDreamingConfig(phrenPath: string, project?: string): DreamingConfig;
78
+ /**
79
+ * Write a validated patch globally or for one project. `null` for a key on a
80
+ * project removes that project's override so it inherits again.
81
+ */
82
+ export declare function updateDreamingConfig(phrenPath: string, patch: Partial<DreamingConfig>, project?: string, clear?: Array<keyof DreamingConfig>): Partial<DreamingConfig>;
@@ -0,0 +1,195 @@
1
+ /**
2
+ * The `dreaming` config domain: the offline pass that reorganizes a project's
3
+ * memory between sessions (docs/dreaming.md). Off by default.
4
+ *
5
+ * Global values live in `.config/dreaming.json`; a project overrides any of
6
+ * them under `config.dreaming` in its `phren.project.yaml`. Reads are lenient
7
+ * (an invalid value falls back to the level below it); writes validate and say
8
+ * why a value was refused.
9
+ */
10
+ import * as crypto from "crypto";
11
+ import * as fs from "fs";
12
+ import * as path from "path";
13
+ import { appendAuditLog, isRecord } from "../shared.js";
14
+ import { withFileLock } from "../governance/locks.js";
15
+ import { readProjectConfig, updateProjectConfigOverrides } from "../project-config.js";
16
+ export const DREAM_MODES = ["propose", "apply"];
17
+ export const DREAM_CADENCES = ["nightly", "idle", "weekly", "manual"];
18
+ export const DREAM_PHASES = ["capture", "correct", "organize", "prune"];
19
+ export const DEFAULT_DREAMING_CONFIG = Object.freeze({
20
+ enabled: false,
21
+ mode: "propose",
22
+ cadence: "nightly",
23
+ window: "02:00-05:00",
24
+ idleMinutes: 45,
25
+ lookbackHours: 24,
26
+ maxChanges: 25,
27
+ injectBudgetKB: 8,
28
+ phases: [...DREAM_PHASES],
29
+ model: "",
30
+ });
31
+ /** Inclusive ranges for the numeric keys; the schema descriptors share them. */
32
+ export const DREAMING_RANGES = {
33
+ idleMinutes: { min: 5, max: 1440, step: 5 },
34
+ lookbackHours: { min: 1, max: 720, step: 1 },
35
+ maxChanges: { min: 1, max: 200, step: 1 },
36
+ injectBudgetKB: { min: 1, max: 256, step: 1 },
37
+ };
38
+ export const DREAMING_KEYS = Object.keys(DEFAULT_DREAMING_CONFIG);
39
+ const WINDOW_RE = /^([01]\d|2[0-3]):([0-5]\d)-([01]\d|2[0-3]):([0-5]\d)$/;
40
+ const MODEL_RE = /^[A-Za-z0-9][A-Za-z0-9._:\[\]-]{0,99}$/;
41
+ /** Minutes after local midnight for each end of a `HH:MM-HH:MM` window, or null when malformed. */
42
+ export function parseDreamWindow(window) {
43
+ const match = WINDOW_RE.exec(window.trim());
44
+ if (!match)
45
+ return null;
46
+ const start = Number(match[1]) * 60 + Number(match[2]);
47
+ const end = Number(match[3]) * 60 + Number(match[4]);
48
+ return start === end ? null : { start, end };
49
+ }
50
+ /** True when `date`'s local time of day falls inside the window (start inclusive, end exclusive). */
51
+ export function insideDreamWindow(window, date) {
52
+ const parsed = parseDreamWindow(window) ?? parseDreamWindow(DEFAULT_DREAMING_CONFIG.window);
53
+ const minute = date.getHours() * 60 + date.getMinutes();
54
+ return parsed.start < parsed.end
55
+ ? minute >= parsed.start && minute < parsed.end
56
+ : minute >= parsed.start || minute < parsed.end;
57
+ }
58
+ function intIn(key) {
59
+ const { min, max } = DREAMING_RANGES[key];
60
+ return (value) => {
61
+ const n = typeof value === "string" && value.trim() !== "" ? Number(value) : value;
62
+ return typeof n === "number" && Number.isInteger(n) && n >= min && n <= max
63
+ ? { ok: true, value: n }
64
+ : { ok: false, reason: `${key} must be a whole number from ${min} to ${max}.` };
65
+ };
66
+ }
67
+ function oneOf(key, values) {
68
+ return (value) => typeof value === "string" && values.includes(value.trim().toLowerCase())
69
+ ? { ok: true, value: value.trim().toLowerCase() }
70
+ : { ok: false, reason: `${key} must be one of: ${values.join(", ")}.` };
71
+ }
72
+ const CHECKS = {
73
+ enabled: (value) => {
74
+ if (typeof value === "boolean")
75
+ return { ok: true, value };
76
+ if (value === "true" || value === "on")
77
+ return { ok: true, value: true };
78
+ if (value === "false" || value === "off")
79
+ return { ok: true, value: false };
80
+ return { ok: false, reason: "enabled must be true or false." };
81
+ },
82
+ mode: oneOf("mode", DREAM_MODES),
83
+ cadence: oneOf("cadence", DREAM_CADENCES),
84
+ window: (value) => typeof value === "string" && parseDreamWindow(value)
85
+ ? { ok: true, value: value.trim() }
86
+ : { ok: false, reason: "window must be HH:MM-HH:MM in local time, with different start and end (e.g. 02:00-05:00)." },
87
+ idleMinutes: intIn("idleMinutes"),
88
+ lookbackHours: intIn("lookbackHours"),
89
+ maxChanges: intIn("maxChanges"),
90
+ injectBudgetKB: intIn("injectBudgetKB"),
91
+ // Unknown phases are ignored, so a newer store's phase list still loads here.
92
+ phases: (value) => {
93
+ const list = typeof value === "string" ? value.split(",") : value;
94
+ if (!Array.isArray(list))
95
+ return { ok: false, reason: `phases must be a list of: ${DREAM_PHASES.join(", ")}.` };
96
+ const known = [...new Set(list.map((p) => String(p).trim().toLowerCase()))]
97
+ .filter((p) => DREAM_PHASES.includes(p));
98
+ return known.length ? { ok: true, value: known } : { ok: false, reason: `phases must include at least one of: ${DREAM_PHASES.join(", ")}.` };
99
+ },
100
+ model: (value) => typeof value === "string" && (value.trim() === "" || MODEL_RE.test(value.trim()))
101
+ ? { ok: true, value: value.trim() }
102
+ : { ok: false, reason: "model must be empty (the project's helper model) or a model name such as sonnet or claude-sonnet-5-5." },
103
+ };
104
+ /** Validate a user-supplied partial config. Values may be strings (CLI) or typed (MCP, JSON). */
105
+ export function parseDreamingPatch(raw) {
106
+ const result = { patch: {}, errors: [], unknown: [] };
107
+ if (!isRecord(raw)) {
108
+ result.errors.push("Dreaming settings must be an object.");
109
+ return result;
110
+ }
111
+ for (const [key, value] of Object.entries(raw)) {
112
+ const check = CHECKS[key];
113
+ if (!check) {
114
+ result.unknown.push(key);
115
+ continue;
116
+ }
117
+ if (value === undefined)
118
+ continue;
119
+ const checked = check(value);
120
+ if (checked.ok)
121
+ result.patch[key] = checked.value;
122
+ else
123
+ result.errors.push(checked.reason);
124
+ }
125
+ return result;
126
+ }
127
+ /** The valid keys of a stored object; anything malformed is dropped so the level below shows through. */
128
+ export function normalizeDreamingLevel(raw) {
129
+ return parseDreamingPatch(isRecord(raw) ? raw : {}).patch;
130
+ }
131
+ export function globalDreamingPath(phrenPath) {
132
+ return path.join(phrenPath, ".config", "dreaming.json");
133
+ }
134
+ export function readGlobalDreaming(phrenPath) {
135
+ try {
136
+ return normalizeDreamingLevel(JSON.parse(fs.readFileSync(globalDreamingPath(phrenPath), "utf8")));
137
+ }
138
+ catch {
139
+ return {};
140
+ }
141
+ }
142
+ export function readProjectDreaming(phrenPath, project) {
143
+ try {
144
+ return normalizeDreamingLevel(readProjectConfig(phrenPath, project).config?.dreaming);
145
+ }
146
+ catch {
147
+ return {};
148
+ }
149
+ }
150
+ /** The effective dreaming config: defaults, then the global file, then the project's override. */
151
+ export function getDreamingConfig(phrenPath, project) {
152
+ return {
153
+ ...DEFAULT_DREAMING_CONFIG,
154
+ phases: [...DEFAULT_DREAMING_CONFIG.phases],
155
+ ...readGlobalDreaming(phrenPath),
156
+ ...(project ? readProjectDreaming(phrenPath, project) : {}),
157
+ };
158
+ }
159
+ /**
160
+ * Write a validated patch globally or for one project. `null` for a key on a
161
+ * project removes that project's override so it inherits again.
162
+ */
163
+ export function updateDreamingConfig(phrenPath, patch, project, clear = []) {
164
+ if (project) {
165
+ let written = {};
166
+ updateProjectConfigOverrides(phrenPath, project, (current) => {
167
+ const existing = normalizeDreamingLevel(current.dreaming);
168
+ for (const key of clear)
169
+ delete existing[key];
170
+ written = { ...existing, ...patch };
171
+ const next = { ...current };
172
+ if (Object.keys(written).length)
173
+ next.dreaming = written;
174
+ else
175
+ delete next.dreaming;
176
+ return next;
177
+ });
178
+ appendAuditLog(phrenPath, "update_dreaming_config", JSON.stringify({ project, ...written }));
179
+ return written;
180
+ }
181
+ const file = globalDreamingPath(phrenPath);
182
+ fs.mkdirSync(path.dirname(file), { recursive: true });
183
+ const next = withFileLock(file, () => {
184
+ const current = readGlobalDreaming(phrenPath);
185
+ for (const key of clear)
186
+ delete current[key];
187
+ const merged = { ...current, ...patch };
188
+ const tmp = `${file}.tmp-${crypto.randomUUID()}`;
189
+ fs.writeFileSync(tmp, JSON.stringify(merged, null, 2) + "\n");
190
+ fs.renameSync(tmp, file);
191
+ return merged;
192
+ });
193
+ appendAuditLog(phrenPath, "update_dreaming_config", JSON.stringify(next));
194
+ return next;
195
+ }
@@ -15,6 +15,7 @@ import { readGovernanceInstallPreferences } from "../init/preferences.js";
15
15
  import { readProjectConfig } from "../project-config.js";
16
16
  import { isRecord } from "../shared.js";
17
17
  import { allConfigFields, getConfigField } from "./schema.js";
18
+ import { DREAMING_KEYS, globalDreamingPath, readGlobalDreaming, readProjectDreaming } from "./dreaming.js";
18
19
  /** Structural equality good enough for config values (scalars + flat arrays). */
19
20
  function valuesEqual(a, b) {
20
21
  if (a === b)
@@ -227,6 +228,16 @@ export function buildConfigView(phrenPath, project) {
227
228
  const resolved = resolveConfigField(fieldKey, [], levels);
228
229
  fields[fieldKey] = { ...resolved, value: union };
229
230
  }
231
+ // ── dreaming ───────────────────────────────────────────────────────────────
232
+ const globalDreaming = readGlobalDreaming(phrenPath);
233
+ const projectDreaming = project ? readProjectDreaming(phrenPath, project) : {};
234
+ for (const prop of DREAMING_KEYS) {
235
+ const fieldKey = `dreaming.${prop}`;
236
+ const levels = [];
237
+ pushIfSet(levels, "project", projectDreaming[prop], projectConfigPath);
238
+ pushIfSet(levels, "global", globalDreaming[prop], globalDreamingPath(phrenPath));
239
+ fields[fieldKey] = resolveConfigField(fieldKey, getConfigField(fieldKey)?.default, levels);
240
+ }
230
241
  return {
231
242
  scope: project ? "project" : "global",
232
243
  ...(project ? { project } : {}),
@@ -6,13 +6,13 @@
6
6
  * defaults, and ranges can never drift apart.
7
7
  *
8
8
  * Each field is a {@link ConfigFieldDescriptor}; fields are grouped into the
9
- * eight {@link CONFIG_DOMAINS}. Nothing here renders UI — descriptors are pure
9
+ * nine {@link CONFIG_DOMAINS}. Nothing here renders UI — descriptors are pure
10
10
  * data so every surface can present them in its own idiom.
11
11
  */
12
- /** The eight configurable domains, named to match the `get_config`/`set_config` MCP tools. */
13
- export type ConfigDomainId = "proactivity" | "taskMode" | "findingSensitivity" | "retention" | "workflow" | "index" | "topic" | "access";
12
+ /** The nine configurable domains, named to match the `get_config`/`set_config` MCP tools. */
13
+ export type ConfigDomainId = "proactivity" | "taskMode" | "findingSensitivity" | "retention" | "workflow" | "index" | "topic" | "access" | "dreaming";
14
14
  /** How a field's value is entered. Surfaces pick a widget from this. */
15
- export type ConfigControl = "enum" | "number" | "boolean" | "string-list" | "object";
15
+ export type ConfigControl = "enum" | "number" | "boolean" | "string" | "string-list" | "object";
16
16
  /** Where a field may be set. `global+project` fields support per-project overrides. */
17
17
  export type ConfigScope = "global+project" | "global-only" | "project-only";
18
18
  /** One choice for an `enum` field, with plain-English copy. */
@@ -6,10 +6,11 @@
6
6
  * defaults, and ranges can never drift apart.
7
7
  *
8
8
  * Each field is a {@link ConfigFieldDescriptor}; fields are grouped into the
9
- * eight {@link CONFIG_DOMAINS}. Nothing here renders UI — descriptors are pure
9
+ * nine {@link CONFIG_DOMAINS}. Nothing here renders UI — descriptors are pure
10
10
  * data so every surface can present them in its own idiom.
11
11
  */
12
12
  import { DEFAULT_POLICY, DEFAULT_WORKFLOW_POLICY, DEFAULT_INDEX_POLICY, } from "../governance/policy.js";
13
+ import { DEFAULT_DREAMING_CONFIG, DREAMING_RANGES } from "./dreaming.js";
13
14
  // ── Reusable option lists ─────────────────────────────────────────────────────
14
15
  const PROACTIVITY_OPTIONS = [
15
16
  {
@@ -457,6 +458,159 @@ export const CONFIG_DOMAINS = [
457
458
  },
458
459
  ],
459
460
  },
461
+ {
462
+ id: "dreaming",
463
+ label: "Dreaming",
464
+ icon: "sparkle",
465
+ summary: "An offline pass that reorganizes a project's memory between sessions. Off by default.",
466
+ scope: "global+project",
467
+ fields: [
468
+ {
469
+ key: "dreaming.enabled",
470
+ domain: "dreaming",
471
+ label: "Dreaming",
472
+ summary: "Whether the Hook runs dream passes on its own.",
473
+ help: "A dream reads recent transcripts, the project's findings, truths and pages, and the repo's git log, "
474
+ + "then corrects, merges and reorganizes memory. `phren dream run --force` still works when this is off.",
475
+ control: "boolean",
476
+ default: DEFAULT_DREAMING_CONFIG.enabled,
477
+ scope: "global+project",
478
+ impact: "On = the Hook spends helper-model usage on a scheduled pass for each enabled project.",
479
+ risk: "caution",
480
+ },
481
+ {
482
+ key: "dreaming.mode",
483
+ domain: "dreaming",
484
+ label: "Mode",
485
+ summary: "Whether a dream proposes its changes or applies them.",
486
+ help: "Propose puts one review-queue item per change, with its evidence, for you to accept. "
487
+ + "Apply makes the changes through the normal finding, truth and topic APIs and logs them in dreams/journal.md.",
488
+ control: "enum",
489
+ options: [
490
+ { value: "propose", label: "Propose", blurb: "Every change waits in the review queue for you.", recommended: true },
491
+ { value: "apply", label: "Apply", blurb: "Changes are made directly and recorded in the dream journal." },
492
+ ],
493
+ default: DEFAULT_DREAMING_CONFIG.mode,
494
+ scope: "global+project",
495
+ impact: "Apply edits, supersedes and retracts findings without asking; every change stays in history.",
496
+ risk: "caution",
497
+ },
498
+ {
499
+ key: "dreaming.cadence",
500
+ domain: "dreaming",
501
+ label: "Cadence",
502
+ summary: "When the Hook starts a dream on its own.",
503
+ help: "Nightly runs once a day inside the window; weekly once a week inside the window; idle after the project "
504
+ + "has had no live agent session for the idle time; manual only when you run `phren dream run`.",
505
+ control: "enum",
506
+ options: [
507
+ { value: "nightly", label: "Nightly", blurb: "Once a day, inside the window.", recommended: true },
508
+ { value: "idle", label: "Idle", blurb: "After the project has had no live agent session for a while." },
509
+ { value: "weekly", label: "Weekly", blurb: "Once every seven days, inside the window." },
510
+ { value: "manual", label: "Manual", blurb: "Only when you run it yourself." },
511
+ ],
512
+ default: DEFAULT_DREAMING_CONFIG.cadence,
513
+ scope: "global+project",
514
+ impact: "More frequent dreams use more helper usage and churn memory more often.",
515
+ risk: "safe",
516
+ },
517
+ {
518
+ key: "dreaming.window",
519
+ domain: "dreaming",
520
+ label: "Window",
521
+ summary: "Local time range nightly and weekly dreams may start in (HH:MM-HH:MM).",
522
+ help: "A range like 02:00-05:00; it may wrap midnight (23:00-04:00). Idle and manual dreams ignore it.",
523
+ control: "string",
524
+ default: DEFAULT_DREAMING_CONFIG.window,
525
+ scope: "global+project",
526
+ impact: "Pick hours when you are not working, so a dream never competes with a live session.",
527
+ risk: "safe",
528
+ },
529
+ {
530
+ key: "dreaming.idleMinutes",
531
+ domain: "dreaming",
532
+ label: "Idle minutes",
533
+ summary: "For the idle cadence: minutes without a live agent session before a dream starts.",
534
+ help: "The Hook checks every ten minutes, so a dream starts up to ten minutes after this much quiet.",
535
+ control: "number",
536
+ range: { ...DREAMING_RANGES.idleMinutes },
537
+ default: DEFAULT_DREAMING_CONFIG.idleMinutes,
538
+ scope: "global+project",
539
+ impact: "Lower = dreams follow work sooner; higher = only after longer breaks.",
540
+ risk: "safe",
541
+ },
542
+ {
543
+ key: "dreaming.lookbackHours",
544
+ domain: "dreaming",
545
+ label: "Lookback (hours)",
546
+ summary: "How far back a dream reads transcripts when it has no earlier run to start from.",
547
+ help: "After the first dream, each one reads from the previous run's end; this caps the window otherwise.",
548
+ control: "number",
549
+ range: { ...DREAMING_RANGES.lookbackHours },
550
+ default: DEFAULT_DREAMING_CONFIG.lookbackHours,
551
+ scope: "global+project",
552
+ impact: "Longer = more transcript evidence per dream, and a larger prompt.",
553
+ risk: "safe",
554
+ },
555
+ {
556
+ key: "dreaming.maxChanges",
557
+ domain: "dreaming",
558
+ label: "Max changes",
559
+ summary: "The most changes one dream may make or propose.",
560
+ help: "Changes past this cap are dropped and recorded in the dream's report.",
561
+ control: "number",
562
+ range: { ...DREAMING_RANGES.maxChanges },
563
+ default: DEFAULT_DREAMING_CONFIG.maxChanges,
564
+ scope: "global+project",
565
+ impact: "Higher lets one dream reorganize more, and gives you more to review.",
566
+ risk: "safe",
567
+ },
568
+ {
569
+ key: "dreaming.injectBudgetKB",
570
+ domain: "dreaming",
571
+ label: "Inject budget (KB)",
572
+ summary: "The cap on truths plus always-injected context; a dream demotes to stay under it.",
573
+ help: "Whatever Phren injects at every session start spreads its errors to every session, so it stays small. "
574
+ + "A dream will not promote a truth past this budget without demoting another.",
575
+ control: "number",
576
+ range: { ...DREAMING_RANGES.injectBudgetKB },
577
+ default: DEFAULT_DREAMING_CONFIG.injectBudgetKB,
578
+ scope: "global+project",
579
+ impact: "Lower = a leaner session start; higher = more pinned context every session.",
580
+ risk: "safe",
581
+ },
582
+ {
583
+ key: "dreaming.phases",
584
+ domain: "dreaming",
585
+ label: "Phases",
586
+ summary: "What a dream works on.",
587
+ help: "Any of capture, correct, organize, prune. Unknown values are ignored.",
588
+ control: "string-list",
589
+ options: [
590
+ { value: "capture", label: "Capture", blurb: "Save decisions and lessons the transcripts show but memory lacks." },
591
+ { value: "correct", label: "Correct", blurb: "Fix or retract notes that transcripts, code or git contradict." },
592
+ { value: "organize", label: "Organize", blurb: "Merge duplicates, move findings to topics, write subject pages." },
593
+ { value: "prune", label: "Prune", blurb: "Demote and retire what no longer earns its place." },
594
+ ],
595
+ default: [...DEFAULT_DREAMING_CONFIG.phases],
596
+ scope: "global+project",
597
+ impact: "Fewer phases = a narrower, cheaper pass.",
598
+ risk: "safe",
599
+ },
600
+ {
601
+ key: "dreaming.model",
602
+ domain: "dreaming",
603
+ label: "Model",
604
+ summary: "The model a dream runs on; empty uses the project's helper model.",
605
+ help: "Runs under the project's helper account (phren.project.yaml helper: { account, model }).",
606
+ control: "string",
607
+ default: DEFAULT_DREAMING_CONFIG.model,
608
+ scope: "global+project",
609
+ impact: "A stronger model gives better judgment at a higher cost per dream.",
610
+ risk: "safe",
611
+ },
612
+ ],
613
+ },
460
614
  ];
461
615
  // ── Lookups ───────────────────────────────────────────────────────────────────
462
616
  const DOMAIN_BY_ID = new Map(CONFIG_DOMAINS.map((d) => [d.id, d]));
@@ -491,6 +645,8 @@ export const CONFIG_DOMAIN_ALIASES = {
491
645
  topic: "topic",
492
646
  topics: "topic",
493
647
  access: "access",
648
+ dreaming: "dreaming",
649
+ dream: "dreaming",
494
650
  };
495
651
  /** Resolve a user-supplied domain/subcommand token to a canonical domain id. */
496
652
  export function resolveConfigDomainAlias(token) {
@@ -70,6 +70,12 @@ function repository(citation, opts, entries, deadline) {
70
70
  const kind = ["github", "gitlab", "gitboy"].includes(named) ? named : kindFromDomain(parsed.domain);
71
71
  if (kind === "gitboy")
72
72
  value = { ...parsed, root: remote ? local : undefined };
73
+ else {
74
+ // A gitboy mirror of another host keeps the owner/repo path and the commit ids.
75
+ const mirror = read("config", ...(local ? [] : ["--global"]), "--get", `phren.${parsed.domain}.mirror`).trim().toLowerCase();
76
+ if (mirror && validDomain(mirror))
77
+ value = { ...parsed, domain: mirror, root: remote ? local : undefined };
78
+ }
73
79
  }
74
80
  // A budget-limited git lookup must not become a day-long negative resolution.
75
81
  if (Date.now() < deadline)
@@ -1,6 +1,7 @@
1
1
  import { type PhrenResult, type FindingTag } from "../shared.js";
2
2
  import { type FindingCitation, type FindingProvenance } from "./citation.js";
3
3
  interface AddFindingOptions {
4
+ expectedFindings?: Record<string, string>;
4
5
  extraAnnotations?: string[];
5
6
  sessionId?: string;
6
7
  scope?: string;
@@ -1,4 +1,5 @@
1
1
  import * as fs from "fs";
2
+ import { assertFindingVersions } from "../finding/versions.js";
2
3
  import * as path from "path";
3
4
  import { renameOverSync } from "../phren-paths.js";
4
5
  import * as crypto from "crypto";
@@ -267,6 +268,7 @@ export function addFindingToFile(phrenPath, project, learning, citationInput, op
267
268
  if (!fs.existsSync(resolvedDir))
268
269
  return phrenErr(`Project "${project}" does not exist.`, PhrenError.INVALID_PROJECT_NAME);
269
270
  const result = withFileLock(learningsPath, () => {
271
+ assertFindingVersions(learningsPath, opts?.expectedFindings);
270
272
  const preparedForNewFile = prepareFinding({
271
273
  finding: learning, project, fullHistory: "", extraAnnotations: opts?.extraAnnotations,
272
274
  citationInput: resolvedCitationInput, scope, provenance: opts?.provenance, nowIso, inferredRepo, headCommit, phrenPath,