rubik 0.5.0 → 0.7.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.
@@ -0,0 +1,193 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../coeffects"
4
+ require_relative "../tools/result"
5
+
6
+ module Rubik
7
+ module Orchestrator
8
+ # Bounded tool execution behind `tools.call_timeout`. The dispatch seam
9
+ # runs the call on a worker thread and joins with the resolved budget.
10
+ # Ruby threads cannot be force-killed: an expired call is ABANDONED —
11
+ # it keeps running in the background and its result is discarded — so
12
+ # the budget bounds turn latency, not resource use. Budget off (nil)
13
+ # yields inline: byte-identical to the unwrapped seam.
14
+ module ToolTimeout
15
+ # Raised in the CALLER thread when the join budget expires. The
16
+ # dispatch seam's rescue converts it into an honest error Result so
17
+ # the turn continues.
18
+ class BudgetExceeded < StandardError
19
+ attr_reader :tool_name, :budget_seconds, :elapsed_seconds
20
+
21
+ def initialize(tool_name:, budget_seconds:, elapsed_seconds:)
22
+ @tool_name = tool_name
23
+ @budget_seconds = budget_seconds
24
+ @elapsed_seconds = elapsed_seconds
25
+ super("tool '#{tool_name}' exceeded the #{budget_seconds}s call budget")
26
+ end
27
+ end
28
+
29
+ ENV_KEY = "RUBIK_TOOLS_CALL_TIMEOUT"
30
+ OFF = :off
31
+
32
+ module_function
33
+
34
+ # Budget resolution precedence: an explicit env disable wins, then the
35
+ # per-tool override (off or budget), then the env / config global.
36
+ # Returns nil = off (inline execution).
37
+ def budget_for(config, canonical_name)
38
+ env = resolve_env_budget
39
+ return nil if env == OFF
40
+
41
+ override = resolve_override(config, canonical_name)
42
+ return nil if override == OFF
43
+ return override unless override.nil?
44
+
45
+ env.nil? ? resolve_config_budget(config) : env
46
+ end
47
+
48
+ # The seam entry point. budget nil ⇒ yield inline (no Thread.new — the
49
+ # "knob unset ⇒ byte-identical" contract; the tool is not even asked
50
+ # for its name). Otherwise the yield runs on a named worker thread; an
51
+ # expired join abandons the worker and raises BudgetExceeded in the
52
+ # caller.
53
+ def call(tool, config:, canonical_name: nil)
54
+ budget = budget_for(config, canonical_name)
55
+ return yield if budget.nil?
56
+
57
+ name = canonical_name || tool.name
58
+ result = nil
59
+ error = nil
60
+ # Distinguishes "worker never completed" (killed before the body /
61
+ # hard VM abort — no honest answer exists) from a legitimate nil
62
+ # return. A kill landing mid-body still runs the ensure, which reads
63
+ # as a nil result — the inline-parity residual this seam accepts.
64
+ done = false
65
+ t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
66
+ worker = Thread.new do
67
+ result = yield
68
+ # Re-raised verbatim in the caller below, preserving today's
69
+ # raise-path semantics for ANY exception class, not just
70
+ # StandardError. The re-raise carries the worker-side backtrace;
71
+ # dispatch-site frames are not prepended (the tool's own failure
72
+ # site is what matters for debugging).
73
+ rescue Exception => e # rubocop:disable Lint/RescueException
74
+ error = e
75
+ ensure
76
+ done = true
77
+ end
78
+ worker.name = "rubik-tool-#{name}"
79
+
80
+ unless worker.join(budget)
81
+ elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0
82
+ raise BudgetExceeded.new(tool_name: name, budget_seconds: budget, elapsed_seconds: elapsed)
83
+ end
84
+ raise error if error
85
+ raise StandardError, "tool worker for '#{name}' died without completing or raising" unless done
86
+
87
+ result
88
+ end
89
+
90
+ # Honest error result: names the tool and budget, discloses the
91
+ # abandonment, and points at the narrower-retry / override escapes.
92
+ def timeout_result(tool_name:, call_id:, exceeded:, duration_ms:)
93
+ msg = "Tool '#{tool_name}' timed out after #{exceeded.budget_seconds}s. " \
94
+ "The call was abandoned (it may still be running in the background) and its result was discarded. " \
95
+ "Retry with a narrower scope (e.g. add a 'path' or 'extension' filter), or adjust " \
96
+ "'tools.call_timeout_overrides' for this tool."
97
+ Rubik::Tools::Result.new(
98
+ tool_name: tool_name, call_id: call_id, status: :error,
99
+ error: "tool call timeout (budget #{exceeded.budget_seconds}s)", output: msg,
100
+ duration_ms: duration_ms,
101
+ metadata: { "timed_out" => true, "budget_seconds" => exceeded.budget_seconds }
102
+ )
103
+ end
104
+
105
+ # Observability door (mirrors MCP Manager#emit_mcp_event): post —
106
+ # never emit (drain) — so the dispatcher's dmesg door records the
107
+ # timeout under the "tools" subsystem. An unresolved bus, or a post
108
+ # refused by a stopped dispatcher (returns false without raising),
109
+ # falls back to the log; a failing emission never alters the tool
110
+ # result.
111
+ def emit_timeout_event(tool_name:, budget_seconds:, elapsed_seconds:, context:)
112
+ bus = Rubik::Coeffects.get(context, Rubik::Coeffects::EVENTS)
113
+ if bus.respond_to?(:post)
114
+ posted = bus.post(:tool_call_timeout, { tool: tool_name },
115
+ subsystem: :tools, level: :warn,
116
+ budget_seconds: budget_seconds, elapsed_seconds: elapsed_seconds.round(1))
117
+ return if posted
118
+
119
+ Rubik::Log.warn(:tools, "tool '#{tool_name}' exceeded the #{budget_seconds}s call budget " \
120
+ "(event bus refused the record; abandoned after #{elapsed_seconds.round(1)}s)")
121
+ else
122
+ Rubik::Log.warn(:tools, "tool '#{tool_name}' exceeded the #{budget_seconds}s call budget " \
123
+ "(abandoned after #{elapsed_seconds.round(1)}s)")
124
+ end
125
+ rescue StandardError => e
126
+ Rubik::Log.warn(:tools, "failed to emit tool timeout event for '#{tool_name}' " \
127
+ "(budget #{budget_seconds}s: #{e.class}: #{e.message})")
128
+ end
129
+
130
+ # "0" / "off" / "false" / "no" explicitly disable (beats the config
131
+ # file and per-tool overrides); any other non-positive number or
132
+ # garbage warns and falls through to config.
133
+ def resolve_env_budget
134
+ raw = ENV.fetch(ENV_KEY, nil)
135
+ return nil if raw.nil? || raw.strip.empty?
136
+ return OFF if ["off", "false", "no"].include?(raw.strip.downcase)
137
+
138
+ value = parse_seconds(raw)
139
+ if value.nil?
140
+ Rubik::Log.warn(:tools, "ignoring invalid #{ENV_KEY} #{raw.inspect}; falling back to config")
141
+ return nil
142
+ end
143
+ return OFF if value <= 0
144
+
145
+ value
146
+ end
147
+
148
+ # mcp.call_timeout mirror at the config boundary: an invalid value
149
+ # warns and lands on off — the knob must never fail a turn.
150
+ def resolve_config_budget(config)
151
+ raw = config&.fetch("tools.call_timeout", nil)
152
+ return nil if raw.nil?
153
+
154
+ value = parse_seconds(raw)
155
+ return value if value&.positive?
156
+
157
+ Rubik::Log.warn(:tools, "ignoring invalid tools.call_timeout #{raw.inspect} (expected a positive number); treating as off")
158
+ nil
159
+ end
160
+
161
+ # Canonical tool name => seconds. 0/false disables the budget for that
162
+ # tool (the per-tool escape hatch); a positive value replaces the
163
+ # global budget; garbage warns and inherits. Lookup uses key presence,
164
+ # not truthiness — a `false` override must survive the `||` shorthand.
165
+ def resolve_override(config, canonical_name)
166
+ overrides = config&.fetch("tools.call_timeout_overrides", nil)
167
+ return nil unless overrides.is_a?(Hash)
168
+
169
+ key = canonical_name.to_s
170
+ raw = overrides.key?(key) ? overrides[key] : overrides[key.to_sym]
171
+ return nil if raw.nil?
172
+
173
+ value = parse_seconds(raw)
174
+ return OFF if value.nil? && ["off", "false"].include?(raw.to_s.strip.downcase)
175
+ return OFF if value && value <= 0
176
+ return value if value
177
+
178
+ Rubik::Log.warn(:tools, "ignoring invalid call_timeout override for '#{canonical_name}' #{raw.inspect}; using the global budget")
179
+ nil
180
+ end
181
+
182
+ # Non-finite values (Infinity, NaN) are rejected: an infinite budget
183
+ # would silently block the turn forever, the exact failure this knob
184
+ # exists to bound.
185
+ def parse_seconds(raw)
186
+ value = Float(raw)
187
+ value&.finite? ? value : nil
188
+ rescue ArgumentError, TypeError
189
+ nil
190
+ end
191
+ end
192
+ end
193
+ end
@@ -52,9 +52,13 @@ module Rubik
52
52
  # "head_tail" (default, original behavior) keeps head + tail around the
53
53
  # omission notice; "head_only" keeps the message head — useful when the
54
54
  # actionable guidance at the tail must not crowd out the error header.
55
- # Truncator normalizes strings/symbols and falls back to head_tail on
56
- # unknown values.
57
- strategy = config["emergency_truncate_strategy"] || config[:emergency_truncate_strategy] || "head_tail"
55
+ # Truncator.resolve_strategy normalizes strings/symbols, falls back to
56
+ # head_tail on unknown values AND warns once — the same typo-honesty
57
+ # contract as the tools.truncation_strategy knob (issue #349).
58
+ strategy = Rubik::Tools::Truncator.resolve_strategy(
59
+ config["emergency_truncate_strategy"] || config[:emergency_truncate_strategy],
60
+ key: "context.emergency_truncate_strategy"
61
+ )
58
62
 
59
63
  history.each do |msg|
60
64
  next unless ConversationRows.row?(msg)
@@ -188,6 +188,12 @@ module Rubik
188
188
  @shell.warm_ast_graph(async: async)
189
189
  end
190
190
 
191
+ # Huge-root guidance (#356): boot and !context scan share the
192
+ # assessment and the once-per-session memo on the Shell.
193
+ def maybe_warn_huge_root!(strong_only: true)
194
+ @shell.maybe_warn_huge_root!(strong_only: strong_only)
195
+ end
196
+
191
197
  def build_tool_registry
192
198
  @shell.build_tool_registry
193
199
  end
@@ -49,9 +49,23 @@ module Rubik
49
49
  end
50
50
 
51
51
  private_class_method def self.handle_context_scan(ctx)
52
+ # Explicit opt-in point: weak signals (a plain gitless root) speak here.
53
+ ctx.maybe_warn_huge_root!(strong_only: false)
52
54
  ctx.context_index.full_scan
53
55
  ctx.warm_ast_graph(async: false)
54
- ctx.out.puts "Context index and AST symbol graph updated."
56
+ summary = ctx.context_index.status_summary
57
+ if ctx.context_index.files.empty?
58
+ # Scanner#scan swallows mid-walk aborts into a possibly empty
59
+ # index; claiming success here would loop the model forever.
60
+ ctx.out.puts "Context scan produced NO indexed files — the scan aborted partway (see the log for " \
61
+ "'context scan aborted') or the root has no indexable files. " \
62
+ "Tools will answer 'not ready' until a scan yields files."
63
+ elsif summary[:last_scan_aborted]
64
+ ctx.out.puts "Context scan finished PARTIALLY: #{summary[:file_count]} files indexed, but the scan " \
65
+ "aborted (#{summary[:last_scan_error]}). Results may be incomplete."
66
+ else
67
+ ctx.out.puts "Context index and AST symbol graph updated."
68
+ end
55
69
  rescue Errno::EACCES => e
56
70
  root_path = begin
57
71
  ctx.buffer_manager.root_dir
@@ -122,6 +136,7 @@ module Rubik
122
136
  ctx.out.puts " • Consumed Tokens : #{est_tokens} tokens (#{pct}% of usable capacity)"
123
137
  ctx.out.puts " • Active Turns : #{ctx.conversation_history.size} turn(s)"
124
138
  ctx.out.puts " • Indexed Files : #{summary[:file_count]} files"
139
+ ctx.out.puts " • Index State : PARTIAL — last scan aborted (#{summary[:last_scan_error]})" if summary[:last_scan_aborted]
125
140
  ctx.out.puts " • AST Symbol Count : #{ast_symbols_count} symbols"
126
141
  ctx.out.puts "=================================="
127
142
  guidance = Rubik::Tools::DiagnosticReporter.render_context_status_guidance(
@@ -159,6 +174,7 @@ module Rubik
159
174
  ctx.out.puts "Estimated Prompt Tokens: #{est_tokens} / #{ceiling} tokens #{bar_str}"
160
175
  ctx.out.puts "Compaction Strategy: #{strategy}"
161
176
  ctx.out.puts "Indexed Files: #{summary[:file_count]}, AST Symbols: #{ast_symbols_count}"
177
+ ctx.out.puts "Index State: PARTIAL — last scan aborted (#{summary[:last_scan_error]})" if summary[:last_scan_aborted]
162
178
  ctx.out.puts "============================================="
163
179
  return unless (args && (args.include?("--guidance") || args.include?("-g"))) || est_tokens > (ceiling * 0.8)
164
180
 
@@ -270,6 +270,13 @@ module Rubik
270
270
  private_class_method def self.suspend_goal_turn(ctx, orchestrator:, goal_state:, goal_ledger:,
271
271
  goal_text:, goal_id:, record_pair:, reason:, tokens: nil)
272
272
  attempt = suspended_attempt(ctx, goal_id) + 1
273
+ # Ledger kimliği askıdan ÖNCE okunur: suspend! → ledger.suspend!
274
+ # sırası metanın bu turun token'larını içermesi için zorunlu,
275
+ # ama o damga storage_id'yi değiştirdiği için sonradan atanan id
276
+ # SUSPEND_EVENT'e geç kalırdı — ilk askıda kronik satırı slug
277
+ # kimliğine düşer, ledger= bağlantısı kaybolurdu.
278
+ # resume_cross_process ile aynı uçuş-içi atama önceliği.
279
+ goal_state.ledger_id = goal_ledger.snapshot[:storage_id] if goal_ledger
273
280
  goal_state.suspend!(reason, tokens: tokens)
274
281
  goal_ledger&.suspend!(suspend_stamp_meta(goal_state, goal_id, reason, attempt))
275
282
  registry = goal_registry_for(ctx)
@@ -16,7 +16,8 @@ module Rubik
16
16
  Parts = ServiceCatalog.parts_struct
17
17
 
18
18
  def self.build(config:, root_dir: nil, event_bus: nil, buffer_manager: nil, snapshot_store: nil, dmesg: nil, dispatcher: nil, init: nil)
19
- effective_root = File.expand_path(root_dir || buffer_manager&.root_dir || config&.root_dir || Dir.pwd)
19
+ fallback_root = (ENV["RUBIK_TEST"] == "1" && ENV.fetch("RUBIK_TEST_ROOT", nil)) || Dir.pwd
20
+ effective_root = File.expand_path(root_dir || buffer_manager&.root_dir || config&.root_dir || fallback_root)
20
21
  scope = ServiceCatalog::Scope.new(
21
22
  root_dir: effective_root,
22
23
  overrides: {
@@ -82,7 +82,11 @@ module Rubik
82
82
  clean_raw = Rubik::Security::Redactor.redact(parsed.raw)
83
83
  @recorder&.record_repl_command(clean_raw, output_text)
84
84
  # Plan 61 D-8: bound what a bang command leaves in LLM memory; the recorder keeps the full text.
85
- trunc = Rubik::Tools::Truncator.truncate(output_text, max_chars: @config.fetch("tools.max_output_chars", 12_000), strategy: :head_tail)
85
+ max_chars = @config.fetch("tools.max_output_chars", Rubik::Tools::Truncator::DEFAULT_MAX_CHARS)
86
+ # Deliberately context-scoped (issue #349 F8): truncation_strategy is a
87
+ # tool-output contract (the two orchestrator planes); bang-command echo
88
+ # is REPL history capture and stays head_tail, outside the knob's promise.
89
+ trunc = Rubik::Tools::Truncator.truncate(output_text, max_chars: max_chars, strategy: :head_tail)
86
90
  @conversation_history << { role: "user", content: clean_raw.delete_prefix("!") } # bangs stay out of LLM history; recorder keeps the literal
87
91
  @conversation_history << { role: "assistant", content: trunc[:truncated] ? trunc[:text] : output_text }
88
92
  trim_conversation_window!
@@ -141,7 +141,11 @@ module Rubik
141
141
  # default (RUBIK_TEST=1 warms synchronously-off) so the schema entry
142
142
  # never forces async warm in tests.
143
143
  warm_async = Platform.async_knob(@config, "ast.async_warm")
144
- warm_ast_graph(async: warm_async)
144
+ maybe_warn_huge_root!
145
+ # A strong huge-root signal skips the boot warm walk: the index
146
+ # stays empty and tools answer the honest not-ready message until
147
+ # an explicit '!context scan' opts in. Warning only — never a block.
148
+ warm_ast_graph(async: warm_async) unless skip_huge_root_boot_scan?
145
149
  register_default_commands
146
150
  Rubik.current_shell = self
147
151
  Rubik.runtime_manager = @runtime_manager
@@ -159,6 +163,52 @@ module Rubik
159
163
  wire_subagent_events!
160
164
  end
161
165
 
166
+ # Huge-root guidance: classify the session root with cheap probes,
167
+ # print ONE guidance notice per session, and (via skip_huge_root_boot_scan?)
168
+ # gate the boot warm walk. Boot warns on STRONG signals only — a plain
169
+ # gitless root stays silent so ordinary sessions and tests see no new
170
+ # output; the weak gitless aggravator surfaces at the explicit
171
+ # '!context scan' (strong_only: false). Memoized so the scan reuses
172
+ # the assessment without a second git spawn.
173
+ def maybe_warn_huge_root!(strong_only: true)
174
+ return unless @config.nil? || @config.fetch("context.huge_root_notice", true)
175
+ return if @huge_root_notice_shown
176
+
177
+ assessment = huge_root_assessment
178
+ return if strong_only && !assessment.strong
179
+
180
+ guidance = Rubik::Context::RootHeuristics.guidance(assessment, boot_scan_skipped: huge_root_boot_scan_skipped?)
181
+ return if guidance.empty?
182
+
183
+ @huge_root_notice_shown = true
184
+ if @terminal_guard
185
+ @terminal_guard.print_safe_notice(guidance)
186
+ else
187
+ @output&.puts guidance
188
+ end
189
+ end
190
+
191
+ def huge_root_assessment
192
+ @huge_root_assessment ||= Rubik::Context::RootHeuristics.assess(
193
+ @buffer_manager&.root_dir || @config&.root_dir || Dir.pwd,
194
+ home_dir: @config.respond_to?(:home_dir) ? @config.home_dir : nil
195
+ )
196
+ end
197
+
198
+ # Boot scans by default; only a STRONG signal (home dir, filesystem
199
+ # root, OS-data dir) skips the walk, and the knob re-enables it.
200
+ # Gitless roots are weak: guidance only, boot unaffected.
201
+ def skip_huge_root_boot_scan?
202
+ huge_root_boot_scan_skipped?
203
+ end
204
+
205
+ def huge_root_boot_scan_skipped?
206
+ return false unless huge_root_assessment.strong
207
+ return false unless @config.respond_to?(:fetch)
208
+
209
+ !@config.fetch("context.boot_scan_on_huge_root", false)
210
+ end
211
+
162
212
  # Async MCP boot progress notices (mcp-async-boot D8): subscribe BEFORE
163
213
  # the boot triggers so no event is missed, with the unsubscribe inverse
164
214
  # registered in the same breath (wire_subagent_events! pattern). Async
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "digest"
4
+
3
5
  module Rubik
4
6
  module Storage
5
7
  module Vakanuvis
@@ -35,6 +37,44 @@ module Rubik
35
37
  [["goal.#{payload[:goal_ordinal]}.#{state}", "#{head} (event=goal.#{payload[:goal_ordinal]}.#{state})"]]
36
38
  end
37
39
 
40
+ # Askı satırı (issue #350): anahtar PEEK sırası DEĞİL hedef
41
+ # kimliğidir. Askı peek'lediği sıraya ait görünür; araya başka bir
42
+ # goal bitişi girerse peek yanlış kayda bağlanır, iki askı aynı
43
+ # peek'i paylaşınca dedup ikinci satırı yutar. Kimlik = ledger_id
44
+ # (goal.ledger açıkken post_lifecycle'nin damgası), yoksa goal
45
+ # metninin slug'ı; steps + hata özeti anahtara işlenir — gerçek
46
+ # yeniden teslim düşer, içerik değişen askı kalır. Satır goal=
47
+ # tek-satırını da taşır: sıra bağlantısı kalkınca metnin kendisi
48
+ # dürüst bağdır (goal kaydı askıda henüz mint edilmez).
49
+ def suspend_line(seq, payload)
50
+ ledger = payload[:ledger_id].to_s
51
+ identity = ledger.empty? ? Vocabulary.slug(payload[:goal]) : ledger
52
+ head = "- [#{seq}] goal status=suspended steps=#{payload[:steps]}/#{payload[:max_steps]}"
53
+ head += " error=#{one_line(payload[:last_error], 80)}" unless payload[:last_error].to_s.empty?
54
+ head += " ledger=#{one_line(ledger, 40)}" unless ledger.empty?
55
+ head += " goal=#{one_line(payload[:goal], 60)}"
56
+ error = payload[:last_error].to_s
57
+ err_part = error.empty? ? "ok" : Digest::SHA256.hexdigest(error)[0, 8]
58
+ key = "goal.suspend.#{identity}.#{payload[:steps]}.#{err_part}"
59
+ [[key, "#{head} (event=#{key})"]]
60
+ end
61
+
62
+ # Olay-kimliği eki (issue #351 F7): handle_event'in kurtarma
63
+ # günlüğü tek başına kind ile askı satırını bitiş satırından
64
+ # ayırt edemez — düşen kronik satırının kimliği status + goal
65
+ # tek-satırıdır (bitiş ayrıca maintain(goal_end: true)'i atlar).
66
+ # Üretilemezse boş dizgi; günlük satırı asla patlamaz.
67
+ def event_context(kind, payload)
68
+ return "" unless payload.is_a?(Hash)
69
+
70
+ case kind
71
+ when :goal then " status=#{payload[:status]} goal=#{one_line(payload[:goal], 40)}"
72
+ when :subagent then " id=#{payload[:storage_id] || payload[:id]} state=#{payload[:state]}"
73
+ when :turn then " kind=#{payload[:kind]} prompt=#{one_line(payload[:prompt], 40)}"
74
+ else ""
75
+ end
76
+ end
77
+
38
78
  # Kök-turn satırı (root-turn planı 2026-10-04): REPL turn'ünün
39
79
  # deterministik özeti. Boş alan (tools/tokens) satırda görünmez;
40
80
  # ordinal harness-lokal sayaçtan gelir, anahtar turn.<n>.<kind>.
@@ -64,13 +104,20 @@ module Rubik
64
104
  "goal: #{text}"
65
105
  end
66
106
 
67
- # Satır ekleme + tekilleştirme: body'de anahtarı olan satır bir
68
- # daha yazılmaz (olay yeniden teslimi — resume sonrası ikinci
69
- # tamamlanma gibi — yinelenen satır açmaz).
107
+ # Satır ekleme + tekilleştirme: body'de SATIR SONU (event=anahtar)
108
+ # taşıyan satır bir daha yazılmaz (olay yeniden teslimi — resume
109
+ # sonrası ikinci tamamlanma gibi — yinelenen satır açmaz). Bağ
110
+ # (end_with?) zorunludur: serbest metin alanları (goal=, error=,
111
+ # prompt= …) bir "(event=X)" dizgisi TAŞIYABİLİR; gövde-geniş
112
+ # include taraması o dizgiyi sahte anahtar sayıp gelecekteki
113
+ # gerçek X satırını sessizce yutardı (review #353: zehirlenmiş
114
+ # dedup). Anahtar daima satırı bitirdiğinden bağ tarama hem dürüst
115
+ # hem ucuzdur.
70
116
  def append(store, ref:, title:, tags: Vocabulary::ANNAL_TAGS, links: {}, lines: [])
71
117
  existing = store.get(type: "note", id: ref)
72
118
  body = existing ? existing["body"].to_s : ""
73
- fresh = lines.reject { |key, _line| body.include?("(event=#{key})") }
119
+ settled = body.lines.map(&:rstrip)
120
+ fresh = lines.reject { |key, _line| settled.any? { |l| l.end_with?("(event=#{key})") } }
74
121
  return existing if existing && fresh.empty?
75
122
 
76
123
  merged = ([body] + fresh.map { |_key, line| line }).reject { |l| l.to_s.strip.empty? }.join("\n")
@@ -25,11 +25,13 @@ module Rubik
25
25
  # v2 §4-V6: öneri sonundaki smoke-test sorgularının sayı sınırı.
26
26
  CHECK_LIMIT = 5
27
27
 
28
- def receipt(query:, target:, spawned:)
28
+ def receipt(query:, target:, spawned:, spawn_failed: false)
29
29
  head = "Digest queued (async): the chronicler will compile '#{AnnalWriter.one_line(query, 80)}' into '#{target}'."
30
30
  tail = if spawned
31
31
  "This call did NOT wait for the LLM — conclude your turn; recall it later with " \
32
32
  "vakanuvis(action: 'recall', query: '...') once compiled."
33
+ elsif spawn_failed
34
+ "The distiller spawn attempt failed (see dmesg) — the job stays queued and the spawn retries with the next digest or flush."
33
35
  else
34
36
  "No distiller run started yet (subagents.vakanuvis.distiller or the chronicler type may be " \
35
37
  "disabled) — the job stays queued and compiles when the distiller becomes available."
@@ -37,6 +39,16 @@ module Rubik
37
39
  "#{head} #{tail}"
38
40
  end
39
41
 
42
+ def duplicate_receipt(query, target)
43
+ "Digest already queued for '#{target}' (#{AnnalWriter.one_line(query, 60)}): the chronicler is " \
44
+ "compiling it — recall it later with vakanuvis(action: 'recall', query: '...')."
45
+ end
46
+
47
+ def full_receipt(target, capacity)
48
+ "Digest not accepted for '#{target}': capacity #{capacity} is full. " \
49
+ "Existing jobs are preserved; retry after a digest finishes."
50
+ end
51
+
40
52
  # Öneri şeması: ilk satır hedef ref (wiki.<slug>), gerisi gövde;
41
53
  # gövde sonunda isteğe bağlı `CHECK: <sorgu>` satırları (v2 §4-V6
42
54
  # smoke testi — en fazla CHECK_LIMIT adet, gövdeden AYIKLANIR,
@@ -128,7 +140,7 @@ module Rubik
128
140
  "read_file(path: '#{annal_uri}')"
129
141
  end
130
142
  Array(job[:transcript_uris]).each { |u| sources << "- Transcript: read_file(path: '#{u}')" }
131
- sources << "- Goal record: read_file(path: '#{store.uri_for('goal', job[:goal_id])}')" if job[:goal_id]
143
+ sources << "- Goal record: read_file(path: '#{store.uri_for('note', Vocabulary.goal_ref(job[:goal_ordinal]))}')" if job[:goal_ordinal]
132
144
  if (gaps = open_recall_gaps(store))
133
145
  sources << gaps
134
146
  end
@@ -58,7 +58,9 @@ module Rubik
58
58
  # submit_with_status aynı kabulü [makbuz, durum] ikilisi olarak
59
59
  # verir (:accepted|:duplicate|:full) — otomatik damıtım red'i
60
60
  # makbuz dizgesinden ayırt edebilsin diye (review #346).
61
- def submit_with_status(query, spawn: true)
61
+ # goal_ordinal: goal-end auto-digest'in kanıt hedefi (tarama kartı 1,
62
+ # 2026-11-01) — işe işlenir, brief goal kaydını kaynak gösterir.
63
+ def submit_with_status(query, spawn: true, goal_ordinal: nil)
62
64
  target = Vocabulary.wiki_ref(query)
63
65
  # v2 §4-V5: aynı hedefli iş zaten kuyrukta ya da uçuştaysa makbuz
64
66
  # 'already queued' varyantına düşer — çift doğum yok.
@@ -66,21 +68,18 @@ module Rubik
66
68
  next :duplicate if @digest_targets.key?(target)
67
69
  next :full if @digest_targets.size >= @max_digest_jobs
68
70
 
69
- @pending_digests << { query: query, target: target, transcript_uris: source_transcript_uris }
71
+ @pending_digests << Job.new(query: query, target: target, transcript_uris: source_transcript_uris, goal_ordinal: goal_ordinal)
70
72
  @digest_targets[target] = true
71
73
  :accepted
72
74
  end
73
- if admission == :duplicate
74
- return ["Digest already queued for '#{target}' (#{AnnalWriter.one_line(query, 60)}): the chronicler is " \
75
- "compiling it — recall it later with vakanuvis(action: 'recall', query: '...').", admission]
76
- end
77
- if admission == :full
78
- return ["Digest not accepted for '#{target}': capacity #{@max_digest_jobs} is full. " \
79
- "Existing jobs are preserved; retry after a digest finishes.", admission]
80
- end
75
+ return [DistillGate.duplicate_receipt(query, target), admission] if admission == :duplicate
76
+
77
+ return [DistillGate.full_receipt(target, @max_digest_jobs), admission] if admission == :full
81
78
 
82
79
  spawned = spawn ? spawn_job!(batch: false) : nil
83
- [DistillGate.receipt(query: query, target: target, spawned: !spawned.nil?), admission]
80
+ # REVIEW: patlak doğum "disabled" makbuzuyla yalanlanmasın (F2).
81
+ failed_spawn = spawn && spawned.nil? && spawn_allowed?
82
+ [DistillGate.receipt(query: query, target: target, spawned: !spawned.nil?, spawn_failed: failed_spawn), admission]
84
83
  end
85
84
 
86
85
  def submit(query, spawn: true) = submit_with_status(query, spawn: spawn)[0]
@@ -150,7 +149,7 @@ module Rubik
150
149
  # Salt-okunuma peeki (test/kurcalama yüzeyi): kuyruğun başını
151
150
  # gösterir — tüketmez. Üretim görünürlüğü aşağıdaki job_targets'tır.
152
151
  def peek_job(batch: false)
153
- @lock.synchronize { @pending_digests.first || (batch ? { batch: true } : nil) }
152
+ @lock.synchronize { @pending_digests.first || (batch ? Job.new(batch: true) : nil) }
154
153
  end
155
154
 
156
155
  # İş defteri görünümü (issue #100 P2b): kuyruktaki + uçuştaki
@@ -219,11 +218,15 @@ module Rubik
219
218
  @supervisor.respond_to?(:spawn) &&
220
219
  @supervisor.respond_to?(:type_registry) && @supervisor.type_registry.get(TYPE_NAME)
221
220
  end
221
+ # Genel durum sorgusu (inceleme turu 2): Harness, kabul edilen
222
+ # digest topic'lerinin hiç derlenemeyeceğini dürüstçe
223
+ # bildirmek için doğum kapısını sorabilir olmalı.
224
+ public :spawn_allowed?
222
225
 
223
226
  # Aşağısı YALNIZ @lock altından çağrılır (çağıran: submit /
224
227
  # spawn_job! / completion_event) — kendi kilidi almaz.
225
228
  def claim_job(batch: false)
226
- @pending_digests.shift || (batch ? { batch: true, transcript_uris: source_transcript_uris } : nil)
229
+ @pending_digests.shift || (batch ? Job.new(batch: true, transcript_uris: source_transcript_uris) : nil)
227
230
  end
228
231
 
229
232
  def restore_job(job)