kairos-chain 3.100.0 → 3.101.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: 3c610dc7518cd8df952cd41f62e05bb4fc6e63ec011403f8885ed1f9b74f65aa
4
- data.tar.gz: 8b1bf01b6465efa19c624d708625384bbb0f3c7262165650a782e4d6b85cb4bb
3
+ metadata.gz: a16d51cad2a913a4f5914035e68a301959234a5af6f0e16175caa51bcb3b436a
4
+ data.tar.gz: 816b44086375fa9a8f8d6eb3b2c5944f8e91edaeef4dc39b4fbf25c87c29ea23
5
5
  SHA512:
6
- metadata.gz: e4da00252c1ae24b431eed473dc164b3258ca9972808f41d031f6574c8d32a5f7c5b599e503c8e33108808e7df85c8c514b40bdde48f3540e89a55e56795bcba
7
- data.tar.gz: cd4a2186ed8c757816545cad57daebb7bd6338cc133d151d0a56f5ad424a8ef3d81a8e8e679292265f27e91ace2d29df38fb42f0fbc2650cc31fa51639ca8394
6
+ metadata.gz: 1842916505079de71ad956939b30acacf989c008b62654947d05dff6baf4260d94677e51c2cf332c40d4e317e6886f306644a0fc84125ec0188c9cbfc3cbc1ab
7
+ data.tar.gz: a8c4824c8aea908a7d0e6fca7131440e888dc767cdbfb4c656157ddc9cd63dbdc5e22d5643d93cb474625bc46e127c1f174e71e1b1c1a25ab89a1dc251d0b727
data/CHANGELOG.md CHANGED
@@ -6,6 +6,69 @@ This project follows [Semantic Versioning](https://semver.org/).
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [3.101.0] - 2026-11-20
10
+
11
+ ### Added — succession edges on the L2 save path; dream 0.4.0 digests read them, label membership and record checks
12
+
13
+ Implements dream_digest design v0.13. First use of dream_digest (0.3.0) showed three ways a digest could
14
+ misstate its sources: a change of mind read as a disagreement, a digest calling itself fresh while its
15
+ topic had grown, and no reader but its writer.
16
+
17
+ - **Core: succession edges.** An L2 node declares that it replaces or corrects an earlier L2 node in its
18
+ own frontmatter: `relations: [{type: replaces | corrects, target: "v1:<session_id>/<name>", part:
19
+ <optional>, grounds: {quote, by} | {contradicted_by}}]`. An edge is valid when it carries grounds and
20
+ its formal target exists (a soft-archived node exists). `ContextGraph.succession_edge_failures` states
21
+ the two conditions once, for the save path and for any reader. **`context_save` now refuses a save
22
+ whose `replaces` / `corrects` edge fails either one**, stores nothing and returns the reason; the
23
+ writer may save the node without the edge. Saves that declare no such edge are untouched, and
24
+ `informed_by` may still point forward. Other relation types, `supersedes` included, stay accepted and
25
+ declare no succession. A writer holds names and an edge stores only the formal form:
26
+ `ContextManager#formal_targets_for(name)` lists the nodes that bear a name, and a refusal for a missing
27
+ target names them.
28
+ - **dream 0.4.0 — what a digest reads.** The READ set is the selected nodes closed under succession: a
29
+ node that declares succession over a member is a member whether or not it carries the topic's tag, and
30
+ so is the target of a member's valid edge. The generation directive lists the declared edges as data,
31
+ states a replacement only where a valid edge declares one, does not compose edges, and labels every
32
+ other difference between sources as date-only. Selection by tag no longer aborts on a node whose
33
+ frontmatter does not parse. A soft-archive stub keeps the relations its node declared.
34
+ - **dream 0.4.0 — labels.** `read` evaluates two independent conditions now, for the caller, and stores
35
+ neither: drift (a source changed) and membership (the recorded selection rule, applied again and
36
+ closed, against the snapshot). A digest made from an explicit list, a node whose relations cannot be
37
+ read, and a store not read in full are membership-unknown, never fresh. Pass the `selection_rule`
38
+ that `package` and `refresh` return on to `write`.
39
+ - **dream 0.4.0 — events and checks.** A generation and a check are events in an append-only,
40
+ hash-chained log per topic (`dream/digest_events/<slug>.jsonl`), apart from the artifact. The latest
41
+ generation event of a topic is its current one; labels are given only to stored text whose hash is its
42
+ output hash, and other stored text is not shown. New modes `check_package` and `check` let a context
43
+ other than the author compare a digest with its sources. A check counts only when both identities were
44
+ supplied by the invoking layer (an authenticated HTTP user), they differ, and the text compared is the
45
+ generation's output; a check of other text is recorded and listed on no label. Over stdio no identity
46
+ is supplied, so checks are recorded and listed and none counts. New mode `targets` turns a node name
47
+ into formal targets.
48
+ - **dream 0.4.0 — access.** Nodes resolve under the roots core gives the caller's user context. A caller
49
+ that cannot read the whole READ set of a topic's current generation gets the reply a topic with no
50
+ digest gets, from every mode. A write whose snapshot names a source that no longer resolves is refused.
51
+ - **Upgrade notes.** A digest written by dream 0.3.0 has no generation event: it is not shown, and
52
+ `sweep` reports it for regeneration. The blockchain block of a digest event is now
53
+ `dream_digest_event` with the event id alone (was `dream_digest_generation` with the provenance
54
+ refs). dream 0.4.0 needs this core (`min_core_version` 3.101.0).
55
+ - Reviewed in two implementation-review rounds by nine seats; one blocking finding in round 1 (a write
56
+ that dropped a vanished source recorded too narrow an access scope), fixed, none in round 2. Left
57
+ open: a source edited between `package` and `write` is recorded with its new hash; the event log is
58
+ never compacted; a topic name is one namespace across user contexts.
59
+
60
+ ## [3.100.1] - 2026-11-18
61
+
62
+ ### Changed — multi_llm_review codex seat moves to gpt-6.2-astra
63
+
64
+ - The codex slot of the default roster runs `gpt-6.2-astra` (label `codex_gpt6.2-astra`), replacing
65
+ `gpt-6-astra`. Same slot and effort (high); roster size and reference ratios unchanged.
66
+ - Tested before the swap through the shipping adapter, prompt builder and verdict parser: two trials per
67
+ model on one function with three planted defects; both models found all three and put the verdict on
68
+ line one. 6.2 graded the same defects higher and used about 4% more total tokens. Not a calibration.
69
+ - Runs recorded under `codex_gpt6-astra` keep that label. L1 `multi_llm_review_workflow` 3.17.2 records
70
+ the change.
71
+
9
72
  ## [3.100.0] - 2026-11-04
10
73
 
11
74
  ### Added — compaction_handoff 0.2.0 and Kairomone 0.9.0 ship as SkillSet templates (opt-in)
@@ -25,6 +25,11 @@ module KairosMcp
25
25
  # (forward-compat) but skipped on traverse.
26
26
  KNOWN_TYPES = %w[informed_by].freeze
27
27
 
28
+ # Succession edges: an L2 node declares that it replaces or corrects another L2 node,
29
+ # wholly or in a named part. The edge is held by the node that replaces. Any other type
30
+ # name, and any mark kept outside relations[], declares no succession.
31
+ SUCCESSION_TYPES = %w[replaces corrects].freeze
32
+
28
33
  # Target canonical regex (v2.1 §2). Permissive enough to reference both
29
34
  # canonical session_ids (session_<8>_<6>_<8hex>) and the human-readable
30
35
  # forms already on disk (e.g. coaching_insights_20260327, received_skills).
@@ -58,6 +63,7 @@ module KairosMcp
58
63
  class SymlinkRejectedError < Error; end
59
64
  class PathResolutionError < Error; end
60
65
  class InvalidFrontmatterError < Error; end
66
+ class SuccessionRefusedError < Error; end
61
67
 
62
68
  module_function
63
69
 
@@ -150,6 +156,43 @@ module KairosMcp
150
156
  nil
151
157
  end
152
158
 
159
+ # True if a relations[] item is a succession edge.
160
+ def succession_edge?(item)
161
+ item.is_a?(Hash) && SUCCESSION_TYPES.include?(item['type'] || item[:type])
162
+ end
163
+
164
+ # The two conditions under which a succession edge is valid: it carries grounds, and its
165
+ # target, written in the formal form, exists under context_root (a soft-archived node
166
+ # exists). The same two are evaluated when a node is saved and whenever the edge is read;
167
+ # both callers use this method, each with its own context_root and at its own time.
168
+ #
169
+ # @return [Array<Symbol>] the conditions that fail (:no_grounds, :target_missing); [] = valid
170
+ def succession_edge_failures(item, context_root)
171
+ failures = []
172
+ failures << :no_grounds unless succession_grounds?(item['grounds'] || item[:grounds])
173
+ failures << :target_missing unless succession_target_exists?(item['target'] || item[:target], context_root)
174
+ failures
175
+ end
176
+
177
+ # Grounds are what made the change: the words, quoted, and whose words they are; or, for a
178
+ # correction of fact, a reference to the node that contradicts the replaced one. Their
179
+ # presence is checked. Whether quoted words were said, and whether a reference resolves,
180
+ # is not.
181
+ def succession_grounds?(grounds)
182
+ return false unless grounds.is_a?(Hash)
183
+
184
+ present = ->(key) { v = grounds[key] || grounds[key.to_sym]; v.is_a?(String) && !v.strip.empty? }
185
+ (present.call('quote') && present.call('by')) || present.call('contradicted_by')
186
+ end
187
+
188
+ # True if the target names a node that exists under context_root. A target that is
189
+ # malformed, dangling, or that cannot be resolved does not exist for this caller.
190
+ def succession_target_exists?(target, context_root)
191
+ resolve_target(target, context_root)[:status] == :ok
192
+ rescue Error
193
+ false
194
+ end
195
+
153
196
  # Recursively check that a value tree contains only SAFE_VALUE_TYPES.
154
197
  # Bounded by MAX_VALUE_NESTING to prevent SystemStackError from
155
198
  # pathological frontmatter input.
@@ -146,6 +146,26 @@ module KairosMcp
146
146
  target = item['target'] || item[:target]
147
147
  ContextGraph.resolve_target(target, @context_dir)
148
148
  end
149
+
150
+ refuse_failing_succession_edges!(relations)
151
+ end
152
+
153
+ # Formal targets (v1:<session id>/<name>) of every node under this manager's context root
154
+ # that bears the given name. A writer holds names; an edge stores only the formal form,
155
+ # which names one node.
156
+ #
157
+ # @param name [String] a context name
158
+ # @return [Array<String>] sorted formal targets; [] if the name is not a safe segment
159
+ def formal_targets_for(name)
160
+ return [] unless segments?(name)
161
+
162
+ session_dirs.filter_map do |session_dir|
163
+ node_file = File.join(session_dir, name, "#{name}.md")
164
+ next unless contained?(node_file) && File.file?(node_file)
165
+
166
+ target = "v1:#{File.basename(session_dir)}/#{name}"
167
+ target if ContextGraph.parse_target(target)
168
+ end.sort
149
169
  end
150
170
 
151
171
  # Delete a context
@@ -248,6 +268,46 @@ module KairosMcp
248
268
 
249
269
  private
250
270
 
271
+ # A save whose succession edge fails either validity condition is refused and stores
272
+ # nothing. Evaluated from what is on disk now, under this manager's context root (the
273
+ # saving principal's). Only succession edges are looked at, so a node that declares none
274
+ # is never refused here. Reading an edge evaluates the same conditions again and decides;
275
+ # this refusal anticipates that evaluation and does not replace it.
276
+ #
277
+ # @raise ContextGraph::SuccessionRefusedError
278
+ def refuse_failing_succession_edges!(relations)
279
+ relations.each_with_index do |item, idx|
280
+ next unless ContextGraph.succession_edge?(item)
281
+
282
+ failures = ContextGraph.succession_edge_failures(item, @context_dir)
283
+ next if failures.empty?
284
+
285
+ type = item['type'] || item[:type]
286
+ target = item['target'] || item[:target]
287
+ reasons = []
288
+ if failures.include?(:no_grounds)
289
+ reasons << 'it carries no grounds (grounds.quote with grounds.by, or grounds.contradicted_by)'
290
+ end
291
+ if failures.include?(:target_missing)
292
+ reasons << "its target #{target} does not exist#{formal_target_hint(target)}"
293
+ end
294
+ raise ContextGraph::SuccessionRefusedError,
295
+ "relations[#{idx}] (#{type}) is refused: #{reasons.join('; ')}. Nothing was stored. " \
296
+ 'Correct the edge, or save the node without it.'
297
+ end
298
+ end
299
+
300
+ # For a refused target: the nodes that do bear its name, so the writer can pick one.
301
+ def formal_target_hint(target)
302
+ name = ContextGraph.parse_target(target)&.fetch(:name)
303
+ candidates = name ? formal_targets_for(name) : []
304
+ return '' if candidates.empty?
305
+
306
+ shown = candidates.first(10)
307
+ more = candidates.size > shown.size ? " (#{candidates.size - shown.size} more)" : ''
308
+ " (nodes named #{name}: #{shown.join(', ')}#{more})"
309
+ end
310
+
251
311
  # True if a path built from a caller-supplied session_id / name still
252
312
  # resolves inside the context store.
253
313
  def contained?(path)
@@ -12,7 +12,11 @@ module KairosMcp
12
12
  end
13
13
 
14
14
  def description
15
- 'Save (create or update) a L2 context. No blockchain recording - free modification for temporary work.'
15
+ 'Save (create or update) a L2 context. No blockchain recording - free modification for temporary work. ' \
16
+ 'A node that replaces or corrects an earlier L2 node says so in its own frontmatter: ' \
17
+ 'relations: [{type: replaces|corrects, target: "v1:<session_id>/<name>", part: <optional>, ' \
18
+ 'grounds: {quote: <the words>, by: <whose words>} or {contradicted_by: <node>}}]. ' \
19
+ 'A save whose such edge has no grounds or names a node that does not exist is refused.'
16
20
  end
17
21
 
18
22
  def category
@@ -1,4 +1,4 @@
1
1
  module KairosMcp
2
- VERSION = "3.100.0"
2
+ VERSION = "3.101.0"
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
@@ -3,6 +3,7 @@
3
3
  require 'digest'
4
4
  require 'fileutils'
5
5
  require 'yaml'
6
+ require 'date'
6
7
  require 'zlib'
7
8
  require 'time'
8
9
 
@@ -349,6 +350,11 @@ module KairosMcp
349
350
  'has_references' => has_references,
350
351
  'summary' => summary
351
352
  }
353
+ # The edges a node declares are part of what it states to the context graph. A stub
354
+ # that dropped them would withdraw, by archiving, a succession the node declared.
355
+ %w[relations_schema relations].each do |key|
356
+ frontmatter[key] = original_meta[key] if original_meta.key?(key)
357
+ end
352
358
 
353
359
  includes = []
354
360
  includes << 'scripts/' if has_scripts
@@ -388,8 +394,11 @@ module KairosMcp
388
394
  # ---------------------------------------------------------------
389
395
 
390
396
  def extract_frontmatter(content)
391
- if content =~ /\A---\n(.*?)\n---/m
392
- YAML.safe_load($1, permitted_classes: [Symbol]) || {}
397
+ # Date and Time are permitted, as on the save path: a node with a date in its
398
+ # frontmatter must not read as empty here, or its stub would lose what it declares.
399
+ if content =~ /\A---\r?\n(.*?)\r?\n---/m
400
+ meta = YAML.safe_load($1, permitted_classes: [Symbol, Date, Time])
401
+ meta.is_a?(Hash) ? meta : {}
393
402
  else
394
403
  {}
395
404
  end
@@ -0,0 +1,160 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'digest'
4
+ require 'fileutils'
5
+ require 'json'
6
+ require 'time'
7
+
8
+ module KairosMcp
9
+ module SkillSets
10
+ module Dream
11
+ # DigestEvents — the generation and check events of dream_digest (design v0.13, I7).
12
+ #
13
+ # One append-only log per topic, kept apart from the digest artifact: the artifact is
14
+ # derived and may be deleted or regenerated without losing an event. An event is one
15
+ # line. The store, not the caller, sets what orders and identifies it: `seq`, `prev`
16
+ # (the id of the event before it), `recorded_at`, and `id`, the hash of everything else
17
+ # in the line. A log in which any line fails that chain is not read at all.
18
+ #
19
+ # This class has no method that changes or removes an event. It cannot stop a process
20
+ # with write access to the data directory from replacing the file; the chain makes a
21
+ # partial rewrite detectable, and the id anchored on the instance's blockchain by the
22
+ # tool makes a whole one detectable by audit. Labels do not consult the anchor.
23
+ class DigestEvents
24
+ class CorruptError < StandardError; end
25
+
26
+ # A verified log, oldest event first.
27
+ class Log
28
+ attr_reader :events
29
+
30
+ def initialize(events)
31
+ @events = events
32
+ end
33
+
34
+ # The latest generation event recorded for the topic: the same event for every reader.
35
+ def current_generation
36
+ @events.reverse_each.find { |e| e['kind'] == 'generation' }
37
+ end
38
+
39
+ def generation(id)
40
+ @events.find { |e| e['kind'] == 'generation' && e['id'] == id }
41
+ end
42
+
43
+ def checks_naming(generation_id)
44
+ @events.select { |e| e['kind'] == 'check' && e['generation'] == generation_id }
45
+ end
46
+ end
47
+
48
+ def initialize(base_dir)
49
+ @base_dir = base_dir
50
+ end
51
+
52
+ # Topic slugs that have a log.
53
+ def slugs
54
+ return [] unless Dir.exist?(@base_dir)
55
+
56
+ Dir.children(@base_dir).filter_map { |f| f[/\A([a-z0-9_]+)\.jsonl\z/, 1] }.sort
57
+ end
58
+
59
+ # @return [Log] empty when the topic has no log
60
+ # @raise [CorruptError] when the log does not verify
61
+ def load(slug)
62
+ path = path_for(slug)
63
+ return Log.new([]) unless File.exist?(path)
64
+
65
+ Log.new(verified(complete_lines(File.read(path, encoding: 'UTF-8'))))
66
+ end
67
+
68
+ # Append one event. The block receives the verified log as it stands under the lock and
69
+ # returns the event's fields; raising in the block appends nothing.
70
+ #
71
+ # @return [Hash] the event as recorded
72
+ def append(slug)
73
+ FileUtils.mkdir_p(@base_dir)
74
+ File.open(path_for(slug), File::RDWR | File::CREAT, 0o600, encoding: 'UTF-8') do |f|
75
+ f.flock(File::LOCK_EX)
76
+ lines = complete_lines(f.read)
77
+ events = verified(lines)
78
+ fields = yield Log.new(events)
79
+
80
+ event = seal(fields, seq: events.size + 1, prev: events.last && events.last['id'])
81
+ # A fragment left by an append that never completed was never an event; the next
82
+ # event starts where the last complete one ends.
83
+ kept = lines.sum { |l| l.bytesize + 1 }
84
+ f.truncate(kept)
85
+ f.seek(kept)
86
+ f.write("#{JSON.generate(event)}\n")
87
+ f.flush
88
+ f.fsync
89
+ event
90
+ end
91
+ end
92
+
93
+ private
94
+
95
+ def path_for(slug)
96
+ raise ArgumentError, "not a topic slug: #{slug.inspect}" unless slug.to_s.match?(/\A[a-z0-9_]+\z/)
97
+
98
+ File.join(@base_dir, "#{slug}.jsonl")
99
+ end
100
+
101
+ # Lines terminated by a newline. Bytes after the last newline are an append that did
102
+ # not complete.
103
+ def complete_lines(raw)
104
+ raw = raw.to_s
105
+ cut = raw.rindex("\n")
106
+ cut ? raw[0..cut].split("\n") : []
107
+ end
108
+
109
+ def verified(lines)
110
+ prev = nil
111
+ lines.each_with_index.map do |line, i|
112
+ event = begin
113
+ JSON.parse(line)
114
+ rescue JSON::ParserError, EncodingError
115
+ raise CorruptError, "event #{i + 1} is not a record"
116
+ end
117
+ ok = event.is_a?(Hash) && event['seq'] == i + 1 && event['prev'] == prev &&
118
+ event['id'] == event_id(event)
119
+ raise CorruptError, "event #{i + 1} does not verify" unless ok
120
+
121
+ prev = event['id']
122
+ event
123
+ end
124
+ end
125
+
126
+ def seal(fields, seq:, prev:)
127
+ event = stringify(fields)
128
+ %w[id seq prev recorded_at].each { |k| event.delete(k) }
129
+ event['seq'] = seq
130
+ event['prev'] = prev
131
+ event['recorded_at'] = Time.now.utc.iso8601(6)
132
+ event['id'] = event_id(event)
133
+ event
134
+ end
135
+
136
+ def event_id(event)
137
+ Digest::SHA256.hexdigest("dream_digest.event\0#{canonical(event.reject { |k, _| k == 'id' })}")
138
+ end
139
+
140
+ # JSON with keys in sorted order at every depth: one byte sequence per event content.
141
+ def canonical(value)
142
+ case value
143
+ when Hash then "{#{value.sort_by { |k, _| k.to_s }.map { |k, v| "#{JSON.generate(k.to_s)}:#{canonical(v)}" }.join(',')}}"
144
+ when Array then "[#{value.map { |v| canonical(v) }.join(',')}]"
145
+ else JSON.generate(value)
146
+ end
147
+ end
148
+
149
+ def stringify(value)
150
+ case value
151
+ when Hash then value.each_with_object({}) { |(k, v), acc| acc[k.to_s] = stringify(v) }
152
+ when Array then value.map { |v| stringify(v) }
153
+ when Symbol then value.to_s
154
+ else value
155
+ end
156
+ end
157
+ end
158
+ end
159
+ end
160
+ end