kairos-chain 3.102.0 → 3.104.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f92cefb68006ad142c4c25bf42b56118408706706c594dd277fbcc011166b355
4
- data.tar.gz: 874c9a039bcefa99c681edef56738e078977df4db5db6def05b1594cebe32106
3
+ metadata.gz: e97580dacef02f7ff394c9cb2161433f38e56db94d3802cd877c8c8e65ba3545
4
+ data.tar.gz: 6cc89ee2cd421c7c08622351c4d63d439cedf5850b4475d042a6913f5a0709fe
5
5
  SHA512:
6
- metadata.gz: ffa02e574a2d88a867a32bf09924e4d19dccd68eda6a2e7bccd053385f2770b53a1c5e72301fb0f36acb899540aa04df21e0ba964b4c2f3d7b627eac188f2422
7
- data.tar.gz: 4e99bc88884fa32696047393de4186e29f9d8f6c5a5972307e46a7dad90904458bd63947bbb5f6d335363cac41fb651e3e625fb076926aa8550b4819e5602535
6
+ metadata.gz: 29ba0269d2fdf9b5efe7b87e6bd1ab67b62084a60ee900835318f8719a4ead47b769584186f1ed4ed21a10df2146b83257c2de2c2c1d60b0fec2411dcbb5438e
7
+ data.tar.gz: 863ee1af47ce88ac412cfcefc2bba242ecba8191dd7235abc83229db7f645ddbed4f2403347560003d7df3eb9efa98042571dfaa0387d65c881ad038033db4d3
data/CHANGELOG.md CHANGED
@@ -6,6 +6,81 @@ This project follows [Semantic Versioning](https://semver.org/).
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [3.104.0] - 2026-11-28
10
+
11
+ ### Added — handoff 0.1.0: one command for the end-of-session handoff (opt-in SkillSet)
12
+
13
+ - New SkillSet `handoff`. `/handoff` has the session write a handoff to L2 with `context_save` and
14
+ then run `scripts/record.rb`. The script checks that the saved file exists and ties it to the
15
+ Claude Code session that wrote it.
16
+ - A handoff carries the writing session's estimate of priority in its frontmatter: `importance` and
17
+ `urgency`, each 1 to 5, with a one-line basis. The script copies the numbers from there. They are
18
+ the session's reading and not the operator's ruling.
19
+ - **Nothing outside L2 unless the instance asks.** `config/handoff.yml` ships with `log_file` empty.
20
+ When an instance names a file there, `/handoff` appends a comment block with the L2 name, the
21
+ priority and the resume command. A SessionEnd hook appends the last prompt the operator typed, the
22
+ model's final reply, the handoffs the session recorded (or the line that it recorded none) and the
23
+ resume command. Every line starts with `#` except the resume command, which is
24
+ `claude --resume <uuid>`, or `claude --resume "<title>"` when the title is made of letters,
25
+ digits, `_ . - /` and spaces.
26
+ - **Not in the core list.** It is installed only on request: `kairos-chain skillset install
27
+ handoff`, or `system_upgrade` with `names: ["handoff"]`. An upgrade check lists it as optional and
28
+ changes nothing for instances that do not install it. It adds no MCP tools, and installing it
29
+ records nothing on the chain (layer L2).
30
+ - **Claude Code only.** The hook and the script read Claude Code's session id, its SessionEnd input
31
+ and its transcript rows. The transcript format is internal and undocumented (checked on 2.1.332),
32
+ and the readers skip what they do not recognise. Hook input the hook cannot read ends quietly with
33
+ exit 0, so a copy delivered to another host does nothing there. A session end cannot ask the model
34
+ for anything, so a session that ends without `/handoff` gets the line
35
+ `L2 handoff: none saved in this session`.
36
+ - A relative `log_file` is read from the directory that holds the data directory, for the hook and
37
+ the script alike. Both write the log and the session's state under one lock, the log first.
38
+ - Known limits:
39
+ - A run cut between the log append and the state write can repeat a block or leave a handoff
40
+ unlisted at the next session end.
41
+ - The prompt and the reply shown are the last of each and are not always a pair.
42
+ - A title shared by two sessions makes the title form of the resume line ambiguous. The session
43
+ id is on the comment line above it.
44
+ - The scripts need the Ruby that runs KairosChain. An older `ruby` first on the host's PATH makes
45
+ the hook exit 1.
46
+ - Implementation review: one pre-flight falsifier and three rounds. New blocking findings by class
47
+ went 9, 10, 2. The seat that runs mutations was not convened in round 3 and untested behavior
48
+ became advisory there, so the third count is not comparable with the first two. In round 3 the
49
+ two persona reviewers, Cursor and Gemini approved, and Opus 5.5, Sonnet 5.5 and Codex asked for
50
+ one shared change (rows that start with a tag carrying attributes). That change was made after
51
+ the round. It was checked by the tests and against 133 real transcripts by its author, and no
52
+ seat has read it. 78 tests, and 89 single-check removals all fail them.
53
+
54
+ ## [3.103.0] - 2026-11-22
55
+
56
+ ### Added — trust_gate 0.1.0: an on-demand gate for trust boundaries (opt-in SkillSet)
57
+
58
+ - New SkillSet `trust_gate`. It asks four questions of a design or a diff that adds or changes an
59
+ entrance into an instance: an external connection, a credential, a run handed to another agent or
60
+ process, or outside text that a model will read. The questions are whether trust is attached to
61
+ verified content or identity and not to a location, whether authority is issued for one piece of
62
+ work and ends with it, whether outside text stays data whichever layer delivers it, and what a
63
+ compromised part could reach.
64
+ - It is a gate that is called, not a norm that is always on. The operator calls it by name. It
65
+ answers per place with file-and-line evidence, it does not block, and it fixes nothing. Every
66
+ report ends by saying that it is what one reading found and not a complete inventory.
67
+ - The SkillSet adds no MCP tools, no hooks and no config. It ships L1 `trust_boundary_questions`
68
+ 0.3.1 (the questions and the only definition of the answer form), a plugin skill for the calling
69
+ session, and the subagent `trust-gatekeeper`, which did not write what it judges.
70
+ - **Not in the core list.** It is installed only on request: `kairos-chain skillset install
71
+ trust_gate`, or `system_upgrade` with `names: ["trust_gate"]`. An upgrade check lists it as
72
+ optional and changes nothing for instances that do not install it.
73
+ - The subagent's tools are an allowlist (read, search, list a directory, retrieve the entry). On
74
+ Claude Code the host's own record showed exactly those tools for a fresh process, and those plus
75
+ the hand-back tool for a subagent. **The OpenCode projection drops the allowlist** and keeps only
76
+ the denial of Write, Edit and Bash, so on that host the judge holds more tools than the work
77
+ needs. A definition edited during a session is not picked up until a new session.
78
+ - The standard the judge obeys is looked up by name. An entry of the same name in an instance's own
79
+ knowledge store is returned before the SkillSet's entry, so an instance that already holds one
80
+ must remove it to use the shipped text.
81
+ - Design review: three rounds. New blocking findings went 9, 2, 0, and round 3 was 5 of 5 seats
82
+ APPROVE. One call of the gate used 119 to 173 thousand subagent tokens in the trial.
83
+
9
84
  ## [3.102.0] - 2026-11-20
10
85
 
11
86
  ### Added — llm_client 0.5.0: provider `antigravity` (the Antigravity CLI, `agy`)
@@ -1,4 +1,4 @@
1
1
  module KairosMcp
2
- VERSION = "3.102.0"
2
+ VERSION = "3.104.0"
3
3
  CHANGELOG_URL = "https://github.com/masaomi/KairosChain_2026/blob/main/CHANGELOG.md"
4
4
  end
@@ -0,0 +1,21 @@
1
+ # handoff — per-instance values (operator-owned).
2
+ handoff:
3
+ # A file that receives one block per /handoff and one block per session end.
4
+ # Empty (the shipped value) turns both off: the handoff then lives in L2 only.
5
+ # A relative path is read from the directory that holds the data directory
6
+ # (the project root in the usual layout); an absolute path or ~ also works.
7
+ # Example: log_file: command.log
8
+ log_file:
9
+ # Copy the last turn (the operator's last prompt and the final reply) into the
10
+ # session-end block, as comment lines.
11
+ last_turn: true
12
+ # Longest copy of the last turn, in lines. A longer one keeps its end.
13
+ last_turn_max_lines: 200
14
+ # SessionEnd reasons that write a block: the operator leaving, /clear, a switch
15
+ # to another session with /resume, logout. "other" is left out so that runs
16
+ # started by tools (claude -p) do not write.
17
+ end_reasons:
18
+ - prompt_input_exit
19
+ - clear
20
+ - resume
21
+ - logout
@@ -0,0 +1,390 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'yaml'
5
+ require 'time'
6
+ require 'date'
7
+ require 'digest'
8
+ require 'fileutils'
9
+
10
+ # Shared parts of the session-end hook and the record script.
11
+ # Claude Code layer: this file knows the hook input and the transcript rows.
12
+ # It lives in hooks/, outside lib/, so nothing on the KairosChain side reaches
13
+ # it by name. The transcript format is internal to Claude Code and changes
14
+ # between versions; every reader here returns nil when a row is not in the
15
+ # shape it knows, and the callers write their block without that part.
16
+ #
17
+ # Text: everything read here (stdin, files, environment) is taken as UTF-8
18
+ # whatever the locale says, and made valid before anything looks at it.
19
+ module HandoffHook
20
+ SESSION_ID = /\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/
21
+ L2_NAME = /\A[A-Za-z0-9][A-Za-z0-9_.-]{0,200}\z/
22
+ DEFAULT_END_REASONS = %w[prompt_input_exit clear resume logout].freeze
23
+ # A title written as a command: letters and digits of any script, then also
24
+ # _ . - / and space. Nothing a shell reads, and no leading dash, which
25
+ # `claude --resume` would take as an option.
26
+ PLAIN_TITLE = %r{\A[\p{L}\p{N}_][\p{L}\p{N}_.\-/ ]*\z}
27
+ # Whatever a reader of the log file may take as the end of a line.
28
+ LINE_BREAK = /\r\n?|[\n\v\f\u0085\u2028\u2029]/
29
+ CONTROL = /[\p{Cc}\p{Cf}\u2028\u2029]/
30
+ # Who wrote a user row. Its `origin` says so when it has one: `human` is the
31
+ # operator (also when the text starts with a tag, as a paste does), anything
32
+ # else is another writer (a plugin, a task notification). A row without an
33
+ # `origin` is the operator's unless it is the mark Claude Code leaves for an
34
+ # interrupted turn or starts with a tag, with or without attributes (the
35
+ # output of a local command, a shell line run with `!`); a slash command
36
+ # starts with a tag too and is kept, by its name.
37
+ HUMAN = 'human'
38
+ INTERRUPTED = /\A\[Request interrupted by user[^\]\n]*\]\z/
39
+ HOST_TAG = %r{\A\s*<([A-Za-z][A-Za-z0-9_-]*)(?=[\s/>])}
40
+ COMMAND_TAGS = %w[command-name command-message].freeze
41
+ COMMAND_NAME = %r{<command-name>([^<]+)</command-name>}
42
+ COMMAND_ARGS = %r{<command-args>(.*?)</command-args>}m
43
+ SYNTHETIC_MODEL = '<synthetic>'
44
+ KEPT_ENDS = 20
45
+ PRIORITY_KEYS = %w[importance urgency].freeze
46
+ PRIORITY_RANGE = (1..5).freeze
47
+
48
+ class Unreadable < StandardError; end
49
+
50
+ Config = Struct.new(:log_file, :last_turn, :last_turn_max_lines, :end_reasons, keyword_init: true)
51
+
52
+ module_function
53
+
54
+ # --- text -----------------------------------------------------------------
55
+
56
+ def utf8(value)
57
+ value.to_s.dup.force_encoding(Encoding::UTF_8).scrub
58
+ end
59
+
60
+ # A parsed JSON value with every string made valid (an escaped lone surrogate
61
+ # parses to a string that is not).
62
+ def clean(value)
63
+ case value
64
+ when String then value.scrub
65
+ when Array then value.map { |v| clean(v) }
66
+ when Hash then value.to_h { |k, v| [clean(k), clean(v)] }
67
+ else value
68
+ end
69
+ end
70
+
71
+ # --- inputs ---------------------------------------------------------------
72
+
73
+ def read_input(io = $stdin)
74
+ input = clean(JSON.parse(utf8(io.binmode.read)))
75
+ raise Unreadable, 'hook input is not a JSON object' unless input.is_a?(Hash)
76
+
77
+ path = input['transcript_path']
78
+ raise Unreadable, 'hook input carries a transcript path that is not a path' unless path.nil? || (path.is_a?(String) && !path.include?("\0"))
79
+
80
+ input
81
+ rescue JSON::ParserError
82
+ raise Unreadable, 'hook input is not JSON'
83
+ end
84
+
85
+ def session_id(input)
86
+ sid = input['session_id']
87
+ raise Unreadable, 'hook input carries no well-formed session id' unless sid.is_a?(String) && SESSION_ID.match?(sid)
88
+
89
+ sid
90
+ end
91
+
92
+ def subagent?(input)
93
+ input['transcript_path'].to_s.include?('/subagents/')
94
+ end
95
+
96
+ def config_file
97
+ named = utf8(ENV['HANDOFF_CONFIG'])
98
+ named.empty? ? File.join(skillset_dir, 'config', 'handoff.yml') : named
99
+ end
100
+
101
+ def config(path = config_file)
102
+ raw = YAML.safe_load(File.read(path, encoding: 'UTF-8').scrub)
103
+ c = raw.is_a?(Hash) ? raw['handoff'] : nil
104
+ raise Unreadable, "#{path} has no handoff section" unless c.is_a?(Hash)
105
+
106
+ max = c.fetch('last_turn_max_lines', 200)
107
+ raise Unreadable, 'last_turn_max_lines must be an integer of at least 1' unless max.is_a?(Integer) && max >= 1
108
+
109
+ reasons = c.fetch('end_reasons', DEFAULT_END_REASONS)
110
+ unless reasons.is_a?(Array) && reasons.all? { |r| r.is_a?(String) && !r.empty? }
111
+ raise Unreadable, 'end_reasons must be a list of names'
112
+ end
113
+
114
+ log_file = c['log_file']
115
+ raise Unreadable, 'log_file must be a path in quotes or empty' unless log_file.nil? || log_file.is_a?(String)
116
+
117
+ last_turn = c.fetch('last_turn', true)
118
+ raise Unreadable, 'last_turn must be true or false' unless [true, false].include?(last_turn)
119
+
120
+ Config.new(log_file: log_file.to_s.strip, last_turn: last_turn, last_turn_max_lines: max, end_reasons: reasons)
121
+ rescue Errno::ENOENT
122
+ raise Unreadable, "no config at #{path}"
123
+ rescue Psych::Exception => e
124
+ raise Unreadable, "config is not readable YAML: #{e.message}"
125
+ end
126
+
127
+ def skillset_dir
128
+ utf8(File.expand_path('..', __dir__))
129
+ end
130
+
131
+ # The data directory this copy of the SkillSet is installed in, unless the
132
+ # caller names another one.
133
+ def data_dir
134
+ named = utf8(ENV['KAIROS_DATA_DIR'])
135
+ named.empty? ? File.expand_path('../..', skillset_dir) : named
136
+ end
137
+
138
+ # nil when the instance has named no log file. A relative path is read from
139
+ # the directory that holds the data directory, for the hook and the record
140
+ # script alike: it is the one place both can find without the host's help.
141
+ def log_path(cfg)
142
+ return nil if cfg.log_file.empty?
143
+
144
+ # The home directory comes from the environment in the locale's encoding;
145
+ # it is put in as UTF-8 here so that the rest of the path can be any text.
146
+ named = cfg.log_file.sub(%r{\A~(?=/|\z)}) { utf8(Dir.home) }
147
+ File.expand_path(named, File.dirname(File.expand_path(data_dir)))
148
+ rescue ArgumentError, EncodingError => e
149
+ raise Unreadable, "log_file is not a usable path: #{e.message}"
150
+ end
151
+
152
+ # --- state: which handoffs a Claude Code session saved, which ends were logged
153
+
154
+ def state_dir
155
+ File.join(data_dir, 'storage', 'handoff')
156
+ end
157
+
158
+ def state_path(sid)
159
+ raise Unreadable, 'not a session id' unless SESSION_ID.match?(sid.to_s)
160
+
161
+ File.join(state_dir, "#{sid}.json")
162
+ end
163
+
164
+ # Reads the session's state, yields it, and puts the new state in place of
165
+ # the old in one step (a file under another name, then a rename), all under
166
+ # one lock for the directory. An interrupted run leaves the old state whole,
167
+ # and so does a block that raises. Both writers append to the log inside
168
+ # this block, so neither sees the other between its log line and its state.
169
+ def with_state(sid)
170
+ path = state_path(sid)
171
+ FileUtils.mkdir_p(state_dir)
172
+ File.open(File.join(state_dir, '.lock'), File::RDWR | File::CREAT, 0o600) do |lock|
173
+ lock.flock(File::LOCK_EX)
174
+ state = parse_state(File.file?(path) ? File.read(path, encoding: 'UTF-8') : '')
175
+ result = yield state
176
+ temp = "#{path}.#{Process.pid}.tmp"
177
+ File.write(temp, JSON.pretty_generate(state), perm: 0o600)
178
+ File.rename(temp, path)
179
+ result
180
+ end
181
+ end
182
+
183
+ def parse_state(raw)
184
+ state = clean(JSON.parse(utf8(raw)))
185
+ state = {} unless state.is_a?(Hash)
186
+ %w[handoffs ends].each { |key| state[key] = Array(state[key]).grep(Hash) }
187
+ state
188
+ rescue JSON::ParserError
189
+ { 'handoffs' => [], 'ends' => [] }
190
+ end
191
+
192
+ # --- the saved handoff ----------------------------------------------------
193
+
194
+ def frontmatter(file)
195
+ text = File.read(file, encoding: 'UTF-8').scrub
196
+ return {} unless text.start_with?('---')
197
+
198
+ block = text.split(/^---\s*$/, 3)[1]
199
+ data = YAML.safe_load(block.to_s, permitted_classes: [Date, Time])
200
+ data.is_a?(Hash) ? data : {}
201
+ rescue Psych::Exception, SystemCallError
202
+ {}
203
+ end
204
+
205
+ # The session's own estimate, read from the handoff it saved: importance and
206
+ # urgency, each 1 (low) to 5 (high). A value that is absent or out of range
207
+ # is left out, not replaced by a middle one.
208
+ def priority(file)
209
+ fm = frontmatter(file)
210
+ PRIORITY_KEYS.each_with_object({}) { |key, out| out[key] = fm[key] if rating?(fm[key]) }
211
+ end
212
+
213
+ def rating?(value)
214
+ value.is_a?(Integer) && PRIORITY_RANGE.cover?(value)
215
+ end
216
+
217
+ def priority_text(entry)
218
+ parts = PRIORITY_KEYS.filter_map { |k| "#{k} #{entry[k]}/5" if rating?(entry[k]) }
219
+ parts.empty? ? nil : "#{parts.join(', ')} (the session's estimate)"
220
+ end
221
+
222
+ # --- transcript -----------------------------------------------------------
223
+
224
+ def find_transcript(sid)
225
+ root = utf8(ENV['CLAUDE_CONFIG_DIR'])
226
+ root = File.join(utf8(Dir.home), '.claude') if root.empty?
227
+ projects = File.join(root, 'projects')
228
+ found = Dir.glob(File.join('*', "#{sid}.jsonl"), base: projects).map { |rel| File.join(projects, rel) }
229
+ found.select { |p| File.file?(p) }.max_by { |p| File.mtime(p) }
230
+ end
231
+
232
+ def read_rows(path)
233
+ return [] if path.to_s.empty? || !File.file?(path)
234
+
235
+ File.foreach(path, encoding: 'UTF-8').filter_map do |line|
236
+ row = JSON.parse(line)
237
+ clean(row) if row.is_a?(Hash)
238
+ rescue JSON::ParserError
239
+ nil
240
+ end
241
+ end
242
+
243
+ # The newest name of the session (--name and /rename both write such a row).
244
+ def title(rows)
245
+ row = rows.reverse_each.find { |r| r['type'] == 'custom-title' && r['customTitle'].is_a?(String) && !r['customTitle'].strip.empty? }
246
+ row && row['customTitle'].strip
247
+ end
248
+
249
+ def message(row)
250
+ row['message'].is_a?(Hash) ? row['message'] : {}
251
+ end
252
+
253
+ def text_blocks(content)
254
+ content.filter_map { |b| b['text'] if b.is_a?(Hash) && b['type'] == 'text' && b['text'].is_a?(String) }.join("\n")
255
+ end
256
+
257
+ # What the operator typed, or nil when the row is not a prompt.
258
+ def prompt_text(row)
259
+ return nil unless row['type'] == 'user' && !row['isMeta'] && !row['isCompactSummary']
260
+
261
+ writer = row['origin'].is_a?(Hash) ? row['origin']['kind'] : row['origin']
262
+ return nil unless writer.nil? || writer == HUMAN
263
+
264
+ content = message(row)['content']
265
+ text = case content
266
+ when String then content
267
+ when Array
268
+ return nil if content.any? { |b| b.is_a?(Hash) && b['type'] == 'tool_result' }
269
+
270
+ text_blocks(content)
271
+ end
272
+ return nil if text.to_s.strip.empty? || INTERRUPTED.match?(text.strip)
273
+
274
+ tag = text[HOST_TAG, 1]
275
+ return text.strip if writer == HUMAN || !tag
276
+ return nil unless COMMAND_TAGS.include?(tag) && (name = text[COMMAND_NAME, 1])
277
+
278
+ [name.strip, text[COMMAND_ARGS, 1].to_s.strip].reject(&:empty?).join(' ')
279
+ end
280
+
281
+ # An answer of the model. A row Claude Code wrote in the model's place (an
282
+ # API error, the placeholder for a turn that asked for no answer) is not one.
283
+ def reply_text(row)
284
+ return nil unless row['type'] == 'assistant' && !row['isApiErrorMessage']
285
+ return nil if message(row)['model'] == SYNTHETIC_MODEL
286
+
287
+ content = message(row)['content']
288
+ return nil unless content.is_a?(Array)
289
+
290
+ text = text_blocks(content).strip
291
+ text.empty? ? nil : text
292
+ end
293
+
294
+ # The last prompt that was answered, the final reply to it, and the mark that
295
+ # tells one session end from the next: the id of the row the reply sits in,
296
+ # or, for a row without one, a digest of the reply.
297
+ def last_turn(rows)
298
+ main = rows.reject { |r| r['isSidechain'] }
299
+ reply_at = main.rindex { |r| reply_text(r) }
300
+ return { prompt: nil, reply: nil, recap: nil, mark: nil } unless reply_at
301
+
302
+ reply = reply_text(main[reply_at])
303
+ uuid = main[reply_at]['uuid']
304
+ prompt_at = main[0...reply_at].rindex { |r| prompt_text(r) }
305
+ recap = main[reply_at..].reverse_each.find do |r|
306
+ r['type'] == 'system' && r['subtype'] == 'away_summary' && r['content'].is_a?(String)
307
+ end
308
+ { prompt: prompt_at && prompt_text(main[prompt_at]), reply: reply, recap: recap && recap['content'].strip,
309
+ mark: uuid.is_a?(String) && !uuid.empty? ? uuid : "sha256:#{Digest::SHA256.hexdigest(reply)}" }
310
+ end
311
+
312
+ # --- blocks ---------------------------------------------------------------
313
+
314
+ # The only way text reaches the log file as notes: every line gets the comment
315
+ # mark, and no character is left in it that a reader could take as a line end
316
+ # or act on (CONTROL covers every character LINE_BREAK names).
317
+ def comment(lines)
318
+ lines.map do |l|
319
+ l = utf8(l).gsub(CONTROL, ' ').rstrip
320
+ l.empty? ? '#' : "# #{l}"
321
+ end
322
+ end
323
+
324
+ def led(mark, text)
325
+ lines = text.to_s.split(LINE_BREAK, -1)
326
+ lines.each_with_index.map { |l, i| i.zero? ? "#{mark} #{l}" : (l.strip.empty? ? '' : " #{l}") }
327
+ end
328
+
329
+ def last_turn_lines(turn, max)
330
+ lines = []
331
+ lines.concat(led('❯', turn[:prompt])).push('') if turn[:prompt]
332
+ lines.concat(led('⏺', turn[:reply]))
333
+ lines.push('', "※ recap: #{turn[:recap].split(LINE_BREAK).map(&:strip).join(' ')}") unless turn[:recap].to_s.empty?
334
+ return lines if lines.size <= max
335
+
336
+ ["(the first #{lines.size - max} lines of the last turn are left out)"] + lines.last(max)
337
+ end
338
+
339
+ # live: the last line is a command, not a comment. A command line has one of
340
+ # two shapes only: the session id, or a plain title in double quotes. A title
341
+ # that is not plain is not written at all; the id resumes the same session.
342
+ def resume_lines(sid, title, live:)
343
+ raise Unreadable, 'not a session id' unless SESSION_ID.match?(sid.to_s)
344
+
345
+ lead = live ? '' : '# '
346
+ return ["#{lead}claude --resume #{sid}"] unless title.is_a?(String) && PLAIN_TITLE.match?(title)
347
+
348
+ ["# claude --resume #{sid}", %(#{lead}claude --resume "#{title}")]
349
+ end
350
+
351
+ def handoff_line(entry)
352
+ [["L2 handoff: #{entry['name']} (#{entry['l2_session']})", "saved #{entry['at']}"].join(', '),
353
+ priority_line(entry)].compact
354
+ end
355
+
356
+ def priority_line(entry)
357
+ text = priority_text(entry)
358
+ text && "priority: #{text}"
359
+ end
360
+
361
+ def handoff_block(entry, sid, title, now: Time.now)
362
+ lines = ["[handoff] #{stamp(now)}", "L2 handoff: #{entry['name']} (#{entry['l2_session']})",
363
+ priority_line(entry)].compact
364
+ resume = sid ? resume_lines(sid, title, live: false) : ['# (Claude Code session id unknown: no resume command)']
365
+ comment(lines) + resume
366
+ end
367
+
368
+ def session_end_block(sid:, title:, reason:, turn:, handoffs:, cfg:, now: Time.now)
369
+ head = ["[session end] #{stamp(now)} (#{reason})"]
370
+ body = cfg.last_turn ? last_turn_lines(turn, cfg.last_turn_max_lines) + [''] : []
371
+ saved = handoffs.empty? ? ['L2 handoff: none saved in this session'] : handoffs.flat_map { |h| handoff_line(h) }
372
+ comment(head + body + saved + ['Resume this session with:']) + resume_lines(sid, title, live: true)
373
+ end
374
+
375
+ def stamp(time)
376
+ time.strftime('%Y-%m-%d %H:%M')
377
+ end
378
+
379
+ # One empty line, then the block. The empty line is the only line this
380
+ # SkillSet writes that neither starts with the comment mark nor is a resume
381
+ # command.
382
+ def append(path, lines)
383
+ raise Unreadable, "the log file's directory does not exist: #{File.dirname(path)}" unless File.directory?(File.dirname(path))
384
+
385
+ File.open(path, 'a:UTF-8') do |f|
386
+ f.flock(File::LOCK_EX)
387
+ f.write("\n#{lines.join("\n")}\n")
388
+ end
389
+ end
390
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ # SessionEnd hook: appends one block to the instance's log file. Never blocks
4
+ # (SessionEnd cannot). Input it cannot read is taken as another host's call
5
+ # (the projector can deliver this hook to hosts other than Claude Code) and
6
+ # ends quietly, exit 0. A fault of this instance (config, log file, state) is
7
+ # exit 1 with the cause in one line on stderr.
8
+ require_relative 'common'
9
+
10
+ begin
11
+ begin
12
+ input = HandoffHook.read_input
13
+ sid = HandoffHook.session_id(input)
14
+ rescue HandoffHook::Unreadable
15
+ exit 0
16
+ end
17
+ exit 0 if HandoffHook.subagent?(input)
18
+
19
+ cfg = HandoffHook.config
20
+ log = HandoffHook.log_path(cfg)
21
+ exit 0 unless log
22
+ reason = input['reason']
23
+ exit 0 unless reason.is_a?(String) && cfg.end_reasons.include?(reason)
24
+
25
+ rows = HandoffHook.read_rows(input['transcript_path'])
26
+ turn = HandoffHook.last_turn(rows)
27
+ # A session in which the model answered nothing leaves nothing to come back to.
28
+ exit 0 unless turn[:reply]
29
+
30
+ HandoffHook.with_state(sid) do |state|
31
+ # The same final reply was already logged: the hook ran twice for one end,
32
+ # or the session was resumed and left again without a new answer.
33
+ next if state['ends'].any? { |e| e['mark'] == turn[:mark] }
34
+
35
+ block = HandoffHook.session_end_block(sid: sid, title: HandoffHook.title(rows), reason: reason, turn: turn,
36
+ handoffs: state['handoffs'], cfg: cfg)
37
+ # The block first, the mark second: a run cut between the two repeats the
38
+ # block at the next end; the other order would lose it.
39
+ HandoffHook.append(log, block)
40
+ state['ends'] = (state['ends'] + [{ 'mark' => turn[:mark], 'at' => Time.now.iso8601 }]).last(HandoffHook::KEPT_ENDS)
41
+ end
42
+ rescue HandoffHook::Unreadable, SystemCallError => e
43
+ warn "handoff: #{e.message}"
44
+ exit 1
45
+ rescue StandardError => e
46
+ warn "handoff: #{e.class}: #{HandoffHook.utf8(e.message).lines.first.to_s.strip}"
47
+ exit 1
48
+ end
@@ -0,0 +1,76 @@
1
+ ---
2
+ name: handoff
3
+ description: >
4
+ Write this session's handoff to L2 and record it against the session, in one
5
+ step. Use when the operator types /handoff, asks for a handoff, says the
6
+ session is ending or pausing, or asks to leave the work so it can be picked
7
+ up later. 引き継ぎ、handoff を残す、セッションを終える、中断する、続きは後日。
8
+ ---
9
+
10
+ # Handoff
11
+
12
+ One command for the end of a session or a pause in it. The handoff itself goes
13
+ to L2. A script then ties it to this Claude Code session, and writes the
14
+ instance's log file when the instance has named one.
15
+
16
+ Text typed after `/handoff` is a hint for the topic or the emphasis.
17
+
18
+ ## Steps
19
+
20
+ 1. **Save the handoff to L2** with `context_save`.
21
+ - Name: `handoff_<topic>_<YYYYMMDD>`, lowercase letters, digits and underscores.
22
+ - Frontmatter: `type: handoff`, `status: pending`, `date`, `tags`, and your
23
+ estimate of the priority of what is left to do:
24
+ - `importance`: integer 1 (low) to 5 (high). How much the remaining work
25
+ matters to what the operator has said they are working toward.
26
+ - `urgency`: integer 1 (low) to 5 (high). How soon it has to move: a
27
+ deadline, someone waiting, something that breaks or expires if left.
28
+ - `priority_basis`: one line naming what in the session each number rests
29
+ on (a date, the operator's words, a dependency).
30
+ These are your reading of the session, not the operator's ruling. Leave a
31
+ number out when the session gives no ground for it; do not fill in a
32
+ middle value. The script copies the numbers from this frontmatter, so they
33
+ are written once, here.
34
+ - Write for a reader who has none of this session's context and may be a
35
+ different model. The least a handoff carries:
36
+ - the state in one line (what is done, what is not);
37
+ - what the operator asked for and decided, in the operator's own words, quoted;
38
+ - what was changed and where: paths, branches, commits, and whether pushed;
39
+ - what was checked and how, and what was not checked;
40
+ - the first action of the next session;
41
+ - the decisions that are still the operator's.
42
+ - When this instance has its own convention for handoffs (an L1 entry, its
43
+ instruction mode, its memory), that convention wins over this list.
44
+
45
+ 2. **Record it.** Run, with the name you saved and the L2 session id that
46
+ `context_save` returned:
47
+
48
+ ```
49
+ ruby <data dir>/skillsets/handoff/scripts/record.rb --name <name> --session <L2 session id>
50
+ ```
51
+
52
+ `<data dir>` is `.kairos` under the project root unless `KAIROS_DATA_DIR`
53
+ says otherwise. Use an absolute path. The script checks that the saved file
54
+ exists, ties it to this Claude Code session, and appends a block to the log
55
+ file when one is configured. It prints what it did.
56
+
57
+ 3. **Report** to the operator: the L2 name and session, the importance and
58
+ urgency you gave with their basis, and what the script printed. The operator
59
+ can correct the numbers; then change the frontmatter with `context_save` and
60
+ run the script again. Then do the other end-of-session duties this instance's own
61
+ instructions list, if any.
62
+
63
+ ## What not to do
64
+
65
+ - Do not write the log file yourself. The script and the session-end hook are
66
+ its only writers, so that its blocks keep one shape.
67
+ - Do not report the handoff as recorded when the script failed. Give its error.
68
+ - Do not write the session-end block. The hook writes it when the session
69
+ ends, from the conversation record.
70
+
71
+ ## What happens at session end
72
+
73
+ When a log file is configured, the SessionEnd hook appends the last turn as
74
+ comment lines, the handoffs this session saved (or that it saved none), and the
75
+ resume command. A session that ends without `/handoff` is therefore still
76
+ findable, and visibly without a handoff.
@@ -0,0 +1,24 @@
1
+ {
2
+ "_comment": [
3
+ "handoff: SessionEnd appends one block to the instance's log file (config/handoff.yml, log_file).",
4
+ "With no log file named the hook does nothing. It never blocks. Hook input it cannot read (another",
5
+ "host's shape) ends quietly with exit 0; a fault of this instance (config, log file) is exit 1 with",
6
+ "the cause on stderr. The session is over when it runs, so it cannot ask the model for a handoff;",
7
+ "it records which handoffs the session saved, or that it saved none.",
8
+ "The projector merges this into the host settings under a _projected_by tag; nobody edits",
9
+ "settings.json by hand."
10
+ ],
11
+ "hooks": {
12
+ "SessionEnd": [
13
+ {
14
+ "hooks": [
15
+ {
16
+ "type": "command",
17
+ "command": "f=\"${KAIROS_DATA_DIR:-$CLAUDE_PROJECT_DIR/.kairos}/skillsets/handoff/hooks/session_end.rb\"; [ -f \"$f\" ] || exit 0; ruby \"$f\"",
18
+ "timeout": 20
19
+ }
20
+ ]
21
+ }
22
+ ]
23
+ }
24
+ }