@litfamily/litcodex 1.0.37 → 1.0.38

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 (67) hide show
  1. package/README-Ko-KR.md +9 -9
  2. package/README.md +9 -9
  3. package/marketplace/plugins/litcodex/.codex-plugin/plugin.json +1 -1
  4. package/marketplace/plugins/litcodex/components/auto-update/package.json +1 -1
  5. package/marketplace/plugins/litcodex/components/comment-checker/package.json +1 -1
  6. package/marketplace/plugins/litcodex/components/git-bash/package.json +1 -1
  7. package/marketplace/plugins/litcodex/components/lit-loop/directives/lit-adhd.md +32 -13
  8. package/marketplace/plugins/litcodex/components/lit-loop/dist/hook-cli.js +2 -1
  9. package/marketplace/plugins/litcodex/components/lit-loop/dist/rewind-board.d.ts +192 -0
  10. package/marketplace/plugins/litcodex/components/lit-loop/dist/rewind-board.js +437 -0
  11. package/marketplace/plugins/litcodex/components/lit-loop/dist/rewind-cli.js +17 -3
  12. package/marketplace/plugins/litcodex/components/lit-loop/dist/rewind-go.d.ts +3 -2
  13. package/marketplace/plugins/litcodex/components/lit-loop/dist/rewind-go.js +6 -4
  14. package/marketplace/plugins/litcodex/components/lit-loop/dist/rewind.d.ts +9 -2
  15. package/marketplace/plugins/litcodex/components/lit-loop/dist/rewind.js +245 -30
  16. package/marketplace/plugins/litcodex/components/lit-loop/dist/route-heads.js +3 -3
  17. package/marketplace/plugins/litcodex/components/lit-loop/dist/state-types.d.ts +1 -1
  18. package/marketplace/plugins/litcodex/components/lit-loop/dist/state-types.js +2 -0
  19. package/marketplace/plugins/litcodex/components/lit-loop/dist/workflow-map.js +5 -1
  20. package/marketplace/plugins/litcodex/components/lit-loop/package.json +1 -1
  21. package/marketplace/plugins/litcodex/components/lsp/package.json +1 -1
  22. package/marketplace/plugins/litcodex/components/rules/package.json +1 -1
  23. package/marketplace/plugins/litcodex/components/start-work-continuation/directive.md +5 -5
  24. package/marketplace/plugins/litcodex/components/start-work-continuation/dist/cli.js +30 -5
  25. package/marketplace/plugins/litcodex/components/start-work-continuation/dist/codex-hook.d.ts +6 -5
  26. package/marketplace/plugins/litcodex/components/start-work-continuation/dist/codex-hook.js +184 -62
  27. package/marketplace/plugins/litcodex/components/start-work-continuation/dist/host-reads.d.ts +7 -0
  28. package/marketplace/plugins/litcodex/components/start-work-continuation/dist/host-reads.js +30 -0
  29. package/marketplace/plugins/litcodex/components/start-work-continuation/dist/index.d.ts +9 -4
  30. package/marketplace/plugins/litcodex/components/start-work-continuation/dist/index.js +5 -2
  31. package/marketplace/plugins/litcodex/components/start-work-continuation/dist/lifecycle-root.d.ts +9 -0
  32. package/marketplace/plugins/litcodex/components/start-work-continuation/dist/lifecycle-root.js +117 -0
  33. package/marketplace/plugins/litcodex/components/start-work-continuation/dist/lifecycle-store.d.ts +72 -1
  34. package/marketplace/plugins/litcodex/components/start-work-continuation/dist/lifecycle-store.js +525 -103
  35. package/marketplace/plugins/litcodex/components/start-work-continuation/dist/pre-tool-hook.d.ts +8 -0
  36. package/marketplace/plugins/litcodex/components/start-work-continuation/dist/pre-tool-hook.js +131 -0
  37. package/marketplace/plugins/litcodex/components/start-work-continuation/dist/protected-paths.d.ts +13 -0
  38. package/marketplace/plugins/litcodex/components/start-work-continuation/dist/protected-paths.js +103 -0
  39. package/marketplace/plugins/litcodex/components/start-work-continuation/dist/work-state-reader.d.ts +14 -2
  40. package/marketplace/plugins/litcodex/components/start-work-continuation/dist/work-state-reader.js +14 -4
  41. package/marketplace/plugins/litcodex/components/start-work-continuation/package.json +1 -1
  42. package/marketplace/plugins/litcodex/components/telemetry/package.json +1 -1
  43. package/marketplace/plugins/litcodex/components/wikify-knowledge/package.json +1 -1
  44. package/marketplace/plugins/litcodex/hooks/hooks.json +11 -0
  45. package/marketplace/plugins/litcodex/skills/lit-adhd/SKILL.md +43 -21
  46. package/marketplace/plugins/litcodex/skills/lit-adhd/agents/openai.yaml +1 -1
  47. package/marketplace/plugins/litcodex/skills/lit-adhd/references/card-examples.md +103 -3
  48. package/marketplace/plugins/litcodex/skills/lit-adhd/references/status-taxonomy.md +19 -1
  49. package/marketplace/plugins/litcodex/skills/start-work/SKILL.md +18 -4
  50. package/node_modules/@litcodex/lit-loop/directives/lit-adhd.md +32 -13
  51. package/node_modules/@litcodex/lit-loop/dist/hook-cli.js +2 -1
  52. package/node_modules/@litcodex/lit-loop/dist/rewind-board.d.ts +192 -0
  53. package/node_modules/@litcodex/lit-loop/dist/rewind-board.js +437 -0
  54. package/node_modules/@litcodex/lit-loop/dist/rewind-cli.js +17 -3
  55. package/node_modules/@litcodex/lit-loop/dist/rewind-go.d.ts +3 -2
  56. package/node_modules/@litcodex/lit-loop/dist/rewind-go.js +6 -4
  57. package/node_modules/@litcodex/lit-loop/dist/rewind.d.ts +9 -2
  58. package/node_modules/@litcodex/lit-loop/dist/rewind.js +245 -30
  59. package/node_modules/@litcodex/lit-loop/dist/route-heads.js +3 -3
  60. package/node_modules/@litcodex/lit-loop/dist/state-types.d.ts +1 -1
  61. package/node_modules/@litcodex/lit-loop/dist/state-types.js +2 -0
  62. package/node_modules/@litcodex/lit-loop/dist/workflow-map.js +5 -1
  63. package/node_modules/@litcodex/lit-loop/package.json +1 -1
  64. package/node_modules/@litcodex/lit-loop/skills/lit-adhd/SKILL.md +43 -21
  65. package/node_modules/@litcodex/lit-loop/skills/start-work/SKILL.md +18 -4
  66. package/package.json +2 -2
  67. package/readme-assets/badge-version.svg +1 -1
@@ -1,12 +1,13 @@
1
- import type { StoreOptions } from "./lifecycle-store.js";
1
+ import type { CancelNotice, StoreOptions } from "./lifecycle-store.js";
2
2
  import type { ReadonlyFileSystem } from "./types.js";
3
3
  export declare function runStopHook(input: unknown, _legacyFs?: ReadonlyFileSystem): string;
4
- export type BoundaryAnswer = "approve" | "deny";
4
+ export type TypedRunCommand = "approve" | "deny" | "cancel";
5
5
  /**
6
- * The whole prompt `lit approve` / `lit 승인` or `lit deny` / `lit 거절`, case-sensitive, at most 512 bytes.
7
- * Anything around it (a quote, a code fence, a leading word) is ordinary text and answers nothing.
6
+ * The whole prompt `lit approve` / `lit 승인`, `lit deny` / `lit 거절` or `lit cancel` / `lit 취소`, case-sensitive,
7
+ * at most 512 characters. Anything around it (a quote, a code fence, a leading word) is ordinary text.
8
8
  */
9
- export declare function parseBoundaryAnswer(prompt: string): BoundaryAnswer | null;
9
+ export declare function parseTypedRunCommand(prompt: string): TypedRunCommand | null;
10
+ export declare function cancelNoticeText(notice: CancelNotice): string;
10
11
  export declare function runUserPromptSubmitHook(input: unknown, options?: StoreOptions): string;
11
12
  interface StartWorkRoute {
12
13
  readonly selector: string | null;
@@ -2,7 +2,8 @@ import { createHash } from "node:crypto";
2
2
  import { closeSync, constants, fstatSync, openSync, readSync, realpathSync } from "node:fs";
3
3
  import { basename, isAbsolute } from "node:path";
4
4
  import { START_WORK_CONTINUATION_DIRECTIVE } from "./directive.js";
5
- import { advanceStopLease, inspectLifecycleState, reconcileLifecycleState, selectWorkForSession, transitionWork, } from "./lifecycle-store.js";
5
+ import { findLifecycleRoot } from "./lifecycle-root.js";
6
+ import { advanceStopLease, cancelWorkFromUserPrompt, denyParkedBoundaries, dropVanishedParkedBoundary, inspectLifecycleState, LifecycleStoreError, reconcileLifecycleState, selectWorkForSession, takeCancelNotice, transitionWork, } from "./lifecycle-store.js";
6
7
  import { readContinuationState } from "./work-state-reader.js";
7
8
  const MAX_TRANSCRIPT_BYTES = 2_000_000;
8
9
  const MAX_INPUT_STRING = 100_000;
@@ -38,100 +39,217 @@ export function runStopHook(input, _legacyFs) {
38
39
  }
39
40
  }
40
41
  /**
41
- * The whole prompt `lit approve` / `lit 승인` or `lit deny` / `lit 거절`, case-sensitive, at most 512 bytes.
42
- * Anything around it (a quote, a code fence, a leading word) is ordinary text and answers nothing.
42
+ * The whole prompt `lit approve` / `lit 승인`, `lit deny` / `lit 거절` or `lit cancel` / `lit 취소`, case-sensitive,
43
+ * at most 512 characters. Anything around it (a quote, a code fence, a leading word) is ordinary text.
43
44
  */
44
- export function parseBoundaryAnswer(prompt) {
45
+ export function parseTypedRunCommand(prompt) {
45
46
  if (prompt.length > 512)
46
47
  return null;
47
- const match = prompt.trim().match(/^lit[ \t]+(approve|승인|deny|거절)$/u);
48
+ const match = prompt.trim().match(/^lit[ \t]+(approve|승인|deny|거절|cancel|취소)$/u);
48
49
  if (match === null)
49
50
  return null;
50
- return match[1] === "approve" || match[1] === "승인" ? "approve" : "deny";
51
+ if (match[1] === "approve" || match[1] === "승인")
52
+ return "approve";
53
+ return match[1] === "deny" || match[1] === "거절" ? "deny" : "cancel";
51
54
  }
52
55
  function answerContext(text) {
53
56
  return JSON.stringify({ hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: text } });
54
57
  }
55
- const NOTHING_WAITING = "The user typed a start-work boundary answer, but this session has no paused start-work run waiting at a boundary, so nothing changed. Tell the user that in one sentence.";
58
+ const nothingParked = (word) => `The user typed \`lit ${word}\`, but this session's start-work has no parked step, so nothing changed. Tell the user that in one sentence.`;
59
+ const REFUSED = "The user typed a start-work boundary answer, but the lifecycle store refused it, so the run is unchanged. Tell the user in one sentence and offer to show the run's state.";
60
+ export function cancelNoticeText(notice) {
61
+ return `Before this prompt, the user ended start-work ${inert(notice.work_id)} (${inert(notice.plan_name)}) by typing \`lit cancel\` in another Codex session. That run is over: none of its tasks or parked steps are pending any more, so do not pick its plan back up. Handle this prompt as a new request.`;
62
+ }
63
+ /** `lit cancel` ends the project's run, whichever of the project's Codex sessions typed it. */
64
+ function answerCancel(root, input, options) {
65
+ try {
66
+ const result = cancelWorkFromUserPrompt(root, { sessionId: input.session_id, turnId: input.turn_id }, options);
67
+ if (result.outcome === "nothing") {
68
+ return "The user typed `lit cancel`, but this project has no start-work in progress, so nothing changed. Tell the user that in one sentence.";
69
+ }
70
+ const other = result.outcome === "cancelled" && result.otherSession
71
+ ? " That run belonged to another Codex session, which hears about it when its user next types there."
72
+ : "";
73
+ return `The user typed \`lit cancel\`, and the lifecycle store ended start-work ${inert(result.workId)} (${inert(result.plan)}); its status is now abandoned.${other} Confirm the cancellation to the user in one sentence. Do not run any task of that plan.`;
74
+ }
75
+ catch (error) {
76
+ if (!(error instanceof Error))
77
+ throw error;
78
+ const code = error instanceof LifecycleStoreError ? error.code : "STATE_UNREADABLE";
79
+ if (code === "LOCK_BUSY") {
80
+ return "The user typed `lit cancel`, but another LitCodex process held the start-work state lock, so the run is unchanged. Ask the user to type `lit cancel` once more, and do nothing else meanwhile.";
81
+ }
82
+ return `BLOCKED: the user typed \`lit cancel\`, but the lifecycle store refused it (${code}), so the run is unchanged. Tell the user in one sentence and offer to show \`litcodex-start-work-continuation doctor\` output.`;
83
+ }
84
+ }
56
85
  /**
57
- * Typed answer to the boundary a paused start-work run waits at. `lit approve` resumes the run with a grant the
58
- * hook derives from this turn, through the same transition as the exact resume line, so the stored authority
59
- * still decides what the grant may cover. `lit deny` changes no state: the run stays paused and the model is told
60
- * not to take that action. Both answer only this session's own paused run.
86
+ * Typed answer to this session's parked steps. `lit approve` grants each parked step through the same resume
87
+ * transition as the exact resume line, so the stored authority still decides what a grant may cover; release-class
88
+ * and protected steps are never granted. `lit deny` refuses them all for the rest of the run. Both are optional:
89
+ * the run keeps going either way.
61
90
  */
62
- function answerBoundary(input, answer, options) {
91
+ function answerParked(input, answer, options) {
63
92
  try {
64
93
  reconcileLifecycleState(input.cwd, options);
65
94
  const inspected = inspectLifecycleState(input.cwd);
66
95
  if (!inspected.ok || inspected.state.active_work_id === null)
67
- return answerContext(NOTHING_WAITING);
68
- const work = selectWorkForSession(inspected.state, input.session_id, ["paused"]);
69
- const pending = work?.pending_boundary;
70
- if (work === null || pending === undefined)
71
- return answerContext(NOTHING_WAITING);
72
- const what = `boundary ${pending.boundary_id} (action ${pending.action}, root ${pending.root}) of work ${work.work_id}`;
96
+ return nothingParked(answer);
97
+ const work = selectWorkForSession(inspected.state, input.session_id, ["active"]);
98
+ const parked = work?.parked_boundaries ?? [];
99
+ if (work === null || parked.length === 0)
100
+ return nothingParked(answer);
73
101
  if (answer === "deny") {
74
- return answerContext(`The user typed \`lit deny\` for ${what}. Do not take that action or retry it. The run stays paused; ask what to do instead or replan inside the stored authority, and resume only after a new \`lit approve\`.`);
102
+ const result = denyParkedBoundaries(input.cwd, { sessionId: input.session_id, turnId: input.turn_id }, options);
103
+ if (result.outcome === "nothing")
104
+ return nothingParked(answer);
105
+ return `The user typed \`lit deny\`, so these parked steps of start-work ${inert(result.workId)} are refused for the rest of this run: ${listOf(result.boundaries)}. Continue with the plan without them; when a task cannot be finished without one, leave its box unchecked and name it on a \`BLOCKED:\` line in your final message.`;
75
106
  }
76
- const key = digest([work.work_id, pending.boundary_id, input.session_id, input.turn_id].join("\0"));
77
- transitionWork(input.cwd, {
78
- action: "resume",
79
- expectedRevision: inspected.state.revision,
80
- sessionId: input.session_id,
81
- transitionId: `prompt-approve:${key}`,
82
- workId: work.work_id,
83
- reasonCode: "explicit_user_resume",
84
- turnId: input.turn_id,
85
- boundary: pending,
86
- grant: {
87
- grant_id: `typed-approve:${key}`,
88
- authority_id: pending.authority_id,
89
- boundary_id: pending.boundary_id,
90
- action: pending.action,
91
- root: pending.root,
92
- },
93
- }, options);
94
- return answerContext(`The user typed \`lit approve\` for ${what}. The run is active again with a grant for exactly that action and root. Continue the plan's next open task inside it, and ask again before anything beyond it.`);
107
+ return approveParked(input, work, parked, options);
95
108
  }
96
109
  catch (error) {
97
110
  if (!(error instanceof Error))
98
111
  throw error;
99
- return answerContext("The user typed a start-work boundary answer, but the lifecycle store refused it, so the run is unchanged. Tell the user in one sentence and offer to show the run's state.");
112
+ return REFUSED;
113
+ }
114
+ }
115
+ function approveParked(input, work, parked, options) {
116
+ const granted = [];
117
+ const gone = [];
118
+ const remaining = [];
119
+ let stopped = null;
120
+ for (const entry of parked) {
121
+ const boundary = {
122
+ boundary_id: entry.boundary_id,
123
+ authority_id: entry.authority_id,
124
+ action: entry.action,
125
+ root: entry.root,
126
+ };
127
+ if (stopped !== null) {
128
+ remaining.push({ boundary, reason: stopped });
129
+ continue;
130
+ }
131
+ const key = digest([work.work_id, entry.boundary_id, input.session_id, input.turn_id].join("\0"));
132
+ try {
133
+ const inspected = inspectLifecycleState(input.cwd);
134
+ if (!inspected.ok)
135
+ throw new LifecycleStoreError(inspected.code, inspected.message);
136
+ transitionWork(input.cwd, {
137
+ action: "resume",
138
+ expectedRevision: inspected.state.revision,
139
+ sessionId: input.session_id,
140
+ transitionId: `prompt-approve:${key}`,
141
+ workId: work.work_id,
142
+ reasonCode: "explicit_user_resume",
143
+ turnId: input.turn_id,
144
+ boundary,
145
+ grant: {
146
+ grant_id: `typed-approve:${key}`,
147
+ authority_id: entry.authority_id,
148
+ boundary_id: entry.boundary_id,
149
+ action: entry.action,
150
+ root: entry.root,
151
+ },
152
+ }, options);
153
+ granted.push(boundary);
154
+ }
155
+ catch (error) {
156
+ if (!(error instanceof Error))
157
+ throw error;
158
+ const code = error instanceof LifecycleStoreError ? error.code : "STATE_UNREADABLE";
159
+ if (code === "BOUNDARY_INVALID" &&
160
+ dropVanishedParkedBoundary(input.cwd, input.session_id, entry.boundary_id, options)) {
161
+ gone.push(boundary);
162
+ continue;
163
+ }
164
+ const reason = reasonFor(code);
165
+ remaining.push({ boundary, reason });
166
+ if (code === "GRANT_LIMIT" || code === "LOCK_BUSY")
167
+ stopped = reason;
168
+ }
169
+ }
170
+ const goneText = gone.length === 0 ? "" : ` Dropped because the path no longer exists: ${listOf(gone)}.`;
171
+ const remainingText = remaining.length === 0
172
+ ? ""
173
+ : ` Still parked, not granted: ${remaining.map((item) => `${stepOf(item.boundary)} (${item.reason})`).join("; ")}.`;
174
+ if (granted.length === 0) {
175
+ return `${REFUSED}${goneText}${remainingText}`;
100
176
  }
177
+ return `The user typed \`lit approve\`, so start-work ${inert(work.work_id)} now holds a grant for each of these parked steps, for exactly its action and root: ${listOf(granted)}.${goneText}${remainingText} Run the granted steps now, then continue with the plan.`;
178
+ }
179
+ function reasonFor(code) {
180
+ if (code === "BOUNDARY_MISMATCH")
181
+ return "a release-class or forbidden action the user does outside the run";
182
+ if (code === "BOUNDARY_PROTECTED")
183
+ return "a protected path";
184
+ if (code === "GRANT_LIMIT")
185
+ return "the run already holds 64 grants";
186
+ if (code === "LOCK_BUSY")
187
+ return "the state lock was busy";
188
+ return `refused with ${code}`;
189
+ }
190
+ function stepOf(boundary) {
191
+ return `${inert(boundary.action)} ${inert(boundary.root).slice(0, 120)}`;
192
+ }
193
+ function listOf(boundaries) {
194
+ return boundaries.map(stepOf).join("; ");
195
+ }
196
+ /** Control characters become spaces so a stored label cannot break the line it is quoted in. */
197
+ function inert(text) {
198
+ return text.replace(/\p{Cc}/gu, " ");
101
199
  }
102
200
  export function runUserPromptSubmitHook(input, options = {}) {
103
201
  if (!isUserPromptSubmitInput(input))
104
202
  return "";
105
- const answer = parseBoundaryAnswer(input.prompt);
106
- if (answer !== null)
107
- return answerBoundary(input, answer, options);
203
+ const root = findLifecycleRoot(input.cwd, { wantSession: input.session_id });
204
+ let note = null;
205
+ try {
206
+ const lifted = takeCancelNotice(root, input.session_id, options);
207
+ if (lifted !== null)
208
+ note = cancelNoticeText(lifted);
209
+ }
210
+ catch (error) {
211
+ if (!(error instanceof Error))
212
+ throw error;
213
+ }
214
+ const withNote = (text) => answerContext(note === null ? text : `${note} ${text}`);
215
+ const command = parseTypedRunCommand(input.prompt);
216
+ if (command === "cancel")
217
+ return withNote(answerCancel(root, input, options));
218
+ if (command !== null)
219
+ return withNote(answerParked(input, command, options));
220
+ resumeFromExactRoute(input, options);
221
+ // Codex accepts a zero-byte successful UserPromptSubmit hook. The lit-loop handler owns the
222
+ // additionalContext directive for this same prompt; this lifecycle handler must not steal it.
223
+ return note === null ? "" : answerContext(note);
224
+ }
225
+ /** The exact `start-work … --resume <boundary> --grant <grant>` line grants one parked step. */
226
+ function resumeFromExactRoute(input, options) {
108
227
  const route = parseExplicitStartWorkPrompt(input.prompt);
109
- if (route === null)
110
- return "";
228
+ if (route === null || route.resumeBoundaryId === null || route.grantId === null)
229
+ return;
111
230
  try {
112
231
  reconcileLifecycleState(input.cwd, options);
113
232
  const inspected = inspectLifecycleState(input.cwd);
114
233
  if (!inspected.ok || inspected.state.active_work_id === null)
115
- return "";
116
- if (route.resumeBoundaryId === null || route.grantId === null)
117
- return "";
234
+ return;
118
235
  const transitionId = `prompt-resume:${digest([inspected.state.active_work_id, route.resumeBoundaryId, route.grantId, input.session_id, input.turn_id].join("\0"))}`;
119
- const paused = selectWorkForSession(inspected.state, input.session_id, ["paused"]);
120
- const selected = paused ??
121
- matchingResumeReplay(inspected.state.works[inspected.state.active_work_id], input.session_id, transitionId);
236
+ const active = selectWorkForSession(inspected.state, input.session_id, ["active"]);
237
+ const entry = active?.parked_boundaries?.find((item) => item.boundary_id === route.resumeBoundaryId);
238
+ const selected = entry === undefined
239
+ ? matchingResumeReplay(inspected.state.works[inspected.state.active_work_id], input.session_id, transitionId)
240
+ : active;
122
241
  if (selected === null ||
123
242
  !selectorMatches(route.selector, selected) ||
124
243
  !worktreeMatches(route.worktreePath, selected)) {
125
- return "";
244
+ return;
126
245
  }
127
- const pending = selected.pending_boundary ??
246
+ const pending = entry ??
128
247
  (selected.last_transition?.kind === "start_work_resumed" ? selected.last_transition.boundary : undefined);
129
248
  if (pending === undefined || pending.boundary_id !== route.resumeBoundaryId)
130
- return "";
131
- const grant = {
132
- grant_id: route.grantId,
133
- authority_id: pending.authority_id,
249
+ return;
250
+ const boundary = {
134
251
  boundary_id: pending.boundary_id,
252
+ authority_id: pending.authority_id,
135
253
  action: pending.action,
136
254
  root: pending.root,
137
255
  };
@@ -143,17 +261,20 @@ export function runUserPromptSubmitHook(input, options = {}) {
143
261
  workId: selected.work_id,
144
262
  reasonCode: "explicit_user_resume",
145
263
  turnId: input.turn_id,
146
- boundary: pending,
147
- grant,
264
+ boundary,
265
+ grant: {
266
+ grant_id: route.grantId,
267
+ authority_id: boundary.authority_id,
268
+ boundary_id: boundary.boundary_id,
269
+ action: boundary.action,
270
+ root: boundary.root,
271
+ },
148
272
  }, options);
149
273
  }
150
274
  catch (error) {
151
275
  if (!(error instanceof Error))
152
276
  throw error;
153
277
  }
154
- // Codex accepts a zero-byte successful UserPromptSubmit hook. The lit-loop handler owns the
155
- // additionalContext directive for this same prompt; this lifecycle handler must not steal it.
156
- return "";
157
278
  }
158
279
  function block(reason) {
159
280
  return JSON.stringify({ decision: "block", reason });
@@ -171,7 +292,8 @@ function renderDirective(state, sessionId) {
171
292
  worktreePath: state.worktreePath,
172
293
  authority: state.authority,
173
294
  authorityGrants: state.authorityGrants,
174
- pendingBoundary: state.pendingBoundary,
295
+ parkedBoundaries: state.parkedBoundaries,
296
+ deniedBoundaries: state.deniedBoundaries,
175
297
  ledgerPath: state.ledgerPath,
176
298
  sessionId: `codex:${sessionId}`,
177
299
  };
@@ -0,0 +1,7 @@
1
+ /**
2
+ * True when reading `root` belongs to the Codex host rather than to the plan: this session's own rollout file, the
3
+ * Codex home's `AGENTS.md`, `skills/`, `agents/` and `litcodex/` folders, the transcript Codex named, or this
4
+ * plugin. Such a read never needs a boundary. A folder under `sessions/` is not included, since listing it shows
5
+ * other sessions. The protected-path check runs first and always wins.
6
+ */
7
+ export declare function isHostOwnedRead(root: string, sessionId: string, env?: NodeJS.ProcessEnv, transcriptPath?: string): boolean;
@@ -0,0 +1,30 @@
1
+ import { basename, isAbsolute, join, relative, sep } from "node:path";
2
+ import { fileURLToPath } from "node:url";
3
+ import { canonical, codexHomeOf } from "./protected-paths.js";
4
+ const PLUGIN_ROOT = fileURLToPath(new URL("../../..", import.meta.url));
5
+ /**
6
+ * True when reading `root` belongs to the Codex host rather than to the plan: this session's own rollout file, the
7
+ * Codex home's `AGENTS.md`, `skills/`, `agents/` and `litcodex/` folders, the transcript Codex named, or this
8
+ * plugin. Such a read never needs a boundary. A folder under `sessions/` is not included, since listing it shows
9
+ * other sessions. The protected-path check runs first and always wins.
10
+ */
11
+ export function isHostOwnedRead(root, sessionId, env = process.env, transcriptPath) {
12
+ const target = canonical(root);
13
+ if (transcriptPath !== undefined && isAbsolute(transcriptPath) && canonical(transcriptPath) === target)
14
+ return true;
15
+ if (within(canonical(PLUGIN_ROOT), target))
16
+ return true;
17
+ const home = codexHomeOf(env);
18
+ if (home === null)
19
+ return false;
20
+ if (within(join(home, "sessions"), target)) {
21
+ return basename(target).toLowerCase().endsWith(`-${sessionId.toLowerCase()}.jsonl`);
22
+ }
23
+ if (target === canonical(join(home, "AGENTS.md")))
24
+ return true;
25
+ return ["skills", "agents", "litcodex"].some((folder) => within(canonical(join(home, folder)), target));
26
+ }
27
+ function within(base, candidate) {
28
+ const rel = relative(base, candidate);
29
+ return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
30
+ }
@@ -1,11 +1,16 @@
1
- export { runStopHook, runUserPromptSubmitHook } from "./codex-hook.js";
1
+ export type { TypedRunCommand } from "./codex-hook.js";
2
+ export { parseTypedRunCommand, runStopHook, runUserPromptSubmitHook } from "./codex-hook.js";
2
3
  export { START_WORK_CONTINUATION_DIRECTIVE } from "./directive.js";
3
- export type { AuthorityBoundary, AuthorityEnvelope, AuthorityGrant, CanonicalPlan, InitRequest, InitResult, LifecycleState, StoreOptions, TransitionRequest, TransitionResult, WorkLifecycleEvent, WorkLifecycleKind, WorkReasonCode, WorkStateEntry, WorkStatus, WorkTransitionAction, } from "./lifecycle-store.js";
4
- export { advanceStopLease, initializeWork, inspectLifecycleState, isBoundedLifecycleText, readLifecycleState, reconcileLifecycleState, resolveCanonicalPlan, START_WORK_MAX_HISTORY_EVENTS, selectWorkForSession, transitionWork, } from "./lifecycle-store.js";
4
+ export { findLifecycleRoot } from "./lifecycle-root.js";
5
+ export type { AuthorityBoundary, AuthorityEnvelope, AuthorityGrant, CancelNotice, CancelResult, CanonicalPlan, DenyResult, InitRequest, InitResult, LifecycleState, ParkedBoundary, StoreOptions, TransitionOutcome, TransitionRequest, TransitionResult, WorkLifecycleEvent, WorkLifecycleKind, WorkReasonCode, WorkStateEntry, WorkStatus, WorkTransitionAction, } from "./lifecycle-store.js";
6
+ export { advanceStopLease, cancelWorkFromUserPrompt, denyParkedBoundaries, initializeWork, inspectLifecycleState, isBoundedLifecycleText, readLifecycleState, reconcileLifecycleState, resolveCanonicalPlan, START_WORK_MAX_HISTORY_EVENTS, selectWorkForSession, takeCancelNotice, transitionWork, } from "./lifecycle-store.js";
5
7
  export type { PlanProgress } from "./plan-progress.js";
6
8
  export { analyzePlanProgress } from "./plan-progress.js";
7
9
  export type { PublishedPlan } from "./plan-publisher.js";
8
10
  export { PlanPublisherError, publishPlan } from "./plan-publisher.js";
11
+ export { runPreToolUseHook } from "./pre-tool-hook.js";
12
+ export type { AccessKind } from "./protected-paths.js";
13
+ export { protectedReason } from "./protected-paths.js";
9
14
  export type { ReadonlyFileSystem, StopHookEventName, StopHookOutput, StopInput, UserPromptSubmitInput, } from "./types.js";
10
- export type { ContinuationState, PlanChecklist } from "./work-state-reader.js";
15
+ export type { ContinuationState, DeniedStep, ParkedStep, PlanChecklist } from "./work-state-reader.js";
11
16
  export { diagnoseLifecycle, parsePlanChecklist, readContinuationState } from "./work-state-reader.js";
@@ -1,6 +1,9 @@
1
- export { runStopHook, runUserPromptSubmitHook } from "./codex-hook.js";
1
+ export { parseTypedRunCommand, runStopHook, runUserPromptSubmitHook } from "./codex-hook.js";
2
2
  export { START_WORK_CONTINUATION_DIRECTIVE } from "./directive.js";
3
- export { advanceStopLease, initializeWork, inspectLifecycleState, isBoundedLifecycleText, readLifecycleState, reconcileLifecycleState, resolveCanonicalPlan, START_WORK_MAX_HISTORY_EVENTS, selectWorkForSession, transitionWork, } from "./lifecycle-store.js";
3
+ export { findLifecycleRoot } from "./lifecycle-root.js";
4
+ export { advanceStopLease, cancelWorkFromUserPrompt, denyParkedBoundaries, initializeWork, inspectLifecycleState, isBoundedLifecycleText, readLifecycleState, reconcileLifecycleState, resolveCanonicalPlan, START_WORK_MAX_HISTORY_EVENTS, selectWorkForSession, takeCancelNotice, transitionWork, } from "./lifecycle-store.js";
4
5
  export { analyzePlanProgress } from "./plan-progress.js";
5
6
  export { PlanPublisherError, publishPlan } from "./plan-publisher.js";
7
+ export { runPreToolUseHook } from "./pre-tool-hook.js";
8
+ export { protectedReason } from "./protected-paths.js";
6
9
  export { diagnoseLifecycle, parsePlanChecklist, readContinuationState } from "./work-state-reader.js";
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The folder whose start-work state a hook in `cwd` should act on. From `cwd` upward, the nearest folder whose
3
+ * state holds a nonterminal run (or, with `wantSession`, a cancel notice for that session) wins, so a nested
4
+ * project's own run beats an outer one. A linked Git worktree falls back to its main checkout. With neither, the
5
+ * answer is `cwd` itself, as before. Only files are read; no subprocess runs inside the hook's time budget.
6
+ */
7
+ export declare function findLifecycleRoot(cwd: string, options?: {
8
+ readonly wantSession?: string;
9
+ }): string;
@@ -0,0 +1,117 @@
1
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync } from "node:fs";
2
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
3
+ import { inspectLifecycleState } from "./lifecycle-store.js";
4
+ const MAX_LEVELS = 64;
5
+ const MAX_POINTER_BYTES = 4096;
6
+ /**
7
+ * The folder whose start-work state a hook in `cwd` should act on. From `cwd` upward, the nearest folder whose
8
+ * state holds a nonterminal run (or, with `wantSession`, a cancel notice for that session) wins, so a nested
9
+ * project's own run beats an outer one. A linked Git worktree falls back to its main checkout. With neither, the
10
+ * answer is `cwd` itself, as before. Only files are read; no subprocess runs inside the hook's time budget.
11
+ */
12
+ export function findLifecycleRoot(cwd, options = {}) {
13
+ let start;
14
+ try {
15
+ start = realpathSync(cwd);
16
+ }
17
+ catch {
18
+ return cwd;
19
+ }
20
+ let dir = start;
21
+ for (let level = 0; level < MAX_LEVELS; level += 1) {
22
+ if (holdsRun(dir, options.wantSession))
23
+ return dir;
24
+ const parent = dirname(dir);
25
+ if (parent === dir)
26
+ break;
27
+ dir = parent;
28
+ }
29
+ const main = mainCheckoutOf(start);
30
+ if (main !== null && holdsRun(main, options.wantSession))
31
+ return main;
32
+ return start;
33
+ }
34
+ function holdsRun(dir, wantSession) {
35
+ try {
36
+ if (!lstatSync(join(dir, ".litcodex", "start-work", "state.json")).isFile())
37
+ return false;
38
+ }
39
+ catch {
40
+ return false;
41
+ }
42
+ const inspected = inspectLifecycleState(dir);
43
+ if (!inspected.ok)
44
+ return false;
45
+ return hasNonterminalRun(inspected.state) || (wantSession !== undefined && hasNotice(inspected.state, wantSession));
46
+ }
47
+ function hasNonterminalRun(state) {
48
+ if (state.active_work_id === null)
49
+ return false;
50
+ const status = state.works[state.active_work_id]?.status;
51
+ return status === "active" || status === "paused";
52
+ }
53
+ function hasNotice(state, sessionId) {
54
+ return state.cancel_notices?.[`codex:${sessionId}`] !== undefined;
55
+ }
56
+ /** The main checkout behind the nearest `.git` file (`gitdir:` → `commondir`), or null. */
57
+ function mainCheckoutOf(start) {
58
+ let dir = start;
59
+ for (let level = 0; level < MAX_LEVELS; level += 1) {
60
+ const marker = join(dir, ".git");
61
+ let isFile = false;
62
+ let exists = false;
63
+ try {
64
+ const stat = lstatSync(marker);
65
+ exists = true;
66
+ isFile = stat.isFile();
67
+ }
68
+ catch {
69
+ // No marker at this level.
70
+ }
71
+ if (exists) {
72
+ if (!isFile)
73
+ return null;
74
+ const pointer = readSmall(marker)?.match(/^gitdir:[ \t]*(.+?)[ \t]*$/mu)?.[1];
75
+ if (pointer === undefined)
76
+ return null;
77
+ const gitdir = isAbsolute(pointer) ? pointer : resolve(dir, pointer);
78
+ const common = readSmall(join(gitdir, "commondir"))?.trim();
79
+ if (common === undefined || common.length === 0)
80
+ return null;
81
+ const commonDir = resolve(gitdir, common);
82
+ if (basename(commonDir) !== ".git")
83
+ return null;
84
+ try {
85
+ return realpathSync(dirname(commonDir));
86
+ }
87
+ catch {
88
+ return null;
89
+ }
90
+ }
91
+ const parent = dirname(dir);
92
+ if (parent === dir)
93
+ return null;
94
+ dir = parent;
95
+ }
96
+ return null;
97
+ }
98
+ function readSmall(path) {
99
+ const noFollow = typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0;
100
+ let fd;
101
+ try {
102
+ fd = openSync(path, constants.O_RDONLY | noFollow);
103
+ const stat = fstatSync(fd);
104
+ if (!stat.isFile() || stat.size > MAX_POINTER_BYTES)
105
+ return undefined;
106
+ const buffer = Buffer.alloc(stat.size);
107
+ const read = readSync(fd, buffer, 0, buffer.byteLength, 0);
108
+ return buffer.subarray(0, read).toString("utf8");
109
+ }
110
+ catch {
111
+ return undefined;
112
+ }
113
+ finally {
114
+ if (fd !== undefined)
115
+ closeSync(fd);
116
+ }
117
+ }