@brainervirus/workit-core 8.7.0 → 8.9.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@brainervirus/workit-core",
3
- "version": "8.7.0",
3
+ "version": "8.9.0",
4
4
  "private": false,
5
5
  "description": "Workit shared core — task, policy, evidence, review, decision, worker, and writer state for agentic coding workflows",
6
6
  "keywords": [
@@ -2,6 +2,7 @@
2
2
  // forge-neutral status document, the `next` priority, the CI-wait verdict,
3
3
  // and rerun planning with the rerun-once rule.
4
4
  import { aheadBehind, currentBranch, fetchRefs, hasCommit, headSha, resolveRef } from "../git/rev";
5
+ import { appendObserved, readLedger, type LedgerActor } from "../ledger";
5
6
  import type { ResolvedForge } from "./resolve";
6
7
  import { rerunCounts, recordReruns, withRerunLock, type RerunRow } from "./reruns";
7
8
  import {
@@ -425,11 +426,59 @@ export function buildStatusDoc(
425
426
  });
426
427
  }
427
428
 
428
- /** Select, read and document one PR/MR. */
429
+ /**
430
+ * Record what the forge said about a PR as a CLI-observed `pr.status` row
431
+ * (pr, branch, head, state: open|merged|closed, checks), only when it
432
+ * differs from the newest row for that PR, so polling never floods the
433
+ * ledger. Hooks read it without calling the forge: an open PR's checks
434
+ * (passing|failing|pending; one without gating checks is not recorded), and
435
+ * a PR merged or closed outside workit (the forge UI). Never fails the verb:
436
+ * a ledger error only loses the row.
437
+ */
438
+ export function recordPrStatus(cwd: string, doc: PrStatusDoc, actor: LedgerActor): void {
439
+ const checks = doc.checks.state;
440
+ const state = doc.state;
441
+ if (state !== "open" && state !== "merged" && state !== "closed") return;
442
+ if (state === "open" && checks !== "passing" && checks !== "failing" && checks !== "pending")
443
+ return;
444
+ try {
445
+ const ledger = readLedger(cwd);
446
+ if (!ledger.ok) return;
447
+ const last = ledger.value.rows.findLast(
448
+ (row) =>
449
+ row.type === "pr.status" &&
450
+ row.observer === "workit_cli" &&
451
+ row.pr === doc.number &&
452
+ row.repo === doc.repo,
453
+ );
454
+ if (
455
+ last &&
456
+ last.head === doc.head.sha &&
457
+ last.checks === checks &&
458
+ (last.state ?? "open") === state
459
+ )
460
+ return;
461
+ appendObserved(cwd, {
462
+ type: "pr.status",
463
+ actor,
464
+ branch: doc.head.branch,
465
+ head: doc.head.sha,
466
+ pr: doc.number,
467
+ repo: doc.repo,
468
+ forge: doc.forge,
469
+ state,
470
+ checks,
471
+ });
472
+ } catch {
473
+ // The row is an observation for hooks; the verb's answer stands without it.
474
+ }
475
+ }
476
+
477
+ /** Select, read and document one PR/MR (recorded as a `pr.status` row when `actor` is given). */
429
478
  export function prStatusReport(
430
479
  cwd: string,
431
480
  resolved: ResolvedForge,
432
- options: ReportOptions & { identity?: PrStatusDoc["identity"] } = {},
481
+ options: ReportOptions & { identity?: PrStatusDoc["identity"]; actor?: LedgerActor } = {},
433
482
  ): ForgeResult<{ doc: PrStatusDoc; raw: ForgePrStatus }> {
434
483
  const number = selectPr(cwd, resolved, options);
435
484
  if (!number.ok) return number;
@@ -441,6 +490,7 @@ export function prStatusReport(
441
490
  identity: options.identity,
442
491
  });
443
492
  if (!doc.ok) return doc;
493
+ if (options.actor) recordPrStatus(cwd, doc.data, options.actor);
444
494
  return success({ doc: doc.data, raw: status.data });
445
495
  }
446
496
 
@@ -0,0 +1,521 @@
1
+ // The prepare-commit-msg hook that gives a plain `git commit` the
2
+ // `Workit-Session:` trailer `workit git commit` adds (D18), for agents that
3
+ // cannot run `workit git` (a Claude Code worktree-isolated subagent).
4
+ // `workit doctor` reports it; `workit doctor --fix` installs it, in a Workit
5
+ // workspace only.
6
+ //
7
+ // - One source of truth: the trailer logic is SESSION_TRAILER_SCRIPT, written
8
+ // to `<git-common-dir>/workit/session-trailer.sh` (Workit-owned, never a hook
9
+ // slot, never the working tree). The hook Workit installs, and every line a
10
+ // user is told to add to a hook Workit does not own, is the same one-liner
11
+ // that runs it with the hook's arguments.
12
+ // - Slot: prepare-commit-msg, not commit-msg. Git runs it for -m/-F, amend,
13
+ // merge and squash, even with --no-verify, and before commit-msg, so a
14
+ // commitlint there sees the trailer. commit-msg stays the user's.
15
+ // - Where: `git rev-parse --git-path hooks`, so core.hooksPath is honoured.
16
+ // Workit writes only an empty slot or its own hook. Another tool's hook in
17
+ // the slot (husky, lefthook, a hand-written one) is never renamed, wrapped or
18
+ // edited: the state is `blocked` and `manual` names the line to add there;
19
+ // once that hook (or husky script, or lefthook config) runs the helper, the
20
+ // state is `manual`.
21
+ // A hooks directory outside the repository (a global core.hooksPath), or one
22
+ // in the working tree that git does not ignore, gets no hook either.
23
+ // - The session comes from the same variables as host-session.ts: WORKIT_SESSION_ID
24
+ // (unless WORKIT_HOST names another host than the shell's own), else
25
+ // OPENCODE_SESSION_ID, PI_SESSION_ID or CODEX_THREAD_ID. The message is left
26
+ // unchanged with no session or an unsafe id; for a plain editor commit (no
27
+ // message source: the trailer would sit in the buffer, and a user who empties
28
+ // it would commit a trailer-only message instead of aborting); for a
29
+ // template (git aborts an unedited one); for a comment-only message; and in a
30
+ // rebase or cherry-pick replaying commits that keep their own trailers.
31
+ // - `--if-exists addIfDifferent`: the same session's trailer is never repeated;
32
+ // another session that amends adds its own, as `workit git commit --amend` does.
33
+ import { spawnSync } from "node:child_process";
34
+ import {
35
+ chmodSync,
36
+ existsSync,
37
+ lstatSync,
38
+ mkdirSync,
39
+ readFileSync,
40
+ renameSync,
41
+ rmSync,
42
+ statSync,
43
+ writeFileSync,
44
+ } from "node:fs";
45
+ import path from "node:path";
46
+ import { GIT_TIMEOUTS } from "./rev";
47
+
48
+ export const SESSION_HOOK_NAME = "prepare-commit-msg";
49
+ export const SESSION_HOOK_MARKER = "# workit-session-trailer-hook";
50
+ /** The helper under the git common dir that holds the trailer logic. */
51
+ const HELPER = ["workit", "session-trailer.sh"] as const;
52
+ /** Left by an unreleased build that chained commit-msg; reported, never used. */
53
+ const LEGACY_CHAINED = "commit-msg.workit-chained";
54
+
55
+ // LF only: Git for Windows runs hooks with its own sh, which reads LF scripts.
56
+ export const SESSION_TRAILER_SCRIPT = `#!/bin/sh
57
+ # Workit (https://github.com/BrainerVirus/workit) wrote this file with
58
+ # \`workit doctor --fix\`. A prepare-commit-msg hook runs it with its own
59
+ # arguments to add a Workit-Session trailer to commits made in an agent session.
60
+ # Not a hook itself; delete it together with the line that runs it.
61
+ # lefthook passes a missing argument as its literal placeholder.
62
+ case "\${2-}" in "" | "{2}" | template) exit 0 ;; esac
63
+ gitdir=$(git rev-parse --git-dir) || exit 0
64
+ if [ -d "$gitdir/rebase-merge" ] || [ -d "$gitdir/rebase-apply" ] || [ -f "$gitdir/CHERRY_PICK_HEAD" ]; then
65
+ exit 0
66
+ fi
67
+ trim() { printf '%s' "$1" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'; }
68
+ inner=$(trim "\${OPENCODE_SESSION_ID-}"); inner_host=opencode
69
+ if [ -z "$inner" ]; then inner=$(trim "\${PI_SESSION_ID-}"); inner_host=pi; fi
70
+ if [ -z "$inner" ]; then inner=$(trim "\${CODEX_THREAD_ID-}"); inner_host=codex; fi
71
+ [ -n "$inner" ] || inner_host=
72
+ declared=$(trim "\${WORKIT_HOST-}")
73
+ family=$(printf '%s' "$declared" | sed 's/_cli$//;s/_desktop$//')
74
+ session=$inner
75
+ if [ "\${WORKIT_SESSION_ID+set}" = set ]; then
76
+ if [ -z "$inner" ] || [ -z "$declared" ] || [ "$family" = "$inner_host" ]; then
77
+ session=$(trim "$WORKIT_SESSION_ID")
78
+ fi
79
+ fi
80
+ [ -n "$session" ] || exit 0
81
+ [ \${#session} -le 128 ] || exit 0
82
+ case "$session" in *[!A-Za-z0-9_.:@/+-]*) exit 0 ;; esac
83
+ add_trailer() {
84
+ [ -f "$1" ] && [ -r "$1" ] || return 0
85
+ body=$(sed '/^# -\\{24\\} >8 -\\{24\\}$/,$d' "$1" | git stripspace --strip-comments)
86
+ [ -n "$body" ] || return 0
87
+ # A merge message has no final newline; interpret-trailers would glue the
88
+ # trailer to the subject line.
89
+ [ -z "$(tail -c 1 "$1")" ] || printf '\\n' >> "$1"
90
+ git -c trailer.separators=: -c trailer.where=end interpret-trailers --in-place \\
91
+ --no-divider --if-exists addIfDifferent --trailer "Workit-Session: $session" "$1" || return 0
92
+ }
93
+ # $1 is the message file. lefthook cannot quote a path it pastes in, so its
94
+ # job passes '' and the file is found here: git hands the hook COMMIT_EDITMSG,
95
+ # except \`git merge\`, which hands it MERGE_MSG. With source "merge" both are
96
+ # updated: the one git did not hand over is stale or removed after the commit.
97
+ case "\${1-}" in "" | "{1}") ;; *) add_trailer "$1"; exit 0 ;; esac
98
+ add_trailer "$(git rev-parse --git-path COMMIT_EDITMSG)"
99
+ [ "$2" != merge ] || add_trailer "$(git rev-parse --git-path MERGE_MSG)"
100
+ exit 0
101
+ `;
102
+
103
+ /**
104
+ * The line that runs the helper from a shell prepare-commit-msg hook, with the
105
+ * hook's own arguments. Hooks run at the top of the work tree, where the
106
+ * relative common dir resolves. A clone without the helper (a teammate who
107
+ * never ran `--fix`, while the line sits in a committed husky hook) runs
108
+ * nothing and prints nothing.
109
+ */
110
+ export const manualTrailerLine = (): string =>
111
+ `h="$(git rev-parse --git-common-dir 2>/dev/null)/${HELPER.join("/")}"; [ ! -f "$h" ] || sh "$h" "$@" || true`;
112
+
113
+ /**
114
+ * The same for a lefthook `run:`, with no double quote in it: on Windows
115
+ * lefthook starts `"sh" -c "<run>"` as one raw command line, so a `"` in the
116
+ * run ends that argument early. `set -f` and an empty IFS keep the unquoted
117
+ * `$h` one word (a path with spaces) and unglobbed. lefthook pastes `{1}` in
118
+ * raw, and from a linked worktree it is an absolute path that may hold a
119
+ * space or a quote, which no quoting survives; so the job passes '' and the
120
+ * helper finds the message file itself. `{2}` and `{3}` are a source word and
121
+ * a sha, safe unquoted.
122
+ */
123
+ export const lefthookTrailerRun = (): string =>
124
+ `set -f; IFS=; h=$(git rev-parse --git-common-dir 2>/dev/null)/${HELPER.join("/")}; [ ! -f $h ] || sh $h '' {2} {3} || true`;
125
+
126
+ /** What marks a hook or config that already runs the helper. */
127
+ const HELPER_REF = HELPER.join("/");
128
+
129
+ export const SESSION_HOOK_SCRIPT = `#!/bin/sh
130
+ ${SESSION_HOOK_MARKER} v4
131
+ # Workit (https://github.com/BrainerVirus/workit) installed this hook with
132
+ # \`workit doctor --fix\`: it runs Workit's session-trailer helper, which adds a
133
+ # Workit-Session trailer to commits made in an agent session. To remove it,
134
+ # delete this file.
135
+ ${manualTrailerLine()}
136
+ `;
137
+
138
+ export type SessionHookState =
139
+ /** Not inside a git work tree, or git is unavailable. */
140
+ | "not_git"
141
+ /** The current Workit hook and helper are installed. */
142
+ | "installed"
143
+ /** An older Workit hook, or a missing or older helper; --fix rewrites them. */
144
+ | "outdated"
145
+ /** The slot is empty; --fix installs the hook. */
146
+ | "missing"
147
+ /** --fix will not write the hook; `reason` says why and `manual` what to do instead. */
148
+ | "blocked"
149
+ /** Another tool's hook or config already runs the helper (`via`, `manualTarget`). */
150
+ | "manual";
151
+
152
+ /** Who owns the slot when it is blocked by another hook. */
153
+ export type HookOwner = "husky" | "lefthook" | "other";
154
+
155
+ export type SessionHookStatus = {
156
+ state: SessionHookState;
157
+ hooksDir: string | null;
158
+ hookPath: string | null;
159
+ /** The helper the hook and the manual line run. */
160
+ helperPath: string | null;
161
+ /** Whether the helper on disk is the current script. */
162
+ helperCurrent: boolean;
163
+ owner?: HookOwner;
164
+ reason?: string;
165
+ /** The manual fix when --fix cannot install the hook. */
166
+ manual?: string;
167
+ /** Where the manual line goes (or already is): a husky script, a lefthook config, a hook. */
168
+ manualTarget?: string;
169
+ /** For `manual`: who runs the helper. */
170
+ via?: "husky" | "lefthook" | "existing hook";
171
+ /** Files left by the unreleased commit-msg design, with how to recover. */
172
+ leftover?: string;
173
+ };
174
+
175
+ const run = (cwd: string, args: string[], env: NodeJS.ProcessEnv) => {
176
+ const r = spawnSync("git", args, {
177
+ cwd,
178
+ encoding: "utf8",
179
+ timeout: GIT_TIMEOUTS.local,
180
+ windowsHide: true,
181
+ stdio: ["ignore", "pipe", "pipe"],
182
+ env: { ...env, GIT_TERMINAL_PROMPT: "0" },
183
+ });
184
+ return { ok: r.status === 0, out: (r.stdout ?? "").trim() };
185
+ };
186
+
187
+ const inside = (child: string, parent: string): boolean => {
188
+ const rel = path.relative(path.resolve(parent), path.resolve(child));
189
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
190
+ };
191
+
192
+ const readText = (file: string): string | null => {
193
+ try {
194
+ return readFileSync(file, "utf8");
195
+ } catch {
196
+ return null;
197
+ }
198
+ };
199
+
200
+ const exists = (file: string): boolean => {
201
+ try {
202
+ lstatSync(file);
203
+ return true;
204
+ } catch {
205
+ return false;
206
+ }
207
+ };
208
+
209
+ const LEFTHOOK_CONFIGS = [
210
+ "lefthook.yml",
211
+ "lefthook.yaml",
212
+ ".lefthook.yml",
213
+ ".lefthook.yaml",
214
+ "lefthook.json",
215
+ "lefthook.toml",
216
+ ];
217
+
218
+ const lefthookConfig = (top: string): string | null =>
219
+ LEFTHOOK_CONFIGS.map((name) => path.join(top, name)).find((file) => existsSync(file)) ?? null;
220
+
221
+ // Whether a hook, script or config really runs the helper, not just mentions
222
+ // it. Shell text: a non-comment line invoking it, either directly
223
+ // (`sh …/workit/session-trailer.sh`) or as `sh "$h"` after an `h=` line
224
+ // naming it. Control flow (an `exit` before the line, an `if false`) is out
225
+ // of scope: this reads lines, it does not run them.
226
+ const isComment = (line: string) => /^\s*#/.test(line);
227
+ // `sh` in command position: line start or after `;`, `&`, `|`, `(`, `!`,
228
+ // `then`, `do` or `else` (so `echo sh $h` does not count).
229
+ const COMMAND_SH = String.raw`(?:^|[;&|(!]|\b(?:then|do|else)\s)\s*sh\s+`;
230
+ const DIRECT_CALL = new RegExp(
231
+ String.raw`${COMMAND_SH}(?:"[^"]*|\S*)${HELPER_REF.replaceAll(".", String.raw`\.`)}`,
232
+ );
233
+ const VAR_CALL = new RegExp(String.raw`${COMMAND_SH}"?\$h\b`);
234
+ const runsHelperText = (text: string): boolean => {
235
+ const lines = text.split(/\r?\n/).filter((line) => !isComment(line));
236
+ const assigned = lines.some((line) => /(?:^|[\s;])h=/.test(line) && line.includes(HELPER_REF));
237
+ return lines.some((line) => DIRECT_CALL.test(line) || (assigned && VAR_CALL.test(line)));
238
+ };
239
+
240
+ const LEFTHOOK_YAML = [
241
+ "lefthook.yml",
242
+ "lefthook.yaml",
243
+ ".lefthook.yml",
244
+ ".lefthook.yaml",
245
+ "lefthook-local.yml",
246
+ "lefthook-local.yaml",
247
+ ".lefthook-local.yml",
248
+ ".lefthook-local.yaml",
249
+ ];
250
+ const indentOf = (line: string) => line.length - line.trimStart().length;
251
+
252
+ /**
253
+ * A small indentation-aware read of a lefthook YAML config (no YAML library
254
+ * in deps): a `run:` value under the top-level `prepare-commit-msg:` key, on
255
+ * a non-comment line (or its `|`/`>` block), that runs the helper.
256
+ * lefthook.json/.toml are not read, so they never count as manual.
257
+ */
258
+ const lefthookRunsHelper = (text: string): boolean => {
259
+ const lines = text.split(/\r?\n/);
260
+ const start = lines.findIndex((line) => /^prepare-commit-msg:\s*(?:#.*)?$/.test(line));
261
+ if (start < 0) return false;
262
+ const block: string[] = [];
263
+ for (const line of lines.slice(start + 1)) {
264
+ if (line.trim() && !isComment(line) && indentOf(line) === 0) break;
265
+ block.push(line);
266
+ }
267
+ return block.some((line, i) => {
268
+ if (isComment(line)) return false;
269
+ const runKey = /^(\s*)(?:-\s+)?run:\s*(.*)$/.exec(line);
270
+ if (!runKey) return false;
271
+ let value = runKey[2] ?? "";
272
+ if (/^[|>][-+]?\s*$/.test(value)) {
273
+ const body: string[] = [];
274
+ for (const next of block.slice(i + 1)) {
275
+ if (next.trim() && indentOf(next) <= indentOf(line)) break;
276
+ body.push(next);
277
+ }
278
+ value = body.join("\n");
279
+ }
280
+ return runsHelperText(value);
281
+ });
282
+ };
283
+
284
+ const isExecutable = (file: string): boolean => {
285
+ if (process.platform === "win32") return true;
286
+ try {
287
+ return (statSync(file).mode & 0o111) !== 0;
288
+ } catch {
289
+ return false;
290
+ }
291
+ };
292
+
293
+ /** Whether the manual line is really in place for this owner. */
294
+ const manualInPlace = (input: ManualInput, target: string): boolean => {
295
+ if (input.owner === "lefthook")
296
+ return LEFTHOOK_YAML.some((name) => {
297
+ const text = readText(path.join(input.top, name));
298
+ return text !== null && lefthookRunsHelper(text);
299
+ });
300
+ const text = readText(target);
301
+ if (text === null || !runsHelperText(text)) return false;
302
+ // husky v9's `h` runs the user script with `sh -e`, so it needs no +x; any
303
+ // other target is a hook git runs itself, which git skips unless executable.
304
+ return (input.owner === "husky" && target !== input.hookPath) || isExecutable(target);
305
+ };
306
+
307
+ /** husky v9 stubs source `h` beside them; v4-v8 hooks source `_/husky.sh`. */
308
+ const isHuskyV9 = (text: string, hooksDir: string): boolean =>
309
+ /\$\(dirname (?:-- )?"\$0"\)\/h"/.test(text) && existsSync(path.join(hooksDir, "h"));
310
+
311
+ const ownerOf = (text: string, hooksDir: string, top: string): HookOwner => {
312
+ if (text.includes("husky.sh") || isHuskyV9(text, hooksDir)) return "husky";
313
+ if (/lefthook/i.test(text) || lefthookConfig(top)) return "lefthook";
314
+ return "other";
315
+ };
316
+
317
+ type ManualInput = {
318
+ owner: HookOwner;
319
+ text: string;
320
+ hooksDir: string;
321
+ hookPath: string;
322
+ top: string;
323
+ /** Workit's earlier hook, moved aside by lefthook. */
324
+ displaced: string | null;
325
+ };
326
+
327
+ /** The file the manual line goes in for this owner. */
328
+ const manualTargetOf = ({ owner, text, hooksDir, hookPath, top }: ManualInput): string => {
329
+ // husky v9 points core.hooksPath at `.husky/_` and runs `.husky/<hook>`
330
+ // from the stub; husky v4-v8 hooks are the user's files themselves.
331
+ if (owner === "husky" && isHuskyV9(text, hooksDir))
332
+ return path.join(path.dirname(hooksDir), SESSION_HOOK_NAME);
333
+ if (owner === "lefthook") return lefthookConfig(top) ?? path.join(top, "lefthook.yml");
334
+ return hookPath;
335
+ };
336
+
337
+ const manualFor = (input: ManualInput): string => {
338
+ const { owner, displaced } = input;
339
+ const target = manualTargetOf(input);
340
+ const stale = displaced ? `; delete the stale ${displaced} (nothing runs it)` : "";
341
+ if (owner === "husky")
342
+ return `add this line to ${target} (create it if missing; husky runs it)${stale}: ${manualTrailerLine()}`;
343
+ if (owner === "lefthook")
344
+ return [
345
+ `merge this job into ${target} (add it to an existing \`${SESSION_HOOK_NAME}:\` \`jobs:\` list rather than a second \`${SESSION_HOOK_NAME}:\` key), then run \`lefthook install\`${stale}:`,
346
+ `${SESSION_HOOK_NAME}:`,
347
+ " jobs:",
348
+ " - name: workit-session",
349
+ ` run: ${lefthookTrailerRun()}`,
350
+ ].join("\n");
351
+ return `add this line to ${target} (a new file needs \`#!/bin/sh\` as its first line and \`chmod +x\`)${stale}: ${manualTrailerLine()}`;
352
+ };
353
+
354
+ const leftoverOf = (hooksDir: string): string | undefined => {
355
+ const chained = path.join(hooksDir, LEGACY_CHAINED);
356
+ const commitMsg = path.join(hooksDir, "commit-msg");
357
+ const oldOurs = readText(commitMsg)?.includes(SESSION_HOOK_MARKER) ?? false;
358
+ if (exists(chained))
359
+ return oldOurs
360
+ ? `${chained} was left by an earlier Workit build: move it back to ${commitMsg} (replacing Workit's old hook there)`
361
+ : `${chained} was left by an earlier Workit build and nothing runs it: if it is your original commit-msg hook, move it back to ${commitMsg}; otherwise delete it`;
362
+ if (oldOurs)
363
+ return `${commitMsg} is a hook from an earlier Workit build; delete it (the trailer now comes from ${SESSION_HOOK_NAME})`;
364
+ return undefined;
365
+ };
366
+
367
+ /** Where the prepare-commit-msg hook of the repository at `cwd` lives, and what it is. */
368
+ export function inspectSessionHook(
369
+ cwd: string,
370
+ env: NodeJS.ProcessEnv = process.env,
371
+ ): SessionHookStatus {
372
+ const none = { hooksDir: null, hookPath: null, helperPath: null, helperCurrent: false };
373
+ if (!existsSync(cwd)) return { state: "not_git", ...none };
374
+ const top = run(cwd, ["rev-parse", "--show-toplevel"], env);
375
+ if (!top.ok || !top.out) return { state: "not_git", ...none };
376
+ const paths = run(
377
+ cwd,
378
+ ["rev-parse", "--path-format=absolute", "--git-common-dir", "--git-path", "hooks"],
379
+ env,
380
+ );
381
+ const [commonDir, hooksDir] = paths.out.split(/\r?\n/);
382
+ if (!paths.ok || !commonDir || !hooksDir) return { state: "not_git", ...none };
383
+ const hookPath = path.join(hooksDir, SESSION_HOOK_NAME);
384
+ const helperPath = path.join(commonDir, ...HELPER);
385
+ const helperCurrent = readText(helperPath) === SESSION_TRAILER_SCRIPT;
386
+ const leftover = leftoverOf(hooksDir);
387
+ const base = { hooksDir, hookPath, helperPath, helperCurrent, ...(leftover ? { leftover } : {}) };
388
+ const blocked = (reason: string, owner: HookOwner, text = ""): SessionHookStatus => {
389
+ const old = `${hookPath}.old`;
390
+ const displaced = readText(old)?.includes(SESSION_HOOK_MARKER) ? old : null;
391
+ const input = { owner, text, hooksDir, hookPath, top: top.out, displaced };
392
+ const manualTarget = manualTargetOf(input);
393
+ const owned = text ? { owner } : {};
394
+ // The user already added the line where it belongs.
395
+ if (manualInPlace(input, manualTarget))
396
+ return {
397
+ state: "manual",
398
+ ...base,
399
+ ...owned,
400
+ manualTarget,
401
+ via: owner === "other" ? "existing hook" : owner,
402
+ };
403
+ return {
404
+ state: "blocked",
405
+ ...base,
406
+ ...owned,
407
+ reason: displaced ? `${reason} (Workit's earlier hook was moved to ${old})` : reason,
408
+ manual: manualFor(input),
409
+ manualTarget,
410
+ };
411
+ };
412
+ if (!inside(hooksDir, commonDir) && !inside(hooksDir, top.out))
413
+ return blocked(
414
+ `core.hooksPath ${hooksDir} is outside the repository; a hook there runs in every repository that uses it`,
415
+ "other",
416
+ );
417
+ const text = exists(hookPath) ? (readText(hookPath) ?? "") : null;
418
+ if (text !== null) {
419
+ if (text === SESSION_HOOK_SCRIPT)
420
+ return { state: helperCurrent ? "installed" : "outdated", ...base };
421
+ if (text.includes(SESSION_HOOK_MARKER)) return { state: "outdated", ...base };
422
+ const owner = ownerOf(text, hooksDir, top.out);
423
+ return blocked(
424
+ `${hookPath} belongs to ${owner === "other" ? "another hook" : owner}; Workit never replaces it`,
425
+ owner,
426
+ text,
427
+ );
428
+ }
429
+ if (!inside(hooksDir, commonDir)) {
430
+ // A hooks directory in the working tree (a committed .githooks): a new
431
+ // file there must be ignored, or it shows up in git status.
432
+ const rel = path.relative(top.out, hookPath).split(path.sep).join("/");
433
+ if (!run(top.out, ["check-ignore", "-q", "--", rel], env).ok)
434
+ return blocked(
435
+ `${hooksDir} is in the working tree and not ignored; the hook would show up as a new file`,
436
+ "other",
437
+ );
438
+ }
439
+ return { state: "missing", ...base };
440
+ }
441
+
442
+ /**
443
+ * Write `content` through a staged file renamed into place. The finally only
444
+ * matters when the write or chmod throws after the staged file exists; a
445
+ * rename failure cannot be provoked through inspect (an unreadable or
446
+ * directory slot is reported blocked first), so that path is not tested.
447
+ */
448
+ const writeExecutable = (file: string, content: string) => {
449
+ mkdirSync(path.dirname(file), { recursive: true });
450
+ const staged = `${file}.workit-new`;
451
+ try {
452
+ writeFileSync(staged, content, { mode: 0o755 });
453
+ chmodSync(staged, 0o755);
454
+ renameSync(staged, file);
455
+ } finally {
456
+ rmSync(staged, { force: true });
457
+ }
458
+ };
459
+
460
+ export type SessionHookInstall = {
461
+ /** What --fix did to the hook slot: wrote the hook, rewrote an older one, or nothing. */
462
+ action: "installed" | "updated" | "unchanged" | "skipped";
463
+ /** Whether the helper was (re)written. */
464
+ helperWritten: boolean;
465
+ status: SessionHookStatus;
466
+ detail: string;
467
+ };
468
+
469
+ /**
470
+ * Install (or refresh) the helper and the hook for the repository at `cwd`.
471
+ * The caller decides that `cwd` is a Workit workspace. The helper is written
472
+ * even when the slot is blocked, so the manual line works; the slot is written
473
+ * only when empty or holding Workit's own hook.
474
+ */
475
+ export function installSessionHook(
476
+ cwd: string,
477
+ env: NodeJS.ProcessEnv = process.env,
478
+ ): SessionHookInstall {
479
+ const status = inspectSessionHook(cwd, env);
480
+ if (status.state === "not_git")
481
+ return {
482
+ action: "skipped",
483
+ helperWritten: false,
484
+ status,
485
+ detail: "not inside a git work tree",
486
+ };
487
+ const helperWritten = !status.helperCurrent;
488
+ if (helperWritten) writeExecutable(status.helperPath!, SESSION_TRAILER_SCRIPT);
489
+ const helper = helperWritten ? `; wrote ${status.helperPath}` : "";
490
+ if (status.state === "installed")
491
+ return {
492
+ action: "unchanged",
493
+ helperWritten,
494
+ status,
495
+ detail: `hook already at ${status.hookPath}`,
496
+ };
497
+ if (status.state === "manual")
498
+ return {
499
+ action: "unchanged",
500
+ helperWritten,
501
+ status: inspectSessionHook(cwd, env),
502
+ detail: `${status.manualTarget} already runs the helper (via ${status.via})${helper}`,
503
+ };
504
+ if (status.state === "blocked")
505
+ return {
506
+ action: "skipped",
507
+ helperWritten,
508
+ status: inspectSessionHook(cwd, env),
509
+ detail: `${status.reason}${helper}`,
510
+ };
511
+ const fresh = status.state === "missing";
512
+ const slotCurrent = readText(status.hookPath!) === SESSION_HOOK_SCRIPT;
513
+ if (!slotCurrent) writeExecutable(status.hookPath!, SESSION_HOOK_SCRIPT);
514
+ const verb = fresh ? "installed" : "updated";
515
+ return {
516
+ action: verb,
517
+ helperWritten,
518
+ status: inspectSessionHook(cwd, env),
519
+ detail: `${verb} the Workit ${SESSION_HOOK_NAME} hook at ${status.hookPath}${helper}`,
520
+ };
521
+ }