@litfamily/litcodex 1.0.12 → 1.0.13

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 (32) hide show
  1. package/README-Ko-KR.md +9 -9
  2. package/README.md +9 -9
  3. package/dist/config-migration/gpt56-policy.js +3 -0
  4. package/dist/install/auto-handoff-doctor.js +22 -2
  5. package/marketplace/plugins/litcodex/.codex-plugin/plugin.json +1 -1
  6. package/marketplace/plugins/litcodex/components/auto-update/package.json +1 -1
  7. package/marketplace/plugins/litcodex/components/comment-checker/package.json +1 -1
  8. package/marketplace/plugins/litcodex/components/git-bash/package.json +1 -1
  9. package/marketplace/plugins/litcodex/components/lit-loop/dist/auto-handoff-settings.d.ts +9 -2
  10. package/marketplace/plugins/litcodex/components/lit-loop/dist/auto-handoff-settings.js +55 -9
  11. package/marketplace/plugins/litcodex/components/lit-loop/dist/auto-handoff.d.ts +10 -2
  12. package/marketplace/plugins/litcodex/components/lit-loop/dist/auto-handoff.js +23 -17
  13. package/marketplace/plugins/litcodex/components/lit-loop/dist/hook-cli.d.ts +1 -1
  14. package/marketplace/plugins/litcodex/components/lit-loop/dist/hook-cli.js +41 -21
  15. package/marketplace/plugins/litcodex/components/lit-loop/package.json +1 -1
  16. package/marketplace/plugins/litcodex/components/lsp/package.json +1 -1
  17. package/marketplace/plugins/litcodex/components/rules/dist/model-metadata.d.ts +1 -1
  18. package/marketplace/plugins/litcodex/components/rules/dist/model-metadata.js +1 -0
  19. package/marketplace/plugins/litcodex/components/rules/package.json +1 -1
  20. package/marketplace/plugins/litcodex/components/start-work-continuation/package.json +1 -1
  21. package/marketplace/plugins/litcodex/components/telemetry/package.json +1 -1
  22. package/marketplace/plugins/litcodex/components/wikify-knowledge/package.json +1 -1
  23. package/model-catalog.json +25 -5
  24. package/node_modules/@litcodex/lit-loop/dist/auto-handoff-settings.d.ts +9 -2
  25. package/node_modules/@litcodex/lit-loop/dist/auto-handoff-settings.js +55 -9
  26. package/node_modules/@litcodex/lit-loop/dist/auto-handoff.d.ts +10 -2
  27. package/node_modules/@litcodex/lit-loop/dist/auto-handoff.js +23 -17
  28. package/node_modules/@litcodex/lit-loop/dist/hook-cli.d.ts +1 -1
  29. package/node_modules/@litcodex/lit-loop/dist/hook-cli.js +41 -21
  30. package/node_modules/@litcodex/lit-loop/package.json +1 -1
  31. package/package.json +2 -2
  32. package/readme-assets/badge-version.svg +1 -1
@@ -9,8 +9,8 @@
9
9
  // hint (./jev-hint.ts) and, once per session while it is on, a plain-text banner; with its switch
10
10
  // off, that path makes no request and writes nothing.
11
11
  import { isAbsolute } from "node:path";
12
- import { evaluateAutoHandoffStop, recordCompaction, takeReloadContext } from "./auto-handoff.js";
13
- import { applyAutoHandoffRoute, parseAutoHandoffRoute } from "./auto-handoff-settings.js";
12
+ import { claimReloadContext, evaluateAutoHandoffStop, recordCompaction, takeReloadContext } from "./auto-handoff.js";
13
+ import { applyAutoHandoffRoute, clearManagedCompactionWhenOff, parseAutoHandoffRoute, } from "./auto-handoff-settings.js";
14
14
  import { applyPreToolUseCreateGoalGuard, isLitUserPromptSubmitInput, runUserPromptSubmitHook } from "./codex-hook.js";
15
15
  import { claimJevOnBanner, formatJevHookOutput, jevSwitchState, runJevSkillHint, withJevBanner, } from "./jev-hint.js";
16
16
  import { evaluatePlanPersistence, formatStopBlockOutput, recordLitPlanActivation } from "./plan-persistence.js";
@@ -98,19 +98,15 @@ export async function runUserPromptSubmitHookCli(stdin, stdout, stderr, repoRoot
98
98
  stdout.write(route);
99
99
  return 0;
100
100
  }
101
- const reload = autoHandoffReload(parsed, repoRoot, auto);
101
+ clearManagedCompactionWhenOff(hookCwd(parsed, repoRoot), auto.env ?? process.env);
102
102
  const decision = runUserPromptSubmitHook(parsed);
103
103
  if (decision.kind === "inject" && decision.mode === "lit-plan") {
104
104
  const scope = hookSessionScope(parsed, repoRoot);
105
105
  if (scope !== null)
106
106
  recordLitPlanActivation(scope.cwd, scope.sessionId);
107
107
  }
108
- if (decision.kind === "inject") {
109
- stdout.write(withReloadContext(decision.stdout, reload));
110
- return 0;
111
- }
112
- const hint = await jevHintOutput(parsed, repoRoot, jev);
113
- const output = withReloadContext(hint, reload);
108
+ const own = decision.kind === "inject" ? decision.stdout : await jevHintOutput(parsed, repoRoot, jev);
109
+ const output = withAutoHandoffReload(own, parsed, repoRoot, auto);
114
110
  if (output !== "")
115
111
  stdout.write(output);
116
112
  return 0;
@@ -127,32 +123,53 @@ function autoHandoffRouteOutput(parsed, repoRoot, options) {
127
123
  const reason = applyAutoHandoffRoute(cwd, options.env ?? process.env, route);
128
124
  return `${JSON.stringify({ decision: "block", reason })}\n`;
129
125
  }
130
- /** The handoff excerpt to bring back after a compaction between turns, or null. Claims it once. */
131
- function autoHandoffReload(parsed, repoRoot, options) {
126
+ /**
127
+ * Put the handoff excerpt for a compaction between turns into this turn's output, claiming it once. The
128
+ * claim is made only when the output is built, and it is given back when the text cannot be merged, so a
129
+ * reload that never reached the model stays available for the next prompt.
130
+ */
131
+ function withAutoHandoffReload(stdout, parsed, repoRoot, options) {
132
132
  const scope = hookSessionScope(parsed, repoRoot);
133
133
  if (scope === null)
134
- return null;
135
- return takeReloadContext(scope.cwd, scope.sessionId, options.env ?? process.env, false);
134
+ return stdout;
135
+ const claim = claimReloadContext(scope.cwd, scope.sessionId, options.env ?? process.env, false);
136
+ if (claim === null)
137
+ return stdout;
138
+ const merged = withReloadContext(stdout, claim.text);
139
+ if (merged === null) {
140
+ claim.release();
141
+ return stdout;
142
+ }
143
+ return merged;
136
144
  }
137
- /** Add reload text to a UserPromptSubmit output that may already carry context; "" stays "" without one. */
145
+ /**
146
+ * Add reload text to a UserPromptSubmit output that may already carry context, or carry only a visible
147
+ * line; "" becomes a context-only output. Null when the output cannot be merged (it is not JSON).
148
+ */
138
149
  function withReloadContext(stdout, reload) {
139
- if (reload === null)
140
- return stdout;
141
150
  if (stdout === "") {
142
151
  return `${JSON.stringify({ hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: reload } })}\n`;
143
152
  }
144
153
  try {
145
154
  const output = JSON.parse(stdout);
146
- const specific = output.hookSpecificOutput;
147
- if (specific === undefined)
148
- return stdout;
155
+ if (typeof output !== "object" || output === null || Array.isArray(output))
156
+ return null;
157
+ const specific = output.hookSpecificOutput ?? { hookEventName: "UserPromptSubmit" };
149
158
  specific.additionalContext = [specific.additionalContext, reload].filter(Boolean).join("\n\n");
159
+ output.hookSpecificOutput = specific;
150
160
  return `${JSON.stringify(output)}\n`;
151
161
  }
152
162
  catch {
153
- return stdout;
163
+ return null;
154
164
  }
155
165
  }
166
+ /** Absolute `cwd` from a hook event, else the fallback root. */
167
+ function hookCwd(parsed, repoRoot) {
168
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
169
+ return repoRoot;
170
+ const cwd = parsed["cwd"];
171
+ return typeof cwd === "string" && isAbsolute(cwd) ? cwd : repoRoot;
172
+ }
156
173
  /** Optional Jev skill hint for a turn the deterministic router left alone. Never throws. */
157
174
  async function jevHintOutput(parsed, repoRoot, options) {
158
175
  const env = options.env ?? process.env;
@@ -208,6 +225,7 @@ export async function runStopPlanPersistenceHookCli(stdin, stdout, stderr, repoR
208
225
  stderr.write(errorLine("LIT_HOOK_STDIN_INVALID_JSON", INVALID_JSON_MESSAGE));
209
226
  return 2;
210
227
  }
228
+ clearManagedCompactionWhenOff(hookCwd(parsed, repoRoot), auto.env ?? process.env);
211
229
  const scope = hookSessionScope(parsed, repoRoot);
212
230
  if (scope !== null) {
213
231
  const persistence = evaluatePlanPersistence(scope.cwd, scope.sessionId);
@@ -254,6 +272,7 @@ export async function runSessionStartHookCli(stdin, stdout, stderr, repoRoot = p
254
272
  const event = await readHookEvent(stdin, stderr);
255
273
  if (event.exit !== null)
256
274
  return event.exit;
275
+ clearManagedCompactionWhenOff(hookCwd(event.parsed, repoRoot), auto.env ?? process.env);
257
276
  const record = event.parsed;
258
277
  if (typeof record !== "object" || record === null || record["source"] !== "compact")
259
278
  return 0;
@@ -267,10 +286,11 @@ export async function runSessionStartHookCli(stdin, stdout, stderr, repoRoot = p
267
286
  return 0;
268
287
  }
269
288
  /** PostCompact: remember that a session that saved a handoff has now been compacted. Writes nothing to stdout. */
270
- export async function runPostCompactHookCli(stdin, _stdout, stderr, repoRoot = process.cwd()) {
289
+ export async function runPostCompactHookCli(stdin, _stdout, stderr, repoRoot = process.cwd(), auto = {}) {
271
290
  const event = await readHookEvent(stdin, stderr);
272
291
  if (event.exit !== null)
273
292
  return event.exit;
293
+ clearManagedCompactionWhenOff(hookCwd(event.parsed, repoRoot), auto.env ?? process.env);
274
294
  const scope = hookSessionScope(event.parsed, repoRoot);
275
295
  if (scope !== null)
276
296
  recordCompaction(scope.cwd, scope.sessionId);
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@litcodex/lit-loop",
3
- "version": "1.0.12",
3
+ "version": "1.0.13",
4
4
  "description": "LitCodex Lit-Loop runtime: durable repo-native multi-goal orchestration with embedded success criteria and observable evidence audit.",
5
5
  "type": "module",
6
6
  "private": true,
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@litcodex/lsp",
3
- "version": "1.0.12",
3
+ "version": "1.0.13",
4
4
  "description": "LitCodex LSP hook (inert placeholder): post-edit diagnostics + cache reset, no-op until an LSP daemon is provided.",
5
5
  "type": "module",
6
6
  "private": true,
@@ -11,5 +11,5 @@ export type ModelMetadataResult = {
11
11
  };
12
12
  export declare function resetModelMetadataCacheForTests(): void;
13
13
  export declare function resolveModelMetadata(model: string, structuredCatalog?: string): ModelMetadataResult;
14
- export type ManagedModelSlug = "gpt-6-astra" | "gpt-6-sol" | "gpt-6-luna" | "gpt-5.6" | "gpt-5.6-sol" | "gpt-5.6-terra" | "gpt-5.6-luna";
14
+ export type ManagedModelSlug = "gpt-6-astra" | "gpt-6.1-sol" | "gpt-6-sol" | "gpt-6-luna" | "gpt-5.6" | "gpt-5.6-sol" | "gpt-5.6-terra" | "gpt-5.6-luna";
15
15
  export declare function managedGpt56Slug(model: string): ManagedModelSlug | null;
@@ -41,6 +41,7 @@ export function managedGpt56Slug(model) {
41
41
  const normalized = model.trim().toLowerCase();
42
42
  for (const slug of [
43
43
  "gpt-6-astra",
44
+ "gpt-6.1-sol",
44
45
  "gpt-6-sol",
45
46
  "gpt-6-luna",
46
47
  "gpt-5.6-sol",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@litcodex/rules",
3
- "version": "1.0.12",
3
+ "version": "1.0.13",
4
4
  "description": "LitCodex rules: injects project rule files (AGENTS.md etc.) into model context through lifecycle hooks.",
5
5
  "type": "module",
6
6
  "private": true,
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@litcodex/start-work-continuation",
3
- "version": "1.0.12",
3
+ "version": "1.0.13",
4
4
  "description": "LitCodex Start-Work continuation hook: resumes in-flight start-work state on root Stop.",
5
5
  "type": "module",
6
6
  "private": true,
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@litcodex/telemetry",
3
- "version": "1.0.12",
3
+ "version": "1.0.13",
4
4
  "description": "LitCodex telemetry: a deliberately inert, local-only SessionStart hook (NO network, NO data collection).",
5
5
  "type": "module",
6
6
  "private": true,
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@litcodex/wikify-knowledge",
3
- "version": "1.0.12",
3
+ "version": "1.0.13",
4
4
  "description": "Local review-gated knowledge records for the LitCodex Wikify surface.",
5
5
  "type": "module",
6
6
  "private": true,
@@ -25,12 +25,32 @@
25
25
  "recommended_role": "lead",
26
26
  "recommended_effort": "xhigh"
27
27
  },
28
+ {
29
+ "id": "gpt-6.1-sol",
30
+ "config_profile": "sol",
31
+ "display_name": "GPT-6.1 Sol",
32
+ "generation": "gpt-6",
33
+ "priority": 2,
34
+ "visibility": "list",
35
+ "supported_in_api": true,
36
+ "speed_tier": "fast",
37
+ "aliases": [],
38
+ "supported_efforts": ["low", "medium", "high", "xhigh", "max", "ultra"],
39
+ "configurable_efforts": ["low", "medium", "high", "xhigh", "max", "ultra"],
40
+ "installer_menu": {
41
+ "lead": ["xhigh", "low", "medium", "high", "max", "ultra"],
42
+ "helper": ["low", "medium", "high", "xhigh", "max", "ultra"]
43
+ },
44
+ "default_effort": "low",
45
+ "recommended_role": "coding-lead",
46
+ "recommended_effort": "xhigh"
47
+ },
28
48
  {
29
49
  "id": "gpt-6-sol",
30
50
  "config_profile": "sol",
31
51
  "display_name": "GPT-6 Sol",
32
52
  "generation": "gpt-6",
33
- "priority": 2,
53
+ "priority": 3,
34
54
  "visibility": "list",
35
55
  "supported_in_api": true,
36
56
  "speed_tier": "fast",
@@ -42,7 +62,7 @@
42
62
  "helper": ["low", "medium", "high", "xhigh", "max", "ultra"]
43
63
  },
44
64
  "default_effort": "medium",
45
- "recommended_role": "coding-lead",
65
+ "recommended_role": "previous-generation",
46
66
  "recommended_effort": "xhigh"
47
67
  },
48
68
  {
@@ -50,7 +70,7 @@
50
70
  "config_profile": "luna",
51
71
  "display_name": "GPT-6 Luna",
52
72
  "generation": "gpt-6",
53
- "priority": 3,
73
+ "priority": 4,
54
74
  "visibility": "list",
55
75
  "supported_in_api": true,
56
76
  "speed_tier": "fast",
@@ -70,7 +90,7 @@
70
90
  "config_profile": "sol",
71
91
  "display_name": "GPT-5.6 Sol",
72
92
  "generation": "gpt-5.6",
73
- "priority": 4,
93
+ "priority": 5,
74
94
  "visibility": "list",
75
95
  "supported_in_api": true,
76
96
  "speed_tier": "standard",
@@ -89,7 +109,7 @@
89
109
  "context_probe": true,
90
110
  "display_name": "GPT-5.6",
91
111
  "generation": "gpt-5.6",
92
- "priority": 5,
112
+ "priority": 6,
93
113
  "visibility": "list",
94
114
  "supported_in_api": true,
95
115
  "speed_tier": "standard",
@@ -36,8 +36,8 @@ export declare function readStoredAutoHandoff(repoRoot: string): {
36
36
  */
37
37
  export declare function resolveAutoHandoff(env: NodeJS.ProcessEnv, stored: StoredAutoHandoff, storedWarning?: string | null): AutoHandoffState;
38
38
  export declare function loadAutoHandoffState(repoRoot: string, env: NodeJS.ProcessEnv): AutoHandoffState;
39
- /** Atomic write that refuses to go through a symlink or replace anything but a regular file. */
40
- export declare function writeSmallFile(path: string, text: string): boolean;
39
+ /** Atomic write that refuses to go through a symlink (in any component below `root`) or replace anything but a regular file. */
40
+ export declare function writeSmallFile(path: string, text: string, root: string): boolean;
41
41
  export declare function writeStoredAutoHandoff(repoRoot: string, stored: StoredAutoHandoff): boolean;
42
42
  export declare function projectConfigPath(repoRoot: string): string;
43
43
  export type ProjectCompaction = {
@@ -63,6 +63,13 @@ export type ProjectConfigResult = "written" | "unchanged-user-key" | "failed" |
63
63
  export declare function writeProjectCompaction(repoRoot: string, percent: number): ProjectConfigResult;
64
64
  /** Remove only the marked block; delete the file (and an empty `.codex`) when nothing else is left. */
65
65
  export declare function removeProjectCompaction(repoRoot: string): ProjectConfigResult;
66
+ /**
67
+ * Remove the managed block when the feature is effectively off, however it got there: `lit-handoff auto
68
+ * off`, `LITCODEX_AUTO_HANDOFF=0`, a deleted settings file, or a percent that is not valid. Without this the
69
+ * block outlives the switch and Codex keeps compacting at that percent with no handoff. Only the marked
70
+ * block goes; a key the user wrote by hand is never touched. Never throws.
71
+ */
72
+ export declare function clearManagedCompactionWhenOff(repoRoot: string, env: NodeJS.ProcessEnv): ProjectConfigResult;
66
73
  export type AutoHandoffRoute = {
67
74
  readonly action: "on";
68
75
  readonly argument: string | null;
@@ -15,7 +15,7 @@
15
15
  import { randomBytes } from "node:crypto";
16
16
  import { closeSync, constants, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, rmdirSync, unlinkSync, writeSync, } from "node:fs";
17
17
  import { homedir } from "node:os";
18
- import { dirname, isAbsolute, join } from "node:path";
18
+ import { dirname, isAbsolute, join, relative, sep } from "node:path";
19
19
  export const AUTO_HANDOFF_FLAG_ENV = "LITCODEX_AUTO_HANDOFF";
20
20
  export const AUTO_HANDOFF_PERCENT_ENV = "LITCODEX_AUTO_HANDOFF_PERCENT";
21
21
  export const AUTO_HANDOFF_DIR = ".litcodex/auto-handoff";
@@ -122,6 +122,30 @@ export function loadAutoHandoffState(repoRoot, env) {
122
122
  return resolveAutoHandoff(env, stored, warning);
123
123
  }
124
124
  // ── Safe small-file writes ───────────────────────────────────────────────────
125
+ /**
126
+ * True when no existing component of `target` below `root` is a symlink, so a write or delete cannot be
127
+ * redirected out of the project. Components that do not exist yet are fine; `root` itself is trusted.
128
+ */
129
+ function clearOfSymlinks(root, target) {
130
+ const below = relative(root, target);
131
+ if (below === "" || below === ".." || below.startsWith(`..${sep}`) || isAbsolute(below))
132
+ return false;
133
+ let current = root;
134
+ try {
135
+ for (const part of below.split(sep)) {
136
+ current = join(current, part);
137
+ const stat = lstatSync(current, { throwIfNoEntry: false });
138
+ if (stat === undefined)
139
+ return true;
140
+ if (stat.isSymbolicLink())
141
+ return false;
142
+ }
143
+ return true;
144
+ }
145
+ catch {
146
+ return false;
147
+ }
148
+ }
125
149
  function ensureDir(dir) {
126
150
  try {
127
151
  const stat = lstatSync(dir, { throwIfNoEntry: false });
@@ -135,9 +159,9 @@ function ensureDir(dir) {
135
159
  return false;
136
160
  }
137
161
  }
138
- /** Atomic write that refuses to go through a symlink or replace anything but a regular file. */
139
- export function writeSmallFile(path, text) {
140
- if (!ensureDir(dirname(path)))
162
+ /** Atomic write that refuses to go through a symlink (in any component below `root`) or replace anything but a regular file. */
163
+ export function writeSmallFile(path, text, root) {
164
+ if (!clearOfSymlinks(root, path) || !ensureDir(dirname(path)))
141
165
  return false;
142
166
  const tmp = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
143
167
  try {
@@ -165,7 +189,7 @@ export function writeSmallFile(path, text) {
165
189
  }
166
190
  }
167
191
  export function writeStoredAutoHandoff(repoRoot, stored) {
168
- return writeSmallFile(settingsPath(repoRoot), `${JSON.stringify({ version: 1, ...stored })}\n`);
192
+ return writeSmallFile(settingsPath(repoRoot), `${JSON.stringify({ version: 1, ...stored })}\n`, repoRoot);
169
193
  }
170
194
  // ── Project config: Codex compacts after the handoff turn ────────────────────
171
195
  const KEY_LINE = new RegExp(`^\\s*${HOST_COMPACT_KEY}\\s*=\\s*(\\d+)\\s*(?:#.*)?$`, "u");
@@ -234,6 +258,8 @@ export function hostCompactsAt(repoRoot, percent, env) {
234
258
  /** Write (or update) the marked block. A key the user wrote by hand stays as it is. */
235
259
  export function writeProjectCompaction(repoRoot, percent) {
236
260
  const path = projectConfigPath(repoRoot);
261
+ if (!clearOfSymlinks(repoRoot, path))
262
+ return "failed";
237
263
  const stat = lstatSync(path, { throwIfNoEntry: false });
238
264
  if (stat !== undefined && !stat.isFile())
239
265
  return "failed";
@@ -248,15 +274,17 @@ export function writeProjectCompaction(repoRoot, percent) {
248
274
  const lines = raw.split("\n");
249
275
  const at = lines.findIndex((line) => KEY_LINE.test(line.replace(/\r$/u, "")));
250
276
  lines[at] = `${HOST_COMPACT_KEY} = ${percent}`;
251
- return writeSmallFile(path, lines.join("\n")) ? "written" : "failed";
277
+ return writeSmallFile(path, lines.join("\n"), repoRoot) ? "written" : "failed";
252
278
  }
253
- return writeSmallFile(path, raw === "" ? block : `${block}\n${raw}`) ? "written" : "failed";
279
+ return writeSmallFile(path, raw === "" ? block : `${block}\n${raw}`, repoRoot) ? "written" : "failed";
254
280
  }
255
281
  /** Remove only the marked block; delete the file (and an empty `.codex`) when nothing else is left. */
256
282
  export function removeProjectCompaction(repoRoot) {
257
283
  const path = projectConfigPath(repoRoot);
258
284
  if (readProjectCompaction(repoRoot).kind !== "managed")
259
285
  return "nothing-to-remove";
286
+ if (!clearOfSymlinks(repoRoot, path))
287
+ return "failed";
260
288
  const raw = readSmallFile(path);
261
289
  if (raw === null)
262
290
  return "failed";
@@ -283,7 +311,23 @@ export function removeProjectCompaction(repoRoot) {
283
311
  return "failed";
284
312
  }
285
313
  }
286
- return writeSmallFile(path, rest) ? "removed" : "failed";
314
+ return writeSmallFile(path, rest, repoRoot) ? "removed" : "failed";
315
+ }
316
+ /**
317
+ * Remove the managed block when the feature is effectively off, however it got there: `lit-handoff auto
318
+ * off`, `LITCODEX_AUTO_HANDOFF=0`, a deleted settings file, or a percent that is not valid. Without this the
319
+ * block outlives the switch and Codex keeps compacting at that percent with no handoff. Only the marked
320
+ * block goes; a key the user wrote by hand is never touched. Never throws.
321
+ */
322
+ export function clearManagedCompactionWhenOff(repoRoot, env) {
323
+ try {
324
+ if (!isAbsolute(repoRoot) || loadAutoHandoffState(repoRoot, env).active)
325
+ return "nothing-to-remove";
326
+ return removeProjectCompaction(repoRoot);
327
+ }
328
+ catch {
329
+ return "failed";
330
+ }
287
331
  }
288
332
  /** Only the complete prompt `lit-handoff auto ...` (case-insensitive, edge whitespace allowed) is a route. */
289
333
  export function parseAutoHandoffRoute(prompt) {
@@ -329,8 +373,10 @@ export function applyAutoHandoffRoute(repoRoot, env, route) {
329
373
  if (route.action === "usage")
330
374
  return USAGE;
331
375
  const { stored } = readStoredAutoHandoff(repoRoot);
332
- if (route.action === "status")
376
+ if (route.action === "status") {
377
+ clearManagedCompactionWhenOff(repoRoot, env);
333
378
  return describeAutoHandoff(repoRoot, loadAutoHandoffState(repoRoot, env), env);
379
+ }
334
380
  const envNote = (env[AUTO_HANDOFF_FLAG_ENV]?.trim() ?? "") === ""
335
381
  ? ""
336
382
  : ` ${AUTO_HANDOFF_FLAG_ENV} is set in the environment and takes priority over this command.`;
@@ -53,11 +53,19 @@ interface FreshHandoff {
53
53
  }
54
54
  /** The newest HANDOFF file written after `since` that names `sessionId`; everything else is ignored. */
55
55
  export declare function findFreshHandoff(repoRoot: string, sessionId: string, since: number): FreshHandoff | null;
56
+ /** A reload the record has already been moved past; `release` puts the record back if the text never reached the model. */
57
+ export interface ReloadClaim {
58
+ readonly text: string;
59
+ readonly release: () => void;
60
+ }
56
61
  /**
57
- * The reload text for a session that fired and then compacted, or null when there is nothing to bring
62
+ * Claim the reload text for a session that fired and then compacted, or null when there is nothing to bring
58
63
  * back. `allowFired` lets SessionStart (source "compact") reload even when PostCompact has not run yet.
59
- * The record moves to "reloaded" first, so the excerpt is injected once.
64
+ * The record moves to "reloaded" first, so the excerpt is injected once; a caller that then fails to put
65
+ * the text into its hook output calls `release` so the next prompt can try again.
60
66
  */
67
+ export declare function claimReloadContext(repoRoot: string, sessionId: string, env: NodeJS.ProcessEnv, allowFired: boolean): ReloadClaim | null;
68
+ /** The reload text, claimed for good. Use `claimReloadContext` when the text might not reach the output. */
61
69
  export declare function takeReloadContext(repoRoot: string, sessionId: string, env: NodeJS.ProcessEnv, allowFired: boolean): string | null;
62
70
  /** Mirror of the rendered state for the doctor: what this session's record says. */
63
71
  export declare function readSessionPhase(repoRoot: string, sessionId: string): AutoHandoffPhase | null;
@@ -65,9 +65,10 @@ function readSession(path, sessionId) {
65
65
  return freshSession(sessionId);
66
66
  }
67
67
  }
68
- function writeSession(path, session) {
69
- return writeSmallFile(path, `${JSON.stringify(session)}\n`);
68
+ function writeSession(repoRoot, path, session) {
69
+ return writeSmallFile(path, `${JSON.stringify(session)}\n`, repoRoot);
70
70
  }
71
+ /** The last `bytes` bytes of a file. Byte counts are compared with byte counts, never with decoded text length. */
71
72
  function readTail(path, bytes) {
72
73
  let fd;
73
74
  try {
@@ -83,8 +84,8 @@ function readTail(path, bytes) {
83
84
  const size = fstatSync(fd).size;
84
85
  const length = Math.min(size, bytes);
85
86
  const buffer = Buffer.alloc(length);
86
- readSync(fd, buffer, 0, length, size - length);
87
- return buffer.toString("utf8");
87
+ const read = readSync(fd, buffer, 0, length, size - length);
88
+ return { text: buffer.subarray(0, read).toString("utf8"), whole: size <= bytes };
88
89
  }
89
90
  catch {
90
91
  return null;
@@ -126,13 +127,13 @@ export function readContextPercent(transcriptPath) {
126
127
  if (typeof transcriptPath !== "string" || transcriptPath === "" || !isAbsolute(transcriptPath))
127
128
  return null;
128
129
  for (const bytes of TAIL_STEPS) {
129
- const text = readTail(transcriptPath, bytes);
130
- if (text === null)
130
+ const tail = readTail(transcriptPath, bytes);
131
+ if (tail === null)
131
132
  return null;
132
- const reading = lastTokenCount(text);
133
+ const reading = lastTokenCount(tail.text);
133
134
  if (reading !== null)
134
135
  return reading;
135
- if (text.length < bytes)
136
+ if (tail.whole)
136
137
  return null;
137
138
  }
138
139
  return null;
@@ -176,10 +177,10 @@ export function evaluateAutoHandoffStop(input) {
176
177
  if (reading.percent < state.percent) {
177
178
  if (session.phase === "idle" || session.phase === "compacted") {
178
179
  if (session.lastPercent !== seen.lastPercent)
179
- writeSession(path, seen);
180
+ writeSession(input.repoRoot, path, seen);
180
181
  return PASS;
181
182
  }
182
- writeSession(path, { ...seen, phase: "idle", firedAt: null, firedPercent: null });
183
+ writeSession(input.repoRoot, path, { ...seen, phase: "idle", firedAt: null, firedPercent: null });
183
184
  return PASS;
184
185
  }
185
186
  if (session.phase !== "idle")
@@ -190,7 +191,7 @@ export function evaluateAutoHandoffStop(input) {
190
191
  firedAt: input.now ?? Date.now(),
191
192
  firedPercent: state.percent,
192
193
  };
193
- if (!writeSession(path, fired))
194
+ if (!writeSession(input.repoRoot, path, fired))
194
195
  return PASS;
195
196
  return {
196
197
  decision: "block",
@@ -210,7 +211,7 @@ export function recordCompaction(repoRoot, sessionId) {
210
211
  return;
211
212
  const session = readSession(path, sessionId);
212
213
  if (session.phase === "fired")
213
- writeSession(path, { ...session, phase: "compacted" });
214
+ writeSession(repoRoot, path, { ...session, phase: "compacted" });
214
215
  }
215
216
  catch {
216
217
  // fail-open
@@ -279,11 +280,12 @@ function buildReloadContext(repoRoot, session) {
279
280
  ].join("\n");
280
281
  }
281
282
  /**
282
- * The reload text for a session that fired and then compacted, or null when there is nothing to bring
283
+ * Claim the reload text for a session that fired and then compacted, or null when there is nothing to bring
283
284
  * back. `allowFired` lets SessionStart (source "compact") reload even when PostCompact has not run yet.
284
- * The record moves to "reloaded" first, so the excerpt is injected once.
285
+ * The record moves to "reloaded" first, so the excerpt is injected once; a caller that then fails to put
286
+ * the text into its hook output calls `release` so the next prompt can try again.
285
287
  */
286
- export function takeReloadContext(repoRoot, sessionId, env, allowFired) {
288
+ export function claimReloadContext(repoRoot, sessionId, env, allowFired) {
287
289
  try {
288
290
  const state = loadAutoHandoffState(repoRoot, env);
289
291
  if (!state.active)
@@ -294,14 +296,18 @@ export function takeReloadContext(repoRoot, sessionId, env, allowFired) {
294
296
  const session = readSession(path, sessionId);
295
297
  if (session.phase !== "compacted" && !(allowFired && session.phase === "fired"))
296
298
  return null;
297
- if (!writeSession(path, { ...session, phase: "reloaded" }))
299
+ if (!writeSession(repoRoot, path, { ...session, phase: "reloaded" }))
298
300
  return null;
299
- return buildReloadContext(repoRoot, session);
301
+ return { text: buildReloadContext(repoRoot, session), release: () => void writeSession(repoRoot, path, session) };
300
302
  }
301
303
  catch {
302
304
  return null;
303
305
  }
304
306
  }
307
+ /** The reload text, claimed for good. Use `claimReloadContext` when the text might not reach the output. */
308
+ export function takeReloadContext(repoRoot, sessionId, env, allowFired) {
309
+ return claimReloadContext(repoRoot, sessionId, env, allowFired)?.text ?? null;
310
+ }
305
311
  /** Mirror of the rendered state for the doctor: what this session's record says. */
306
312
  export function readSessionPhase(repoRoot, sessionId) {
307
313
  const path = sessionPath(repoRoot, sessionId);
@@ -32,5 +32,5 @@ export declare function runStopPlanPersistenceHookCli(stdin: NodeJS.ReadableStre
32
32
  /** SessionStart: after a compaction inside a turn, bring this session's fresh handoff back once. */
33
33
  export declare function runSessionStartHookCli(stdin: NodeJS.ReadableStream, stdout: NodeJS.WritableStream, stderr: NodeJS.WritableStream, repoRoot?: string, auto?: AutoHandoffHookOptions): Promise<number>;
34
34
  /** PostCompact: remember that a session that saved a handoff has now been compacted. Writes nothing to stdout. */
35
- export declare function runPostCompactHookCli(stdin: NodeJS.ReadableStream, _stdout: NodeJS.WritableStream, stderr: NodeJS.WritableStream, repoRoot?: string): Promise<number>;
35
+ export declare function runPostCompactHookCli(stdin: NodeJS.ReadableStream, _stdout: NodeJS.WritableStream, stderr: NodeJS.WritableStream, repoRoot?: string, auto?: AutoHandoffHookOptions): Promise<number>;
36
36
  export declare function runPreToolUseCreateGoalGuardCli(stdin: NodeJS.ReadableStream, stdout: NodeJS.WritableStream, stderr: NodeJS.WritableStream): Promise<number>;