@opencorelabs/lucidity 0.6.0 → 0.8.0

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 (253) hide show
  1. package/README.md +18 -3
  2. package/dist/assets/speech/lucidity-speech +0 -0
  3. package/dist/automations/agent.d.ts.map +1 -1
  4. package/dist/automations/agent.js +2 -0
  5. package/dist/automations/designer.d.ts +1 -1
  6. package/dist/chat/server.d.ts +1 -0
  7. package/dist/chat/server.d.ts.map +1 -1
  8. package/dist/chat/server.js +6 -1
  9. package/dist/coding/conduct.d.ts +1 -22
  10. package/dist/coding/conduct.d.ts.map +1 -1
  11. package/dist/coding/conduct.js +9 -94
  12. package/dist/coding/runCodeTurn.d.ts +3 -16
  13. package/dist/coding/runCodeTurn.d.ts.map +1 -1
  14. package/dist/coding/runCodeTurn.js +157 -165
  15. package/dist/coding/workspaceRegistry.d.ts +24 -0
  16. package/dist/coding/workspaceRegistry.d.ts.map +1 -0
  17. package/dist/coding/workspaceRegistry.js +230 -0
  18. package/dist/coding/worktree.d.ts +11 -14
  19. package/dist/coding/worktree.d.ts.map +1 -1
  20. package/dist/coding/worktree.js +41 -21
  21. package/dist/config.d.ts +2 -0
  22. package/dist/config.d.ts.map +1 -1
  23. package/dist/daemonLease.d.ts +12 -0
  24. package/dist/daemonLease.d.ts.map +1 -0
  25. package/dist/daemonLease.js +32 -0
  26. package/dist/goals/assessment.d.ts +115 -0
  27. package/dist/goals/assessment.d.ts.map +1 -0
  28. package/dist/goals/assessment.js +67 -0
  29. package/dist/goals/notes.d.ts +18 -0
  30. package/dist/goals/notes.d.ts.map +1 -0
  31. package/dist/goals/notes.js +72 -0
  32. package/dist/index.js +63 -15
  33. package/dist/jobs/goals.d.ts +15 -0
  34. package/dist/jobs/goals.d.ts.map +1 -0
  35. package/dist/jobs/goals.js +286 -0
  36. package/dist/jobs/weeklyReview.d.ts.map +1 -1
  37. package/dist/jobs/weeklyReview.js +3 -2
  38. package/dist/queue.d.ts +1 -0
  39. package/dist/queue.d.ts.map +1 -1
  40. package/dist/queue.js +4 -0
  41. package/dist/room/client.d.ts +5 -0
  42. package/dist/room/client.d.ts.map +1 -1
  43. package/dist/room/client.js +124 -107
  44. package/dist/room/computer.d.ts.map +1 -1
  45. package/dist/room/computer.js +2 -0
  46. package/dist/room/durablePublish.d.ts +6 -0
  47. package/dist/room/durablePublish.d.ts.map +1 -0
  48. package/dist/room/durablePublish.js +19 -0
  49. package/dist/room/incidents.d.ts +1 -1
  50. package/dist/room/incidents.d.ts.map +1 -1
  51. package/dist/room/incidents.js +14 -7
  52. package/dist/room/turnQueue.d.ts.map +1 -1
  53. package/dist/room/turnQueue.js +27 -24
  54. package/dist/runtimeStore.d.ts +44 -0
  55. package/dist/runtimeStore.d.ts.map +1 -0
  56. package/dist/runtimeStore.js +188 -0
  57. package/dist/setup/server.js +1 -1
  58. package/dist/turnLog.d.ts +10 -40
  59. package/dist/turnLog.d.ts.map +1 -1
  60. package/dist/turnLog.js +33 -56
  61. package/package.json +4 -4
  62. package/src/automations/agent.ts +2 -0
  63. package/src/chat/server.ts +7 -1
  64. package/src/coding/conduct.ts +10 -147
  65. package/src/coding/runCodeTurn.ts +42 -61
  66. package/src/coding/workspaceRegistry.ts +210 -0
  67. package/src/coding/worktree.ts +44 -20
  68. package/src/config.ts +2 -0
  69. package/src/daemonLease.ts +33 -0
  70. package/src/goals/assessment.ts +106 -0
  71. package/src/goals/notes.ts +88 -0
  72. package/src/index.ts +63 -18
  73. package/src/jobs/goals.ts +384 -0
  74. package/src/jobs/weeklyReview.ts +4 -3
  75. package/src/queue.ts +4 -0
  76. package/src/room/client.ts +85 -80
  77. package/src/room/computer.ts +2 -0
  78. package/src/room/durablePublish.ts +25 -0
  79. package/src/room/incidents.ts +16 -8
  80. package/src/room/turnQueue.ts +26 -27
  81. package/src/runtimeStore.ts +190 -0
  82. package/src/setup/server.ts +1 -1
  83. package/src/turnLog.ts +32 -75
  84. package/vendor/decisions/dist/dayPlan.d.ts +9 -0
  85. package/vendor/decisions/dist/dayPlan.js +82 -0
  86. package/vendor/decisions/dist/index.d.ts +1 -0
  87. package/vendor/decisions/dist/index.js +1 -0
  88. package/vendor/decisions/dist/jev.js +3 -1
  89. package/vendor/decisions/src/dayPlan.ts +80 -0
  90. package/vendor/decisions/src/index.ts +1 -0
  91. package/vendor/decisions/src/jev.ts +3 -1
  92. package/vendor/mcp-server/dist/index.js +2 -0
  93. package/vendor/mcp-server/dist/tools/goals.d.ts +4 -0
  94. package/vendor/mcp-server/dist/tools/goals.d.ts.map +1 -0
  95. package/vendor/mcp-server/dist/tools/goals.js +38 -0
  96. package/vendor/mcp-server/package.json +1 -1
  97. package/vendor/mcp-server/src/index.ts +2 -0
  98. package/vendor/mcp-server/src/tools/goals.ts +62 -0
  99. package/vendor/runtime/README.md +2 -2
  100. package/vendor/runtime/dist/executor/asyncQueue.d.ts +1 -0
  101. package/vendor/runtime/dist/executor/asyncQueue.d.ts.map +1 -1
  102. package/vendor/runtime/dist/executor/asyncQueue.js +3 -0
  103. package/vendor/runtime/dist/executor/claudeAgent.d.ts +1 -1
  104. package/vendor/runtime/dist/executor/claudeAgent.d.ts.map +1 -1
  105. package/vendor/runtime/dist/executor/claudeAgent.js +25 -10
  106. package/vendor/runtime/dist/executor/codex.d.ts +1 -0
  107. package/vendor/runtime/dist/executor/codex.d.ts.map +1 -1
  108. package/vendor/runtime/dist/executor/codex.js +69 -36
  109. package/vendor/runtime/dist/executor/codexProtocol/FunctionCallOutputContentItem.d.ts +4 -1
  110. package/vendor/runtime/dist/executor/codexProtocol/FunctionCallOutputContentItem.d.ts.map +1 -1
  111. package/vendor/runtime/dist/executor/codexProtocol/Personality.d.ts +3 -0
  112. package/vendor/runtime/dist/executor/codexProtocol/Personality.d.ts.map +1 -1
  113. package/vendor/runtime/dist/executor/codexProtocol/PlanType.d.ts +1 -1
  114. package/vendor/runtime/dist/executor/codexProtocol/PlanType.d.ts.map +1 -1
  115. package/vendor/runtime/dist/executor/codexProtocol/v2/CyberAccessProgram.d.ts +6 -0
  116. package/vendor/runtime/dist/executor/codexProtocol/v2/CyberAccessProgram.d.ts.map +1 -0
  117. package/vendor/runtime/dist/executor/codexProtocol/v2/CyberAccessProgram.js +2 -0
  118. package/vendor/runtime/dist/executor/codexProtocol/v2/GetAccountRateLimitsResponse.d.ts +5 -0
  119. package/vendor/runtime/dist/executor/codexProtocol/v2/GetAccountRateLimitsResponse.d.ts.map +1 -1
  120. package/vendor/runtime/dist/executor/codexProtocol/v2/Model.d.ts +8 -0
  121. package/vendor/runtime/dist/executor/codexProtocol/v2/Model.d.ts.map +1 -1
  122. package/vendor/runtime/dist/executor/codexProtocol/v2/ModelAccessPrograms.d.ts +11 -0
  123. package/vendor/runtime/dist/executor/codexProtocol/v2/ModelAccessPrograms.d.ts.map +1 -0
  124. package/vendor/runtime/dist/executor/codexProtocol/v2/ModelAccessPrograms.js +2 -0
  125. package/vendor/runtime/dist/executor/codexProtocol/v2/RateLimitSnapshot.d.ts +4 -0
  126. package/vendor/runtime/dist/executor/codexProtocol/v2/RateLimitSnapshot.d.ts.map +1 -1
  127. package/vendor/runtime/dist/executor/codexProtocol/v2/ReviewStartParams.d.ts +2 -0
  128. package/vendor/runtime/dist/executor/codexProtocol/v2/ReviewStartParams.d.ts.map +1 -1
  129. package/vendor/runtime/dist/executor/codexProtocol/v2/ThreadResumeParams.d.ts +4 -1
  130. package/vendor/runtime/dist/executor/codexProtocol/v2/ThreadResumeParams.d.ts.map +1 -1
  131. package/vendor/runtime/dist/executor/codexProtocol/v2/ThreadStartParams.d.ts +3 -1
  132. package/vendor/runtime/dist/executor/codexProtocol/v2/ThreadStartParams.d.ts.map +1 -1
  133. package/vendor/runtime/dist/executor/codexProtocol/v2/TurnStartParams.d.ts +7 -2
  134. package/vendor/runtime/dist/executor/codexProtocol/v2/TurnStartParams.d.ts.map +1 -1
  135. package/vendor/runtime/dist/executor/codexProtocol/v2/UserInput.d.ts +3 -0
  136. package/vendor/runtime/dist/executor/codexProtocol/v2/UserInput.d.ts.map +1 -1
  137. package/vendor/runtime/dist/executor/codexRpc.d.ts +10 -3
  138. package/vendor/runtime/dist/executor/codexRpc.d.ts.map +1 -1
  139. package/vendor/runtime/dist/executor/codexRpc.js +18 -3
  140. package/vendor/runtime/dist/executor/codexSessions.d.ts +30 -0
  141. package/vendor/runtime/dist/executor/codexSessions.d.ts.map +1 -0
  142. package/vendor/runtime/dist/executor/codexSessions.js +88 -0
  143. package/vendor/runtime/dist/executor/health.d.ts +2 -1
  144. package/vendor/runtime/dist/executor/health.d.ts.map +1 -1
  145. package/vendor/runtime/dist/executor/health.js +17 -5
  146. package/vendor/runtime/dist/executor/liveTurns.d.ts +2 -1
  147. package/vendor/runtime/dist/executor/liveTurns.d.ts.map +1 -1
  148. package/vendor/runtime/dist/executor/liveTurns.js +12 -5
  149. package/vendor/runtime/dist/executor/ownership.d.ts +35 -0
  150. package/vendor/runtime/dist/executor/ownership.d.ts.map +1 -0
  151. package/vendor/runtime/dist/executor/ownership.js +99 -0
  152. package/vendor/runtime/dist/executor/providerRouter.d.ts +1 -0
  153. package/vendor/runtime/dist/executor/providerRouter.d.ts.map +1 -1
  154. package/vendor/runtime/dist/executor/providerRouter.js +5 -0
  155. package/vendor/runtime/dist/executor/types.d.ts +4 -0
  156. package/vendor/runtime/dist/executor/types.d.ts.map +1 -1
  157. package/vendor/runtime/dist/harness/index.d.ts +1 -0
  158. package/vendor/runtime/dist/harness/index.d.ts.map +1 -1
  159. package/vendor/runtime/dist/harness/index.js +12 -1
  160. package/vendor/runtime/dist/harness/types.d.ts +2 -1
  161. package/vendor/runtime/dist/harness/types.d.ts.map +1 -1
  162. package/vendor/runtime/dist/index.d.ts +1 -0
  163. package/vendor/runtime/dist/index.d.ts.map +1 -1
  164. package/vendor/runtime/dist/index.js +1 -0
  165. package/vendor/runtime/dist/prompts/dayPlanning.d.ts +44 -0
  166. package/vendor/runtime/dist/prompts/dayPlanning.d.ts.map +1 -0
  167. package/vendor/runtime/dist/prompts/dayPlanning.js +42 -0
  168. package/vendor/runtime/src/executor/asyncQueue.ts +3 -0
  169. package/vendor/runtime/src/executor/claudeAgent.ts +20 -9
  170. package/vendor/runtime/src/executor/codex.ts +76 -44
  171. package/vendor/runtime/src/executor/codexProtocol/FunctionCallOutputContentItem.ts +1 -1
  172. package/vendor/runtime/src/executor/codexProtocol/Personality.ts +3 -0
  173. package/vendor/runtime/src/executor/codexProtocol/PlanType.ts +1 -1
  174. package/vendor/runtime/src/executor/codexProtocol/README.md +2 -2
  175. package/vendor/runtime/src/executor/codexProtocol/v2/CyberAccessProgram.ts +9 -0
  176. package/vendor/runtime/src/executor/codexProtocol/v2/GetAccountRateLimitsResponse.ts +5 -0
  177. package/vendor/runtime/src/executor/codexProtocol/v2/Model.ts +11 -2
  178. package/vendor/runtime/src/executor/codexProtocol/v2/ModelAccessPrograms.ts +13 -0
  179. package/vendor/runtime/src/executor/codexProtocol/v2/RateLimitSnapshot.ts +5 -1
  180. package/vendor/runtime/src/executor/codexProtocol/v2/ReviewStartParams.ts +2 -0
  181. package/vendor/runtime/src/executor/codexProtocol/v2/ThreadResumeParams.ts +5 -1
  182. package/vendor/runtime/src/executor/codexProtocol/v2/ThreadStartParams.ts +4 -1
  183. package/vendor/runtime/src/executor/codexProtocol/v2/TurnStartParams.ts +7 -2
  184. package/vendor/runtime/src/executor/codexProtocol/v2/UserInput.ts +1 -1
  185. package/vendor/runtime/src/executor/codexRpc.ts +22 -4
  186. package/vendor/runtime/src/executor/codexSessions.ts +108 -0
  187. package/vendor/runtime/src/executor/health.ts +16 -6
  188. package/vendor/runtime/src/executor/liveTurns.ts +12 -5
  189. package/vendor/runtime/src/executor/ownership.ts +76 -0
  190. package/vendor/runtime/src/executor/providerRouter.ts +6 -0
  191. package/vendor/runtime/src/executor/types.ts +4 -0
  192. package/vendor/runtime/src/harness/index.ts +12 -1
  193. package/vendor/runtime/src/harness/types.ts +2 -1
  194. package/vendor/runtime/src/index.ts +1 -0
  195. package/vendor/runtime/src/prompts/dayPlanning.ts +46 -0
  196. package/vendor/shared/dist/agentCommands.d.ts +1 -0
  197. package/vendor/shared/dist/agentCommands.d.ts.map +1 -1
  198. package/vendor/shared/dist/cardStudio.d.ts +41 -0
  199. package/vendor/shared/dist/cardStudio.d.ts.map +1 -1
  200. package/vendor/shared/dist/cardStudio.js +13 -3
  201. package/vendor/shared/dist/commandLocal.d.ts.map +1 -1
  202. package/vendor/shared/dist/commandLocal.js +2 -0
  203. package/vendor/shared/dist/commands.d.ts +18 -0
  204. package/vendor/shared/dist/commands.d.ts.map +1 -1
  205. package/vendor/shared/dist/commands.js +2 -0
  206. package/vendor/shared/dist/computer.d.ts +7 -1
  207. package/vendor/shared/dist/computer.d.ts.map +1 -1
  208. package/vendor/shared/dist/computer.js +13 -2
  209. package/vendor/shared/dist/constants.d.ts +3 -3
  210. package/vendor/shared/dist/constants.d.ts.map +1 -1
  211. package/vendor/shared/dist/constants.js +5 -4
  212. package/vendor/shared/dist/dayPlan.d.ts +86 -0
  213. package/vendor/shared/dist/dayPlan.d.ts.map +1 -0
  214. package/vendor/shared/dist/dayPlan.js +46 -0
  215. package/vendor/shared/dist/dayPlanning.d.ts +139 -0
  216. package/vendor/shared/dist/dayPlanning.d.ts.map +1 -0
  217. package/vendor/shared/dist/dayPlanning.js +67 -0
  218. package/vendor/shared/dist/goalNotes.d.ts +4 -0
  219. package/vendor/shared/dist/goalNotes.d.ts.map +1 -0
  220. package/vendor/shared/dist/goalNotes.js +23 -0
  221. package/vendor/shared/dist/goals.d.ts +835 -0
  222. package/vendor/shared/dist/goals.d.ts.map +1 -0
  223. package/vendor/shared/dist/goals.js +198 -0
  224. package/vendor/shared/dist/index.d.ts +5 -0
  225. package/vendor/shared/dist/index.d.ts.map +1 -1
  226. package/vendor/shared/dist/index.js +5 -0
  227. package/vendor/shared/dist/schemas/harness.d.ts +155 -0
  228. package/vendor/shared/dist/schemas/harness.d.ts.map +1 -1
  229. package/vendor/shared/dist/schemas/harness.js +8 -0
  230. package/vendor/shared/dist/workspaces.d.ts +138 -0
  231. package/vendor/shared/dist/workspaces.d.ts.map +1 -0
  232. package/vendor/shared/dist/workspaces.js +40 -0
  233. package/vendor/shared/src/agentCommands.ts +1 -0
  234. package/vendor/shared/src/cardStudio.ts +13 -3
  235. package/vendor/shared/src/commandLocal.ts +2 -0
  236. package/vendor/shared/src/commands.ts +2 -0
  237. package/vendor/shared/src/computer.ts +18 -2
  238. package/vendor/shared/src/constants.ts +5 -4
  239. package/vendor/shared/src/dayPlan.ts +81 -0
  240. package/vendor/shared/src/dayPlanning.ts +77 -0
  241. package/vendor/shared/src/goalNotes.ts +23 -0
  242. package/vendor/shared/src/goals.ts +237 -0
  243. package/vendor/shared/src/index.ts +6 -0
  244. package/vendor/shared/src/schemas/harness.ts +8 -0
  245. package/vendor/shared/src/workspaces.ts +48 -0
  246. package/dist/coding/fleetIntegrate.d.ts +0 -37
  247. package/dist/coding/fleetIntegrate.d.ts.map +0 -1
  248. package/dist/coding/fleetIntegrate.js +0 -64
  249. package/dist/coding/openFleetPr.d.ts +0 -41
  250. package/dist/coding/openFleetPr.d.ts.map +0 -1
  251. package/dist/coding/openFleetPr.js +0 -121
  252. package/src/coding/fleetIntegrate.ts +0 -95
  253. package/src/coding/openFleetPr.ts +0 -148
@@ -70,6 +70,30 @@ export async function currentBranch(repoRoot: string): Promise<string> {
70
70
  return (await git(repoRoot, ['rev-parse', '--abbrev-ref', 'HEAD'])).trim();
71
71
  }
72
72
 
73
+ export async function workspaceBranchExists(repoRoot: string, repoId: string, workerId?: string): Promise<boolean> {
74
+ return git(repoRoot, ['show-ref', '--verify', `refs/heads/${sessionBranch(repoId, workerId)}`]).then(() => true, () => false);
75
+ }
76
+
77
+ /** Resolve the fetched remote base without changing the existing checkout. */
78
+ export async function workspaceBase(repoRoot: string, configured?: string): Promise<{ ref: string; sha: string }> {
79
+ const remotes = (await git(repoRoot, ['remote'])).trim().split('\n');
80
+ if (!remotes.includes('origin')) {
81
+ if (configured) throw new Error('The configured workspace base requires an origin remote.');
82
+ return { ref: 'HEAD', sha: (await git(repoRoot, ['rev-parse', 'HEAD'])).trim() };
83
+ }
84
+ await git(repoRoot, ['fetch', 'origin']);
85
+ let ref = configured;
86
+ if (!ref) {
87
+ const remoteHead = await git(repoRoot, ['ls-remote', '--symref', 'origin', 'HEAD']);
88
+ const branch = /^ref: refs\/heads\/(.+)\s+HEAD$/m.exec(remoteHead)?.[1];
89
+ if (!branch) throw new Error('Could not resolve the remote default branch. Set this repository\'s baseRef.');
90
+ ref = `origin/${branch}`;
91
+ }
92
+ if (!ref.startsWith('origin/')) ref = `origin/${ref}`;
93
+ const sha = (await git(repoRoot, ['rev-parse', '--verify', '--end-of-options', `${ref}^{commit}`])).trim();
94
+ return { ref, sha };
95
+ }
96
+
73
97
  /**
74
98
  * How many commits this worktree's HEAD carries that `base` doesn't.
75
99
  *
@@ -138,26 +162,15 @@ export async function repoWebUrl(repoRoot: string): Promise<string | undefined>
138
162
  return githubWebUrlFromRemote(raw);
139
163
  }
140
164
 
141
- /**
142
- * Prepare the workspace for a coding turn.
143
- *
144
- * `worktree` (default): ensure the persistent worktree for this repo's session exists
145
- * on its `lucid/<repoId>` branch, at a STABLE path so Claude Code's `--resume` resolves
146
- * across turns. `fresh: true` (a new session — no resume) resets the branch and worktree
147
- * to HEAD, discarding any prior session's state. Otherwise the existing worktree is
148
- * reused as-is so prior turns' commits (files) carry forward; if it's missing (first
149
- * turn, or pruned), it's created off HEAD.
150
- *
151
- * `in-place` (#121): the user's own checkout, on its live branch, uncommitted work and
152
- * all — the point of the mode is that Lucid continues from where the user left off, so
153
- * `fresh` resets NOTHING here. It would mean discarding their work.
154
- */
165
+ /** Resolve a persistent workspace. Provider session changes never reset its files. */
155
166
  export async function ensureWorkspace(
156
167
  repoRoot: string,
157
168
  repoId: string,
158
169
  opts: {
159
170
  mode?: WorkspaceMode;
171
+ /** Legacy callers may pass this; conversation resets never reset a workspace. */
160
172
  fresh?: boolean;
173
+ startPoint?: string;
161
174
  baseDir?: string;
162
175
  /** Conductor worker id (the fleet subtask's id). Present → an isolated per-worker
163
176
  * worktree/branch so N workers run in parallel on one repo. Absent → the classic
@@ -175,12 +188,15 @@ export async function ensureWorkspace(
175
188
  const path = sessionWorktreePath(repoId, baseDir, opts.workerId);
176
189
  mkdirSync(baseDir, { recursive: true });
177
190
 
178
- const present = existsSync(path);
179
- if (present && !opts.fresh) return { path, branch, mode }; // reuse (resume) — files carry forward
180
-
181
- if (present) await removeWorktree(repoRoot, { path, branch, mode }, { keepBranch: false }); // fresh: wipe old session
182
- // (Re)create the branch + worktree at the stable path off HEAD.
183
- await git(repoRoot, ['worktree', 'add', '-B', branch, path, 'HEAD']);
191
+ if (existsSync(path)) {
192
+ return { path, branch: await currentBranch(path), mode };
193
+ }
194
+ // Recover branches left behind by the old automatic delivery path.
195
+ const existing = await git(repoRoot, ['show-ref', '--verify', `refs/heads/${branch}`])
196
+ .then(() => true, () => false);
197
+ await git(repoRoot, existing
198
+ ? ['worktree', 'add', path, branch]
199
+ : ['worktree', 'add', '-b', branch, path, opts.startPoint ?? 'HEAD']);
184
200
  return { path, branch, mode };
185
201
  }
186
202
 
@@ -304,3 +320,11 @@ export async function removeWorktree(
304
320
  }
305
321
  }
306
322
  }
323
+
324
+
325
+ /** A review can inspect tracked changes without staging or reading unrelated untracked files. */
326
+ export async function reviewDiff(ws: Workspace): Promise<string> {
327
+ const diff = await git(ws.path, ['diff', '--no-ext-diff', '--no-textconv', 'HEAD', '--']);
328
+ const limit = 80_000;
329
+ return diff.length > limit ? diff.slice(0, limit) + '\n[Diff truncated. Read the relevant files for the rest.]' : diff;
330
+ }
package/src/config.ts CHANGED
@@ -44,6 +44,8 @@ export const VOICE_DIAG_DIR = join(CONFIG_DIR, 'voice-diag');
44
44
 
45
45
  /** An allowlisted repo Lucid may code in (M7). The phone sends the `id`, never a path. */
46
46
  export interface RepoEntry {
47
+ /** Remote base for new workers, e.g. origin/main; defaults to origin's HEAD. */
48
+ baseRef?: string;
47
49
  /** Short name the phone selects, e.g. `"lucidity"`. */
48
50
  id: string;
49
51
  /** Absolute path to the repo on this machine. `~` expands. */
@@ -0,0 +1,33 @@
1
+ // @ts-expect-error Node 22 runtime API; the repository's Node type baseline is 20.
2
+ import { DatabaseSync } from 'node:sqlite';
3
+ import { chmodSync, mkdirSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { randomUUID } from 'node:crypto';
6
+
7
+ /** The OS releases this lock on exit, including a crash. Never unlink its database. */
8
+ export class DaemonLease {
9
+ readonly owner = { epoch: randomUUID(), pid: process.pid, startedAt: new Date().toISOString() };
10
+ private db: any;
11
+
12
+ constructor(directory: string) {
13
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
14
+ const path = join(directory, 'daemon-owner.sqlite');
15
+ const db = new DatabaseSync(path);
16
+ try {
17
+ chmodSync(path, 0o600);
18
+ db.exec('PRAGMA busy_timeout=0; BEGIN EXCLUSIVE;');
19
+ this.db = db;
20
+ } catch (error) {
21
+ db.close();
22
+ if ((error as { errcode?: number }).errcode === 5)
23
+ throw new Error('Lucidity is already running for this configuration. Stop that daemon before starting another.');
24
+ throw error;
25
+ }
26
+ }
27
+
28
+ close(): void {
29
+ if (!this.db) return;
30
+ this.db.close();
31
+ this.db = undefined;
32
+ }
33
+ }
@@ -0,0 +1,106 @@
1
+ import {
2
+ goalReferenceKey,
3
+ type GoalCandidate,
4
+ type GoalCheck,
5
+ type GoalDetail,
6
+ type GoalEvidence,
7
+ } from '@lucidity/shared';
8
+
9
+ function bounded<T>(items: T[], characters: number, count: number): T[] {
10
+ const result: T[] = [];
11
+ let used = 2;
12
+ for (const item of items) {
13
+ const size = JSON.stringify(item).length + 1;
14
+ if (result.length >= count || used + size > characters) break;
15
+ result.push(item);
16
+ used += size;
17
+ }
18
+ return result;
19
+ }
20
+
21
+ /** Keep stored evidence intact; send a bounded, explicitly partial view to the model. */
22
+ export function goalAssessmentInput(input: {
23
+ detail: GoalDetail;
24
+ period: Pick<GoalCheck, 'cadence' | 'key' | 'start' | 'end'>;
25
+ sources: GoalCandidate[];
26
+ evidence: GoalEvidence[];
27
+ complete: boolean;
28
+ }) {
29
+ const { detail, period, complete } = input;
30
+ const direct = new Set(
31
+ detail.links
32
+ .filter((link) => link.state === 'active')
33
+ .map(goalReferenceKey),
34
+ );
35
+ const dated = new Set(
36
+ input.evidence.map((item) => goalReferenceKey(item.reference)),
37
+ );
38
+ const priority = (source: GoalCandidate) =>
39
+ direct.has(goalReferenceKey(source))
40
+ ? 0
41
+ : dated.has(goalReferenceKey(source))
42
+ ? 1
43
+ : 2;
44
+ const sources = bounded(
45
+ [...input.sources]
46
+ .sort(
47
+ (a, b) =>
48
+ priority(a) - priority(b) ||
49
+ (b.updatedAt ?? '').localeCompare(a.updatedAt ?? ''),
50
+ )
51
+ .map((source) => ({
52
+ ...source,
53
+ title: source.title.slice(0, 240),
54
+ description: source.description?.slice(0, 600) ?? null,
55
+ })),
56
+ 30_000,
57
+ 100,
58
+ );
59
+ const evidence = bounded(
60
+ [...input.evidence]
61
+ .sort((a, b) => b.at.localeCompare(a.at))
62
+ .map((item) => ({ ...item, title: item.title?.slice(0, 240) ?? null })),
63
+ 15_000,
64
+ 100,
65
+ );
66
+ const priorChecks = bounded(
67
+ detail.checks.slice(0, 14).map((check) => ({
68
+ key: check.key,
69
+ cadence: check.cadence,
70
+ start: check.start,
71
+ end: check.end,
72
+ signal: check.signal,
73
+ summary: check.summary.slice(0, 400),
74
+ timeframe: check.timeframe,
75
+ })),
76
+ 6_000,
77
+ 14,
78
+ );
79
+ const allNotes = detail.links.filter(
80
+ (link) => link.kind === 'note' && link.state === 'active',
81
+ );
82
+ const notes = bounded(
83
+ allNotes.map(({ kind, id }) => ({ kind, id })),
84
+ 3_000,
85
+ 40,
86
+ );
87
+ return {
88
+ goal: detail.goal,
89
+ period,
90
+ sources,
91
+ notes,
92
+ evidence,
93
+ priorChecks,
94
+ complete,
95
+ coverage: {
96
+ sources: { provided: sources.length, total: input.sources.length },
97
+ evidence: { provided: evidence.length, total: input.evidence.length },
98
+ priorChecks: {
99
+ provided: priorChecks.length,
100
+ total: detail.checks.length,
101
+ },
102
+ notes: { provided: notes.length, total: allNotes.length },
103
+ descriptionsAreExcerpts: true,
104
+ },
105
+ };
106
+ }
@@ -0,0 +1,88 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { listNotes, readNote, editNote, writeNote } from '@lucidity/notes';
3
+ import {
4
+ goalNoteId,
5
+ withGoalNoteId,
6
+ type GoalCandidate,
7
+ } from '@lucidity/shared';
8
+
9
+ export interface GoalNote extends GoalCandidate {
10
+ kind: 'note';
11
+ path: string;
12
+ content: string;
13
+ }
14
+ export interface GoalNotes {
15
+ list(): { notes: GoalNote[]; complete: boolean };
16
+ link(note: GoalNote): void;
17
+ read(id: string): GoalNote;
18
+ saveDraft(id: string, markdown: string): void;
19
+ }
20
+
21
+ /** Paths and note text never leave this computer for the hosted Goals API. */
22
+ export function createGoalNotes(
23
+ root: string | undefined,
24
+ ): GoalNotes | undefined {
25
+ if (!root) return undefined;
26
+ function scan() {
27
+ const summaries = listNotes(root!, { limit: 2001 });
28
+ const notes: GoalNote[] = [];
29
+ let complete = summaries.length <= 2000;
30
+ for (const summary of summaries.slice(0, 2000)) {
31
+ try {
32
+ const note = readNote(root!, summary.path);
33
+ notes.push({
34
+ kind: 'note',
35
+ id: goalNoteId(note.content) ?? randomUUID(),
36
+ path: note.path,
37
+ content: note.content,
38
+ title: note.title,
39
+ description: note.body.slice(0, 2000),
40
+ updatedAt: note.mtime,
41
+ status: null,
42
+ projectId: null,
43
+ });
44
+ } catch {
45
+ complete = false;
46
+ }
47
+ }
48
+ const counts = new Map<string, number>();
49
+ notes.forEach((note) =>
50
+ counts.set(note.id, (counts.get(note.id) ?? 0) + 1),
51
+ );
52
+ if ([...counts.values()].some((count) => count > 1)) complete = false;
53
+ return {
54
+ notes: notes.filter((note) => counts.get(note.id) === 1),
55
+ complete,
56
+ };
57
+ }
58
+ return {
59
+ list: scan,
60
+ link(note) {
61
+ const current = readNote(root, note.path);
62
+ if (current.content !== note.content)
63
+ throw new Error('The note changed during linking. Try again.');
64
+ const next = withGoalNoteId(current.content, note.id);
65
+ if (next !== current.content) {
66
+ if (!current.content)
67
+ throw new Error('Write something in this note before linking it.');
68
+ editNote(root, note.path, current.content, next);
69
+ }
70
+ },
71
+ read(id) {
72
+ const note = scan().notes.find((item) => goalNoteId(item.content) === id);
73
+ if (!note)
74
+ throw new Error('The linked note is not available in this vault.');
75
+ return note;
76
+ },
77
+ saveDraft(id, markdown) {
78
+ const content = withGoalNoteId(markdown, id);
79
+ const path = `Goals/Draft-${id}.md`;
80
+ try {
81
+ writeNote(root, path, content, 'create');
82
+ } catch (error) {
83
+ // Idempotent retry of our own exact output; never overwrite a user's edits.
84
+ if (readNote(root, path).content !== content) throw error;
85
+ }
86
+ },
87
+ };
88
+ }
package/src/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { HealthAwareExecutor } from '@lucidity/runtime';
2
+ import { HealthAwareExecutor, ExecutionOwnership, OwnedExecutor } from '@lucidity/runtime';
3
3
  import { AgentControls } from './agentControls.js';
4
+ import { WorkspaceRegistry } from './coding/workspaceRegistry.js';
4
5
  import { join } from 'node:path';
5
6
  import {
6
7
  ClaudeAgentExecutor,
@@ -33,6 +34,8 @@ import { importJobHistory } from './automations/history.js';
33
34
  import { setupDesign } from './automations/setup.js';
34
35
  import { runJob } from './jobs/runner.js';
35
36
  import { runBriefing } from './jobs/briefing.js';
37
+ import { runGoalTracking } from './jobs/goals.js';
38
+ import { createGoalNotes } from './goals/notes.js';
36
39
  import { runWeeklyReview } from './jobs/weeklyReview.js';
37
40
  import { runExtraction } from './jobs/extraction.js';
38
41
  import { fileState, runVoiceReview } from './jobs/voiceReview.js';
@@ -50,6 +53,7 @@ import { SpeechService } from './speech/service.js';
50
53
  import { FluidAudioEngine } from './speech/fluidAudio.js';
51
54
  import { createSessionJournalSource } from './room/journalSource.js';
52
55
  import { TurnLogStore } from './turnLog.js';
56
+ import { DaemonLease } from './daemonLease.js';
53
57
  import { commandContext } from './coding/commandContext.js';
54
58
  import { runCodeTurn } from './coding/runCodeTurn.js';
55
59
  import { runConductTurn } from './coding/conduct.js';
@@ -156,11 +160,14 @@ async function main(): Promise<void> {
156
160
  // (ask/voice) passes the Chat pair explicitly, and coding turns pass the Coding pair
157
161
  // explicitly; this default catches only the batch jobs (briefing/weekly/attention),
158
162
  // which want depth, not speed. So nothing ever silently falls back to the fast model.
163
+ const lease = args.runNow === undefined ? new DaemonLease(CONFIG_DIR) : undefined;
164
+ process.once('exit', () => lease?.close());
165
+ const ownership = new ExecutionOwnership();
159
166
  const providers = {
160
167
  claude: new HealthAwareExecutor(
161
- new ClaudeAgentExecutor({ oauthToken: config.oauthToken }),
168
+ new OwnedExecutor(new ClaudeAgentExecutor({ oauthToken: config.oauthToken }), 'claude', ownership),
162
169
  ),
163
- codex: new HealthAwareExecutor(new CodexExecutor()),
170
+ codex: new HealthAwareExecutor(new OwnedExecutor(new CodexExecutor(), 'codex', ownership)),
164
171
  };
165
172
  const controls = new AgentControls(Object.values(providers));
166
173
  const executor = new ProviderRouter(providers, () => ({
@@ -173,6 +180,11 @@ async function main(): Promise<void> {
173
180
  model: config.chatModel,
174
181
  effort: config.chatEffort,
175
182
  }));
183
+ const planningExecutor = new ProviderRouter(providers, () => ({
184
+ provider: config.codeProvider ?? 'claude',
185
+ model: /haiku/i.test(config.codeModel ?? '') ? 'default' : config.codeModel,
186
+ effort: 'high',
187
+ }));
176
188
  const queue = new LaneQueue();
177
189
 
178
190
  // Chat/ask tool dial (GitHub #98): when the user opts a capability in, wire the
@@ -233,6 +245,8 @@ async function main(): Promise<void> {
233
245
  }
234
246
 
235
247
  const turnLogs = new TurnLogStore();
248
+ turnLogs.runtime.set('supervisor', 'current', lease!.owner);
249
+ const workspaces = new WorkspaceRegistry(turnLogs.runtime, () => listAllowlist(config));
236
250
  turnLogs.prune();
237
251
  const automationStore = new AutomationStore(join(CONFIG_DIR, 'automations'));
238
252
  const designer = createDeckDesigner({
@@ -279,6 +293,14 @@ async function main(): Promise<void> {
279
293
  result = await runBriefing(config, bounded, deliverer, attention);
280
294
  else if (job.id === 'builtin:weekly-review')
281
295
  result = await runWeeklyReview(config, bounded, deliverer);
296
+ else if (job.id === 'builtin:goals')
297
+ // Goals composes this run's signal with each draft's cancellation signal.
298
+ result = await runGoalTracking({
299
+ api: createApiClient({ apiUrl: config.apiUrl, apiKey: config.apiKey }),
300
+ executor,
301
+ notes: createGoalNotes(config.notesPath),
302
+ signal,
303
+ });
282
304
  else if (job.id === 'builtin:extraction')
283
305
  result = await runExtraction(config, bounded);
284
306
  else if (job.id === 'builtin:voice-review')
@@ -336,6 +358,9 @@ async function main(): Promise<void> {
336
358
  },
337
359
  config.weeklyReview,
338
360
  );
361
+ automations.registerBuiltin('builtin:goals', 'Goals', {
362
+ ...daily('00:00'), frequency: 'interval', everyHours: 1,
363
+ });
339
364
  automations.registerBuiltin('builtin:extraction', 'Journal extraction', {
340
365
  ...daily('00:00'),
341
366
  frequency: 'interval',
@@ -368,7 +393,9 @@ async function main(): Promise<void> {
368
393
  automations.start();
369
394
 
370
395
  // Interactive chat server (lite local gateway): loopback + token auth.
396
+ const roomController = new AbortController();
371
397
  const chatServer = createChatServer({
398
+ signal: roomController.signal,
372
399
  config,
373
400
  executor: chatExecutor,
374
401
  token: ensureChatToken(),
@@ -382,11 +409,11 @@ async function main(): Promise<void> {
382
409
  // Room client (free path): dial the hosted relay so the phone can reach Lucid,
383
410
  // serving ask/briefing/journal through the shared harness. Best-effort — it
384
411
  // reconnects on its own and never takes the daemon down.
385
- const roomController = new AbortController();
386
412
  const vault = createVault(config.vaultPath);
387
413
  const harness = createLucidHarness({
388
414
  executor,
389
415
  chatExecutor,
416
+ planningExecutor,
390
417
  persona: vault.readPersona(),
391
418
  journalSource: createSessionJournalSource(
392
419
  join(config.vaultPath, 'sessions'),
@@ -414,10 +441,14 @@ async function main(): Promise<void> {
414
441
  harness,
415
442
  controls,
416
443
  models: (provider) => providers[provider].models(),
417
- commands: (provider, context) => providers[provider].commands({
418
- ...commandContext(context, config),
419
- mcp: context ? codingMcp : mcp,
420
- }),
444
+ commands: async (provider, context) => {
445
+ const commands = await providers[provider].commands({
446
+ ...commandContext(context, config), mcp: context ? codingMcp : mcp,
447
+ });
448
+ return context ? [...commands.filter((command) => command.name !== 'review'), {
449
+ name: 'review', description: 'Read-only review without a workspace checkpoint', argumentHint: '[instructions]', acceptsArguments: true, startsConversation: true,
450
+ }] : commands;
451
+ },
421
452
  providerHealth: () => ({
422
453
  claude: providers.claude.health(),
423
454
  codex: providers.codex.health(),
@@ -431,6 +462,7 @@ async function main(): Promise<void> {
431
462
  vault,
432
463
  signal: roomController.signal,
433
464
  turnLogs,
465
+ workspaces,
434
466
  attention,
435
467
  // The same lane queue the scheduler and local chat use, so a phone turn can't run a second
436
468
  // `claude` on a session that a briefing (or another device) already has open.
@@ -441,7 +473,8 @@ async function main(): Promise<void> {
441
473
  codeHandler:
442
474
  config.repos.length || config.repoRoots.length
443
475
  ? (req, ctx) =>
444
- runCodeTurn(req, {
476
+ runCodeTurn({ ...req, resume: workspaces.resume(req) }, {
477
+ prepareWorkspace: (request) => workspaces.prepare(request),
445
478
  repos: listAllowlist(config),
446
479
  executor,
447
480
  mcp: codingMcp,
@@ -461,6 +494,7 @@ async function main(): Promise<void> {
461
494
  config.repos.length || config.repoRoots.length
462
495
  ? (req, ctx) =>
463
496
  runConductTurn(req, {
497
+ runWorker: ctx.runWorker,
464
498
  onWorkerApproval: (requestId, approval) =>
465
499
  controls.request(requestId, approval, ctx.signal, ctx.send),
466
500
  onEnd: (requestId) => controls.end(requestId),
@@ -510,8 +544,7 @@ async function main(): Promise<void> {
510
544
  requestRestart: () => {
511
545
  console.error('[daemon] restarting to apply a config change.');
512
546
  setTimeout(() => {
513
- speech.dispose();
514
- process.exit(0);
547
+ void shutdown();
515
548
  }, RESTART_ACK_FLUSH_MS);
516
549
  },
517
550
  });
@@ -560,19 +593,31 @@ async function main(): Promise<void> {
560
593
  `Room dialing ${config.apiUrl}. ${tools}.${shell} ${runtimeVersions}.`,
561
594
  );
562
595
 
563
- const shutdown = () => {
596
+ let shuttingDown: Promise<void> | undefined;
597
+ const shutdown = (): Promise<void> => {
598
+ if (shuttingDown) return shuttingDown;
564
599
  console.error('[daemon] shutting down.');
565
600
  speech.dispose();
566
- void automations.stop();
601
+ const stoppedAutomations = automations.stop();
567
602
  chatServer.close();
568
603
  branchWatcher?.stop();
569
604
  roomClient.stop();
570
605
  roomController.abort();
571
- void Promise.all(
572
- Object.values(providers).map((provider) => provider.dispose()),
573
- );
574
- // Give owned children time to interrupt and reach their kill fallback.
575
- setTimeout(() => process.exit(0), 2500).unref();
606
+ shuttingDown = (async () => {
607
+ await Promise.all([
608
+ stoppedAutomations,
609
+ roomClient.drain(),
610
+ ...Object.values(providers).map((provider) => provider.dispose()),
611
+ ]);
612
+ await queue.drain();
613
+ turnLogs.close();
614
+ lease?.close();
615
+ process.exit(0);
616
+ })().catch((error) => {
617
+ console.error(`[daemon] shutdown failed: ${String(error)}`);
618
+ process.exit(1);
619
+ });
620
+ return shuttingDown;
576
621
  };
577
622
  process.on('SIGINT', shutdown);
578
623
  process.on('SIGTERM', shutdown);