@opencorelabs/lucidity 0.7.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 (219) hide show
  1. package/README.md +9 -2
  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 +57 -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 +116 -101
  44. package/dist/room/computer.d.ts.map +1 -1
  45. package/dist/room/computer.js +1 -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 +57 -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 +77 -74
  77. package/src/room/computer.ts +1 -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/mcp-server/dist/index.js +2 -0
  85. package/vendor/mcp-server/dist/tools/goals.d.ts +4 -0
  86. package/vendor/mcp-server/dist/tools/goals.d.ts.map +1 -0
  87. package/vendor/mcp-server/dist/tools/goals.js +38 -0
  88. package/vendor/mcp-server/package.json +1 -1
  89. package/vendor/mcp-server/src/index.ts +2 -0
  90. package/vendor/mcp-server/src/tools/goals.ts +62 -0
  91. package/vendor/runtime/README.md +2 -2
  92. package/vendor/runtime/dist/executor/asyncQueue.d.ts +1 -0
  93. package/vendor/runtime/dist/executor/asyncQueue.d.ts.map +1 -1
  94. package/vendor/runtime/dist/executor/asyncQueue.js +3 -0
  95. package/vendor/runtime/dist/executor/claudeAgent.d.ts +1 -1
  96. package/vendor/runtime/dist/executor/claudeAgent.d.ts.map +1 -1
  97. package/vendor/runtime/dist/executor/claudeAgent.js +20 -9
  98. package/vendor/runtime/dist/executor/codex.d.ts +1 -0
  99. package/vendor/runtime/dist/executor/codex.d.ts.map +1 -1
  100. package/vendor/runtime/dist/executor/codex.js +68 -36
  101. package/vendor/runtime/dist/executor/codexProtocol/FunctionCallOutputContentItem.d.ts +4 -1
  102. package/vendor/runtime/dist/executor/codexProtocol/FunctionCallOutputContentItem.d.ts.map +1 -1
  103. package/vendor/runtime/dist/executor/codexProtocol/Personality.d.ts +3 -0
  104. package/vendor/runtime/dist/executor/codexProtocol/Personality.d.ts.map +1 -1
  105. package/vendor/runtime/dist/executor/codexProtocol/PlanType.d.ts +1 -1
  106. package/vendor/runtime/dist/executor/codexProtocol/PlanType.d.ts.map +1 -1
  107. package/vendor/runtime/dist/executor/codexProtocol/v2/CyberAccessProgram.d.ts +6 -0
  108. package/vendor/runtime/dist/executor/codexProtocol/v2/CyberAccessProgram.d.ts.map +1 -0
  109. package/vendor/runtime/dist/executor/codexProtocol/v2/CyberAccessProgram.js +2 -0
  110. package/vendor/runtime/dist/executor/codexProtocol/v2/GetAccountRateLimitsResponse.d.ts +5 -0
  111. package/vendor/runtime/dist/executor/codexProtocol/v2/GetAccountRateLimitsResponse.d.ts.map +1 -1
  112. package/vendor/runtime/dist/executor/codexProtocol/v2/Model.d.ts +8 -0
  113. package/vendor/runtime/dist/executor/codexProtocol/v2/Model.d.ts.map +1 -1
  114. package/vendor/runtime/dist/executor/codexProtocol/v2/ModelAccessPrograms.d.ts +11 -0
  115. package/vendor/runtime/dist/executor/codexProtocol/v2/ModelAccessPrograms.d.ts.map +1 -0
  116. package/vendor/runtime/dist/executor/codexProtocol/v2/ModelAccessPrograms.js +2 -0
  117. package/vendor/runtime/dist/executor/codexProtocol/v2/RateLimitSnapshot.d.ts +4 -0
  118. package/vendor/runtime/dist/executor/codexProtocol/v2/RateLimitSnapshot.d.ts.map +1 -1
  119. package/vendor/runtime/dist/executor/codexProtocol/v2/ReviewStartParams.d.ts +2 -0
  120. package/vendor/runtime/dist/executor/codexProtocol/v2/ReviewStartParams.d.ts.map +1 -1
  121. package/vendor/runtime/dist/executor/codexProtocol/v2/ThreadResumeParams.d.ts +4 -1
  122. package/vendor/runtime/dist/executor/codexProtocol/v2/ThreadResumeParams.d.ts.map +1 -1
  123. package/vendor/runtime/dist/executor/codexProtocol/v2/ThreadStartParams.d.ts +3 -1
  124. package/vendor/runtime/dist/executor/codexProtocol/v2/ThreadStartParams.d.ts.map +1 -1
  125. package/vendor/runtime/dist/executor/codexProtocol/v2/TurnStartParams.d.ts +7 -2
  126. package/vendor/runtime/dist/executor/codexProtocol/v2/TurnStartParams.d.ts.map +1 -1
  127. package/vendor/runtime/dist/executor/codexProtocol/v2/UserInput.d.ts +3 -0
  128. package/vendor/runtime/dist/executor/codexProtocol/v2/UserInput.d.ts.map +1 -1
  129. package/vendor/runtime/dist/executor/codexRpc.d.ts +10 -3
  130. package/vendor/runtime/dist/executor/codexRpc.d.ts.map +1 -1
  131. package/vendor/runtime/dist/executor/codexRpc.js +18 -3
  132. package/vendor/runtime/dist/executor/codexSessions.d.ts +30 -0
  133. package/vendor/runtime/dist/executor/codexSessions.d.ts.map +1 -0
  134. package/vendor/runtime/dist/executor/codexSessions.js +88 -0
  135. package/vendor/runtime/dist/executor/health.d.ts +2 -1
  136. package/vendor/runtime/dist/executor/health.d.ts.map +1 -1
  137. package/vendor/runtime/dist/executor/health.js +17 -5
  138. package/vendor/runtime/dist/executor/liveTurns.d.ts +2 -1
  139. package/vendor/runtime/dist/executor/liveTurns.d.ts.map +1 -1
  140. package/vendor/runtime/dist/executor/liveTurns.js +12 -5
  141. package/vendor/runtime/dist/executor/ownership.d.ts +35 -0
  142. package/vendor/runtime/dist/executor/ownership.d.ts.map +1 -0
  143. package/vendor/runtime/dist/executor/ownership.js +99 -0
  144. package/vendor/runtime/dist/executor/providerRouter.d.ts +1 -0
  145. package/vendor/runtime/dist/executor/providerRouter.d.ts.map +1 -1
  146. package/vendor/runtime/dist/executor/providerRouter.js +5 -0
  147. package/vendor/runtime/dist/executor/types.d.ts +2 -0
  148. package/vendor/runtime/dist/executor/types.d.ts.map +1 -1
  149. package/vendor/runtime/dist/index.d.ts +1 -0
  150. package/vendor/runtime/dist/index.d.ts.map +1 -1
  151. package/vendor/runtime/dist/index.js +1 -0
  152. package/vendor/runtime/src/executor/asyncQueue.ts +3 -0
  153. package/vendor/runtime/src/executor/claudeAgent.ts +16 -9
  154. package/vendor/runtime/src/executor/codex.ts +75 -44
  155. package/vendor/runtime/src/executor/codexProtocol/FunctionCallOutputContentItem.ts +1 -1
  156. package/vendor/runtime/src/executor/codexProtocol/Personality.ts +3 -0
  157. package/vendor/runtime/src/executor/codexProtocol/PlanType.ts +1 -1
  158. package/vendor/runtime/src/executor/codexProtocol/README.md +2 -2
  159. package/vendor/runtime/src/executor/codexProtocol/v2/CyberAccessProgram.ts +9 -0
  160. package/vendor/runtime/src/executor/codexProtocol/v2/GetAccountRateLimitsResponse.ts +5 -0
  161. package/vendor/runtime/src/executor/codexProtocol/v2/Model.ts +11 -2
  162. package/vendor/runtime/src/executor/codexProtocol/v2/ModelAccessPrograms.ts +13 -0
  163. package/vendor/runtime/src/executor/codexProtocol/v2/RateLimitSnapshot.ts +5 -1
  164. package/vendor/runtime/src/executor/codexProtocol/v2/ReviewStartParams.ts +2 -0
  165. package/vendor/runtime/src/executor/codexProtocol/v2/ThreadResumeParams.ts +5 -1
  166. package/vendor/runtime/src/executor/codexProtocol/v2/ThreadStartParams.ts +4 -1
  167. package/vendor/runtime/src/executor/codexProtocol/v2/TurnStartParams.ts +7 -2
  168. package/vendor/runtime/src/executor/codexProtocol/v2/UserInput.ts +1 -1
  169. package/vendor/runtime/src/executor/codexRpc.ts +22 -4
  170. package/vendor/runtime/src/executor/codexSessions.ts +108 -0
  171. package/vendor/runtime/src/executor/health.ts +16 -6
  172. package/vendor/runtime/src/executor/liveTurns.ts +12 -5
  173. package/vendor/runtime/src/executor/ownership.ts +76 -0
  174. package/vendor/runtime/src/executor/providerRouter.ts +6 -0
  175. package/vendor/runtime/src/executor/types.ts +2 -0
  176. package/vendor/runtime/src/index.ts +1 -0
  177. package/vendor/shared/dist/agentCommands.d.ts +1 -0
  178. package/vendor/shared/dist/agentCommands.d.ts.map +1 -1
  179. package/vendor/shared/dist/cardStudio.d.ts +41 -0
  180. package/vendor/shared/dist/cardStudio.d.ts.map +1 -1
  181. package/vendor/shared/dist/cardStudio.js +13 -3
  182. package/vendor/shared/dist/computer.d.ts +7 -1
  183. package/vendor/shared/dist/computer.d.ts.map +1 -1
  184. package/vendor/shared/dist/computer.js +12 -2
  185. package/vendor/shared/dist/constants.d.ts +3 -3
  186. package/vendor/shared/dist/constants.d.ts.map +1 -1
  187. package/vendor/shared/dist/constants.js +5 -4
  188. package/vendor/shared/dist/goalNotes.d.ts +4 -0
  189. package/vendor/shared/dist/goalNotes.d.ts.map +1 -0
  190. package/vendor/shared/dist/goalNotes.js +23 -0
  191. package/vendor/shared/dist/goals.d.ts +835 -0
  192. package/vendor/shared/dist/goals.d.ts.map +1 -0
  193. package/vendor/shared/dist/goals.js +198 -0
  194. package/vendor/shared/dist/index.d.ts +3 -0
  195. package/vendor/shared/dist/index.d.ts.map +1 -1
  196. package/vendor/shared/dist/index.js +3 -0
  197. package/vendor/shared/dist/schemas/harness.d.ts +101 -0
  198. package/vendor/shared/dist/schemas/harness.d.ts.map +1 -1
  199. package/vendor/shared/dist/schemas/harness.js +6 -0
  200. package/vendor/shared/dist/workspaces.d.ts +138 -0
  201. package/vendor/shared/dist/workspaces.d.ts.map +1 -0
  202. package/vendor/shared/dist/workspaces.js +40 -0
  203. package/vendor/shared/src/agentCommands.ts +1 -0
  204. package/vendor/shared/src/cardStudio.ts +13 -3
  205. package/vendor/shared/src/computer.ts +16 -2
  206. package/vendor/shared/src/constants.ts +5 -4
  207. package/vendor/shared/src/goalNotes.ts +23 -0
  208. package/vendor/shared/src/goals.ts +237 -0
  209. package/vendor/shared/src/index.ts +4 -0
  210. package/vendor/shared/src/schemas/harness.ts +6 -0
  211. package/vendor/shared/src/workspaces.ts +48 -0
  212. package/dist/coding/fleetIntegrate.d.ts +0 -37
  213. package/dist/coding/fleetIntegrate.d.ts.map +0 -1
  214. package/dist/coding/fleetIntegrate.js +0 -64
  215. package/dist/coding/openFleetPr.d.ts +0 -41
  216. package/dist/coding/openFleetPr.d.ts.map +0 -1
  217. package/dist/coding/openFleetPr.js +0 -121
  218. package/src/coding/fleetIntegrate.ts +0 -95
  219. 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, () => ({
@@ -238,6 +245,8 @@ async function main(): Promise<void> {
238
245
  }
239
246
 
240
247
  const turnLogs = new TurnLogStore();
248
+ turnLogs.runtime.set('supervisor', 'current', lease!.owner);
249
+ const workspaces = new WorkspaceRegistry(turnLogs.runtime, () => listAllowlist(config));
241
250
  turnLogs.prune();
242
251
  const automationStore = new AutomationStore(join(CONFIG_DIR, 'automations'));
243
252
  const designer = createDeckDesigner({
@@ -284,6 +293,14 @@ async function main(): Promise<void> {
284
293
  result = await runBriefing(config, bounded, deliverer, attention);
285
294
  else if (job.id === 'builtin:weekly-review')
286
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
+ });
287
304
  else if (job.id === 'builtin:extraction')
288
305
  result = await runExtraction(config, bounded);
289
306
  else if (job.id === 'builtin:voice-review')
@@ -341,6 +358,9 @@ async function main(): Promise<void> {
341
358
  },
342
359
  config.weeklyReview,
343
360
  );
361
+ automations.registerBuiltin('builtin:goals', 'Goals', {
362
+ ...daily('00:00'), frequency: 'interval', everyHours: 1,
363
+ });
344
364
  automations.registerBuiltin('builtin:extraction', 'Journal extraction', {
345
365
  ...daily('00:00'),
346
366
  frequency: 'interval',
@@ -373,7 +393,9 @@ async function main(): Promise<void> {
373
393
  automations.start();
374
394
 
375
395
  // Interactive chat server (lite local gateway): loopback + token auth.
396
+ const roomController = new AbortController();
376
397
  const chatServer = createChatServer({
398
+ signal: roomController.signal,
377
399
  config,
378
400
  executor: chatExecutor,
379
401
  token: ensureChatToken(),
@@ -387,7 +409,6 @@ async function main(): Promise<void> {
387
409
  // Room client (free path): dial the hosted relay so the phone can reach Lucid,
388
410
  // serving ask/briefing/journal through the shared harness. Best-effort — it
389
411
  // reconnects on its own and never takes the daemon down.
390
- const roomController = new AbortController();
391
412
  const vault = createVault(config.vaultPath);
392
413
  const harness = createLucidHarness({
393
414
  executor,
@@ -420,10 +441,14 @@ async function main(): Promise<void> {
420
441
  harness,
421
442
  controls,
422
443
  models: (provider) => providers[provider].models(),
423
- commands: (provider, context) => providers[provider].commands({
424
- ...commandContext(context, config),
425
- mcp: context ? codingMcp : mcp,
426
- }),
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
+ },
427
452
  providerHealth: () => ({
428
453
  claude: providers.claude.health(),
429
454
  codex: providers.codex.health(),
@@ -437,6 +462,7 @@ async function main(): Promise<void> {
437
462
  vault,
438
463
  signal: roomController.signal,
439
464
  turnLogs,
465
+ workspaces,
440
466
  attention,
441
467
  // The same lane queue the scheduler and local chat use, so a phone turn can't run a second
442
468
  // `claude` on a session that a briefing (or another device) already has open.
@@ -447,7 +473,8 @@ async function main(): Promise<void> {
447
473
  codeHandler:
448
474
  config.repos.length || config.repoRoots.length
449
475
  ? (req, ctx) =>
450
- runCodeTurn(req, {
476
+ runCodeTurn({ ...req, resume: workspaces.resume(req) }, {
477
+ prepareWorkspace: (request) => workspaces.prepare(request),
451
478
  repos: listAllowlist(config),
452
479
  executor,
453
480
  mcp: codingMcp,
@@ -467,6 +494,7 @@ async function main(): Promise<void> {
467
494
  config.repos.length || config.repoRoots.length
468
495
  ? (req, ctx) =>
469
496
  runConductTurn(req, {
497
+ runWorker: ctx.runWorker,
470
498
  onWorkerApproval: (requestId, approval) =>
471
499
  controls.request(requestId, approval, ctx.signal, ctx.send),
472
500
  onEnd: (requestId) => controls.end(requestId),
@@ -516,8 +544,7 @@ async function main(): Promise<void> {
516
544
  requestRestart: () => {
517
545
  console.error('[daemon] restarting to apply a config change.');
518
546
  setTimeout(() => {
519
- speech.dispose();
520
- process.exit(0);
547
+ void shutdown();
521
548
  }, RESTART_ACK_FLUSH_MS);
522
549
  },
523
550
  });
@@ -566,19 +593,31 @@ async function main(): Promise<void> {
566
593
  `Room dialing ${config.apiUrl}. ${tools}.${shell} ${runtimeVersions}.`,
567
594
  );
568
595
 
569
- const shutdown = () => {
596
+ let shuttingDown: Promise<void> | undefined;
597
+ const shutdown = (): Promise<void> => {
598
+ if (shuttingDown) return shuttingDown;
570
599
  console.error('[daemon] shutting down.');
571
600
  speech.dispose();
572
- void automations.stop();
601
+ const stoppedAutomations = automations.stop();
573
602
  chatServer.close();
574
603
  branchWatcher?.stop();
575
604
  roomClient.stop();
576
605
  roomController.abort();
577
- void Promise.all(
578
- Object.values(providers).map((provider) => provider.dispose()),
579
- );
580
- // Give owned children time to interrupt and reach their kill fallback.
581
- 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;
582
621
  };
583
622
  process.on('SIGINT', shutdown);
584
623
  process.on('SIGTERM', shutdown);