@zalom/plastic 2.0.0-alpha.2 → 2.0.0-alpha.21

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 (127) hide show
  1. package/agents/plastic-enforcer.md +3 -1
  2. package/agents/plastic-executor.md +9 -3
  3. package/bin/test +24 -4
  4. package/hooks/call-budget +4 -0
  5. package/hooks/hooks.json +24 -0
  6. package/hooks/message-display +134 -0
  7. package/hooks/statusline +4 -27
  8. package/package.json +2 -2
  9. package/scripts/agent-report +8 -2
  10. package/scripts/dashboard.rb +297 -18
  11. package/scripts/doctor.rb +652 -5
  12. package/scripts/end-intent +219 -0
  13. package/scripts/hook-call-budget +222 -0
  14. package/scripts/hook-capture +25 -113
  15. package/scripts/hook-message-display +81 -0
  16. package/scripts/hook-record +12 -4
  17. package/scripts/hook-session-start +45 -7
  18. package/scripts/index-projection +74 -0
  19. package/scripts/intent-screen +77 -0
  20. package/scripts/lib/action_graph_shim.rb +277 -0
  21. package/scripts/lib/arm.rb +26 -1
  22. package/scripts/lib/atomic_write.rb +31 -0
  23. package/scripts/lib/compact_instructions.rb +5 -5
  24. package/scripts/lib/core_integrity.rb +71 -0
  25. package/scripts/lib/dashboard_screen.rb +40 -0
  26. package/scripts/lib/day_summary.rb +7 -2
  27. package/scripts/lib/doctor_core.rb +102 -5
  28. package/scripts/lib/doctor_session_ledger.rb +52 -0
  29. package/scripts/lib/graph_edges.rb +137 -0
  30. package/scripts/lib/graph_file.rb +246 -0
  31. package/scripts/lib/graph_tree.rb +98 -0
  32. package/scripts/lib/guarded_append.rb +155 -0
  33. package/scripts/lib/hook_registry.rb +28 -2
  34. package/scripts/lib/hook_replay.rb +211 -0
  35. package/scripts/lib/index_projection.rb +201 -0
  36. package/scripts/lib/installer_core.rb +141 -6
  37. package/scripts/lib/intent_screen.rb +309 -0
  38. package/scripts/lib/intent_screen_ansi.rb +262 -0
  39. package/scripts/lib/message_display.rb +586 -0
  40. package/scripts/lib/meter_watch.rb +179 -0
  41. package/scripts/lib/node_file.rb +214 -0
  42. package/scripts/lib/node_ids.rb +99 -0
  43. package/scripts/lib/node_ledger.rb +377 -0
  44. package/scripts/lib/node_packet.rb +908 -0
  45. package/scripts/lib/node_return.rb +199 -0
  46. package/scripts/lib/node_worktree.rb +337 -0
  47. package/scripts/lib/outcome_report.rb +440 -0
  48. package/scripts/lib/packet_wrapper.rb +132 -0
  49. package/scripts/lib/ready_set.rb +462 -0
  50. package/scripts/lib/release_guard.rb +16 -0
  51. package/scripts/lib/report_screen.rb +1967 -0
  52. package/scripts/lib/roadmap_graph.rb +210 -0
  53. package/scripts/lib/roadmap_migration.rb +95 -0
  54. package/scripts/lib/roadmap_queue.rb +155 -5
  55. package/scripts/lib/roadmap_render.rb +150 -0
  56. package/scripts/lib/roadmap_savepoint.rb +62 -12
  57. package/scripts/lib/runner_absorb.rb +620 -0
  58. package/scripts/lib/runner_answer.rb +206 -0
  59. package/scripts/lib/runner_core.rb +194 -0
  60. package/scripts/lib/runner_dispatch.rb +506 -0
  61. package/scripts/lib/runner_policy.rb +173 -0
  62. package/scripts/lib/runner_proposals.rb +275 -0
  63. package/scripts/lib/runner_rewind.rb +201 -0
  64. package/scripts/lib/runner_sweep.rb +231 -0
  65. package/scripts/lib/savepoint.rb +149 -12
  66. package/scripts/lib/screen_paint.rb +555 -0
  67. package/scripts/lib/screens/dashboard.rb +20 -0
  68. package/scripts/lib/screens/plan.rb +18 -0
  69. package/scripts/lib/screens/roadmap.rb +15 -0
  70. package/scripts/lib/session_git.rb +49 -18
  71. package/scripts/lib/session_ledger.rb +128 -0
  72. package/scripts/lib/session_usage.rb +190 -0
  73. package/scripts/lib/verify_intent.rb +33 -0
  74. package/scripts/lib/work_graph_validator.rb +201 -0
  75. package/scripts/meter-watch +57 -0
  76. package/scripts/node-packet +92 -0
  77. package/scripts/node-transition +291 -0
  78. package/scripts/outcome-report +74 -0
  79. package/scripts/plastic-lock +8 -1
  80. package/scripts/read-config +3 -3
  81. package/scripts/ready-set +126 -0
  82. package/scripts/release-check +118 -0
  83. package/scripts/report-screen +281 -0
  84. package/scripts/roadmap-graph +119 -0
  85. package/scripts/roadmap-savepoint +7 -0
  86. package/scripts/runner +397 -0
  87. package/scripts/savepoint-note +69 -0
  88. package/scripts/session-usage +56 -0
  89. package/scripts/spawn-preamble +9 -2
  90. package/scripts/validate-work-graph +39 -0
  91. package/scripts/verify-intent +2 -1
  92. package/skills/auto/SKILL.md +41 -34
  93. package/skills/auto/references/human-report-contract.md +136 -54
  94. package/skills/conventions/references/locks-and-worktrees.md +12 -0
  95. package/skills/dashboard/SKILL.md +13 -2
  96. package/skills/dashboard/templates/dashboard-global.md +1 -1
  97. package/skills/dashboard/templates/dashboard-project.md +2 -2
  98. package/skills/doctor/SKILL.md +10 -4
  99. package/skills/intent-continuing/SKILL.md +51 -41
  100. package/skills/intent-continuing/references/board-fill.md +9 -0
  101. package/skills/intent-continuing/references/boarding-matrix.md +6 -5
  102. package/skills/intent-continuing/references/context-management.md +1 -1
  103. package/skills/intent-ending/SKILL.md +36 -16
  104. package/skills/intent-executing/SKILL.md +21 -5
  105. package/skills/intent-executing/implementer-prompt.md +6 -1
  106. package/skills/intent-speccing/SKILL.md +7 -4
  107. package/skills/releasing/SKILL.md +39 -0
  108. package/skills/releasing/references/promotion-and-tagging.md +10 -6
  109. package/skills/releasing/references/release-lines.md +1 -1
  110. package/skills/roadmap/SKILL.md +26 -0
  111. package/skills/roadmap/references/file-format.md +10 -0
  112. package/templates/config.yml +3 -3
  113. package/templates/dashboard-screen.md +22 -0
  114. package/templates/display-fixture.md +21 -0
  115. package/templates/graph.md +16 -0
  116. package/templates/intent-screen.md +17 -0
  117. package/templates/node-decision.md +11 -0
  118. package/templates/node-research.md +11 -0
  119. package/templates/node-verify.md +13 -0
  120. package/templates/node-work.md +22 -0
  121. package/templates/outcome.md +19 -1
  122. package/templates/report-plan.md +15 -0
  123. package/templates/report-roadmap-delivered.md +10 -0
  124. package/templates/report-roadmap-plan.md +9 -0
  125. package/templates/report-roadmap-state.md +9 -0
  126. package/templates/report-state.md +11 -0
  127. package/templates/roadmap.md +13 -0
@@ -207,11 +207,37 @@ module SessionGit
207
207
 
208
208
  # --- commit message ------------------------------------------------------------
209
209
 
210
- # The first line of `summary`, truncated to MAX_SUBJECT_LENGTH characters,
211
- # with no trailer (spec D5).
210
+ # The first line of `summary`, cut at the last word boundary at or before
211
+ # MAX_SUBJECT_LENGTH characters, falling back to the hard slice when no
212
+ # boundary exists at or before the limit (spec D6, amends spec 300 D5's
213
+ # unconditional `first_line[0, MAX_SUBJECT_LENGTH]`, which cut mid-word).
214
+ # A subject at or under the limit is returned unchanged. Post-execution
215
+ # review item 7: when the character immediately after the 72-char prefix
216
+ # is ITSELF a space, the prefix already ends exactly on a word boundary and
217
+ # needs no trimming at all -- checked before consulting `rindex`, because
218
+ # an earlier internal space inside the 72-char prefix would otherwise make
219
+ # `rindex` walk back past a whole trailing word that fit perfectly.
212
220
  def subject_for(summary)
213
221
  first_line = summary.to_s.split(/\r?\n/, 2).first.to_s.strip
214
- first_line[0, MAX_SUBJECT_LENGTH]
222
+ return first_line if first_line.length <= MAX_SUBJECT_LENGTH
223
+
224
+ cut = first_line[0, MAX_SUBJECT_LENGTH]
225
+ return cut if first_line[MAX_SUBJECT_LENGTH] == " "
226
+
227
+ boundary = cut.rindex(" ")
228
+ boundary ? cut[0, boundary] : cut
229
+ end
230
+
231
+ # The commit body for `summary`/`subject` (spec D6): the full summary when
232
+ # `subject` is a cut-down copy of it, nil when the subject already carries
233
+ # the summary whole (no redundant body on a short, single-line summary).
234
+ # Post-execution review item 4: compares the STRIPPED raw summary, not the
235
+ # raw summary verbatim -- a summary with only trailing/leading whitespace
236
+ # around an otherwise-identical subject must not repeat the same sentence
237
+ # twice as a redundant body.
238
+ def body_for(summary, subject)
239
+ raw = summary.to_s
240
+ raw.strip == subject ? nil : raw
215
241
  end
216
242
 
217
243
  # --- git primitives (all use -C, never cwd) -------------------------------------
@@ -273,9 +299,11 @@ module SessionGit
273
299
  parts.each_cons(2).any? { |a, b| a == ".claude" && b == "worktrees" }
274
300
  end
275
301
 
276
- def stage_and_commit(dir, subject, runner:)
302
+ def stage_and_commit(dir, subject, runner:, body: nil)
277
303
  runner.run("-C", dir, "add", "-A")
278
- runner.run("-C", dir, "commit", "-m", subject)
304
+ args = ["-C", dir, "commit", "-m", subject]
305
+ args += ["-m", body] if body
306
+ runner.run(*args)
279
307
  end
280
308
 
281
309
  def short_sha(dir, runner:)
@@ -310,14 +338,16 @@ module SessionGit
310
338
 
311
339
  flow, flow_notes = load_flow(cwd: cwd, repo: repo, plastic_home: plastic_home, runner: runner)
312
340
  subject = subject_for(summary)
341
+ body = body_for(summary, subject)
313
342
 
314
343
  result =
315
344
  if flow["mode"] == "pull_request"
316
- commit_pull_request(repo: repo, subject: subject, day: day, session: session,
345
+ commit_pull_request(repo: repo, subject: subject, body: body, day: day, session: session,
317
346
  store: effective_store, flow: flow, branch_now: branch_now,
318
347
  runner: runner, gh_runner: gh_runner)
319
348
  else
320
- commit_direct(repo: repo, subject: subject, day: day, flow: flow, branch_now: branch_now, runner: runner)
349
+ commit_direct(repo: repo, subject: subject, body: body, day: day, flow: flow, branch_now: branch_now,
350
+ runner: runner)
321
351
  end
322
352
 
323
353
  return result if flow_notes.empty?
@@ -331,7 +361,7 @@ module SessionGit
331
361
 
332
362
  # --- direct mode (spec D3) --------------------------------------------------------
333
363
 
334
- def commit_direct(repo:, subject:, day:, flow:, branch_now:, runner:)
364
+ def commit_direct(repo:, subject:, day:, flow:, branch_now:, runner:, body: nil)
335
365
  return note("nothing to commit") unless dirty?(repo, runner: runner)
336
366
  return note("summary is empty after truncation: no commit") if blank?(subject)
337
367
 
@@ -351,10 +381,10 @@ module SessionGit
351
381
  end
352
382
 
353
383
  if branch_now == base || branch_now == session_branch
354
- commit_on_session_branch(repo: repo, subject: subject, base: base,
384
+ commit_on_session_branch(repo: repo, subject: subject, base: base, body: body,
355
385
  session_branch: session_branch, branch_now: branch_now, runner: runner)
356
386
  else
357
- commit_on_other_branch(repo: repo, subject: subject, branch_now: branch_now, runner: runner)
387
+ commit_on_other_branch(repo: repo, subject: subject, body: body, branch_now: branch_now, runner: runner)
358
388
  end
359
389
  end
360
390
 
@@ -367,7 +397,7 @@ module SessionGit
367
397
  # session branch. `current_branch` is re-read after the switch and used
368
398
  # for the commit message instead of trusting the branch this method
369
399
  # intended to reach.
370
- def commit_on_session_branch(repo:, subject:, base:, session_branch:, branch_now:, runner:)
400
+ def commit_on_session_branch(repo:, subject:, base:, session_branch:, branch_now:, runner:, body: nil)
371
401
  unless branch_exists?(repo, session_branch, runner: runner)
372
402
  create = runner.run("-C", repo, "branch", session_branch, base.to_s)
373
403
  return note("could not create session branch #{session_branch}: #{diagnose(create)}") unless create.success?
@@ -383,11 +413,12 @@ module SessionGit
383
413
  return note("expected to be on #{session_branch} but the checkout is on #{actual_branch.inspect}")
384
414
  end
385
415
 
386
- commit_and_push(dir: repo, push_dir: repo, subject: subject, from: actual_branch, base: base, runner: runner)
416
+ commit_and_push(dir: repo, push_dir: repo, subject: subject, body: body, from: actual_branch, base: base,
417
+ runner: runner)
387
418
  end
388
419
 
389
- def commit_on_other_branch(repo:, subject:, branch_now:, runner:)
390
- res = stage_and_commit(repo, subject, runner: runner)
420
+ def commit_on_other_branch(repo:, subject:, branch_now:, runner:, body: nil)
421
+ res = stage_and_commit(repo, subject, runner: runner, body: body)
391
422
  return note("commit rejected by commit-msg hook: #{diagnose(res)}") unless res.success?
392
423
 
393
424
  sha = short_sha(repo, runner: runner)
@@ -398,8 +429,8 @@ module SessionGit
398
429
  # shared tail. A non-fast-forward push (spec D3, "base moved ahead
399
430
  # independently") stays a Note: the commit itself already landed on the
400
431
  # session branch.
401
- def commit_and_push(dir:, push_dir:, subject:, from:, base:, runner:)
402
- res = stage_and_commit(dir, subject, runner: runner)
432
+ def commit_and_push(dir:, push_dir:, subject:, from:, base:, runner:, body: nil)
433
+ res = stage_and_commit(dir, subject, runner: runner, body: body)
403
434
  return note("commit rejected by commit-msg hook: #{diagnose(res)}") unless res.success?
404
435
 
405
436
  sha = short_sha(dir, runner: runner)
@@ -414,7 +445,7 @@ module SessionGit
414
445
 
415
446
  # --- pull request mode (spec D4) ------------------------------------------------
416
447
 
417
- def commit_pull_request(repo:, subject:, day:, session:, store:, flow:, branch_now:, runner:, gh_runner:)
448
+ def commit_pull_request(repo:, subject:, day:, session:, store:, flow:, branch_now:, runner:, gh_runner:, body: nil)
418
449
  return note("nothing to commit") unless dirty?(repo, runner: runner)
419
450
  return note("summary is empty after truncation: no commit") if blank?(subject)
420
451
 
@@ -439,7 +470,7 @@ module SessionGit
439
470
  return note("could not check out branch #{branch}: #{diagnose(switch)}") unless switch.success?
440
471
  end
441
472
 
442
- res = stage_and_commit(repo, subject, runner: runner)
473
+ res = stage_and_commit(repo, subject, runner: runner, body: body)
443
474
  outcome =
444
475
  if res.success?
445
476
  pull_request_outcome(repo: repo, subject: subject, branch: branch, base: base, gh_runner: gh_runner, runner: runner)
@@ -29,6 +29,10 @@ module SessionLedger
29
29
 
30
30
  SESSIONS_DIR = ".sessions"
31
31
  TMP_DIR = ".tmp"
32
+ # Named here, not in a CLI, so a caller can reference the key without the
33
+ # literal harness-branded env var name appearing in its own source (a few
34
+ # scripts are guarded against naming a harness at all).
35
+ SESSION_ID_ENV_KEY = "CLAUDE_CODE_SESSION_ID"
32
36
  DAY_ID = /\A\d{8}\z/
33
37
  EVENTS = %w[Item Done Note]
34
38
  STATES = { pending: "~", open: " ", done: "x", moved: ">", dropped: "-", promoted: "^" }.freeze
@@ -186,6 +190,130 @@ module SessionLedger
186
190
  "#{collapsed[0, 197]}..."
187
191
  end
188
192
 
193
+ # --- capture_worthy? (spec D2, D7; supersedes 298 D2(c)) -------------------
194
+
195
+ # One complete top-level harness envelope tag block: "<name ...>...</name>".
196
+ # Non-greedy (.*?) so sibling blocks are each matched on their own rather
197
+ # than one match spanning from the first block's opening tag all the way to
198
+ # the LAST block's closing tag (post-execution review item 3: an envelope
199
+ # on both sides of real work, "<system-reminder>...</system-reminder>\nfix
200
+ # the parser\n<task-notification>...</task-notification>", must not be
201
+ # read as one giant envelope swallowing the work in the middle).
202
+ ENVELOPE_BLOCK_RE = /<([A-Za-z][\w-]*)(?:\s[^>]*)?>.*?<\/\1>/m
203
+ private_constant :ENVELOPE_BLOCK_RE
204
+
205
+ # The whole prompt, case- and whitespace-insensitively, and nothing else
206
+ # (rule 3, D2): a trigger word inside a longer real instruction ("continue
207
+ # the dashboard fix and then release") must not match this.
208
+ BARE_TRIGGERS = %w[continue auto].freeze
209
+ private_constant :BARE_TRIGGERS
210
+
211
+ # Words whose presence marks a prompt as actionable work (rule 4's escape
212
+ # hatch, D2's accept bias). Deliberately excludes common nouns that also
213
+ # read as everyday verbs in casual remarks (e.g. "release", "ship", "plan"):
214
+ # including them would make ordinary conversation about a past release or
215
+ # plan look like a work request. Matched with an optional inflection suffix
216
+ # (post-execution review BLOCKER): the bare stems alone missed "fixed",
217
+ # "updated", "added", "reviewed", "implemented" -- exactly the past-tense
218
+ # and -ing forms real work summaries use.
219
+ WORK_MARKER_WORDS = %w[
220
+ fix add remove delete update upgrade implement write build create refactor
221
+ debug investigate review test deploy commit merge revert rename configure
222
+ install migrate document generate draft resolve help need want make change
223
+ setup
224
+ ].freeze
225
+ private_constant :WORK_MARKER_WORDS
226
+
227
+ WORK_MARKER_PHRASES = [
228
+ "can you", "could you", "would you", "let's", "let us", "set up", "look into", "figure out",
229
+ ].freeze
230
+ private_constant :WORK_MARKER_PHRASES
231
+
232
+ WORK_MARKER_RE = /\b(?:#{WORK_MARKER_WORDS.join("|")})(?:s|d|ed|ing)?\b/i
233
+ private_constant :WORK_MARKER_RE
234
+
235
+ # A first word that reads as an interrogative opener, checked case-
236
+ # insensitively against the prompt's first whitespace-separated token.
237
+ # Post-execution review BLOCKER: trimmed from the original, wider list
238
+ # (which also carried "how", "when", "where", "was", "were", "do", "did",
239
+ # "will", "shall", "should") down to words that open a genuine QUESTION at
240
+ # least as often as an ordinary command or request. Measured against 43
241
+ # invented and 27 real day-ledger prompts: the dropped words open ordinary
242
+ # work requests ("do the release now...", "when you are done, tag the
243
+ # release...", "will you push that branch...", "should I bump the version
244
+ # files...") far more often than they open a bare question worth rejecting.
245
+ QUESTION_STARTERS = %w[
246
+ what why who whom whose which is are am does can could would
247
+ ].freeze
248
+ private_constant :QUESTION_STARTERS
249
+
250
+ # A narrow set of retrospective-remark shapes ("that release went smoother
251
+ # than the last one"): comparative or evaluative observations about how
252
+ # something already went. Deliberately narrow (D2's accept bias): a broad
253
+ # "any declarative sentence with no recognized verb" rule would also catch
254
+ # ordinary work summaries like "harness text wins the pending line", which
255
+ # must stay accepted.
256
+ REMARK_PATTERNS = [
257
+ /\bwent\s+\w+\s+than\b/i,
258
+ /\bwent\s+(?:well|badly|smoothly|great|poorly|terribly)\b/i,
259
+ ].freeze
260
+ private_constant :REMARK_PATTERNS
261
+
262
+ # True iff nothing but harness envelope tag block(s) -- and whitespace --
263
+ # remain once every complete top-level block is stripped out. A prompt
264
+ # that is one envelope alone, or several envelopes with no other content,
265
+ # matches; a prompt carrying real work anywhere outside an envelope (before,
266
+ # after, or between several of them) does not.
267
+ def whole_prompt_envelope?(stripped)
268
+ stripped.gsub(ENVELOPE_BLOCK_RE, "").strip.empty?
269
+ end
270
+
271
+ def bare_trigger?(stripped)
272
+ BARE_TRIGGERS.include?(stripped.downcase)
273
+ end
274
+
275
+ def work_marker?(text)
276
+ return true if WORK_MARKER_RE.match?(text)
277
+
278
+ downcased = text.downcase
279
+ WORK_MARKER_PHRASES.any? { |p| downcased.include?(p) }
280
+ end
281
+
282
+ def interrogative?(stripped)
283
+ return true if stripped.end_with?("?")
284
+
285
+ first_word = stripped.split(/\s+/).first.to_s.downcase.gsub(/[^a-z]/, "")
286
+ QUESTION_STARTERS.include?(first_word)
287
+ end
288
+
289
+ def bare_remark?(stripped)
290
+ REMARK_PATTERNS.any? { |re| re.match?(stripped) }
291
+ end
292
+
293
+ # Internal helpers only: #capture_worthy? is the sole public contract
294
+ # (post-execution review item 9).
295
+ private_class_method :whole_prompt_envelope?, :bare_trigger?, :work_marker?, :interrogative?, :bare_remark?
296
+
297
+ # Whether `prompt` earns a pending checklist line (spec D2). Bias is
298
+ # ACCEPT: this rejects only on four named rules -- the 10-char floor (on
299
+ # its own collapsed copy), a whole-prompt harness envelope, a bare
300
+ # continue/auto trigger, and an interrogative or bare-remark prompt
301
+ # carrying no work marker -- and accepts everything else, including a
302
+ # work-shaped question and an envelope followed by real work. Takes the
303
+ # RAW prompt (not the sanitized/truncated line text) so rule 2 sees the
304
+ # prompt's true first character and multi-line shape.
305
+ def capture_worthy?(prompt)
306
+ raw = prompt.to_s
307
+ return false if sanitize_summary(raw).length < 10
308
+
309
+ stripped = raw.strip
310
+ return false if whole_prompt_envelope?(stripped)
311
+ return false if bare_trigger?(stripped)
312
+ return false if !work_marker?(stripped) && (interrogative?(stripped) || bare_remark?(stripped))
313
+
314
+ true
315
+ end
316
+
189
317
  # One LF-terminated checklist line, byte exact per spec D5. The state
190
318
  # marker is fixed width across all three states, which is what lets a later
191
319
  # promote or tick be a one-byte write at a known offset.
@@ -0,0 +1,190 @@
1
+ # encoding: UTF-8
2
+ # frozen_string_literal: true
3
+
4
+ require "json"
5
+ require "time"
6
+
7
+ # SessionUsage (intent 355, D10): reads the harness transcripts modified since
8
+ # a cutoff, dedupes assistant records by message id (the harness logs one
9
+ # record per content block), and reports per session the model, the calls in
10
+ # the window, the boot and last context, the median step, the steps over 5k,
11
+ # and the cache read. Context is input plus cache read plus cache write.
12
+ # Broken records are counted and named, never averaged over. The transcripts
13
+ # root and the rate-limit cache path are injected; nothing reads ENV.
14
+ class SessionUsage
15
+ WINDOW = 5 * 3600
16
+ BIG_STEP = 5_000
17
+ LABEL_WIDTH = 70
18
+ NO_PROMPT = "(no prompt)"
19
+ SYNTHETIC_MODEL = "<synthetic>"
20
+ CONTEXT_FIELDS = %w[input_tokens cache_read_input_tokens cache_creation_input_tokens].freeze
21
+ TRANSCRIPT_GLOBS = [File.join("*", "*.jsonl"), File.join("*", "*", "subagents", "*.jsonl")].freeze
22
+ HEADERS = ["session", "model", "calls", "boot", "last", "median step", "big steps", "cache read", "broken", "prompt"].freeze
23
+
24
+ def initialize(transcripts_root:, rate_limits_path:, now: Time.now)
25
+ @transcripts_root = transcripts_root
26
+ @rate_limits_path = rate_limits_path
27
+ @now = now
28
+ end
29
+
30
+ def cutoff(since: nil)
31
+ return [since, "since"] if since
32
+
33
+ reset = reset_time
34
+ return [reset - WINDOW, "rate-limit reset"] if reset && reset > @now
35
+
36
+ [@now - WINDOW, "last 5 hours"]
37
+ end
38
+
39
+ def report(since: nil)
40
+ at, source = cutoff(since: since)
41
+ header = { "status" => "ok", "root" => @transcripts_root, "cutoff" => at.getutc.iso8601, "cutoff_source" => source }
42
+ return header.merge("status" => "unavailable") unless File.directory?(@transcripts_root)
43
+
44
+ broken = []
45
+ sessions = transcripts(at).filter_map { |path| summarize(path, at, broken) }
46
+ header.merge("sessions" => sessions.sort_by { |s| -s["cache_read"] }, "broken" => broken)
47
+ end
48
+
49
+ def self.render_text(report)
50
+ return "Session usage: unavailable (no transcripts directory at #{report['root']})\n" if report["status"] == "unavailable"
51
+
52
+ out = +"Session usage since #{report['cutoff']} (#{report['cutoff_source']})\n\n"
53
+ out << (report["sessions"].empty? ? "(no sessions)\n" : table(report["sessions"]))
54
+ return out if report["broken"].empty?
55
+
56
+ out << "\nBroken records (#{report['broken'].size}):\n"
57
+ report["broken"].each { |b| out << " #{b['file']}:#{b['line']} #{b['error']}\n" }
58
+ out
59
+ end
60
+
61
+ def self.table(sessions)
62
+ rows = sessions.map do |s|
63
+ boot = tokens(s["boot"]) + (s["started_before_cutoff"] ? "*" : "")
64
+ [s["id"], s["model"].to_s, s["calls"].to_s, boot, tokens(s["last"]), tokens(s["median_step"]),
65
+ s["big_steps"].to_s, tokens(s["cache_read"]), s["broken"].to_s, s["label"]]
66
+ end
67
+ widths = HEADERS.each_index.map { |i| ([HEADERS] + rows).map { |r| r[i].length }.max }
68
+ lines = ([HEADERS] + rows).map { |r| r.each_with_index.map { |cell, i| cell.ljust(widths[i]) }.join(" ").rstrip }
69
+ note = sessions.any? { |s| s["started_before_cutoff"] } ? "\n* boot predates the cutoff\n" : ""
70
+ lines.join("\n") + "\n" + note
71
+ end
72
+
73
+ def self.tokens(count)
74
+ return "-" if count.nil?
75
+
76
+ count.abs >= 1_000 ? format("%.1fk", count / 1_000.0) : count.to_s
77
+ end
78
+
79
+ private_class_method :table, :tokens
80
+
81
+ private
82
+
83
+ def reset_time
84
+ return unless File.file?(@rate_limits_path)
85
+
86
+ value = JSON.parse(File.read(@rate_limits_path))["resets_at"].to_s
87
+ return if value.empty?
88
+
89
+ value.match?(/\A\d+\z/) ? Time.at(value.to_i).utc : Time.iso8601(value)
90
+ rescue JSON::ParserError, ArgumentError, TypeError
91
+ nil
92
+ end
93
+
94
+ def transcripts(cutoff)
95
+ TRANSCRIPT_GLOBS.flat_map { |glob| Dir.glob(File.join(@transcripts_root, glob)) }
96
+ .select { |path| File.mtime(path) >= cutoff }
97
+ .sort
98
+ end
99
+
100
+ def summarize(path, cutoff, broken)
101
+ calls = {}
102
+ label = nil
103
+ torn = 0
104
+ File.foreach(path).with_index(1) do |line, number|
105
+ next if line.strip.empty?
106
+
107
+ record = JSON.parse(line)
108
+ raise TypeError, "record is not a JSON object" unless record.is_a?(Hash)
109
+
110
+ label ||= prompt_line(record)
111
+ call = call_from(record)
112
+ next unless call
113
+
114
+ calls[call[:id]] = calls.key?(call[:id]) ? call.merge(at: calls[call[:id]][:at]) : call
115
+ rescue JSON::ParserError
116
+ torn += 1
117
+ broken << { "file" => path, "line" => number, "error" => "unparsable JSON" }
118
+ rescue ArgumentError, TypeError => e
119
+ torn += 1
120
+ broken << { "file" => path, "line" => number, "error" => e.message }
121
+ end
122
+ row(path, calls.values, cutoff, label, torn)
123
+ end
124
+
125
+ def row(path, calls, cutoff, label, torn)
126
+ window = calls.each_index.select { |i| calls[i][:at] >= cutoff }
127
+ return if window.empty? && torn.zero?
128
+
129
+ steps = window.filter_map { |i| calls[i][:context] - calls[i - 1][:context] if i.positive? }
130
+ {
131
+ "id" => File.basename(path, ".jsonl"),
132
+ "file" => path,
133
+ "label" => label || NO_PROMPT,
134
+ "model" => calls.last && calls.last[:model],
135
+ "calls" => window.size,
136
+ "boot" => calls.first && calls.first[:context],
137
+ "last" => calls.last && calls.last[:context],
138
+ "median_step" => median(steps),
139
+ "big_steps" => steps.count { |step| step > BIG_STEP },
140
+ "cache_read" => window.sum { |i| calls[i][:cache_read] },
141
+ "broken" => torn,
142
+ "started_before_cutoff" => !calls.empty? && calls.first[:at] < cutoff,
143
+ }
144
+ end
145
+
146
+ def call_from(record)
147
+ return unless record["type"] == "assistant"
148
+
149
+ message = record["message"]
150
+ raise TypeError, "assistant record without a message" unless message.is_a?(Hash)
151
+ return if message["model"] == SYNTHETIC_MODEL
152
+
153
+ usage = message["usage"]
154
+ raise ArgumentError, "assistant record without message id or usage" unless message["id"] && usage.is_a?(Hash)
155
+
156
+ {
157
+ id: message["id"],
158
+ model: message["model"],
159
+ at: Time.iso8601(record["timestamp"].to_s),
160
+ context: CONTEXT_FIELDS.sum { |field| usage[field].to_i },
161
+ cache_read: usage["cache_read_input_tokens"].to_i,
162
+ }
163
+ end
164
+
165
+ def prompt_line(record)
166
+ return unless record["type"] == "user" && !record["isMeta"]
167
+
168
+ text = prompt_text(record["message"].is_a?(Hash) ? record["message"]["content"] : nil)
169
+ return if text.nil?
170
+
171
+ first = text.lines.map(&:strip).find { |line| !line.empty? && !line.start_with?("<") }
172
+ first && first[0, LABEL_WIDTH]
173
+ end
174
+
175
+ def prompt_text(content)
176
+ return content if content.is_a?(String)
177
+ return unless content.is_a?(Array)
178
+
179
+ block = content.find { |b| b.is_a?(Hash) && b["type"] == "text" }
180
+ block && block["text"]
181
+ end
182
+
183
+ def median(values)
184
+ return if values.empty?
185
+
186
+ sorted = values.sort
187
+ middle = sorted.size / 2
188
+ sorted.size.odd? ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2
189
+ end
190
+ end
@@ -70,6 +70,10 @@ module VerifyIntent
70
70
  lines.concat(diffstat_lines)
71
71
  checks[:diffstat] = diffstat_check
72
72
 
73
+ report_lines_out, report_check = run_report_lines_check(intent_dir: intent_dir)
74
+ lines.concat(report_lines_out)
75
+ checks[:report] = report_check
76
+
73
77
  if Worktree.blank?(suite)
74
78
  checks[:suite] = { status: "skipped" }
75
79
  else
@@ -235,6 +239,35 @@ module VerifyIntent
235
239
  end
236
240
  end
237
241
 
242
+ # --- check: the Report savepoint lines (intent 331f, F17) ------------------------
243
+
244
+ REPORT_LINE_RE = /\A(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ)\s{2,}(\S+)\s{2,}(.+?)\s*\z/.freeze
245
+
246
+ # Every `Report`-kind savepoint line for this intent, oldest first: [timestamp, text].
247
+ # Never fails or gates anything (D3: the diffstat check already prints a summary block,
248
+ # this folds into the same verdict so verify-intent surfaces them too) - a delivery with
249
+ # no Report line is visible to `doctor`'s intent_reports_printed_check instead.
250
+ def report_lines(intent_dir)
251
+ path = File.join(intent_dir, "savepoint.md")
252
+ return [] unless File.exist?(path)
253
+
254
+ File.readlines(path).filter_map do |line|
255
+ m = line.strip.match(REPORT_LINE_RE)
256
+ next nil unless m && m[2] == "Report"
257
+ [m[1], m[3]]
258
+ end
259
+ end
260
+
261
+ def run_report_lines_check(intent_dir:)
262
+ entries = report_lines(intent_dir)
263
+ if entries.empty?
264
+ [["report lines: none recorded"], { status: "pass", lines: [] }]
265
+ else
266
+ lines = ["report lines:"] + entries.map { |ts, text| "#{ts} Report #{text}" }
267
+ [lines, { status: "pass", lines: entries }]
268
+ end
269
+ end
270
+
238
271
  # --- check 4: the optional suite --------------------------------------------------
239
272
 
240
273
  # The supplied command is very likely a ruby command, so it is spawned with RUBYOPT