sequant 2.10.0 → 2.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +19 -2
  4. package/dist/bin/cli.js +47 -2
  5. package/dist/marketplace/external_plugins/sequant/.claude-plugin/plugin.json +1 -1
  6. package/dist/marketplace/external_plugins/sequant/.mcp.json +1 -1
  7. package/dist/marketplace/external_plugins/sequant/hooks/pre-tool.sh +331 -12
  8. package/dist/marketplace/external_plugins/sequant/skills/_shared/references/subagent-types.md +7 -18
  9. package/dist/marketplace/external_plugins/sequant/skills/assess/SKILL.md +5 -1
  10. package/dist/marketplace/external_plugins/sequant/skills/exec/SKILL.md +62 -8
  11. package/dist/marketplace/external_plugins/sequant/skills/fullsolve/SKILL.md +187 -28
  12. package/dist/marketplace/external_plugins/sequant/skills/loop/SKILL.md +127 -23
  13. package/dist/marketplace/external_plugins/sequant/skills/merger/SKILL.md +130 -13
  14. package/dist/marketplace/external_plugins/sequant/skills/qa/SKILL.md +306 -8
  15. package/dist/marketplace/external_plugins/sequant/skills/release/SKILL.md +79 -0
  16. package/dist/marketplace/external_plugins/sequant/skills/spec/SKILL.md +40 -20
  17. package/dist/marketplace/external_plugins/sequant/skills/spec/references/recommended-workflow.md +14 -1
  18. package/dist/marketplace/external_plugins/sequant/skills/test/SKILL.md +1 -1
  19. package/dist/marketplace/external_plugins/sequant/skills/testgen/SKILL.md +23 -6
  20. package/dist/src/commands/doctor.js +20 -18
  21. package/dist/src/commands/locks.d.ts +20 -1
  22. package/dist/src/commands/locks.js +206 -4
  23. package/dist/src/commands/ready.d.ts +6 -0
  24. package/dist/src/commands/ready.js +19 -1
  25. package/dist/src/commands/run-display.js +1 -0
  26. package/dist/src/commands/worktree.d.ts +31 -0
  27. package/dist/src/commands/worktree.js +95 -0
  28. package/dist/src/lib/ac-linter.js +26 -0
  29. package/dist/src/lib/ac-parser.d.ts +40 -0
  30. package/dist/src/lib/ac-parser.js +202 -16
  31. package/dist/src/lib/cli-flags.d.ts +23 -0
  32. package/dist/src/lib/cli-flags.js +43 -0
  33. package/dist/src/lib/cli-ui/run-renderer-types.d.ts +2 -0
  34. package/dist/src/lib/cli-ui/run-renderer.js +7 -1
  35. package/dist/src/lib/locks/checkout-lock.d.ts +193 -0
  36. package/dist/src/lib/locks/checkout-lock.js +389 -0
  37. package/dist/src/lib/locks/index.d.ts +6 -3
  38. package/dist/src/lib/locks/index.js +4 -2
  39. package/dist/src/lib/locks/lock-manager.d.ts +81 -1
  40. package/dist/src/lib/locks/lock-manager.js +230 -5
  41. package/dist/src/lib/locks/types.d.ts +72 -0
  42. package/dist/src/lib/locks/types.js +28 -0
  43. package/dist/src/lib/markdown-fence.d.ts +24 -0
  44. package/dist/src/lib/markdown-fence.js +51 -0
  45. package/dist/src/lib/mcp-config.d.ts +24 -0
  46. package/dist/src/lib/mcp-config.js +51 -0
  47. package/dist/src/lib/scope/analyzer.d.ts +4 -0
  48. package/dist/src/lib/scope/analyzer.js +7 -1
  49. package/dist/src/lib/settings.d.ts +111 -1
  50. package/dist/src/lib/settings.js +59 -0
  51. package/dist/src/lib/system.d.ts +7 -3
  52. package/dist/src/lib/system.js +7 -3
  53. package/dist/src/lib/test-tautology-detector.d.ts +4 -3
  54. package/dist/src/lib/test-tautology-detector.js +147 -40
  55. package/dist/src/lib/workflow/batch-executor.d.ts +20 -1
  56. package/dist/src/lib/workflow/batch-executor.js +154 -23
  57. package/dist/src/lib/workflow/config-resolver.d.ts +25 -0
  58. package/dist/src/lib/workflow/config-resolver.js +90 -0
  59. package/dist/src/lib/workflow/drivers/agent-driver.d.ts +22 -0
  60. package/dist/src/lib/workflow/drivers/claude-code.js +14 -3
  61. package/dist/src/lib/workflow/effort-escalation.d.ts +73 -0
  62. package/dist/src/lib/workflow/effort-escalation.js +82 -0
  63. package/dist/src/lib/workflow/error-classifier.d.ts +4 -1
  64. package/dist/src/lib/workflow/error-classifier.js +4 -0
  65. package/dist/src/lib/workflow/log-writer.d.ts +10 -1
  66. package/dist/src/lib/workflow/log-writer.js +20 -0
  67. package/dist/src/lib/workflow/metrics-schema.d.ts +49 -6
  68. package/dist/src/lib/workflow/metrics-schema.js +33 -0
  69. package/dist/src/lib/workflow/metrics-writer.d.ts +11 -0
  70. package/dist/src/lib/workflow/mutation-marker.d.ts +86 -0
  71. package/dist/src/lib/workflow/mutation-marker.js +97 -0
  72. package/dist/src/lib/workflow/phase-detection.d.ts +12 -0
  73. package/dist/src/lib/workflow/phase-detection.js +5 -1
  74. package/dist/src/lib/workflow/phase-executor.d.ts +17 -0
  75. package/dist/src/lib/workflow/phase-executor.js +60 -4
  76. package/dist/src/lib/workflow/qa-gaps-marker.d.ts +38 -0
  77. package/dist/src/lib/workflow/qa-gaps-marker.js +66 -0
  78. package/dist/src/lib/workflow/ready-gate.d.ts +53 -1
  79. package/dist/src/lib/workflow/ready-gate.js +105 -14
  80. package/dist/src/lib/workflow/run-log-schema.d.ts +175 -0
  81. package/dist/src/lib/workflow/run-log-schema.js +71 -1
  82. package/dist/src/lib/workflow/run-orchestrator.js +27 -0
  83. package/dist/src/lib/workflow/spec-recommendation.d.ts +71 -0
  84. package/dist/src/lib/workflow/spec-recommendation.js +142 -0
  85. package/dist/src/lib/workflow/state-schema.d.ts +5 -1
  86. package/dist/src/lib/workflow/state-schema.js +8 -1
  87. package/dist/src/lib/workflow/types.d.ts +78 -0
  88. package/dist/src/lib/workflow/worktree-manager.d.ts +8 -1
  89. package/dist/src/lib/workflow/worktree-manager.js +9 -1
  90. package/dist/src/lib/workflow/worktree-resolver.d.ts +73 -0
  91. package/dist/src/lib/workflow/worktree-resolver.js +126 -0
  92. package/package.json +4 -3
  93. package/templates/hooks/pre-tool.sh +331 -12
  94. package/templates/scripts/cleanup-worktree.sh +36 -15
  95. package/templates/scripts/new-feature.sh +25 -19
  96. package/templates/skills/_shared/references/subagent-types.md +7 -18
  97. package/templates/skills/assess/SKILL.md +5 -1
  98. package/templates/skills/exec/SKILL.md +62 -8
  99. package/templates/skills/fullsolve/SKILL.md +187 -28
  100. package/templates/skills/loop/SKILL.md +127 -23
  101. package/templates/skills/merger/SKILL.md +130 -13
  102. package/templates/skills/qa/SKILL.md +306 -8
  103. package/templates/skills/release/SKILL.md +79 -0
  104. package/templates/skills/spec/SKILL.md +40 -20
  105. package/templates/skills/spec/references/recommended-workflow.md +14 -1
  106. package/templates/skills/test/SKILL.md +1 -1
  107. package/templates/skills/testgen/SKILL.md +23 -6
  108. package/templates/agents/sequant-explorer.md +0 -24
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Repo-scoped worktree resolution and verification (#899).
3
+ *
4
+ * Skill-driven `/fullsolve` used to hand `/exec` an unexpanded glob
5
+ * (`../worktrees/feature/<issue>-` followed by a star and a slash) and `/exec`
6
+ * was instructed to trust it without checking. Two things went wrong:
7
+ *
8
+ * 1. When nothing had created the worktree, the `cd` failed and the agent
9
+ * silently kept working in the main checkout.
10
+ * 2. `../worktrees/` is one flat namespace shared by every repo under the same
11
+ * parent directory, and issue numbers are per-repo — so where the glob *did*
12
+ * match, it could match a sibling project's worktree.
13
+ *
14
+ * Both are fixed the same way: never resolve worktrees through the filesystem.
15
+ * `git worktree list` reports only the worktrees of the repository containing
16
+ * `cwd`, so scoping is structural rather than a filter that can be forgotten,
17
+ * and it reports the *branch*, which is the real identity — a worktree
18
+ * directory slug can drift from its branch after a rename.
19
+ */
20
+ import { existsSync, realpathSync, statSync } from "fs";
21
+ import path from "path";
22
+ import { listWorktrees } from "./worktree-manager.js";
23
+ /**
24
+ * Find the worktree of the *current* repository that holds issue `issue`.
25
+ *
26
+ * Selection keys on the branch git reports, never on the directory name, so a
27
+ * worktree whose slug has drifted from its branch still resolves — and a
28
+ * directory that merely looks like a match (a sibling repo's worktree, or a
29
+ * stray directory) never does.
30
+ *
31
+ * @param issue - Issue number to look up.
32
+ * @param cwd - Directory inside the repository to search. Defaults to process cwd.
33
+ */
34
+ export function resolveIssueWorktree(issue, cwd) {
35
+ const matches = listWorktrees(cwd)
36
+ .filter((w) => w.issue === issue)
37
+ .map(({ path: p, branch }) => ({ path: p, branch }));
38
+ if (matches.length === 0) {
39
+ return {
40
+ ok: false,
41
+ error: "WORKTREE_NOT_FOUND",
42
+ message: `WORKTREE_NOT_FOUND: no worktree of this repository has a branch for issue #${issue}. ` +
43
+ `Create one with \`./scripts/new-feature.sh ${issue}\`.`,
44
+ candidates: [],
45
+ };
46
+ }
47
+ if (matches.length > 1) {
48
+ const list = matches.map((m) => `${m.branch} -> ${m.path}`).join("; ");
49
+ return {
50
+ ok: false,
51
+ error: "WORKTREE_AMBIGUOUS",
52
+ message: `WORKTREE_AMBIGUOUS: ${matches.length} worktrees claim issue #${issue} (${list}). ` +
53
+ `Remove the stale one, or set SEQUANT_WORKTREE explicitly.`,
54
+ candidates: matches,
55
+ };
56
+ }
57
+ return { ok: true, ...matches[0] };
58
+ }
59
+ /**
60
+ * Canonicalize a path for comparison, tolerating paths that do not exist.
61
+ *
62
+ * `realpathSync` throws on a missing path, so fall back to resolving the
63
+ * deepest existing ancestor and re-appending the remainder — enough to make
64
+ * `/tmp/...` and `/private/tmp/...` compare equal on macOS.
65
+ */
66
+ function canonicalize(target) {
67
+ const absolute = path.resolve(target);
68
+ try {
69
+ return realpathSync(absolute);
70
+ }
71
+ catch {
72
+ const parent = path.dirname(absolute);
73
+ if (parent === absolute)
74
+ return absolute;
75
+ return path.join(canonicalize(parent), path.basename(absolute));
76
+ }
77
+ }
78
+ /**
79
+ * Verify that a caller-supplied worktree path is safe to work in.
80
+ *
81
+ * This is the guard `/exec` runs before trusting `SEQUANT_WORKTREE`. It fails
82
+ * closed on every uncertain case — a bad path must halt the run, never degrade
83
+ * into "keep going in whatever directory we happen to be in".
84
+ *
85
+ * @param worktreePath - The path to check (typically `$SEQUANT_WORKTREE`).
86
+ * @param options.issue - When set, the branch must belong to this issue.
87
+ * @param options.cwd - Directory inside the repository to check against.
88
+ */
89
+ export function verifyWorktreePath(worktreePath, options = {}) {
90
+ const raw = worktreePath.trim();
91
+ if (raw.length === 0 || raw.includes("*")) {
92
+ return {
93
+ ok: false,
94
+ error: "SEQUANT_WORKTREE_NOT_FOUND",
95
+ message: `SEQUANT_WORKTREE_NOT_FOUND: ${raw.length === 0 ? "empty path" : `unexpanded glob "${raw}"`}. Expected a resolved absolute directory.`,
96
+ };
97
+ }
98
+ const absolute = path.resolve(raw);
99
+ if (!existsSync(absolute) || !statSync(absolute).isDirectory()) {
100
+ return {
101
+ ok: false,
102
+ error: "SEQUANT_WORKTREE_NOT_FOUND",
103
+ message: `SEQUANT_WORKTREE_NOT_FOUND: "${raw}" is not an existing directory.`,
104
+ };
105
+ }
106
+ const canonical = canonicalize(absolute);
107
+ const known = listWorktrees(options.cwd);
108
+ const match = known.find((w) => canonicalize(w.path) === canonical);
109
+ if (!match) {
110
+ return {
111
+ ok: false,
112
+ error: "SEQUANT_WORKTREE_FOREIGN",
113
+ message: `SEQUANT_WORKTREE_FOREIGN: "${raw}" is not a worktree of this repository. ` +
114
+ `It belongs to another project or is stale; \`../worktrees/\` is shared across repos.`,
115
+ };
116
+ }
117
+ if (options.issue !== undefined && match.issue !== options.issue) {
118
+ return {
119
+ ok: false,
120
+ error: "SEQUANT_WORKTREE_ISSUE_MISMATCH",
121
+ message: `SEQUANT_WORKTREE_ISSUE_MISMATCH: "${raw}" has branch "${match.branch}", ` +
122
+ `which is not issue #${options.issue}.`,
123
+ };
124
+ }
125
+ return { ok: true, path: match.path, branch: match.branch };
126
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sequant",
3
- "version": "2.10.0",
3
+ "version": "2.12.0",
4
4
  "description": "AI coding agent orchestrator — resolve GitHub issues end-to-end with isolated git worktrees, quality gates, and an MCP server. Works with Claude Code or Aider.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -24,10 +24,11 @@
24
24
  "build": "rm -rf dist/src dist/bin dist/dashboard && tsc && chmod +x dist/bin/cli.js",
25
25
  "dev": "tsx bin/cli.ts",
26
26
  "test": "vitest run",
27
- "lint": "eslint src/ bin/ --max-warnings 0",
27
+ "lint": "eslint src/ bin/ scripts/ --max-warnings 0",
28
28
  "sync:skills": "npx tsx scripts/check-skill-sync.ts --fix",
29
29
  "sync:hooks": "bash scripts/sync-hooks.sh",
30
30
  "validate:skills": "for skill in templates/skills/*/; do case \"$skill\" in *_shared*|*/references/*) continue;; esac; npx skills-ref validate \"$skill\"; done",
31
+ "typecheck:scripts": "tsc --noEmit -p tsconfig.scripts.json",
31
32
  "lint:skill-calls": "npx tsx scripts/lint-skill-calls.ts",
32
33
  "lint:skill-gates": "npx tsx scripts/lint-skill-gates.ts",
33
34
  "lint:skill-sync": "npx tsx scripts/check-skill-sync.ts",
@@ -93,7 +94,7 @@
93
94
  "@anthropic-ai/claude-agent-sdk": "^0.3.142",
94
95
  "@hono/node-server": "^2.0.0",
95
96
  "boxen": "^8.0.1",
96
- "chalk": "^5.3.0",
97
+ "chalk": "^6.0.0",
97
98
  "chokidar": "^5.0.0",
98
99
  "cli-table3": "^0.6.5",
99
100
  "commander": "^14.0.3",
@@ -17,6 +17,16 @@ INPUT_JSON=$(cat)
17
17
  # Parse JSON using jq (preferred) or fallback to grep
18
18
  if command -v jq &>/dev/null; then
19
19
  TOOL_NAME=$(echo "$INPUT_JSON" | jq -r '.tool_name // empty')
20
+ # Claude Code's hook envelope carries the session id (same field
21
+ # capture-tokens.sh reads). Preferred holder identity for the checkout
22
+ # lock (#901): a skill shell's PID dies right after acquire, the session
23
+ # id does not. `// empty` keeps this safe if the field is ever absent —
24
+ # the guard then falls back to SEQUANT_ISSUE.
25
+ SESSION_ID=$(echo "$INPUT_JSON" | jq -r '.session_id // empty')
26
+ # The shell cwd the tool will run in. Distinct from CLAUDE_PROJECT_DIR,
27
+ # which stays pinned to the main checkout even while the agent works in a
28
+ # worktree — see the checkout-lock guard (#901).
29
+ HOOK_CWD=$(echo "$INPUT_JSON" | jq -r '.cwd // empty')
20
30
  # For Bash tool, extract .command from tool_input; for others, stringify the whole object
21
31
  if [[ "$(echo "$INPUT_JSON" | jq -r '.tool_name // empty')" == "Bash" ]]; then
22
32
  TOOL_INPUT=$(echo "$INPUT_JSON" | jq -r '.tool_input.command // empty')
@@ -25,9 +35,59 @@ if command -v jq &>/dev/null; then
25
35
  fi
26
36
  else
27
37
  TOOL_NAME=$(echo "$INPUT_JSON" | grep -oE '"tool_name"\s*:\s*"[^"]+"' | head -1 | cut -d'"' -f4)
38
+ SESSION_ID=$(echo "$INPUT_JSON" | grep -oE '"session_id"\s*:\s*"[^"]+"' | head -1 | cut -d'"' -f4)
39
+ HOOK_CWD=$(echo "$INPUT_JSON" | grep -oE '"cwd"\s*:\s*"[^"]+"' | head -1 | cut -d'"' -f4)
28
40
  # For Bash tool, extract command from tool_input; for others, extract the whole object
29
41
  if [[ "$TOOL_NAME" == "Bash" ]]; then
30
- TOOL_INPUT=$(echo "$INPUT_JSON" | grep -oE '"command"\s*:\s*"[^"]+"' | head -1 | cut -d'"' -f4)
42
+ # Escape-aware extraction (#963 gap B): the naive `grep -oE '"[^"]+"'`
43
+ # form (still used for the simpler fields above, where an embedded
44
+ # `\"` is implausible) stops at the FIRST escaped quote inside the
45
+ # JSON string, truncating any command containing one — e.g.
46
+ # `git commit -m "msg with \"quotes\""` would be cut down to just
47
+ # `git commit -m ` before it ever reaches the guards below.
48
+ #
49
+ # sed's `(([^"\\]|\\.)*)` captures the full escaped run — any run of
50
+ # non-quote/non-backslash chars, or a backslash paired with whatever
51
+ # follows it — up to the closing unescaped `"`. `JSON.stringify`
52
+ # guarantees the whole payload is one physical line, so a single
53
+ # sed pass is enough (no multi-line `-z` needed, which BSD sed lacks
54
+ # anyway).
55
+ #
56
+ # The captured text still carries JSON string escapes literally
57
+ # (`\"`, `\\`, `\n`, `\t`, ...); the awk pass resolves them in ONE
58
+ # left-to-right scan, consuming two characters per recognized
59
+ # escape. That ordering is what a chain of separate sed/tr
60
+ # substitutions cannot get right without a placeholder: a literal
61
+ # `\\n` in the original command is an escaped backslash (`\\`)
62
+ # immediately followed by a literal `n`, and must stay a backslash
63
+ # plus 'n' — not become an escaped-newline (`\n`) if the two escapes
64
+ # were resolved out of order. Scanning once and advancing past both
65
+ # characters of whichever escape is recognized sidesteps that
66
+ # ambiguity entirely.
67
+ TOOL_INPUT=$(printf '%s' "$INPUT_JSON" \
68
+ | sed -E -n 's/.*"command"[[:space:]]*:[[:space:]]*"(([^"\\]|\\.)*)".*/\1/p' \
69
+ | head -1 \
70
+ | awk '
71
+ {
72
+ s = $0; out = ""; n = length(s)
73
+ for (i = 1; i <= n; i++) {
74
+ c = substr(s, i, 1)
75
+ if (c == "\\" && i < n) {
76
+ nc = substr(s, i + 1, 1)
77
+ if (nc == "\"") { out = out "\""; i++ }
78
+ else if (nc == "\\") { out = out "\\"; i++ }
79
+ else if (nc == "n") { out = out "\n"; i++ }
80
+ else if (nc == "t") { out = out "\t"; i++ }
81
+ else if (nc == "r") { out = out "\r"; i++ }
82
+ else if (nc == "/") { out = out "/"; i++ }
83
+ else { out = out c }
84
+ } else {
85
+ out = out c
86
+ }
87
+ }
88
+ print out
89
+ }
90
+ ')
31
91
  else
32
92
  TOOL_INPUT=$(echo "$INPUT_JSON" | grep -oE '"tool_input"\s*:\s*\{[^}]+\}' | head -1)
33
93
  fi
@@ -246,6 +306,51 @@ seg_match() {
246
306
  [[ -n "$SEGMENTS" ]] && grep -qE "$1" <<< "$SEGMENTS"
247
307
  }
248
308
 
309
+ # resolve_cd_target <tool_input> — print the target directory of the LAST
310
+ # `cd <path>` line in a (possibly multi-line) Bash command, if and only if
311
+ # the path is a static literal (quoted or unquoted) that resolves to an
312
+ # existing directory. Scans the raw command, not $SEGMENTS — emit_segments
313
+ # drops double-quoted regions, so `cd "$WT"` would vanish there before this
314
+ # ever saw it. Prints nothing when there is no `cd` line, the target is
315
+ # dynamic (contains `$` or a backtick), or the path doesn't exist — callers
316
+ # must treat empty output as "fail open", never as license to guess a
317
+ # directory (#963).
318
+ resolve_cd_target() {
319
+ local input="$1" line target
320
+ line=$(printf '%s\n' "$input" | grep -E '^[[:space:]]*cd[[:space:]]+' | tail -1)
321
+ [[ -z "$line" ]] && return 0
322
+
323
+ target=$(printf '%s' "$line" | sed -E 's/^[[:space:]]*cd[[:space:]]+//; s/[[:space:]]*[;&|].*$//; s/[[:space:]]+$//')
324
+
325
+ # Strip one layer of surrounding matching quotes.
326
+ case "$target" in
327
+ \"*\") target="${target#\"}"; target="${target%\"}" ;;
328
+ \'*\') target="${target#\'}"; target="${target%\'}" ;;
329
+ esac
330
+
331
+ # Fail open on anything dynamic — resolving shell expansions means
332
+ # reimplementing the shell, which is disproportionate; `git commit`
333
+ # itself already rejects a genuinely empty commit. A backslash is
334
+ # rejected too: it can escape a following `$`/`` ` `` into a form this
335
+ # literal-string check would otherwise miss, and a backslash also carries
336
+ # its own shell meaning (line continuation, escaped chars) that this
337
+ # function does not attempt to resolve — failing open is the safe
338
+ # direction either way (#963).
339
+ case "$target" in
340
+ *'$'*|*'`'*|*'\'*) return 0 ;;
341
+ esac
342
+
343
+ [[ -n "$target" && -d "$target" ]] && printf '%s' "$target"
344
+ }
345
+
346
+ # Path of the session->issue binding the checkout guard maintains (#906).
347
+ # $1 = repo toplevel, $2 = session id. The id is opaque, so squash everything
348
+ # outside a filename-safe set — it must not be able to escape the directory.
349
+ _co_binding_path() {
350
+ printf '%s/.sequant/locks/session-%s.issue' \
351
+ "$1" "$(printf '%s' "$2" | tr -c 'A-Za-z0-9_-' '_')"
352
+ }
353
+
249
354
  # Precompute the segment list once, for Bash commands only.
250
355
  SEGMENTS=""
251
356
  if [[ "$TOOL_NAME" == "Bash" ]]; then
@@ -458,6 +563,213 @@ if seg_match 'git reset.*(--hard|origin)'; then
458
563
  fi
459
564
  fi
460
565
 
566
+ # --- Session -> issue binding for the checkout guard (Issue #906) ---
567
+ # `SEQUANT_ISSUE` cannot identify the holder interactively, and never could:
568
+ # PreToolUse runs OUTSIDE and BEFORE the command's shell, so nothing a skill
569
+ # bash block exports is visible here — not even an export prepended to the same
570
+ # block as the guarded command. The one path that does export it (`sequant run`)
571
+ # also sets SEQUANT_ORCHESTRATOR, where this guard stands down. So the env
572
+ # fallback below was unreachable in every real flow, and the holder was
573
+ # routinely blocked by its own lock.
574
+ #
575
+ # The hook does see both the acquire and every later command of the same
576
+ # session, and `session_id` survives the shell boundary that kills the
577
+ # acquiring PID. Record the binding when we observe the acquire; read it back
578
+ # when deciding whether the caller is the holder.
579
+ if [[ -n "${SESSION_ID:-}" ]] && seg_match 'locks +checkout +(acquire|release)'; then
580
+ _CO_SB_ROOT=$(git -C "${HOOK_CWD:-$PWD}" rev-parse --show-toplevel 2>/dev/null || echo "")
581
+ if [[ -n "$_CO_SB_ROOT" && -d "$_CO_SB_ROOT/.git" ]]; then
582
+ _CO_SB_FILE=$(_co_binding_path "$_CO_SB_ROOT" "$SESSION_ID")
583
+ _CO_SB_ISSUE=$(printf '%s' "$TOOL_INPUT" \
584
+ | grep -oE '\-\-issue[= ]+[0-9]+' | head -1 | grep -oE '[0-9]+$' || true)
585
+ if seg_match 'locks +checkout +acquire'; then
586
+ if [[ -n "$_CO_SB_ISSUE" ]]; then
587
+ mkdir -p "$(dirname "$_CO_SB_FILE")" 2>/dev/null \
588
+ && printf '%s' "$_CO_SB_ISSUE" > "$_CO_SB_FILE" 2>/dev/null || true
589
+ fi
590
+ elif [[ -f "$_CO_SB_FILE" ]]; then
591
+ # Clear only when the session releases its OWN claim. A refused
592
+ # release (wrong --issue) must not strip the real holder's identity
593
+ # and leave it blocked by its own lock.
594
+ if [[ -n "$_CO_SB_ISSUE" \
595
+ && "$_CO_SB_ISSUE" == "$(cat "$_CO_SB_FILE" 2>/dev/null)" ]]; then
596
+ rm -f "$_CO_SB_FILE" 2>/dev/null || true
597
+ fi
598
+ fi
599
+ fi
600
+ fi
601
+
602
+ # --- Checkout-scoped lock enforcement (Issue #901) ---
603
+ # The per-issue lock (#625) keys on issue number, so two sessions working
604
+ # *different* issues take different lock files and never contend. But
605
+ # `git checkout`, `switch`, `reset`, `rebase`, `merge` and `cherry-pick` are
606
+ # global to a working tree — the contended resource is the checkout, not the
607
+ # issue. `.sequant/locks/checkout.lock` represents the tree; this guard is what
608
+ # makes it binding, because the racing actor is an agent's Bash command, not
609
+ # sequant's TypeScript (which mutates git almost exclusively via `git -C
610
+ # <worktree>`).
611
+ #
612
+ # STALENESS IS A DELIBERATELY WEAKER SUBSET, NOT A MIRROR. The authoritative
613
+ # rules live in `classifyStaleness` (src/lib/locks/lock-manager.ts) and are
614
+ # shared by CheckoutLock. Transcribing them into shell would drift (#871), so
615
+ # this guard checks only the absolute age ceiling and FAILS OPEN past it. A
616
+ # lock this guard lets through is still caught by the TypeScript path; a lock
617
+ # it blocks on is always genuinely fresh. Weaker-but-honest beats a mirror.
618
+ #
619
+ # AC-5: orchestrator/MCP mode is a no-op here too, matching LockManager and
620
+ # CheckoutLock — `sequant run` drives its own worktree isolation and must not
621
+ # be blocked by a lock its own skills took.
622
+ if [[ -z "${SEQUANT_ORCHESTRATOR:-}" ]] \
623
+ && seg_match 'git (checkout|switch|reset|rebase|merge|cherry-pick)( |$)' \
624
+ && ! seg_match 'git +-C ' \
625
+ && ! seg_match 'git checkout ([^ ]+ )?--( |$)'; then
626
+
627
+ # Only the MAIN checkout is protected — a command run inside a worktree
628
+ # touches only that worktree's HEAD and must never be blocked.
629
+ #
630
+ # Resolve where the command will ACTUALLY run. This must NOT use
631
+ # CLAUDE_PROJECT_DIR / PARALLEL_MARKER_PROJECT_ROOT: those name the
632
+ # *project* directory, which stays pinned to the main checkout even while
633
+ # the agent's shell sits in a worktree. Keying off them blocked legitimate
634
+ # in-worktree work — the guard's worst failure mode, since the whole point
635
+ # of the lock is to push sessions *into* worktrees.
636
+ #
637
+ # `.cwd` is part of Claude Code's PreToolUse envelope (verified against a
638
+ # live payload alongside `session_id`), with $PWD as the fallback.
639
+ _CO_CWD="${HOOK_CWD:-$PWD}"
640
+ # Honor a `cd <dir>` the same way the commit guard below does — including
641
+ # multi-line commands and quoted/dynamic targets (#963).
642
+ _CO_CD=$(resolve_cd_target "$TOOL_INPUT")
643
+ [[ -n "$_CO_CD" ]] && _CO_CWD="$_CO_CD"
644
+
645
+ # A linked worktree's toplevel has `.git` as a FILE; the main checkout has
646
+ # it as a directory.
647
+ _CO_ROOT=$(git -C "$_CO_CWD" rev-parse --show-toplevel 2>/dev/null || echo "")
648
+ if [[ -n "$_CO_ROOT" && -d "$_CO_ROOT/.git" ]]; then
649
+ _CO_LOCK="$_CO_ROOT/.sequant/locks/checkout.lock"
650
+
651
+ if [[ -f "$_CO_LOCK" ]]; then
652
+ if command -v jq &>/dev/null; then
653
+ _CO_HOLDER_ISSUE=$(jq -r '.issue // empty' "$_CO_LOCK" 2>/dev/null)
654
+ _CO_HOLDER_SESSION=$(jq -r '.sessionId // empty' "$_CO_LOCK" 2>/dev/null)
655
+ _CO_HOLDER_PID=$(jq -r '.pid // empty' "$_CO_LOCK" 2>/dev/null)
656
+ _CO_HOLDER_HOST=$(jq -r '.hostname // empty' "$_CO_LOCK" 2>/dev/null)
657
+ _CO_HOLDER_STARTED=$(jq -r '.startedAt // empty' "$_CO_LOCK" 2>/dev/null)
658
+ _CO_HOLDER_CMD=$(jq -r '.command // empty' "$_CO_LOCK" 2>/dev/null)
659
+ else
660
+ _CO_HOLDER_ISSUE=$(grep -oE '"issue"[[:space:]]*:[[:space:]]*[0-9]+' "$_CO_LOCK" | head -1 | grep -oE '[0-9]+$')
661
+ _CO_HOLDER_SESSION=$(grep -oE '"sessionId"[[:space:]]*:[[:space:]]*"[^"]*"' "$_CO_LOCK" | head -1 | cut -d'"' -f4)
662
+ _CO_HOLDER_PID=$(grep -oE '"pid"[[:space:]]*:[[:space:]]*[0-9]+' "$_CO_LOCK" | head -1 | grep -oE '[0-9]+$')
663
+ _CO_HOLDER_HOST=$(grep -oE '"hostname"[[:space:]]*:[[:space:]]*"[^"]*"' "$_CO_LOCK" | head -1 | cut -d'"' -f4)
664
+ _CO_HOLDER_STARTED=$(grep -oE '"startedAt"[[:space:]]*:[[:space:]]*"[^"]*"' "$_CO_LOCK" | head -1 | cut -d'"' -f4)
665
+ _CO_HOLDER_CMD=$(grep -oE '"command"[[:space:]]*:[[:space:]]*"[^"]*"' "$_CO_LOCK" | head -1 | cut -d'"' -f4)
666
+ fi
667
+
668
+ # Staleness. These branches mirror `classifyStaleness`
669
+ # (src/lib/locks/lock-manager.ts) in the same order, because AC-4
670
+ # requires the checkout lock's stale recovery to match the per-issue
671
+ # lock's — same-host dead PID, age ceiling, and the env overrides.
672
+ # Implementing only a subset here would let a *dead* holder block
673
+ # the tree for up to 24h, which is the wedge AC-4 forbids.
674
+ #
675
+ # The three rules are plain comparisons plus one `kill -0`, so this
676
+ # is a small enough surface to keep honest; the "hook/TypeScript
677
+ # staleness parity" cases in checkout-lock.integration.test.ts pin
678
+ # both sides to the same verdict so they cannot drift silently
679
+ # (#871 — the repo's drift guard compares literal strings only and
680
+ # would not see a semantic divergence here).
681
+ _CO_MAX_AGE_MS="${SEQUANT_MAX_LOCK_AGE_MS:-86400000}" # 24h ceiling
682
+ _CO_SKILL_TTL_MS="${SEQUANT_SKILL_LOCK_TTL_MS:-21600000}" # 6h skill-shell
683
+ _CO_STALE_AGE_MS=7200000 # 2h cross-host
684
+ _CO_FRESH=true
685
+
686
+ # `startedAt` is ISO-8601 **UTC**. BSD `date -j -f` parses in LOCAL
687
+ # time, so without TZ=UTC the age comes out shifted by the UTC
688
+ # offset — west of UTC that is *negative*, and a stale lock then
689
+ # reads as fresh forever, wedging the tree. TZ=UTC pins the BSD
690
+ # branch; Linux/CI falls through to GNU `date -u -d`, which honors
691
+ # the trailing Z.
692
+ _CO_AGE_MS=""
693
+ if [[ -n "$_CO_HOLDER_STARTED" ]]; then
694
+ _CO_STARTED_EPOCH=$(TZ=UTC date -j -f "%Y-%m-%dT%H:%M:%S" "${_CO_HOLDER_STARTED%%.*}" +%s 2>/dev/null \
695
+ || date -u -d "$_CO_HOLDER_STARTED" +%s 2>/dev/null || echo "")
696
+ if [[ -n "$_CO_STARTED_EPOCH" ]]; then
697
+ _CO_AGE_MS=$(( ( $(date +%s) - _CO_STARTED_EPOCH ) * 1000 ))
698
+ # Negative age = clock skew between hosts. Treat as unknown
699
+ # rather than stale: refusing is recoverable, silently
700
+ # ignoring a live holder is not.
701
+ [[ "$_CO_AGE_MS" -lt 0 ]] && _CO_AGE_MS=""
702
+ fi
703
+ fi
704
+
705
+ _CO_SKIP_PID=false
706
+ grep -q '"skipPidCheck"[[:space:]]*:[[:space:]]*true' "$_CO_LOCK" 2>/dev/null && _CO_SKIP_PID=true
707
+
708
+ # 0. Absolute ceiling, checked first and unconditionally (#856):
709
+ # past it a PID is no longer trustworthy identity.
710
+ if [[ -n "$_CO_AGE_MS" && "$_CO_AGE_MS" -gt "$_CO_MAX_AGE_MS" ]]; then
711
+ _CO_FRESH=false
712
+ # 1. Same-host PID check is authoritative — unless the holder asked
713
+ # us to skip it (a skill shell whose PID dies after acquire).
714
+ elif [[ "$_CO_HOLDER_HOST" == "$(hostname)" && "$_CO_SKIP_PID" == "false" ]]; then
715
+ # `kill -0` is a bash builtin: no subprocess on the hot path.
716
+ if [[ -n "$_CO_HOLDER_PID" ]] && ! kill -0 "$_CO_HOLDER_PID" 2>/dev/null; then
717
+ _CO_FRESH=false
718
+ fi
719
+ # 2. Cross-host or skipPidCheck: the PID is meaningless, use age.
720
+ elif [[ -n "$_CO_AGE_MS" ]]; then
721
+ if [[ "$_CO_SKIP_PID" == "true" ]]; then
722
+ _CO_TTL_MS="$_CO_SKILL_TTL_MS"
723
+ else
724
+ _CO_TTL_MS="$_CO_STALE_AGE_MS"
725
+ fi
726
+ [[ "$_CO_AGE_MS" -gt "$_CO_TTL_MS" ]] && _CO_FRESH=false
727
+ fi
728
+
729
+ # Is this session the holder? sessionId is the only identity that
730
+ # survives a skill shell exiting between acquire and this call, so
731
+ # it wins when both sides have one. Otherwise fall back to the
732
+ # issue this session is working on.
733
+ _CO_IS_HOLDER=false
734
+ if [[ -n "$_CO_HOLDER_SESSION" && -n "$SESSION_ID" ]]; then
735
+ [[ "$_CO_HOLDER_SESSION" == "$SESSION_ID" ]] && _CO_IS_HOLDER=true
736
+ elif [[ -n "${SEQUANT_ISSUE:-}" && -n "$_CO_HOLDER_ISSUE" ]]; then
737
+ # Reachable only from a parent process that exported it — never
738
+ # from a skill bash block (#906). Kept for `sequant run`-shaped
739
+ # callers; the binding below is what works interactively.
740
+ [[ "${SEQUANT_ISSUE}" == "$_CO_HOLDER_ISSUE" ]] && _CO_IS_HOLDER=true
741
+ elif [[ -n "${SESSION_ID:-}" && -n "$_CO_HOLDER_ISSUE" ]]; then
742
+ # The binding this hook recorded when it saw THIS session run
743
+ # `locks checkout acquire --issue=N` (#906).
744
+ _CO_BIND=$(_co_binding_path "$_CO_ROOT" "$SESSION_ID")
745
+ [[ -f "$_CO_BIND" \
746
+ && "$(cat "$_CO_BIND" 2>/dev/null)" == "$_CO_HOLDER_ISSUE" ]] \
747
+ && _CO_IS_HOLDER=true
748
+ fi
749
+
750
+ if [[ "$_CO_FRESH" == "true" && "$_CO_IS_HOLDER" == "false" ]]; then
751
+ log_block "checkout-lock"
752
+ {
753
+ echo "HOOK_BLOCKED: Checkout held by another session"
754
+ echo ""
755
+ echo " The working tree is held by the session working #${_CO_HOLDER_ISSUE:-?}"
756
+ echo " (PID ${_CO_HOLDER_PID:-?} on ${_CO_HOLDER_HOST:-?}, started ${_CO_HOLDER_STARTED:-?})."
757
+ echo " Command: ${_CO_HOLDER_CMD:-?}"
758
+ echo ""
759
+ echo " Branch-mutating git here would race with that session."
760
+ echo ""
761
+ echo " To proceed:"
762
+ echo " • Work in your own worktree: ../worktrees/feature/<your-issue>-*/"
763
+ echo " (create it with: ./scripts/new-feature.sh <your-issue>)"
764
+ echo " • Or target it explicitly: git -C <worktree> <command>"
765
+ echo " • If that session is gone: sequant locks checkout clear --force"
766
+ } >&2
767
+ exit 2
768
+ fi
769
+ fi
770
+ fi
771
+ fi
772
+
461
773
  # CI/CD triggers (automation shouldn't trigger more automation)
462
774
  if seg_match 'gh workflow run'; then
463
775
  log_block "workflow-trigger"
@@ -554,18 +866,25 @@ fi
554
866
  # Skips for --amend since amending doesn't require new changes
555
867
  if [[ "$TOOL_NAME" == "Bash" ]] && seg_match 'git commit'; then
556
868
  if ! echo "$TOOL_INPUT" | grep -qE -- '--amend|--allow-empty'; then
557
- # Extract target directory from cd command if present (for worktree commits)
558
- # Handles: "cd /path && git commit" or "cd /path; git commit"
559
- TARGET_DIR=""
560
- if echo "$TOOL_INPUT" | grep -qE '^cd [^;&|]+'; then
561
- TARGET_DIR=$(echo "$TOOL_INPUT" | grep -oE '^cd [^;&|]+' | head -1 | sed 's/^cd //' | tr -d ' ')
562
- fi
563
-
564
- # Check for changes in the target directory (or current if no cd)
565
- if [[ -n "$TARGET_DIR" && -d "$TARGET_DIR" ]]; then
566
- CHANGES=$(cd "$TARGET_DIR" && git status --porcelain 2>/dev/null | wc -l | tr -d ' ')
869
+ # Resolve where to check for changes: the last resolvable `cd`
870
+ # target if the command has one (multi-line commands included
871
+ # #963), else the command's own cwd from the hook payload (never
872
+ # this hook process's own cwd, which need not match).
873
+ TARGET_DIR=$(resolve_cd_target "$TOOL_INPUT")
874
+ HAS_CD_LINE=false
875
+ echo "$TOOL_INPUT" | grep -qE '^[[:space:]]*cd[[:space:]]+' && HAS_CD_LINE=true
876
+
877
+ if [[ -n "$TARGET_DIR" ]]; then
878
+ CHANGES=$(git -C "$TARGET_DIR" status --porcelain 2>/dev/null | wc -l | tr -d ' ')
879
+ elif [[ "$HAS_CD_LINE" == true ]]; then
880
+ # A `cd` line is present but its target is dynamic (a shell
881
+ # variable/command substitution) or doesn't exist as a
882
+ # directory — fail open rather than check the wrong
883
+ # directory. `git commit` itself already rejects a genuinely
884
+ # empty commit, so this costs one harmless git error (#963).
885
+ CHANGES=1
567
886
  else
568
- CHANGES=$(git status --porcelain 2>/dev/null | wc -l | tr -d ' ')
887
+ CHANGES=$(git -C "${HOOK_CWD:-$PWD}" status --porcelain 2>/dev/null | wc -l | tr -d ' ')
569
888
  fi
570
889
 
571
890
  if [[ "$CHANGES" -eq 0 ]]; then
@@ -357,26 +357,47 @@ else
357
357
  echo -e "${YELLOW}⏭️ Skipped remote-branch delete (PR not merged; pass --delete-remote or --force to override).${NC}"
358
358
  fi
359
359
 
360
- # Update main
360
+ # Refresh local main WITHOUT switching the main checkout's branch (#910). The
361
+ # old flow ran `git checkout main` here unconditionally — a branch switch of
362
+ # the shared main checkout, exactly the mutation the #901 checkout lock exists
363
+ # to serialize. The pre-tool guard cannot see it (the top-level command is this
364
+ # script, which carries no guarded git verb), so a session that lost the lock
365
+ # could still yank the holder off its branch — the same bypass #910 closed in
366
+ # new-feature.sh. Two cases:
367
+ # - already on main: update in place (fetch + ff-only pull; rebase only on
368
+ # divergence). Same landing point as before; no branch switch involved.
369
+ # - on any other branch (or detached HEAD): leave the checkout alone and
370
+ # fast-forward the local `main` REF via `git fetch origin main:main`,
371
+ # which never touches the working tree. When that is not fast-forwardable
372
+ # (local main diverged/ahead, or main is checked out in another worktree),
373
+ # report and skip — resolving that is the holder's call, not this script's.
361
374
  echo -e "${BLUE}📥 Updating main branch...${NC}"
362
- git checkout main
363
375
  git fetch origin main
364
-
365
- # Handle divergent branches gracefully
366
- if ! git merge-base --is-ancestor HEAD origin/main 2>/dev/null; then
367
- # Local is behind or diverged - fast-forward or rebase
368
- if git merge-base --is-ancestor origin/main HEAD 2>/dev/null; then
369
- # Local is ahead - nothing to do
370
- echo -e "${BLUE} Local main is ahead of origin${NC}"
371
- else
372
- # Diverged or behind - try fast-forward first
373
- if ! git pull --ff-only origin main 2>/dev/null; then
374
- echo -e "${YELLOW} Divergent branches detected, rebasing...${NC}"
375
- git rebase origin/main
376
+ CURRENT_BRANCH=$(git symbolic-ref --quiet --short HEAD || echo "")
377
+
378
+ if [ "$CURRENT_BRANCH" = "main" ]; then
379
+ # Handle divergent branches gracefully
380
+ if ! git merge-base --is-ancestor HEAD origin/main 2>/dev/null; then
381
+ # Local is behind or diverged - fast-forward or rebase
382
+ if git merge-base --is-ancestor origin/main HEAD 2>/dev/null; then
383
+ # Local is ahead - nothing to do
384
+ echo -e "${BLUE} Local main is ahead of origin${NC}"
385
+ else
386
+ # Diverged or behind - try fast-forward first
387
+ if ! git pull --ff-only origin main 2>/dev/null; then
388
+ echo -e "${YELLOW} Divergent branches detected, rebasing...${NC}"
389
+ git rebase origin/main
390
+ fi
376
391
  fi
392
+ else
393
+ git pull --ff-only origin main 2>/dev/null || true
377
394
  fi
378
395
  else
379
- git pull --ff-only origin main 2>/dev/null || true
396
+ if git fetch origin main:main 2>/dev/null; then
397
+ echo -e "${BLUE} Updated local main ref (checkout left on ${CURRENT_BRANCH:-detached HEAD})${NC}"
398
+ else
399
+ echo -e "${YELLOW} ⏭️ Skipped local main update (not fast-forwardable); checkout left on ${CURRENT_BRANCH:-detached HEAD}${NC}"
400
+ fi
380
401
  fi
381
402
 
382
403
  echo ""