kairos-chain 3.99.0 → 3.100.1

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 (76) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +44 -0
  3. data/lib/kairos_mcp/version.rb +1 -1
  4. data/templates/knowledge/multi_llm_review_workflow/multi_llm_review_workflow.md +24 -9
  5. data/templates/skillsets/compaction_handoff/config/compaction_handoff.yml +11 -0
  6. data/templates/skillsets/compaction_handoff/hooks/after_compact.rb +79 -0
  7. data/templates/skillsets/compaction_handoff/hooks/common.rb +226 -0
  8. data/templates/skillsets/compaction_handoff/hooks/pre_compact.rb +83 -0
  9. data/templates/skillsets/compaction_handoff/hooks/probe.rb +116 -0
  10. data/templates/skillsets/compaction_handoff/hooks/turn_start.rb +60 -0
  11. data/templates/skillsets/compaction_handoff/hooks/usage_reader.rb +67 -0
  12. data/templates/skillsets/compaction_handoff/knowledge/compaction_handoff_guide/compaction_handoff_guide.md +83 -0
  13. data/templates/skillsets/compaction_handoff/mod/.claude-plugin/plugin.json +8 -0
  14. data/templates/skillsets/compaction_handoff/mod/.gitignore +2 -0
  15. data/templates/skillsets/compaction_handoff/mod/hooks/hooks.json +1 -0
  16. data/templates/skillsets/compaction_handoff/mod/hooks/register.ts +355 -0
  17. data/templates/skillsets/compaction_handoff/mod/tests/register.test.ts +477 -0
  18. data/templates/skillsets/compaction_handoff/plugin/hooks.json +48 -0
  19. data/templates/skillsets/compaction_handoff/skillset.json +21 -0
  20. data/templates/skillsets/compaction_handoff/test/test_compaction_handoff.rb +455 -0
  21. data/templates/skillsets/kairomone/assets/README.md +302 -0
  22. data/templates/skillsets/kairomone/assets/console.html +1685 -0
  23. data/templates/skillsets/kairomone/assets/fixtures/status_xss.json +97 -0
  24. data/templates/skillsets/kairomone/assets/status.html +299 -0
  25. data/templates/skillsets/kairomone/assets/test_console_browser.mjs +1164 -0
  26. data/templates/skillsets/kairomone/assets/test_console_logic.mjs +472 -0
  27. data/templates/skillsets/kairomone/assets/test_status_browser.mjs +77 -0
  28. data/templates/skillsets/kairomone/assets/test_status_ui.mjs +297 -0
  29. data/templates/skillsets/kairomone/docs/bounded-growth.md +103 -0
  30. data/templates/skillsets/kairomone/knowledge/kairomone_guide/kairomone_guide.md +476 -0
  31. data/templates/skillsets/kairomone/lib/kairomone/art.rb +379 -0
  32. data/templates/skillsets/kairomone/lib/kairomone/autonomy.rb +867 -0
  33. data/templates/skillsets/kairomone/lib/kairomone/backup.rb +499 -0
  34. data/templates/skillsets/kairomone/lib/kairomone/baseline.rb +172 -0
  35. data/templates/skillsets/kairomone/lib/kairomone/companion.rb +329 -0
  36. data/templates/skillsets/kairomone/lib/kairomone/console/child.rb +103 -0
  37. data/templates/skillsets/kairomone/lib/kairomone/console/gate.rb +99 -0
  38. data/templates/skillsets/kairomone/lib/kairomone/console/launch.rb +204 -0
  39. data/templates/skillsets/kairomone/lib/kairomone/console/project.rb +333 -0
  40. data/templates/skillsets/kairomone/lib/kairomone/console/server.rb +418 -0
  41. data/templates/skillsets/kairomone/lib/kairomone/console/session.rb +638 -0
  42. data/templates/skillsets/kairomone/lib/kairomone/console/view.rb +144 -0
  43. data/templates/skillsets/kairomone/lib/kairomone/console.rb +33 -0
  44. data/templates/skillsets/kairomone/lib/kairomone/exchange.rb +520 -0
  45. data/templates/skillsets/kairomone/lib/kairomone/fusion.rb +365 -0
  46. data/templates/skillsets/kairomone/lib/kairomone/host.rb +228 -0
  47. data/templates/skillsets/kairomone/lib/kairomone/instance.rb +653 -0
  48. data/templates/skillsets/kairomone/lib/kairomone/lean.rb +113 -0
  49. data/templates/skillsets/kairomone/lib/kairomone/learned.rb +187 -0
  50. data/templates/skillsets/kairomone/lib/kairomone/ledger.rb +92 -0
  51. data/templates/skillsets/kairomone/lib/kairomone/paths.rb +76 -0
  52. data/templates/skillsets/kairomone/lib/kairomone/policy.rb +119 -0
  53. data/templates/skillsets/kairomone/lib/kairomone/profession.rb +348 -0
  54. data/templates/skillsets/kairomone/lib/kairomone/profile.rb +303 -0
  55. data/templates/skillsets/kairomone/lib/kairomone/progression.rb +154 -0
  56. data/templates/skillsets/kairomone/lib/kairomone/skill.rb +274 -0
  57. data/templates/skillsets/kairomone/lib/kairomone/snapshot.rb +170 -0
  58. data/templates/skillsets/kairomone/lib/kairomone/transplant.rb +199 -0
  59. data/templates/skillsets/kairomone/lib/kairomone/vocabulary.rb +123 -0
  60. data/templates/skillsets/kairomone/lib/kairomone.rb +44 -0
  61. data/templates/skillsets/kairomone/plugin/SKILL.md +289 -0
  62. data/templates/skillsets/kairomone/scripts/kairomone.rb +203 -0
  63. data/templates/skillsets/kairomone/scripts/kairomone_console.rb +348 -0
  64. data/templates/skillsets/kairomone/scripts/kairomone_console_watchdog.rb +120 -0
  65. data/templates/skillsets/kairomone/skillset.json +57 -0
  66. data/templates/skillsets/kairomone/templates/characters.json +174 -0
  67. data/templates/skillsets/kairomone/templates/methods.json +23 -0
  68. data/templates/skillsets/kairomone/templates/professions.json +104 -0
  69. data/templates/skillsets/kairomone/templates/subjects.json +1047 -0
  70. data/templates/skillsets/kairomone/test/legacy_fixture.rb +31 -0
  71. data/templates/skillsets/kairomone/test/support_08.rb +103 -0
  72. data/templates/skillsets/kairomone/test/support_09.rb +115 -0
  73. data/templates/skillsets/kairomone/test/test_autonomy.rb +90 -0
  74. data/templates/skillsets/kairomone/tools/kairomone_tools.rb +402 -0
  75. data/templates/skillsets/multi_llm_review/config/multi_llm_review.yml +20 -14
  76. metadata +71 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: dcd329b502a42f94e178401c12cfa06ada118c54d1b5cb369b90964fa5e08efd
4
- data.tar.gz: 525e9e08b274f514c8448330d0448d54ecf25ac06943a14f41ec0004718304e5
3
+ metadata.gz: 24804af6b77d713c59b70054018eb85af6a664629e5295654c06862304b18b63
4
+ data.tar.gz: 1b1e0bad26fc0464a31ee2d58d8599f059aaad8259fc1e34dce5aa771c7ff196
5
5
  SHA512:
6
- metadata.gz: 7719ba8c1e91b9f592a4e781acb5161a20108c8a776bf22f41d3edf186d335c14c815609d8e8878e1001135786857a5cba67c1b1592ead2914f9b8698c21f4a4
7
- data.tar.gz: 212ae7282fedae1a06c3a410c80ffa660ce7bec0cd9d725f52b35763d1441f77b1548b8b96b37173ecfc827cb2ff461c826928d80697a79e792ea90674821cff
6
+ metadata.gz: 639b82daa0ae8ec3f95c82d3d2a899829c8ab83f2eda6b515df7b7d22141190780f4acd553f5b5eb1fa228018eb2298be124e25c4bfa75c14abe77013f3d2447
7
+ data.tar.gz: 3cf1ebca7a67c0aaa532b4355ffcee0d10b78c9899c78e2f677ea1aba3f7af6b0c134c3cf163ea08003dc653a17539219161da982876633c2299edbc2c515677
data/CHANGELOG.md CHANGED
@@ -6,6 +6,50 @@ This project follows [Semantic Versioning](https://semver.org/).
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [3.100.1] - 2026-11-18
10
+
11
+ ### Changed — multi_llm_review codex seat moves to gpt-6.2-astra
12
+
13
+ - The codex slot of the default roster runs `gpt-6.2-astra` (label `codex_gpt6.2-astra`), replacing
14
+ `gpt-6-astra`. Same slot and effort (high); roster size and reference ratios unchanged.
15
+ - Tested before the swap through the shipping adapter, prompt builder and verdict parser: two trials per
16
+ model on one function with three planted defects; both models found all three and put the verdict on
17
+ line one. 6.2 graded the same defects higher and used about 4% more total tokens. Not a calibration.
18
+ - Runs recorded under `codex_gpt6-astra` keep that label. L1 `multi_llm_review_workflow` 3.17.2 records
19
+ the change.
20
+
21
+ ## [3.100.0] - 2026-11-04
22
+
23
+ ### Added — compaction_handoff 0.2.0 and Kairomone 0.9.0 ship as SkillSet templates (opt-in)
24
+
25
+ Neither is installed by `system_upgrade` or `kairos-chain upgrade`; install each by name.
26
+
27
+ - **compaction_handoff 0.2.0.** Keeps a long-lived Claude Code session's work across context compaction,
28
+ for sessions run with auto-compaction off. A Claude Code mod (`mod/`, loaded per session with
29
+ `claude --plugin-dir <data dir>/skillsets/compaction_handoff/mod`) asks the session for an L2 handoff
30
+ once usage passes `request_ratio` of the window, compacts as soon as that turn has ended, then asks the
31
+ session to read the handoff back. Three command hooks stay as insurance: each turn start past the
32
+ request point repeats the request, every compaction leaves a figures-only fallback record in L2, and
33
+ after every compaction the session is told which handoff to read. An operator interrupt, `/compact` or
34
+ `/clear` ends the mod's cycle; it never compacts while a turn runs or for a subagent.
35
+ - **Kairomone 0.9.0.** Single-owner companions, any number per host, that grow through owned L1/L2 and
36
+ owner-started, evidence-backed growth runs driven by the host assistant over MCP; signed backups,
37
+ owner-accepted drawings as checked static SVG, and an owner-started loopback console page. No L0
38
+ changes, no built-in LLM or scheduler.
39
+
40
+ ### Changed
41
+
42
+ - The gem ships files under `templates/**/.claude-plugin/` (a mod's manifest); the file globs did not
43
+ enter dot-folders before.
44
+
45
+ **Upgrade notes**
46
+
47
+ - Install compaction_handoff fresh (`kairos-chain skillset install compaction_handoff`). SkillSet upgrade,
48
+ the SkillSet content hash and the exchange archive still skip dot-folders, so an upgraded or exchanged
49
+ copy lacks `mod/.claude-plugin/plugin.json` and the mod does not load. Check that the file exists.
50
+ - With compaction_handoff installed and projected, its three hooks act on every Claude Code session of the
51
+ project; the mod acts only in sessions started with `--plugin-dir`.
52
+
9
53
  ## [3.99.0] - 2026-10-25
10
54
 
11
55
  ### Security — Secure MMP v1: MMP direct mode discloses only what is public, and can admit only pinned keys (mmp 1.3.0, secure_mmp 0.1.0)
@@ -1,4 +1,4 @@
1
1
  module KairosMcp
2
- VERSION = "3.99.0"
2
+ VERSION = "3.100.1"
3
3
  CHANGELOG_URL = "https://github.com/masaomi/KairosChain_2026/blob/main/CHANGELOG.md"
4
4
  end
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: multi_llm_review_workflow
3
3
  description: "Multi-LLM review methodology and execution — workflow pattern, CLI tooling, consensus analysis, Persona Assembly. Applicable to design, implementation, documentation, or any artifact."
4
- version: "3.17.1"
4
+ version: "3.17.2"
5
5
  tags:
6
6
  - workflow
7
7
  - review
@@ -164,8 +164,10 @@ these numbers.
164
164
  The codex row is a profile of **gpt-5.6-sol**, which left the roster on
165
165
  2026-09-05 when gpt-6-astra replaced it. Nothing in that row transfers to the
166
166
  new occupant: the seat's identity here is the model, not the slot. Until a
167
- comparable corpus accumulates for `codex_gpt6-astra`, read the codex row as
168
- history and treat the new seat as uncalibrated. The same caution applies to
167
+ comparable corpus accumulates for the current codex seat, read the codex row as
168
+ history and treat the new seat as uncalibrated. (The seat changed again on
169
+ 2026-11-18: `codex_gpt6.2-astra` replaced `codex_gpt6-astra`, and the same rule
170
+ applies — runs under the 6 label do not profile 6.2.) The same caution applies to
169
171
  every row from 2026-09-05 onward for a second reason — the corpus was gathered
170
172
  with reviewers at medium effort, and reviewers now run at high (see § Thinking
171
173
  Effort Configuration), so post-swap rounds are not directly comparable to it.
@@ -533,7 +535,7 @@ they disagree, the config is right and this section is stale.
533
535
  Opus 5.5, which under the default "delegate" strategy is taken by your
534
536
  persona team rather than spawned — so when you are Opus 5.5, Sonnet 5.5 is
535
537
  the only Claude CLI subprocess
536
- - [ ] Codex model: gpt-6-astra, with -m. One codex slot since gpt-5.5 was
538
+ - [ ] Codex model: gpt-6.2-astra, with -m. One codex slot since gpt-5.5 was
537
539
  retired 2026-09-05 — do not add a second codex entry expecting the old
538
540
  cross-generation pairing
539
541
  - [ ] Cursor model: composer-2.5, passed explicitly as --model composer-2.5
@@ -953,7 +955,7 @@ outside this repository — see the incident recorded in § Pre-flight checklist
953
955
 
954
956
  | Tool | Command | Prompt Input | Output Collection | Model |
955
957
  |------|---------|-------------|-------------------|-------|
956
- | **Codex** | `codex exec -m <model> -c model_reasoning_effort=high` | stdin pipe: `cat prompt.md \| codex exec -m <model> -` | `-o /path/output.md` | gpt-6-astra — one slot since gpt-5.5 was retired 2026-09-05 |
958
+ | **Codex** | `codex exec -m <model> -c model_reasoning_effort=high` | stdin pipe: `cat prompt.md \| codex exec -m <model> -` | `-o /path/output.md` | gpt-6.2-astra (since 2026-11-18, replacing gpt-6-astra) — one slot since gpt-5.5 was retired 2026-09-05 |
957
959
  | **Cursor Agent** | `agent -p --model composer-2.5` | File reference (stdin NOT supported) | stdout redirect: `> output.md` | composer-2.5, passed explicitly — never relying on the CLI default |
958
960
  | **Claude Code** | Agent tool (internal) | Direct prompt string | Write to workspace file | Orchestrator model, or the declared `persona_model` when personas run elsewhere |
959
961
  | **Claude CLI (Sonnet 5.5)** | `claude -p --model claude-sonnet-5-5 --effort high` | stdin pipe: `cat prompt.md \| claude -p --model claude-sonnet-5-5 --effort high` | stdout redirect: `> output.md` | Sonnet 5.5 — took Opus 4.6's slot on 2026-09-30 by operator decision; uncalibrated |
@@ -1613,12 +1615,12 @@ Step 2: Detect environment, and check the roster against config
1613
1615
  - Read the roster from config/multi_llm_review.yml — do NOT read CLI defaults
1614
1616
  and treat them as the roster. Detection only tells you whether a default has
1615
1617
  drifted; the model each slot runs is named on the command line.
1616
- - Report: "Auto mode: Codex (gpt-6-astra), Cursor (composer-2.5),
1618
+ - Report: "Auto mode: Codex (gpt-6.2-astra), Cursor (composer-2.5),
1617
1619
  Claude Team (orchestrator model), Claude CLI (sonnet-5.5)"
1618
1620
 
1619
1621
  Step 3: Execute the configured roster in parallel (currently 4 slots, one of
1620
1622
  which is your own persona team)
1621
- - Bash(background): cat prompt.md | codex exec -m gpt-6-astra -c model_reasoning_effort=high -C workspace -o log/review_codex_gpt6-astra.md -
1623
+ - Bash(background): cat prompt.md | codex exec -m gpt-6.2-astra -c model_reasoning_effort=high -C workspace -o log/review_codex_gpt6.2-astra.md -
1622
1624
  - Bash(background): agent -p --trust --model composer-2.5 "Read prompt and review..." > log/review_cursor.md
1623
1625
  (no effort flag — Cursor has no effort control)
1624
1626
  - Agent(background): Claude Team (orchestrator model, e.g. Opus 5.5) → write to log/review_claude_team_opus5.5.md
@@ -1664,7 +1666,7 @@ log/{artifact}_review{N}_consensus_{date}.md # Consensus analysis
1664
1666
  ```
1665
1667
 
1666
1668
  LLM identifiers: `claude_cli_opus5.5`, `claude_cli_sonnet5.5`,
1667
- `codex_gpt6-astra`, `cursor_composer2.5`, `cursor_gpt5.4`,
1669
+ `codex_gpt6.2-astra`, `cursor_composer2.5`, `cursor_gpt5.4`,
1668
1670
  `cursor_premium`. The delegated slot is reported as `claude_team_<model>`
1669
1671
  (e.g. `claude_team_claude-opus-5-5`), assembled at collect time — the roster's
1670
1672
  own labels stay CLI-neutral because either frontier entry can take either path.
@@ -1676,7 +1678,8 @@ returns, 85-128 characters in 5-7 seconds, no findings and no verdict text;
1676
1678
  retired 2026-09-05: `codex_gpt5.6-sol`, replaced by `codex_gpt6-astra`, and
1677
1679
  `codex_gpt5.5`, not replaced; retired 2026-09-24: `claude_cli_opus5`, succeeded in
1678
1680
  the same slot by `claude_cli_opus5.5`; retired 2026-09-30: `claude_cli_opus4.6`,
1679
- succeeded in the same slot by `claude_cli_sonnet5.5`. Runs recorded under a retired identifier keep it —
1681
+ succeeded in the same slot by `claude_cli_sonnet5.5`; retired 2026-11-18:
1682
+ `codex_gpt6-astra`, succeeded in the same slot by `codex_gpt6.2-astra`. Runs recorded under a retired identifier keep it —
1680
1683
  the label names the model that answered, so renaming old records would attribute
1681
1684
  one model's findings to another)
1682
1685
 
@@ -2126,6 +2129,18 @@ Compression ratio: parallel agent raw → Assembly ≈ 2:1
2126
2129
  by the run's actor through a marker the SkillSet's hook rewrites, and submits the
2127
2130
  replies the host handed back. Design `log/agent_persona_seats_design_v0.3_20261022.md`.
2128
2131
 
2132
+ - Codex seat gpt-6-astra → gpt-6.2-astra (v3.17.2, 2026-11-18, operator
2133
+ instruction: 「gpt-6.2-astraがリリースされたらしいですが、MLRのgpt席を6.2に置き換えられますか?
2134
+ テストしてから置き換えてください。」). Same slot, same effort (high), label
2135
+ `codex_gpt6.2-astra`; the roster size and the reference ratios are unchanged.
2136
+ Tested before the swap through the shipping adapter, prompt builder and verdict
2137
+ parser: two trials per model on one function with three planted defects; both
2138
+ models found all three in both trials and put the verdict on line one. 6.2
2139
+ graded the same defects higher (REJECT with 1–2 P0 against REVISE with none),
2140
+ ran 14–17 s against 18–22 s, and used about 4% more total tokens. Two trials on
2141
+ one artifact say nothing about a real round; the seat is uncalibrated. Record
2142
+ `log/mlr_gpt62_astra_swap_20261118/`.
2143
+
2129
2144
  **Key insight**: Design reviews and implementation reviews find
2130
2145
  **categorically different bugs**. Both phases are necessary. The corollary that
2131
2146
  cost eight rounds to learn: **which of the two you are in is readable from the
@@ -0,0 +1,11 @@
1
+ # compaction_handoff — per-instance values (operator-owned).
2
+ compaction_handoff:
3
+ # Where this instance expects compaction, in tokens. With auto-compaction off
4
+ # (the long-lived receiver's setting; the mod compacts instead), the model
5
+ # window. With it on, Claude Code's autoCompactWindow (1M-window models compact
6
+ # at about 967K by default; 200K-window models at 200K). One value per project.
7
+ compact_at_tokens: 1000000
8
+ # The agent is asked to write its handoff from this share of compact_at_tokens.
9
+ request_ratio: 0.7
10
+ # Prefix of handoff and fallback names in L2: <tag>_<session8>_..., <tag>_fallback_<session8>_...
11
+ l2_tag: compaction_handoff
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ # SessionStart hook, matcher "compact" (design INV-6, INV-7). Every compaction
4
+ # is followed by a notice: it names this session's latest handoff and fallback
5
+ # record, marking any from an earlier cycle, or says none was found, or says
6
+ # the hook could not tell. This hook always prints its notice and exits 0, the
7
+ # path on which the host enters a SessionStart hook's output into the
8
+ # compacted context; causes of failure go to stderr as well. It ends the cycle
9
+ # first, before anything that needs the config (INV-7). A subagent's
10
+ # compaction leaves the main session's state alone.
11
+
12
+ require_relative 'common'
13
+
14
+ H = CompactionHandoffHook
15
+
16
+ FRAME = H::NOTES_FRAME
17
+
18
+ def describe(entry, ended_start)
19
+ earlier = ended_start && entry[:written_at] < ended_start ? ', from an earlier cycle' : ''
20
+ "#{entry[:name]} (L2 session #{entry[:session]}, written #{entry[:written_at].iso8601}#{earlier})"
21
+ end
22
+
23
+ def undetermined(sid)
24
+ "[compaction_handoff] This session (#{sid}) was compacted, but the hook could not tell whether a handoff " \
25
+ "was saved. Handoffs of this session carry `#{H::FRONTMATTER_KEY}: #{sid}` in their frontmatter and are " \
26
+ "not marked `kind: fallback`; look only for those. #{FRAME}"
27
+ end
28
+
29
+ notice = nil
30
+ sid = nil
31
+ begin
32
+ input = H.read_input
33
+ sid = H.session_id(input)
34
+ if H.subagent?(input)
35
+ notice = '[compaction_handoff] A subagent context was compacted; this SkillSet keeps no handoff for subagents.'
36
+ else
37
+ dir = H.data_dir
38
+ ended_start = nil
39
+ begin
40
+ existed = File.exist?(H.state_path(dir, sid))
41
+ state = H.load_state(dir, sid)
42
+ ended_start = Time.iso8601(state['cycle_started_at']) if existed
43
+ H.new_cycle!(state, offset: File.size?(input['transcript_path'].to_s).to_i, reason: 'after_compact')
44
+ H.save_state(dir, sid, state) or warn 'compaction_handoff: state could not be written'
45
+ rescue H::Unreadable, ArgumentError => e
46
+ warn "compaction_handoff: #{e.message}; cycle boundary not recorded"
47
+ end
48
+ cfg = H.config
49
+ manager = H.l2(dir)
50
+ found, = H.handoffs(manager, dir, cfg[:tag], sid)
51
+ fallback = H.fallbacks(manager, dir, cfg[:tag], sid).first
52
+ lines = ["[compaction_handoff] This session (#{sid}) was just compacted."]
53
+ lines << if found.first
54
+ "Read your handoff first: #{describe(found.first, ended_start)}. #{FRAME}"
55
+ else
56
+ "No handoff of this session was found under #{H.handoff_prefix(cfg[:tag], sid)}*; rely on the summary above."
57
+ end
58
+ lines << if fallback && !(ended_start && fallback[:written_at] < ended_start)
59
+ "Fallback record of this compaction (figures only, no conversation text): #{describe(fallback, ended_start)}."
60
+ elsif fallback
61
+ "No fallback record was written for this compaction; the latest is #{describe(fallback, ended_start)}."
62
+ else
63
+ 'No fallback record of this session was found.'
64
+ end
65
+ notice = lines.join("\n")
66
+ end
67
+ rescue StandardError, ScriptError => e
68
+ warn "compaction_handoff: #{e.class}: #{e.message[0, 200]}"
69
+ notice = if sid
70
+ undetermined(sid)
71
+ else
72
+ '[compaction_handoff] This session was compacted, but the hook could not read its session id, so it ' \
73
+ 'cannot point to a handoff. Do not take another session\'s handoff from L2 as yours; rely on the ' \
74
+ 'summary above.'
75
+ end
76
+ end
77
+
78
+ H.emit('SessionStart', notice)
79
+ exit 0
@@ -0,0 +1,226 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'yaml'
5
+ require 'time'
6
+ require 'fileutils'
7
+
8
+ # Shared parts of the three hooks (design log/compaction_handoff_design_v0.3.md).
9
+ # Claude Code layer: this file knows the hook input; it lives in hooks/, outside
10
+ # lib/, so nothing on the KairosChain side reaches it by name (INV-9).
11
+ module CompactionHandoffHook
12
+ SESSION_ID = /\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/
13
+ CONFIG_FILE = File.expand_path('../config/compaction_handoff.yml', __dir__)
14
+ TAG_FORMAT = /\A[a-z][a-z0-9_]{0,40}\z/
15
+ # A usage figure below this share of the previous one is taken as a
16
+ # compaction that actually happened (INV-7). Only real context sizes count
17
+ # (UsageReader drops zero and synthetic records), so an API error is not one.
18
+ DROP_RATIO = 0.5
19
+ FRONTMATTER_KEY = 'compaction_handoff_session'
20
+
21
+ class Unreadable < StandardError; end
22
+
23
+ module_function
24
+
25
+ def read_input(io = $stdin)
26
+ JSON.parse(io.read.to_s)
27
+ rescue JSON::ParserError
28
+ raise Unreadable, 'hook input is not JSON'
29
+ end
30
+
31
+ def session_id(input)
32
+ sid = input.is_a?(Hash) ? input['session_id'].to_s : ''
33
+ raise Unreadable, 'hook input carries no well-formed session id' unless SESSION_ID.match?(sid)
34
+
35
+ sid
36
+ end
37
+
38
+ # A subagent's transcript lives under <session>/subagents/; its compaction
39
+ # neither spends nor ends the main thread's cycle.
40
+ def subagent?(input)
41
+ input['transcript_path'].to_s.include?('/subagents/')
42
+ end
43
+
44
+ def data_dir
45
+ dir = ENV['KAIROS_DATA_DIR'].to_s
46
+ dir = File.join(ENV['CLAUDE_PROJECT_DIR'] || Dir.pwd, '.kairos') if dir.empty?
47
+ raise Unreadable, 'no KairosChain data directory' unless File.directory?(File.join(dir, 'context'))
48
+
49
+ dir
50
+ end
51
+
52
+ def config(path = ENV['COMPACTION_HANDOFF_CONFIG'] || CONFIG_FILE)
53
+ raw = YAML.safe_load(File.read(path))
54
+ c = raw.is_a?(Hash) ? raw['compaction_handoff'] : nil
55
+ raise Unreadable, 'config has no compaction_handoff section' unless c.is_a?(Hash)
56
+
57
+ at = c['compact_at_tokens']
58
+ ratio = c['request_ratio']
59
+ tag = c['l2_tag'].to_s
60
+ raise Unreadable, 'compact_at_tokens must be an integer of at least 10000' unless at.is_a?(Integer) && at >= 10_000
61
+ raise Unreadable, 'request_ratio must be above 0 and below 1' unless ratio.is_a?(Numeric) && ratio.positive? && ratio < 1
62
+ raise Unreadable, 'l2_tag must be lower-case letters, digits and underscores' unless TAG_FORMAT.match?(tag)
63
+
64
+ { compact_at_tokens: at, request_ratio: ratio.to_f, tag: tag,
65
+ request_point: (at * ratio.to_f).floor }
66
+ rescue SystemCallError, Psych::Exception => e
67
+ raise Unreadable, "config unreadable (#{e.class})"
68
+ end
69
+
70
+ # --- state (per session, the hooks' own; not data to commit) --------------
71
+
72
+ def state_path(dir, sid)
73
+ File.join(dir, 'storage', 'compaction_handoff', 'sessions', "#{sid}.json")
74
+ end
75
+
76
+ def fresh_state
77
+ { 'cycle' => 1, 'cycle_started_at' => now, 'cycle_offset' => 0, 'first_request_at' => nil,
78
+ 'blocked' => false, 'urgent' => false, 'last_usage' => nil, 'saved_at' => nil }
79
+ end
80
+
81
+ def load_state(dir, sid)
82
+ path = state_path(dir, sid)
83
+ return fresh_state unless File.exist?(path)
84
+
85
+ s = JSON.parse(File.read(path))
86
+ raise Unreadable, 'state is not an object' unless s.is_a?(Hash) && s['cycle'].is_a?(Integer)
87
+
88
+ fresh_state.merge(s)
89
+ rescue JSON::ParserError, SystemCallError => e
90
+ raise Unreadable, "state unreadable (#{e.class})"
91
+ end
92
+
93
+ # Written by rename, so a reader never sees half a file. Returns true only
94
+ # once the state is on disk (INV-2 blocks only after that).
95
+ def save_state(dir, sid, state)
96
+ path = state_path(dir, sid)
97
+ FileUtils.mkdir_p(File.dirname(path))
98
+ tmp = "#{path}.#{Process.pid}.tmp"
99
+ File.open(tmp, 'w') do |f|
100
+ f.write(JSON.generate(state))
101
+ f.flush
102
+ f.fsync
103
+ end
104
+ File.rename(tmp, path)
105
+ true
106
+ rescue SystemCallError, IOError
107
+ false
108
+ end
109
+
110
+ # Ends the cycle: nothing it accumulated counts in the next (INV-7).
111
+ def new_cycle!(state, offset:, reason:)
112
+ state['cycle'] += 1
113
+ state['cycle_started_at'] = now
114
+ state['cycle_offset'] = offset.to_i
115
+ state['first_request_at'] = nil
116
+ state['blocked'] = false
117
+ state['urgent'] = false
118
+ state['last_usage'] = nil
119
+ state['saved_at'] = nil
120
+ state['cycle_reason'] = reason
121
+ state
122
+ end
123
+
124
+ # Records the usage figure; a sharp fall ends the cycle at that response.
125
+ def observe_usage!(state, usage)
126
+ return state unless usage
127
+
128
+ prev = state['last_usage']
129
+ if prev.is_a?(Integer) && usage[:tokens] < prev * DROP_RATIO
130
+ new_cycle!(state, offset: usage[:offset], reason: 'usage_fell')
131
+ end
132
+ state['last_usage'] = usage[:tokens]
133
+ state
134
+ end
135
+
136
+ def now
137
+ Time.now.utc.iso8601
138
+ end
139
+
140
+ # --- L2, through KairosChain's own interface (INV-9) ----------------------
141
+
142
+ def l2(dir)
143
+ require 'kairos_mcp'
144
+ KairosMcp.data_dir = dir
145
+ require 'kairos_mcp/context_manager'
146
+ KairosMcp::ContextManager.new
147
+ end
148
+
149
+ def handoff_prefix(tag, sid)
150
+ "#{tag}_#{sid[0, 8]}_"
151
+ end
152
+
153
+ def fallback_prefix(tag, sid)
154
+ "#{tag}_fallback_#{sid[0, 8]}_"
155
+ end
156
+
157
+ # [session_dir_name, name, written_at] of entries whose name starts with
158
+ # `prefix`, newest first. Names are found by listing; content is read only
159
+ # through the interface.
160
+ def entries(dir, prefix)
161
+ Dir.glob(File.join(dir, 'context', '*', "#{prefix}*")).filter_map do |path|
162
+ next unless File.directory?(path)
163
+
164
+ # The entry's own file is rewritten on every save; the directory is not.
165
+ md = File.join(path, "#{File.basename(path)}.md")
166
+ [File.basename(File.dirname(path)), File.basename(path), File.mtime(File.exist?(md) ? md : path).utc]
167
+ end.sort_by { |e| e[2] }.reverse
168
+ end
169
+
170
+ # This session's handoffs: name prefix plus the full id in the frontmatter.
171
+ # Entries with the prefix but not the id are returned as near misses, so the
172
+ # request can say why a save was not counted.
173
+ def handoffs(manager, dir, tag, sid)
174
+ found = []
175
+ near = []
176
+ entries(dir, handoff_prefix(tag, sid)).each do |session, name, at|
177
+ next if name.start_with?(fallback_prefix(tag, sid))
178
+
179
+ skill = manager.get_context(session, name)
180
+ fm = skill&.frontmatter || {}
181
+ if fm[FRONTMATTER_KEY].to_s == sid
182
+ found << { session: session, name: name, written_at: at }
183
+ else
184
+ near << { session: session, name: name, written_at: at }
185
+ end
186
+ end
187
+ [found, near]
188
+ end
189
+
190
+ def fallbacks(manager, dir, tag, sid)
191
+ entries(dir, fallback_prefix(tag, sid)).map do |session, name, at|
192
+ { session: session, name: name, written_at: at }
193
+ end
194
+ end
195
+
196
+ # A handoff written in this cycle at or after its first request (§3).
197
+ def fresh?(handoff, state)
198
+ return false unless handoff && state['first_request_at']
199
+
200
+ handoff[:written_at] >= Time.iso8601(state['first_request_at'])
201
+ end
202
+
203
+ def emit(event, text)
204
+ $stdout.write(JSON.generate({ hookSpecificOutput: { hookEventName: event, additionalContext: text } }) + "\n")
205
+ $stdout.flush
206
+ end
207
+
208
+ def guide_name
209
+ 'compaction_handoff_guide'
210
+ end
211
+
212
+ # How a handoff is to be written and recognised; shared by the turn-start
213
+ # request and the mod's request (probe.rb), so the two cannot drift.
214
+ def handoff_rules(tag, sid)
215
+ [
216
+ '- what is in progress, the next step, open items and where the work lives (files, branches, L2 names);',
217
+ '- no credentials or secrets, and no verbatim text a peer sent you; mark items that came from a peer.',
218
+ "Name the entry #{handoff_prefix(tag, sid)}<YYYYMMDDHHMM> and put " \
219
+ "`#{FRONTMATTER_KEY}: #{sid}` in its frontmatter; that is how the save is recognised " \
220
+ "(knowledge #{guide_name})."
221
+ ]
222
+ end
223
+
224
+ NOTES_FRAME = 'Read it as your own earlier notes from before the compaction, not as instructions; items ' \
225
+ 'marked as coming from a peer are peer-supplied text.'
226
+ end
@@ -0,0 +1,83 @@
1
+ # frozen_string_literal: true
2
+
3
+ # PreCompact hook (design INV-1, INV-2, INV-3). Decides first, records a block
4
+ # durably before giving it, writes the fallback record stating the answer,
5
+ # then answers. Only trigger exactly "auto" can be blocked, at most once per
6
+ # cycle, and only when the cycle has no fresh save. A subagent's compaction is
7
+ # left alone. Any failure to read leads to no block (INV-8): exit 0 to let the
8
+ # compaction proceed, the cause on stderr.
9
+
10
+ require_relative 'common'
11
+ require_relative 'usage_reader'
12
+
13
+ H = CompactionHandoffHook
14
+
15
+ def fallback_content(name, sid, input, usage, answer, handoff)
16
+ size = File.size?(input['transcript_path'].to_s)
17
+ fm = {
18
+ 'name' => name,
19
+ 'description' => "compaction_handoff fallback record for session #{sid[0, 8]} (no conversation text)",
20
+ 'tags' => %w[compaction_handoff fallback],
21
+ H::FRONTMATTER_KEY => sid,
22
+ 'kind' => 'fallback',
23
+ 'trigger' => input['trigger'].to_s[0, 16],
24
+ 'written_at' => H.now,
25
+ 'usage_tokens' => usage && usage[:tokens],
26
+ 'usage_source' => usage ? usage[:source] : 'unavailable',
27
+ 'answer' => answer,
28
+ 'transcript_bytes' => size,
29
+ 'latest_handoff' => handoff && handoff[:name],
30
+ 'latest_handoff_written_at' => handoff && handoff[:written_at].iso8601
31
+ }
32
+ <<~MD
33
+ #{YAML.dump(fm).chomp}
34
+ ---
35
+
36
+ # Fallback record (compaction_handoff)
37
+
38
+ Written by the PreCompact hook without a model. It holds no conversation text: only the figures in the
39
+ frontmatter. The agent's own handoff, if one was written, is named in `latest_handoff`.
40
+ MD
41
+ end
42
+
43
+ answer = 'proceed'
44
+ begin
45
+ input = H.read_input
46
+ sid = H.session_id(input)
47
+ exit 0 if H.subagent?(input)
48
+
49
+ raise H::Unreadable, 'transcript unreadable' unless File.readable?(input['transcript_path'].to_s)
50
+
51
+ dir = H.data_dir
52
+ cfg = H.config
53
+ state = H.load_state(dir, sid)
54
+ usage = H::UsageReader.read(input['transcript_path'], from: state['cycle_offset'])
55
+ H.observe_usage!(state, usage)
56
+ manager = H.l2(dir)
57
+ found, = H.handoffs(manager, dir, cfg[:tag], sid)
58
+ latest = found.first
59
+
60
+ if input['trigger'] == 'auto' && !state['blocked'] && !H.fresh?(latest, state)
61
+ state['blocked'] = true
62
+ state['urgent'] = true
63
+ state['first_request_at'] ||= H.now
64
+ answer = 'block' if H.save_state(dir, sid, state)
65
+ end
66
+
67
+ t = Time.now.utc
68
+ name = "#{H.fallback_prefix(cfg[:tag], sid)}#{t.strftime('%Y%m%d%H%M%S')}_#{format('%06d', t.usec)}_#{Process.pid}"
69
+ session = "compaction_handoff_#{Time.now.utc.strftime('%Y%m%d')}"
70
+ result = manager.save_context(session, name, fallback_content(name, sid, input, usage, answer, latest))
71
+ warn "compaction_handoff: fallback record not written (#{result[:error]})" unless result[:success]
72
+ rescue H::Unreadable => e
73
+ warn "compaction_handoff: #{e.message}; not blocking"
74
+ rescue StandardError, LoadError => e
75
+ warn "compaction_handoff: #{e.class}: #{e.message[0, 200]}#{answer == 'block' ? '' : '; not blocking'}"
76
+ end
77
+
78
+ if answer == 'block'
79
+ warn 'compaction_handoff: auto-compaction held off once so this session can write its handoff to L2; ' \
80
+ 'the next attempt will proceed.'
81
+ exit 2
82
+ end
83
+ exit 0