kazam 1.29.2

Local infrastructure for coding agents: context, visibility, durable execution. One Rust binary, no cloud.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
use anyhow::{Context, Result};
use std::fs;
use std::path::Path;

// NOTE: r####"..."#### - the script emits markdown headings ("## ", "### "),
// so anything shorter than four hashes terminates the literal early.
const SESSION_START_SH: &str = r####"#!/bin/bash
# kazam workspace - session start hook
#
# Fires on startup / resume / clear / compact. Stdout IS injected into the
# fresh context, which makes this the one reliable place to restore state that
# compaction dropped.
#
#   startup | resume | clear -> quiet orientation: anatomy drift + ready tasks
#   compact                  -> full recovery payload replayed from .kazam/
#
# The compact branch reads only from kazam's existing stores (track/log.yaml,
# track/tasks.yaml, ctx/*). No separate session-state file, so nothing can
# drift out of sync with the work graph.

set -uo pipefail

if ! command -v kazam >/dev/null 2>&1; then
  echo '{"ok":false,"error":"kazam not installed - run: cargo install --git https://github.com/tdiderich/kazam"}'
  exit 0
fi
cd "$(dirname "$0")/../.." || exit 0

INPUT=$(cat 2>/dev/null || echo '{}')
# refresh writes the anatomy (hash-based change/delete/rename detection) and
# reports what moved since the last refresh. Warm runs take tens of ms.
DRIFT=$(kazam ctx refresh --json 2>/dev/null)
READY=$(kazam track ready --json 2>/dev/null)
# Model descriptions for new/changed files, detached at low priority. Cached
# descriptions apply instantly; a missing backend is a silent no-op.
# KAZAM_ENRICH=0 turns it off.
if [ "${KAZAM_ENRICH:-1}" != "0" ]; then
  kazam ctx enrich --background --json >/dev/null 2>&1 || true
fi

# jq drives the compact-recovery payload. Without it, degrade to plain
# orientation rather than failing the hook.
if ! command -v jq >/dev/null 2>&1; then
  HAS_DRIFT=$(echo "$DRIFT" | grep -c '"added":\["\|"changed":\["\|"deleted":\["\|"renamed":\[\[' 2>/dev/null || true)
  HAS_READY=$(echo "$READY" | grep -c '"data":\[{' 2>/dev/null || true)
  [ "$HAS_DRIFT" != "0" ] && echo "$DRIFT"
  [ "$HAS_READY" != "0" ] && echo "$READY"
  exit 0
fi

SOURCE=$(printf '%s' "$INPUT" | jq -r '.source // ""' 2>/dev/null || echo "")
N_DRIFT=$(printf '%s' "$DRIFT" | jq -r \
  '[(.data.diff.changed // []), (.data.diff.added // []), (.data.diff.deleted // []), (.data.diff.renamed // [])] | add | length' 2>/dev/null)
N_READY=$(printf '%s' "$READY" | jq -r '(.data // []) | length' 2>/dev/null)

# ---------------------------------------------------------------- normal start
if [ "$SOURCE" != "compact" ]; then
  [ "${N_DRIFT:-0}" != "0" ] && printf '%s' "$DRIFT" | jq -c '{anatomy_refreshed: .data.diff}' 2>/dev/null
  # One line per task, top 5: the full JSON with notes cost ~1.8k tokens a
  # session. `kazam track ready --json` has the rest when it's needed.
  if [ "${N_READY:-0}" != "0" ]; then
    echo "kazam ready tasks (${N_READY}):"
    printf '%s' "$READY" | jq -r '(.data // [])[0:5][] | "- \(.id) [p\(.priority)] \(.title | .[0:90])"' 2>/dev/null
  fi
  exit 0
fi

# ----------------------------------------------------- post-compaction recovery
echo "## kazam state (post-compaction)"
echo
echo "Replayed from .kazam/ stores. Where this disagrees with the summary above,"
echo "this is correct - the summary is lossy, these files are not."
echo

ACTIVE=$(kazam track list --status active --json 2>/dev/null \
  | jq -r '(.data // [])[] | "- \(.id) [p\(.priority)] \(.title)\(if .note then "\n    note: " + (.note | .[0:220]) else "" end)"' 2>/dev/null)
if [ -n "$ACTIVE" ]; then
  echo "### Claimed / in flight"
  echo "$ACTIVE"
  echo
  echo "Resume these before starting anything new. Close with:"
  echo '  kazam track close <ID> --reason "what you did"'
else
  echo "### Claimed / in flight"
  echo "- none claimed. Claim before working: kazam track claim <ID> --name <your-name>"
fi
echo

if [ "${N_READY:-0}" != "0" ]; then
  echo "### Ready (top 5 by priority)"
  printf '%s' "$READY" | jq -r '(.data // [])[0:5][] | "- \(.id) [p\(.priority)] \(.title | .[0:150])"' 2>/dev/null
  echo
fi

# Activity belonging to the transcript that was just summarized: everything
# logged between the newest compact boundary and the one before it. File
# modifications are split out and deduped so they cannot drown the task events.
SLICE=$(kazam track log --limit 300 --json 2>/dev/null | jq -c '
  (.data // []) as $e
  | [ $e | to_entries[] | select(.value.title | startswith("compact boundary")) | .key ] as $b
  | (if ($b | length) >= 2 then $e[($b[0] + 1):$b[1]]
     elif ($b | length) == 1 then $e[($b[0] + 1):($b[0] + 61)]
     else $e[0:60] end)
' 2>/dev/null)

ACTIVITY=$(printf '%s' "$SLICE" | jq -r '
  .[]
  | select(.title | startswith("Modified ") | not)
  | "- [\(.severity)] \(.title | .[0:160])\(if .detail then "\n    " + (.detail | .[0:240]) else "" end)"
' 2>/dev/null | head -30)
if [ -n "$ACTIVITY" ]; then
  echo "### Work logged in the compacted stretch"
  echo "$ACTIVITY"
  echo
fi

TOUCHED=$(printf '%s' "$SLICE" | jq -r '
  [ .[] | select(.title | startswith("Modified ")) | .title[9:] ] | unique | .[]
' 2>/dev/null)
if [ -n "$TOUCHED" ]; then
  N_TOUCHED=$(printf '%s\n' "$TOUCHED" | wc -l | tr -d ' ')
  echo "### Files edited in the compacted stretch (${N_TOUCHED})"
  printf '%s\n' "$TOUCHED" | head -30 | sed 's/^/- /'
  echo
fi

if [ "${N_DRIFT:-0}" != "0" ]; then
  echo "### Uncommitted file drift (${N_DRIFT} files)"
  printf '%s' "$DRIFT" | jq -r '
    [(.data.diff.added // [] | map("new     " + .)),
     (.data.diff.changed // [] | map("changed " + .)),
     (.data.diff.deleted // [] | map("deleted " + .)),
     (.data.diff.renamed // [] | map("renamed " + .[0] + " -> " + .[1]))] | add | .[0:25][] | "- " + .' 2>/dev/null
  echo
fi

CORR=$(kazam ctx corrections --json 2>/dev/null \
  | jq -r '(.data // [])[0:5][] | "- \(.file_path // "general"): \(.mistake | .[0:130]) -> \(.correction | .[0:200])"' 2>/dev/null)
if [ -n "$CORR" ]; then
  echo "### Standing corrections (do not repeat these)"
  echo "$CORR"
  echo
fi

LEARN=$(kazam ctx learnings --json 2>/dev/null \
  | jq -r '(.data // [])[0:5][] | "- [\(.category // "note")] \(.lesson // .text // .title // "" | .[0:200])"' 2>/dev/null \
  | grep -v '^- \[.*\] $' || true)
if [ -n "$LEARN" ]; then
  echo "### Recent learnings"
  echo "$LEARN"
  echo
fi

echo "### Reminders"
echo "- Navigate via .kazam/ctx/anatomy.tsv then .kazam/ctx/anatomy/<dir>.tsv. Do not grep for structure."
echo "- Dispatch kazam-scout for multi-file exploration so file dumps stay out of this context."
echo "- Before fixing any error: kazam ctx bugs --file <path>"
echo "- Close tasks per commit, do not batch."

exit 0
"####;

const PRE_COMPACT_SH: &str = r##"#!/bin/bash
# kazam workspace - pre-compact hook
#
# Fires immediately before /compact (manual) and before auto-compaction.
# PreCompact stdout is not reliably injected into the compacted context, so
# this hook deliberately prints nothing. Its job is to persist state into
# kazam's stores, where session-start.sh replays it after the transcript has
# been summarized away:
#
#   1. kazam ctx scan       -> anatomy reflects reality, not session start
#   2. kazam track log add  -> durable "compact boundary" marker in log.yaml
#
# The boundary marker is what lets the post-compact hook replay only the
# activity belonging to the transcript that was discarded. No jq dependency.

set -uo pipefail

command -v kazam >/dev/null 2>&1 || exit 0
cd "$(dirname "$0")/../.." || exit 0

INPUT=$(cat 2>/dev/null || echo '{}')
TRIGGER=$(printf '%s' "$INPUT" | sed -n 's/.*"trigger"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')
[ -z "$TRIGGER" ] && TRIGGER="unknown"

kazam ctx scan >/dev/null 2>&1

ACTIVE=$(kazam track list --status active --json 2>/dev/null \
  | grep -o '"id":"[^"]*"' | cut -d'"' -f4 | paste -sd, - | tr -d '[:space:]')
[ -z "$ACTIVE" ] && ACTIVE="none"

TOUCHED=$(kazam ctx scan --check --json 2>/dev/null \
  | grep -oE '"(changed|new)_files":\[[^]]*\]' | grep -o '"[^"]*\.[^"]*"' | wc -l | tr -d ' ')

kazam track log add \
  "compact boundary ($TRIGGER) | active: $ACTIVE | touched: ${TOUCHED:-0} files" \
  --source compact --severity info >/dev/null 2>&1

exit 0
"##;

const POST_TOOL_SH: &str = r##"#!/bin/bash
# kazam workspace - post-tool hook
#
# Runs after Read / Write / Edit. Claude Code delivers the tool payload as JSON
# on STDIN. An earlier version of this hook read a $KAZAM_TOOL_INPUT env var
# that nothing ever sets, so it was a silent no-op in every workspace.
#
#   Write | Edit -> log the modification to the activity feed
#   Read         -> append to ctx/reads.log, folded into anatomy on next scan
#
# Reads are appended rather than counted in place: appends are cheap on the hot
# path and survive parallel subagents, where a read-modify-write of
# anatomy.flat.yaml would silently lose updates.

set -uo pipefail

command -v kazam >/dev/null 2>&1 || exit 0
cd "$(dirname "$0")/../.." || exit 0

INPUT=$(cat 2>/dev/null || echo '{}')

if command -v jq >/dev/null 2>&1; then
  TOOL=$(printf '%s' "$INPUT" | jq -r '.tool_name // ""' 2>/dev/null)
  FILE=$(printf '%s' "$INPUT" | jq -r '.tool_input.file_path // ""' 2>/dev/null)
else
  TOOL=$(printf '%s' "$INPUT" | sed -n 's/.*"tool_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')
  FILE=$(printf '%s' "$INPUT" | grep -o '"file_path":"[^"]*"' | head -1 | cut -d'"' -f4)
fi

[ -n "$FILE" ] || exit 0

# Normalize to a project-relative path so it matches anatomy entries.
ROOT=$(pwd -P)
case "$FILE" in "$ROOT"/*) FILE="${FILE#"$ROOT"/}" ;; esac
# Still absolute means the file lives outside the project - not our business.
case "$FILE" in /*) exit 0 ;; esac

case "$TOOL" in
  Read)
    printf '%s\t%s\n' "$FILE" "$(date +%Y-%m-%dT%H:%M:%S)" >> .kazam/ctx/reads.log
    ;;
  Write|Edit|NotebookEdit)
    kazam track log add "Modified $FILE" \
      --source "${KAZAM_AGENT:-claude-code}" --severity info >/dev/null 2>&1
    ;;
esac

exit 0
"##;

const STOP_SH: &str = r#"#!/bin/bash
# kazam workspace - session stop hook
# Rescans anatomy, then summarizes session activity and suggests enrichment.
kazam ctx scan 2>/dev/null
DIFF=$(kazam ctx scan --check --json 2>/dev/null)
NEW=$(echo "$DIFF" | grep -o '"new_files":\[[^]]*\]' | grep -o '"[^"]*\..*"' | wc -l 2>/dev/null | tr -d ' ')
CHANGED=$(echo "$DIFF" | grep -o '"changed_files":\[[^]]*\]' | grep -o '"[^"]*\..*"' | wc -l 2>/dev/null | tr -d ' ')
if [ "${NEW:-0}" != "0" ] || [ "${CHANGED:-0}" != "0" ]; then
  echo "kazam: session touched ${CHANGED:-0} changed + ${NEW:-0} new files"
  echo "  → enrich descriptions: kazam ctx describe <path> \"what this file does\""
  echo "  → record learnings:    kazam ctx learn \"lesson\" --category correction"
  echo "  → record bugs:         kazam ctx bug \"symptom\" --file <path>"
fi
"#;

const WORKSPACE_RULES: &str = r#"# Kazam Workspace

This project uses **kazam** for task tracking and context intelligence.
Use kazam for ALL task tracking - do NOT use the built-in TaskCreate/TaskUpdate tools.
State lives in `.kazam/` as YAML files.

## Prerequisites
- kazam must be installed: `cargo install --git https://github.com/tdiderich/kazam`
- If `kazam` is not on PATH, install it before using any workspace commands.

## Navigating the codebase - MANDATORY
**Before you `grep`, `find`, `ls`, or spawn a subagent to explore, read the
anatomy index.** This is not optional. The index exists so you don't waste
tokens scanning the filesystem.

**Step 0 - Ask for a brief:** `kazam ctx research "<what you're doing>"`
returns the most relevant files with model-written descriptions and
line-numbered outlines. Read the cited ranges (offset/limit) directly. Fall
back to the steps below only if nothing in the brief fits.

**Step 1 - Read the summary:**
`.kazam/ctx/anatomy.tsv` - compact index with root files and directory rollups
(file count, total tokens, description). ~68 lines even for huge repos.

**Step 2 - Drill into a directory:**
`.kazam/ctx/anatomy/<dir>.tsv` - individual files in that directory.
Nested paths use `--` as separator: `frontend/src/app` → `anatomy/frontend--src--app.tsv`.

**Step 3 - Read the source file you need.**

Summary → detail → source. Three reads, zero exploration.

**For multi-file exploration** (where is X, what calls Y, bug hunts across
directories), dispatch the `kazam-scout` agent instead of exploring in your
own context. It navigates anatomy-first and returns compact `file:line`
citations, keeping file dumps out of the main conversation.

**When delegating to subagents:** subagents don't see these rules, so you
must brief them. Include in every subagent prompt:
1. **Anatomy:** "Read `.kazam/ctx/anatomy.tsv` for project layout, then
   `.kazam/ctx/anatomy/<dir>.tsv` for the directory you need - don't
   grep or find for structure."
2. **Task context:** "You are working on task `<ID>`: <title>. When done,
   run `kazam track close <ID> --reason '<what you did>'`."
3. **Enrichment:** "After reading an unfamiliar file, run
   `kazam ctx describe <path> '<description>'`."

## On session start or context recovery
The `SessionStart` hook already prints anatomy drift and ready tasks, so you
normally start oriented. Re-run `kazam track ready --json` any time you need it
again.

**After a `/compact` or auto-compaction** the same hook prints a fuller recovery
payload: claimed tasks with their notes, the activity logged during the stretch
that was summarized away, uncommitted file drift, standing corrections, and
recent learnings. Treat that payload as authoritative. The compaction summary is
lossy; `.kazam/` is not. Where they disagree, `.kazam/` wins.

This works because the `PreCompact` hook writes a `compact boundary` entry to
`track/log.yaml` on the way out, which is what lets the recovery payload replay
exactly the work belonging to the discarded transcript. Nothing is stored
outside kazam's normal stores, so there is no second source of truth to drift.

## Before starting work
- Claim a task: `kazam track claim <ID> --name <your-name>`.
- **MANDATORY: before fixing any error**, run `kazam ctx bugs --file <path>`
  to check if it was solved before. Do not skip this step.

## During work - close tasks as you go, don't batch
- **After each commit**, check if it completes an open task. If so, close it
  immediately: `kazam track close <ID> --reason "what you did"`.
- Tasks with `--owner human` are not yours to close. If one blocks your work,
  mark it blocked: `kazam track block <ID> --reason "why"`. When the user
  completes a human task, close it for them.
- After reading an unfamiliar file, enrich its description:
  `kazam ctx describe <path> "what this file actually does"`.
- Record non-obvious learnings: `kazam ctx learn "lesson" --category correction`.
- Record bugs you find: `kazam ctx bug "symptom" --file <path>`.
- When the user corrects your approach, record it immediately:
  `kazam ctx correction "what you did wrong" "what to do instead" --file <path>`.

## Quick reference
```
kazam track ready --json     # unblocked tasks by priority
kazam track close <ID> --reason "..."   # mark task done
kazam track block <ID> --reason "..."   # mark task blocked
kazam track list --json      # all tasks with status
kazam ctx describe <path> "description" # enrich file description
kazam ctx bugs --file <path> # known bugs on a file
kazam ctx learn "lesson" --category correction
kazam ctx bug "symptom" --file <path>
kazam ctx correction "mistake" "fix" --file <path>  # record a correction
kazam ctx corrections --json   # view past corrections
```

## Direct YAML editing
You may edit `.kazam/track/tasks.yaml` or `.kazam/ctx/*.yaml` directly.
The board (`kazam board`) auto-refreshes on any `.kazam/*.yaml` change.
"#;

const SCOUT_AGENT: &str = r#"---
name: kazam-scout
description: Read-only repository scout. Locates code fast and returns compact file:line citations instead of file dumps. Use for "where is X defined", "what calls Y", "which files handle Z" before making changes. Navigates via the kazam anatomy index instead of blind grep.
tools: Read, Glob, Grep, Bash
model: sonnet
---

You are kazam-scout, a repository exploration subagent. Your job is to find
code and return citations - never to fix, refactor, or judge it.

## Protocol

1. Check for `.kazam/ctx/anatomy.tsv`. If it exists, read it first - root
   files and directory rollups. If it does not exist, skip to the fallback
   protocol below.
2. Drill into `.kazam/ctx/anatomy/<dir>.tsv` for the directories that matter.
   Nested paths use `--` as separator: `src/app/api` → `anatomy/src--app--api.tsv`.
3. Confirm with targeted Read/Grep on specific files. Issue independent
   searches in parallel, not one at a time.
4. Verify every citation by reading the actual lines before reporting.

## Fallback protocol (no kazam workspace)

No anatomy index? Explore directly: Glob for structure (`**/*.<ext>`,
config files, entry points), Grep for symbols, Read only the files that
match. Same parallel-search discipline, same output contract. Never
error out just because kazam isn't set up.

## Output contract

Return ONLY this format:

FINDINGS
- path/to/file.rs:42-58 - router definition, handles the auth redirect
- path/to/other.ts:101-119 - the only caller

NOT FOUND (only if applicable)
- searched: <patterns and directories covered>

Rules:
- Max 10 citations, ranked by relevance.
- One line of "why it matters" per citation. No code blocks longer than 3 lines.
- Never propose fixes, improvements, or opinions on code quality.
- If anatomy lists a file that doesn't exist on disk, note it as stale and move on.

## Enrichment

After reading a file whose anatomy description is empty or generic, run:
`kazam ctx describe <path> "<one line on what it actually does>"`
"#;

/// Marker line kazam stamps into the second line of every generated hook
/// script (right after the shebang). Lets `workspace status` tell a script
/// that was generated by an older kazam binary apart from the current
/// templates, without diffing file contents against the compiled-in source.
const SCAFFOLD_VERSION_PREFIX: &str = "# kazam-scaffold-version:";

/// The crate version stamped into freshly generated hook scripts.
fn current_scaffold_version() -> &'static str {
    env!("CARGO_PKG_VERSION")
}

/// Insert the scaffold version marker as the second line of a hook script
/// template (after the `#!/bin/bash` shebang).
fn stamp_scaffold_version(script: &str) -> String {
    let marker = format!("{SCAFFOLD_VERSION_PREFIX} {}", current_scaffold_version());
    match script.split_once('\n') {
        Some((shebang, rest)) => format!("{shebang}\n{marker}\n{rest}"),
        None => format!("{script}\n{marker}\n"),
    }
}

/// Read the scaffold version stamped into an installed hook script, if any.
/// `None` means the script predates version stamping.
fn read_scaffold_version(script: &str) -> Option<&str> {
    script.lines().find_map(|line| {
        line.trim()
            .strip_prefix(SCAFFOLD_VERSION_PREFIX)
            .map(|v| v.trim())
    })
}

/// True if a hooks-array entry (either the current nested shape or the
/// legacy flat shape) is one kazam registered, identified by its
/// `kazam-workspace:` description prefix.
fn is_kazam_hook_entry(item: &serde_json::Value) -> bool {
    let nested = item
        .pointer("/hooks/0/description")
        .and_then(|d| d.as_str());
    let flat = item.pointer("/description").and_then(|d| d.as_str());
    nested.is_some_and(|d| d.starts_with("kazam-workspace:"))
        || flat.is_some_and(|d| d.starts_with("kazam-workspace:"))
}

/// Remove kazam-owned hook entries from a settings file that is *not* the
/// current install target. Without this, re-running `workspace init` with a
/// different skunkworks setting (or a config.yaml default that differs from
/// the CLI flag) leaves a stale registration behind in the other file, and
/// Claude Code merges both - every hook then fires twice.
fn strip_kazam_hooks_from_settings(settings_path: &Path) -> Result<()> {
    if !settings_path.exists() {
        return Ok(());
    }
    let text = fs::read_to_string(settings_path)
        .with_context(|| format!("read {}", settings_path.display()))?;
    let Ok(mut settings) = serde_json::from_str::<serde_json::Value>(&text) else {
        return Ok(());
    };

    let mut changed = false;
    if let Some(obj) = settings.as_object_mut() {
        if let Some(hooks_obj) = obj.get_mut("hooks").and_then(|h| h.as_object_mut()) {
            for event in ["SessionStart", "PreCompact", "PostToolUse", "Stop"] {
                if let Some(arr) = hooks_obj.get_mut(event).and_then(|v| v.as_array_mut()) {
                    let before = arr.len();
                    arr.retain(|item| !is_kazam_hook_entry(item));
                    if arr.len() != before {
                        changed = true;
                    }
                }
            }
            if changed {
                hooks_obj.retain(|_, v| !v.as_array().is_some_and(|a| a.is_empty()));
                if hooks_obj.is_empty() {
                    obj.remove("hooks");
                }
            }
        }
    }

    if changed {
        let json = serde_json::to_string_pretty(&settings)?;
        fs::write(settings_path, json)
            .with_context(|| format!("write {}", settings_path.display()))?;
    }
    Ok(())
}

pub fn install(project: &Path, agent: &str, skunkworks: bool) -> Result<()> {
    let hooks_dir = crate::workspace::root(project).join("hooks");
    fs::create_dir_all(&hooks_dir).context("create hooks dir")?;

    fs::write(
        hooks_dir.join("session-start.sh"),
        stamp_scaffold_version(SESSION_START_SH),
    )?;
    fs::write(
        hooks_dir.join("pre-compact.sh"),
        stamp_scaffold_version(PRE_COMPACT_SH),
    )?;
    fs::write(
        hooks_dir.join("post-tool.sh"),
        stamp_scaffold_version(POST_TOOL_SH),
    )?;
    fs::write(hooks_dir.join("stop.sh"), stamp_scaffold_version(STOP_SH))?;

    // post-write.sh was the broken $KAZAM_TOOL_INPUT version, superseded by
    // post-tool.sh. Remove it so stale copies stop shadowing the fix.
    let legacy = hooks_dir.join("post-write.sh");
    if legacy.exists() {
        let _ = fs::remove_file(&legacy);
    }

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        for name in [
            "session-start.sh",
            "pre-compact.sh",
            "post-tool.sh",
            "stop.sh",
        ] {
            let p = hooks_dir.join(name);
            fs::set_permissions(&p, fs::Permissions::from_mode(0o755))?;
        }
    }

    if agent == "claude" || agent == "all" {
        install_claude_hooks(project, skunkworks)?;
    }

    // Write workspace rules (base + optional team override)
    let rules_dir = project.join(".claude").join("rules");
    fs::create_dir_all(&rules_dir).context("create .claude/rules")?;

    let override_path = crate::workspace::root(project).join("ctx/rules-override.md");
    let mut rules = WORKSPACE_RULES.to_string();
    if override_path.exists() {
        let custom = fs::read_to_string(&override_path).unwrap_or_default();
        if !custom.trim().is_empty() {
            rules.push_str("\n## Team overrides\n\n");
            rules.push_str(&custom);
            rules.push('\n');
        }
    }

    fs::write(rules_dir.join("kazam-workspace.md"), &rules).context("write workspace rules")?;

    // Write the scout agent definition (anatomy-first repository explorer)
    let agents_dir = project.join(".claude").join("agents");
    fs::create_dir_all(&agents_dir).context("create .claude/agents")?;
    fs::write(agents_dir.join("kazam-scout.md"), SCOUT_AGENT).context("write kazam-scout agent")?;

    let settings_name = if skunkworks {
        "settings.local.json"
    } else {
        "settings.json"
    };
    println!("  ✓ hooks installed to .kazam/hooks/");
    if agent == "claude" || agent == "all" {
        println!("  ✓ Claude Code hooks registered in .claude/{settings_name}");
    }
    println!("  ✓ workspace rules written to .claude/rules/kazam-workspace.md");
    println!("  ✓ scout agent written to .claude/agents/kazam-scout.md");
    if override_path.exists() {
        println!("  ✓ team overrides applied from .kazam/ctx/rules-override.md");
    }
    Ok(())
}

pub fn uninstall(project: &Path) -> Result<()> {
    let hooks_dir = crate::workspace::root(project).join("hooks");
    if hooks_dir.exists() {
        fs::remove_dir_all(&hooks_dir).context("remove hooks dir")?;
        fs::create_dir_all(&hooks_dir).context("recreate hooks dir")?;
    }

    let rules_file = project.join(".claude/rules/kazam-workspace.md");
    if rules_file.exists() {
        fs::remove_file(&rules_file).context("remove workspace rules")?;
    }

    let scout_file = project.join(".claude/agents/kazam-scout.md");
    if scout_file.exists() {
        fs::remove_file(&scout_file).context("remove kazam-scout agent")?;
    }

    // Remove only kazam entries from .claude/settings.json, preserve everything else
    let settings_path = project.join(".claude/settings.json");
    if settings_path.exists() {
        let text = fs::read_to_string(&settings_path)?;
        if let Ok(mut settings) = serde_json::from_str::<serde_json::Value>(&text) {
            if let Some(obj) = settings.as_object_mut() {
                if let Some(hooks) = obj.get_mut("hooks") {
                    if let Some(hooks_obj) = hooks.as_object_mut() {
                        for event in ["SessionStart", "PreCompact", "PostToolUse", "Stop"] {
                            if let Some(arr) =
                                hooks_obj.get_mut(event).and_then(|v| v.as_array_mut())
                            {
                                arr.retain(|item| !is_kazam_hook_entry(item));
                                if arr.is_empty() {
                                    hooks_obj.remove(event);
                                }
                            }
                        }
                    }
                }
            }
            let json = serde_json::to_string_pretty(&settings)?;
            fs::write(&settings_path, json)?;
        }
    }

    println!("  ✓ hooks uninstalled");
    Ok(())
}

/// Installed hook scripts whose scaffold version marker doesn't match the
/// currently-running binary (or is missing entirely, for scripts generated
/// before version stamping existed). Returned as `(script name, installed
/// version)` pairs, in scripts-array order.
fn stale_hook_scripts(project: &Path) -> Vec<(&'static str, Option<String>)> {
    let hooks_dir = crate::workspace::root(project).join("hooks");
    let scripts = [
        "session-start.sh",
        "pre-compact.sh",
        "post-tool.sh",
        "stop.sh",
    ];
    let current = current_scaffold_version();

    scripts
        .iter()
        .filter_map(|name| {
            let content = fs::read_to_string(hooks_dir.join(name)).ok()?;
            match read_scaffold_version(&content) {
                Some(v) if v == current => None,
                Some(v) => Some((*name, Some(v.to_string()))),
                None => Some((*name, None)),
            }
        })
        .collect()
}

/// The `re-run kazam workspace init` warning line for one stale/unversioned
/// hook script, shared between `workspace status` and the SessionStart hook's
/// drift report so both surfaces phrase it identically.
fn stale_hook_warning(name: &str, installed_version: Option<&str>) -> String {
    let current = current_scaffold_version();
    match installed_version {
        Some(v) => {
            format!("{name} stale (v{v}, current v{current}) - re-run kazam workspace init")
        }
        None => {
            format!("{name} stale (no version marker, current v{current}) - re-run kazam workspace init")
        }
    }
}

pub fn status(project: &Path) -> Result<()> {
    let hooks_dir = crate::workspace::root(project).join("hooks");
    let scripts = [
        "session-start.sh",
        "pre-compact.sh",
        "post-tool.sh",
        "stop.sh",
    ];

    let mut installed = 0;
    for name in &scripts {
        if hooks_dir.join(name).exists() {
            installed += 1;
        }
    }

    let settings_path = project.join(".claude/settings.json");
    let claude_registered = if settings_path.exists() {
        let text = fs::read_to_string(&settings_path).unwrap_or_default();
        text.contains("kazam-workspace")
    } else {
        false
    };

    let rules_exist = project.join(".claude/rules/kazam-workspace.md").exists();

    println!("  hook scripts: {installed}/{} installed", scripts.len());
    for (name, version) in stale_hook_scripts(project) {
        println!("  ⚠ {}", stale_hook_warning(name, version.as_deref()));
    }
    println!(
        "  claude hooks: {}",
        if claude_registered {
            "registered"
        } else {
            "not registered"
        }
    );
    println!(
        "  workspace rules: {}",
        if rules_exist { "present" } else { "missing" }
    );
    Ok(())
}

fn install_claude_hooks(project: &Path, skunkworks: bool) -> Result<()> {
    let settings_file = if skunkworks {
        "settings.local.json"
    } else {
        "settings.json"
    };
    let settings_path = project.join(".claude").join(settings_file);
    fs::create_dir_all(project.join(".claude")).context("create .claude")?;

    // Whichever file we are NOT writing to this run may still be carrying a
    // registration from a previous init (e.g. the CLI flag was absent this
    // time but config.yaml's skunkworks default differed, or skunkworks was
    // toggled). Strip it so the two settings files never both claim the hooks.
    let other_settings_file = if skunkworks {
        "settings.json"
    } else {
        "settings.local.json"
    };
    strip_kazam_hooks_from_settings(&project.join(".claude").join(other_settings_file))?;

    let mut settings: serde_json::Value = if settings_path.exists() {
        let text = fs::read_to_string(&settings_path)?;
        serde_json::from_str(&text).unwrap_or(serde_json::json!({}))
    } else {
        serde_json::json!({})
    };

    // Reference the hook scripts through $CLAUDE_PROJECT_DIR rather than a
    // canonicalized absolute path. .claude/settings.json is committed in plenty
    // of repos, and an absolute path pins those hooks to whichever machine ran
    // `workspace init` - every teammate then gets commands pointing at a
    // directory that does not exist for them. Falls back to the working
    // directory if the variable is ever absent.
    let hooks_abs = format!(
        "\"${{CLAUDE_PROJECT_DIR:-.}}\"/{}/hooks",
        crate::workspace::DIR
    );

    let obj = settings.as_object_mut().unwrap();
    let hooks = obj
        .entry("hooks")
        .or_insert(serde_json::json!({}))
        .as_object_mut()
        .unwrap();

    let kazam_hooks = [
        (
            "SessionStart",
            serde_json::json!({
                "matcher": "",
                "hooks": [{
                    "type": "command",
                    "command": format!("bash {hooks_abs}/session-start.sh"),
                    "description": "kazam-workspace: surface anatomy drift and ready tasks"
                }]
            }),
        ),
        (
            "PreCompact",
            serde_json::json!({
                "matcher": "",
                "hooks": [{
                    "type": "command",
                    "command": format!("bash {hooks_abs}/pre-compact.sh"),
                    "description": "kazam-workspace: flush state and mark compaction boundary",
                    "timeout": 20
                }]
            }),
        ),
        (
            "PostToolUse",
            serde_json::json!({
                "matcher": "Read|Write|Edit|NotebookEdit",
                "hooks": [{
                    "type": "command",
                    "command": format!("bash {hooks_abs}/post-tool.sh"),
                    "description": "kazam-workspace: log file modifications and reads",
                    "timeout": 10
                }]
            }),
        ),
        (
            "Stop",
            serde_json::json!({
                "matcher": "",
                "hooks": [{
                    "type": "command",
                    "command": format!("bash {hooks_abs}/stop.sh"),
                    "description": "kazam-workspace: rescan anatomy on session end"
                }]
            }),
        ),
    ];

    for (event, entry) in kazam_hooks {
        let arr = hooks
            .entry(event)
            .or_insert(serde_json::json!([]))
            .as_array_mut()
            .unwrap();

        // Remove any existing kazam entries (by description prefix) to avoid duplicates.
        arr.retain(|item| !is_kazam_hook_entry(item));

        arr.push(entry);
    }

    let json = serde_json::to_string_pretty(&settings)?;
    fs::write(&settings_path, json).with_context(|| format!("write .claude/{settings_file}"))?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn install_switches_skunkworks_without_duplicating_registration() {
        let tmp = tempfile::tempdir().unwrap();
        let project = tmp.path();
        crate::workspace::ensure(project).unwrap();

        install(project, "claude", true).unwrap();
        let local_path = project.join(".claude/settings.local.json");
        let main_path = project.join(".claude/settings.json");
        assert!(local_path.exists());
        assert!(!main_path.exists());

        // Switching skunkworks off must move the registration to
        // settings.json and strip it out of settings.local.json, not leave
        // both files carrying it (which is what made every hook fire twice).
        install(project, "claude", false).unwrap();
        assert!(main_path.exists());

        let main: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&main_path).unwrap()).unwrap();
        for event in ["SessionStart", "PreCompact", "PostToolUse", "Stop"] {
            assert_eq!(
                main["hooks"][event].as_array().unwrap().len(),
                1,
                "expected exactly one {event} registration"
            );
        }

        if local_path.exists() {
            let local_text = fs::read_to_string(&local_path).unwrap();
            assert!(!local_text.contains("kazam-workspace"));
        }
    }

    #[test]
    fn stamp_and_read_scaffold_version_round_trip() {
        let stamped = stamp_scaffold_version("#!/bin/bash\necho hi\n");
        assert!(stamped.starts_with(&format!(
            "#!/bin/bash\n{SCAFFOLD_VERSION_PREFIX} {}\n",
            current_scaffold_version()
        )));
        assert_eq!(
            read_scaffold_version(&stamped),
            Some(current_scaffold_version())
        );
    }

    #[test]
    fn fresh_install_reports_no_stale_scripts() {
        let tmp = tempfile::tempdir().unwrap();
        let project = tmp.path();
        crate::workspace::ensure(project).unwrap();

        install(project, "claude", false).unwrap();

        assert!(stale_hook_scripts(project).is_empty());
    }

    #[test]
    fn doctored_old_version_marker_is_reported_stale() {
        let tmp = tempfile::tempdir().unwrap();
        let project = tmp.path();
        crate::workspace::ensure(project).unwrap();
        install(project, "claude", false).unwrap();

        let script_path = crate::workspace::root(project).join("hooks/session-start.sh");
        let content = fs::read_to_string(&script_path).unwrap();
        let doctored = content.replacen(
            &format!("{SCAFFOLD_VERSION_PREFIX} {}", current_scaffold_version()),
            &format!("{SCAFFOLD_VERSION_PREFIX} 0.0.1"),
            1,
        );
        fs::write(&script_path, doctored).unwrap();

        let stale = stale_hook_scripts(project);
        assert_eq!(stale.len(), 1);
        assert_eq!(stale[0].0, "session-start.sh");
        assert_eq!(stale[0].1.as_deref(), Some("0.0.1"));
        assert!(stale_hook_warning(stale[0].0, stale[0].1.as_deref())
            .contains("stale (v0.0.1, current v"));
    }

    #[test]
    fn missing_version_marker_is_reported_stale() {
        let tmp = tempfile::tempdir().unwrap();
        let project = tmp.path();
        crate::workspace::ensure(project).unwrap();
        install(project, "claude", false).unwrap();

        // Pre-versioning scripts never had a marker line at all.
        let script_path = crate::workspace::root(project).join("hooks/post-tool.sh");
        fs::write(&script_path, "#!/bin/bash\necho legacy\n").unwrap();

        let stale = stale_hook_scripts(project);
        assert_eq!(stale.len(), 1);
        assert_eq!(stale[0].0, "post-tool.sh");
        assert_eq!(stale[0].1, None);
        assert!(stale_hook_warning(stale[0].0, stale[0].1.as_deref())
            .contains("stale (no version marker, current v"));
    }
}