principles 0.1.4 → 0.1.5

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 (140) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +31 -1
  3. data/exe/principles +1 -1
  4. data/lib/principles/cli.rb +9 -10
  5. data/lib/principles/command_routes.rb +7 -1
  6. data/lib/principles/controllers/carrier_edit_report.rb +40 -0
  7. data/lib/principles/controllers/command.rb +7 -3
  8. data/lib/principles/controllers/context_budget.rb +61 -0
  9. data/lib/principles/controllers/inventory.rb +3 -2
  10. data/lib/principles/controllers/member_addition.rb +1 -1
  11. data/lib/principles/controllers/member_entries.rb +30 -38
  12. data/lib/principles/controllers/member_entry_changes.rb +71 -0
  13. data/lib/principles/controllers/member_problems_report.rb +1 -1
  14. data/lib/principles/controllers/members_in_logged_requests.rb +5 -5
  15. data/lib/principles/controllers/members_to_assess.rb +11 -1
  16. data/lib/principles/controllers/meta_principle_setup.rb +10 -2
  17. data/lib/principles/controllers/parts_to_read.rb +2 -1
  18. data/lib/principles/controllers/plugin_member_addition.rb +4 -4
  19. data/lib/principles/controllers/request_logging.rb +17 -4
  20. data/lib/principles/controllers/running_tool.rb +19 -5
  21. data/lib/principles/controllers/session_start_report.rb +26 -2
  22. data/lib/principles/data/captured_requests.rb +118 -0
  23. data/lib/principles/data/carrier_page_markers.rb +38 -0
  24. data/lib/principles/data/claude_code_home.rb +17 -0
  25. data/lib/principles/data/command-steps.json +59 -19
  26. data/lib/principles/data/kept_line.rb +14 -7
  27. data/lib/principles/data/logged_request_matches.rb +23 -17
  28. data/lib/principles/data/logged_request_scan.rb +79 -11
  29. data/lib/principles/data/map_files.rb +1 -1
  30. data/lib/principles/data/project_files.rb +15 -0
  31. data/lib/principles/data/request_logging_folder.rb +42 -74
  32. data/lib/principles/data/request_shape.rb +33 -0
  33. data/lib/principles/data/running_version.rb +1 -1
  34. data/lib/principles/data/schemas/command-steps.schema.json +1 -1
  35. data/lib/principles/data/schemas/member-map.schema.json +2 -0
  36. data/lib/principles/data/settings_env_keys.rb +26 -0
  37. data/lib/principles/data/user_request_logging_folder.rb +73 -0
  38. data/lib/principles/invocation_options.rb +4 -4
  39. data/lib/principles/launch.rb +15 -6
  40. data/lib/principles/models/captured_sessions.rb +53 -15
  41. data/lib/principles/models/carrier_edit_input.rb +56 -0
  42. data/lib/principles/models/carrier_pages_shown.rb +28 -0
  43. data/lib/principles/models/carved_message_bytes.rb +115 -0
  44. data/lib/principles/models/context_parts.rb +59 -0
  45. data/lib/principles/models/declared_map_changes.rb +22 -13
  46. data/lib/principles/models/dropped_thinking.rb +73 -0
  47. data/lib/principles/models/feature.rb +2 -1
  48. data/lib/principles/models/installed_component.rb +3 -3
  49. data/lib/principles/models/logged_request_reach.rb +19 -11
  50. data/lib/principles/models/map_format_raise.rb +28 -0
  51. data/lib/principles/models/mapped_principles.rb +2 -1
  52. data/lib/principles/models/member.rb +6 -1
  53. data/lib/principles/models/member_justification.rb +52 -0
  54. data/lib/principles/models/member_problems.rb +2 -1
  55. data/lib/principles/models/member_reach.rb +28 -5
  56. data/lib/principles/models/member_snapshots.rb +11 -0
  57. data/lib/principles/models/members_by_part.rb +67 -0
  58. data/lib/principles/models/members_in_logged_requests.rb +56 -17
  59. data/lib/principles/models/meta_principle.rb +4 -4
  60. data/lib/principles/models/part_token_estimates.rb +60 -0
  61. data/lib/principles/models/plugin_enabled_in_project_settings.rb +61 -0
  62. data/lib/principles/models/principle.rb +7 -4
  63. data/lib/principles/models/principle_members.rb +7 -0
  64. data/lib/principles/models/project.rb +20 -31
  65. data/lib/principles/models/project_harness.rb +48 -0
  66. data/lib/principles/models/report_hooks.rb +9 -4
  67. data/lib/principles/models/request_channel.rb +62 -0
  68. data/lib/principles/models/request_kind.rb +62 -0
  69. data/lib/principles/models/request_logging.rb +107 -72
  70. data/lib/principles/models/request_logging_guard.rb +84 -0
  71. data/lib/principles/models/request_time.rb +46 -0
  72. data/lib/principles/models/session_registry.rb +61 -0
  73. data/lib/principles/models/session_start_input.rb +11 -2
  74. data/lib/principles/models/session_trend.rb +36 -0
  75. data/lib/principles/models/turn_opening.rb +83 -0
  76. data/lib/principles/models/turn_position.rb +43 -0
  77. data/lib/principles/models/user_logged_requests.rb +90 -0
  78. data/lib/principles/models/user_settings_entries.rb +49 -0
  79. data/lib/principles/version.rb +2 -2
  80. data/lib/principles/views/assessed_members.rb +4 -4
  81. data/lib/principles/views/assessment_request.rb +6 -3
  82. data/lib/principles/views/audit_result.rb +13 -6
  83. data/lib/principles/views/candidate_files_result.rb +1 -1
  84. data/lib/principles/views/carrier_edit_denial.rb +36 -0
  85. data/lib/principles/views/context_budget_result.rb +99 -0
  86. data/lib/principles/views/correction_request.rb +11 -1
  87. data/lib/principles/views/hook_setup_result.rb +3 -1
  88. data/lib/principles/views/logged_requests_evidence.rb +18 -3
  89. data/lib/principles/views/map_format_raised.rb +28 -0
  90. data/lib/principles/views/map_result.rb +7 -6
  91. data/lib/principles/views/maps_needing_members_or_audit.rb +1 -1
  92. data/lib/principles/views/members_in_logged_requests_result.rb +75 -20
  93. data/lib/principles/views/meta_principle_result.rb +38 -13
  94. data/lib/principles/views/problem_lines.rb +22 -0
  95. data/lib/principles/views/prompts/assess-every-member/ask-whether-a-member-seen-only-as-read-is-loaded.md +3 -0
  96. data/lib/principles/views/prompts/assess-every-member/ask-whether-each-reason-holds.md +2 -0
  97. data/lib/principles/views/prompts/assess-every-member/judge-the-keeping-against-the-other-principles.md +2 -0
  98. data/lib/principles/views/prompts/assess-every-member/weigh-what-reached-the-context.md +2 -2
  99. data/lib/principles/views/prompts/dispose-of-each-finding/answer-guide.json +1 -1
  100. data/lib/principles/views/prompts/dispose-of-each-finding/fix-or-record-each-finding.md +1 -1
  101. data/lib/principles/views/prompts/dispose-of-each-finding/read-the-carrier-page-before-fixing.md +1 -0
  102. data/lib/principles/views/prompts/edit-a-carrier/read-the-page-before-the-first-edit.md +2 -0
  103. data/lib/principles/views/prompts/learn-what-a-command-does/add-member.md +19 -20
  104. data/lib/principles/views/prompts/learn-what-a-command-does/change-member-name.md +12 -0
  105. data/lib/principles/views/prompts/learn-what-a-command-does/change-member-reason.md +12 -0
  106. data/lib/principles/views/prompts/learn-what-a-command-does/every-command-and-how-they-chain.md +1 -1
  107. data/lib/principles/views/prompts/learn-what-a-command-does/list-member-problems.md +4 -4
  108. data/lib/principles/views/prompts/learn-what-a-command-does/remove-logged-requests.md +7 -1
  109. data/lib/principles/views/prompts/learn-what-a-command-does/report-at-session-start.md +7 -3
  110. data/lib/principles/views/prompts/learn-what-a-command-does/report-before-carrier-edit.md +13 -0
  111. data/lib/principles/views/prompts/learn-what-a-command-does/show-context-budget.md +69 -0
  112. data/lib/principles/views/prompts/learn-what-a-command-does/show-hook-setup.md +4 -4
  113. data/lib/principles/views/prompts/learn-what-a-command-does/show-logged-requests.md +4 -2
  114. data/lib/principles/views/prompts/learn-what-a-command-does/show-members-in-logged-requests.md +21 -7
  115. data/lib/principles/views/prompts/learn-what-a-command-does/show-meta-principle-passage.md +13 -10
  116. data/lib/principles/views/prompts/learn-what-a-command-does/show-principle.md +5 -5
  117. data/lib/principles/views/prompts/learn-what-a-command-does/submit-answer.md +7 -7
  118. data/lib/principles/views/prompts/learn-what-a-command-does/turn-off-request-logging.md +8 -0
  119. data/lib/principles/views/prompts/learn-what-a-command-does/turn-on-request-logging.md +12 -0
  120. data/lib/principles/views/prompts/read-what-reached-the-context/explain-user-request-logging-to-the-user.md +10 -0
  121. data/lib/principles/views/prompts/read-what-reached-the-context/what-a-thread-continuation-holds.md +3 -0
  122. data/lib/principles/views/prompts/read-what-reached-the-context/what-each-context-budget-line-says.md +4 -0
  123. data/lib/principles/views/prompts/read-what-reached-the-context/what-each-member-line-says.md +2 -0
  124. data/lib/principles/views/prompts/report-after-a-commit/a-row-ending-audit-asks-to-acknowledge-or-audit-again.md +1 -0
  125. data/lib/principles/views/prompts/report-after-a-commit/a-row-ending-mapping-commit-asks-for-an-audit.md +1 -0
  126. data/lib/principles/views/prompts/report-after-a-commit/a-row-ending-pinned-asks-for-an-audit.md +1 -0
  127. data/lib/principles/views/prompts/run-a-first-audit-in-the-background/follow-the-brief.md +1 -0
  128. data/lib/principles/views/prompts/set-principles-up/ask-to-set-principles-up-after-an-audit.md +1 -0
  129. data/lib/principles/views/prompts/set-principles-up/entry-file-passage.md +1 -1
  130. data/lib/principles/views/prompts/set-principles-up/map-the-enabling-line-at-no-edit.md +3 -0
  131. data/lib/principles/views/prompts/set-principles-up/name-the-step-each-member-lacks.md +2 -2
  132. data/lib/principles/views/prompts/set-principles-up/place-the-passage-with-the-user.md +4 -2
  133. data/lib/principles/views/prompts/set-principles-up/what-the-passage-presumes.md +1 -1
  134. data/lib/principles/views/prompts/set-principles-up/why-set-principles-up.md +1 -0
  135. data/lib/principles/views/prompts/start-a-session/ask-to-set-principles-up.md +2 -0
  136. data/lib/principles/views/prompts/start-a-session/name-the-principles-nothing-checks.md +1 -0
  137. data/lib/principles/views/request_logging_result.rb +48 -2
  138. data/lib/principles/views/set_up_offer_line.rb +43 -0
  139. metadata +55 -3
  140. data/lib/principles/views/prompts/set-principles-up/keep-them-held-between-audits.md +0 -2
@@ -2,6 +2,7 @@
2
2
  # frozen_string_literal: true
3
3
 
4
4
  require_relative "../data/request_logging_folder"
5
+ require_relative "request_time"
5
6
 
6
7
  module Principles
7
8
  # The domain logic, and the mediation of persistence. models/CLAUDE.md owns the boundary.
@@ -25,7 +26,8 @@ module Principles
25
26
  def to_h = { "files" => @files, "bytes" => @bytes }
26
27
  end
27
28
 
28
- # One session's tally: its requests, the files they and their responses fill, and those files' bytes.
29
+ # One session's tally: its requests, the files they and their responses fill, and those files' bytes, and when
30
+ # its first and last requests were sent, in UTC, from those of its index lines' timestamps that are times.
29
31
  class Session
30
32
  #: String
31
33
  attr_reader :session_id
@@ -34,32 +36,60 @@ module Principles
34
36
  #: Tally
35
37
  attr_reader :tally
36
38
 
37
- #: (String, Integer, Tally) -> void
38
- def initialize(session_id, requests, tally)
39
+ # sent_at is when each of its requests was sent, as its index lines give it.
40
+ #: (String, Integer, Tally, Array[RequestTime]) -> void
41
+ def initialize(session_id, requests, tally, sent_at)
39
42
  @session_id = session_id
40
43
  @requests = requests
41
44
  @tally = tally
45
+ @sent_at = sent_at.select(&:utc).sort.freeze #: Array[RequestTime]
42
46
  freeze
43
47
  end
44
48
 
49
+ # When its first request was sent; none, sorting last, when no line of it gives a time.
50
+ #: () -> RequestTime
51
+ def first_sent = @sent_at.first || RequestTime.new(nil)
52
+
45
53
  #: () -> Hash[String, untyped]
46
- def to_h = { "session_id" => @session_id, "requests" => @requests, **@tally.to_h }
54
+ def to_h
55
+ { "session_id" => @session_id, "requests" => @requests, **@tally.to_h,
56
+ "first_request_at" => @sent_at.first&.utc, "last_request_at" => @sent_at.last&.utc }
57
+ end
47
58
  end
48
59
 
49
- #: (Array[Data::RequestLoggingFolder::CapturedFile], Array[Data::RequestLoggingFolder::IndexLine]) -> void
60
+ #: (Array[Data::CapturedRequests::CapturedFile], Array[Data::CapturedRequests::IndexLine]) -> void
50
61
  def initialize(files, index_lines)
51
- @files = files.to_h { |file| [file.name, file] } #: Hash[String, Data::RequestLoggingFolder::CapturedFile]
62
+ @files = files.to_h { |file| [file.name, file] } #: Hash[String, Data::CapturedRequests::CapturedFile]
52
63
  @index_lines = index_lines
53
64
  freeze
54
65
  end
55
66
 
56
- # Each session the index names, in the order it first names them.
67
+ # Only the sessions session_ids names, with the files their lines name, so no other session's file, and no
68
+ # request no line names, is counted or removed.
69
+ #: (Array[String]) -> CapturedSessions
70
+ def of(session_ids)
71
+ lines = @index_lines.select { |line| session_ids.include?(line.session_id) }
72
+ CapturedSessions.new(lines.flat_map { |line| named_files(line) }.uniq, lines)
73
+ end
74
+
75
+ # Each session the index names, once, in the order it first names it.
76
+ #: () -> Array[String]
77
+ def session_ids = @index_lines.map(&:session_id).uniq
78
+
79
+ # The files counted here that other does not count.
80
+ #: (CapturedSessions) -> Array[Data::CapturedRequests::CapturedFile]
81
+ def files_apart_from(other) = @files.values.reject { |file| other.file_names.include?(file.name) }
82
+
83
+ # The name of each file counted here.
84
+ #: () -> Array[String]
85
+ def file_names = @files.keys
86
+
87
+ # Each session the index names, by when its first request was sent, those with no time last in the order the
88
+ # index first names them.
57
89
  #: () -> Array[Session]
58
90
  def sessions
59
- @index_lines.group_by(&:session_id).map do |session_id, lines|
60
- named = lines.flat_map { |line| named_files(line) }.uniq
61
- Session.new(session_id, lines.size, Tally.new(files: named.size, bytes: named.sum(&:bytes)))
62
- end
91
+ named = @index_lines.group_by(&:session_id).map { |session_id, lines| session(session_id, lines) }
92
+ named.each_with_index.sort_by { |session, first| [session.first_sent, first] }.map(&:first)
63
93
  end
64
94
 
65
95
  # The request files no index line names, counted, and their bytes.
@@ -98,7 +128,15 @@ module Principles
98
128
 
99
129
  private
100
130
 
101
- #: (Array[Data::RequestLoggingFolder::IndexLine]) -> Array[String]
131
+ # The session session_id names, from its index lines: their count, the files they name and when each was sent.
132
+ #: (String, Array[Data::CapturedRequests::IndexLine]) -> Session
133
+ def session(session_id, lines)
134
+ files = lines.flat_map { |line| named_files(line) }.uniq
135
+ Session.new(session_id, lines.size, Tally.new(files: files.size, bytes: files.sum(&:bytes)),
136
+ lines.map { |line| RequestTime.new(line.timestamp) })
137
+ end
138
+
139
+ #: (Array[Data::CapturedRequests::IndexLine]) -> Array[String]
102
140
  def orphans_written_before(kept)
103
141
  oldest = kept.flat_map { |line| named_files(line) }.map(&:modified_at).min
104
142
  return [] unless oldest
@@ -106,20 +144,20 @@ module Principles
106
144
  unnamed_requests.select { |file| file.modified_at < oldest }.map(&:name)
107
145
  end
108
146
 
109
- #: () -> Array[Data::RequestLoggingFolder::CapturedFile]
147
+ #: () -> Array[Data::CapturedRequests::CapturedFile]
110
148
  def unnamed_requests
111
149
  indexed = @index_lines.map { |line| base_name(line.request_file) }
112
150
  @files.values.select { |file| file.name.end_with?(".request.json") && !indexed.include?(file.name) }
113
151
  end
114
152
 
115
- #: (Array[Data::RequestLoggingFolder::IndexLine]) -> Array[String]
153
+ #: (Array[Data::CapturedRequests::IndexLine]) -> Array[String]
116
154
  def names(lines) = lines.flat_map { |line| named_files(line) }.map(&:name).uniq
117
155
 
118
156
  #: (String) -> String
119
157
  def base_name(path) = path.split("/").last.to_s
120
158
 
121
159
  # The files a line names that the folder holds, by name, since the index names them by their full paths.
122
- #: (Data::RequestLoggingFolder::IndexLine) -> Array[Data::RequestLoggingFolder::CapturedFile]
160
+ #: (Data::CapturedRequests::IndexLine) -> Array[Data::CapturedRequests::CapturedFile]
123
161
  def named_files(line)
124
162
  [line.request_file, line.response_file].filter_map { |path| @files[base_name(path)] }
125
163
  end
@@ -0,0 +1,56 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ require "json"
5
+ require_relative "carrier_kind"
6
+ require_relative "project"
7
+
8
+ module Principles
9
+ # The domain logic, and the mediation of persistence. models/CLAUDE.md owns the boundary.
10
+ module Models
11
+ # The JSON a PreToolUse hook on Edit and Write is given on stdin, as far as report-before-carrier-edit reads it:
12
+ # the session and the carrier kind of the file the call would edit, inside the project. Input that is not JSON,
13
+ # names a session that is no plain name, or a file outside the project, gives no kind, since a hook reports what
14
+ # it can rather than refuse.
15
+ class CarrierEditInput
16
+ # A session id safe to name a folder by.
17
+ PLAIN = /\A[A-Za-z0-9_-]+\z/ #: Regexp
18
+
19
+ # The session the call is in, or nil.
20
+ #: String?
21
+ attr_reader :session
22
+
23
+ # text is the hook's input; project is the session's project, which places the file the call names.
24
+ #: (String, Project) -> void
25
+ def initialize(text, project)
26
+ given = parsed(text)
27
+ given = {} unless given.is_a?(Hash)
28
+ session = given["session_id"]
29
+ @session = session.is_a?(String) && PLAIN.match?(session) ? session : nil #: String?
30
+ tool_input = given["tool_input"]
31
+ file = tool_input["file_path"] if tool_input.is_a?(Hash)
32
+ @path = file.is_a?(String) ? project.harness.path_in_project(file) : nil #: String?
33
+ freeze
34
+ end
35
+
36
+ # The carrier kind of the file the call would edit, or nil when there is no session, no file in the project,
37
+ # or no kind a host loads by itself.
38
+ #: () -> String?
39
+ def kind
40
+ return nil unless @session && @path
41
+
42
+ name = CarrierKind.new(@path).name
43
+ name == CarrierKind::NONE ? nil : name
44
+ end
45
+
46
+ private
47
+
48
+ #: (String) -> untyped
49
+ def parsed(text)
50
+ JSON.parse(text)
51
+ rescue JSON::ParserError
52
+ nil
53
+ end
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,28 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ require_relative "../data/carrier_page_markers"
5
+
6
+ module Principles
7
+ # The domain logic, and the mediation of persistence. models/CLAUDE.md owns the boundary.
8
+ module Models
9
+ # Which carrier kinds' practices pages each session was pointed at before its first edit of that kind, kept in the
10
+ # temporary folder, so each kind is asked once a session and a new session asks again.
11
+ class CarrierPagesShown
12
+ #: (String) -> void
13
+ def initialize(temp_directory)
14
+ @markers = Data::CarrierPageMarkers.new(temp_directory) #: Data::CarrierPageMarkers
15
+ freeze
16
+ end
17
+
18
+ # Whether session should be pointed at kind's page now: it has not been yet, and it is recorded as pointed now,
19
+ # so the retry goes through. A marker that cannot be left points nowhere, so no edit is denied twice.
20
+ #: (String, String) -> bool
21
+ def point_now?(session, kind)
22
+ return false if @markers.marked?(session, kind)
23
+
24
+ @markers.mark(session, kind)
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,115 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ require "json"
5
+ require_relative "../data/decoded_leaf"
6
+ require_relative "request_channel"
7
+
8
+ module Principles
9
+ # The domain logic, and the mediation of persistence. models/CLAUDE.md owns the boundary.
10
+ module Models
11
+ # The bytes of a request's messages that the host added itself, by the part of the context each is: the text of
12
+ # each string split at its reminder tags, each piece's channel told by RequestChannel, and its bytes counted as
13
+ # JSON writes it inside the string, so the pieces of a string sum to its bytes there. Counts alone, never text.
14
+ class CarvedMessageBytes
15
+ # Each part carved, as [part, kind], in the order they print: a system notice's kind is resent when the same
16
+ # text was sent earlier in the request, told from structure alone, never by reading what it says.
17
+ CARVED = [["reminders", nil], %w[system_notices first_sent], %w[system_notices resent]]
18
+ .freeze #: Array[[String, String?]]
19
+ # The keys under a message's content whose strings are what it says.
20
+ SAID = %w[text content].freeze #: Array[String]
21
+ TAGS = Data::DecodedLeaf::TAGS
22
+ SEGMENT_AFTER = Data::DecodedLeaf::SEGMENT_AFTER
23
+
24
+ #: (Array[untyped]) -> void
25
+ def initialize(messages)
26
+ @messages = messages
27
+ freeze
28
+ end
29
+
30
+ # Each part carved, as CARVED lists them, with its bytes.
31
+ #: () -> Array[Hash[String, untyped]]
32
+ def to_a
33
+ totals = carved
34
+ CARVED.map do |part, kind|
35
+ { "part" => part, **(kind ? { "kind" => kind } : {}), "bytes" => totals[[part, kind]] }
36
+ end
37
+ end
38
+
39
+ private
40
+
41
+ # The bytes carved into each part, by [part, kind].
42
+ #: () -> Hash[[String, String?], Integer]
43
+ def carved
44
+ totals = CARVED.to_h { [it, 0] }
45
+ sent = {} #: Hash[String, bool]
46
+ each_said do |path, role, text|
47
+ pieces(text) do |segment, piece|
48
+ part = part_of(RequestChannel.new(path, segment, role:).to_s, piece, sent)
49
+ totals[part] = totals.fetch(part) + written(piece) if part
50
+ end
51
+ end
52
+ totals
53
+ end
54
+
55
+ # Each string a message says, with its path, keys and indexes joined by dots, and its message's role.
56
+ #: () { (String, String?, String) -> void } -> void
57
+ def each_said(&said)
58
+ each_string(@messages, ["messages"]) do |path, text|
59
+ said.call(path.join("."), role_at(path), text) if said?(path)
60
+ end
61
+ end
62
+
63
+ # The part a piece by channel is carved into, or nil where it stays in the conversation; a system notice's kind
64
+ # by whether sent holds the same piece already, which it then does.
65
+ #: (String, String, Hash[String, bool]) -> [String, String?]?
66
+ def part_of(channel, piece, sent)
67
+ return ["reminders", nil] if channel == "reminder"
68
+ return unless channel == "system_message"
69
+
70
+ resent = sent.key?(piece)
71
+ sent[piece] = true
72
+ ["system_notices", resent ? "resent" : "first_sent"]
73
+ end
74
+
75
+ # Each string in value, with its path from path, keys and indexes as strings.
76
+ #: (untyped, Array[String]) { (Array[String], String) -> void } -> void
77
+ def each_string(value, path, &found)
78
+ case value
79
+ when Hash then value.each { |key, inner| each_string(inner, [*path, key.to_s], &found) }
80
+ when Array then value.each_with_index { |inner, index| each_string(inner, [*path, index.to_s], &found) }
81
+ when String then found.call(path, value)
82
+ end
83
+ end
84
+
85
+ # Whether the string at path is text a message says, in its content, rather than a field naming its role, a
86
+ # block's type or an id.
87
+ #: (Array[String]) -> bool
88
+ def said?(path) = path[2] == "content" && (path.size == 3 || SAID.include?(path.last))
89
+
90
+ # The role of the message path lies in, or nil for none that is a string.
91
+ #: (Array[String]) -> String?
92
+ def role_at(path)
93
+ message = @messages[Integer(path.fetch(1))]
94
+ role = message.is_a?(Hash) ? message["role"] : nil
95
+ role.is_a?(String) ? role : nil
96
+ end
97
+
98
+ # Each piece of text with its segment, as DecodedLeaf splits it, each tag a reminder piece of its own.
99
+ #: (String) { (String, String) -> void } -> void
100
+ def pieces(text, &piece_in)
101
+ segment = "plain"
102
+ text.split(TAGS, -1).each do |piece|
103
+ next piece_in.call(segment, piece) unless SEGMENT_AFTER.key?(piece)
104
+
105
+ piece_in.call("reminder", piece)
106
+ segment = SEGMENT_AFTER.fetch(piece)
107
+ end
108
+ end
109
+
110
+ # The bytes piece takes inside a JSON string.
111
+ #: (String) -> Integer
112
+ def written(piece) = JSON.generate(piece).bytesize - 2
113
+ end
114
+ end
115
+ end
@@ -0,0 +1,59 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ require "json"
5
+ require_relative "carved_message_bytes"
6
+
7
+ module Principles
8
+ # The domain logic, and the mediation of persistence. models/CLAUDE.md owns the boundary.
9
+ module Models
10
+ # A turn opening's context split into parts by bytes, each counted as the request writes it in JSON, so the parts
11
+ # sum to its bytes: the system prompt, the tool definitions, those of the tools the host defers loading, the host's
12
+ # reminders and system notices, and the conversation, every message so far but what the host added. It gives part
13
+ # names and counts alone, never text.
14
+ class ContextParts
15
+ # The keys of a request holding its context.
16
+ KEYS = %w[system tools messages].freeze #: Array[String]
17
+
18
+ # body is the request as the host sent it.
19
+ #: (Hash[String, untyped]) -> void
20
+ def initialize(body)
21
+ @body = body
22
+ freeze
23
+ end
24
+
25
+ # Each part with its bytes, in the order a request holds them.
26
+ #: () -> Array[Hash[String, untyped]]
27
+ def to_a
28
+ deferred = deferred_bytes
29
+ carved = CarvedMessageBytes.new(Array(@body["messages"])).to_a
30
+ conversation = written("messages") - carved.sum { it.fetch("bytes") }
31
+ [{ "part" => "system_prompt", "bytes" => written("system") },
32
+ { "part" => "tool_definitions", "bytes" => written("tools") - deferred },
33
+ { "part" => "deferred_tool_definitions", "bytes" => deferred },
34
+ *carved, { "part" => "conversation", "bytes" => conversation }]
35
+ end
36
+
37
+ # Every part's bytes together: the request's system prompt, tools and messages, each written as compact JSON.
38
+ #: () -> Integer
39
+ def bytes = KEYS.sum { written(it) }
40
+
41
+ private
42
+
43
+ # The bytes of the tools the host defers loading, each as JSON writes it with the comma that parts it from
44
+ # another, while the request lists more than one tool.
45
+ #: () -> Integer
46
+ def deferred_bytes
47
+ tools = @body["tools"]
48
+ return 0 unless tools.is_a?(Array)
49
+
50
+ deferred = tools.select { it.is_a?(Hash) && it["defer_loading"] == true }
51
+ deferred.sum { JSON.generate(it).bytesize } + [deferred.size, tools.size - 1].min
52
+ end
53
+
54
+ # The bytes of the request's value at key, written as compact JSON, or none where it has none.
55
+ #: (String) -> Integer
56
+ def written(key) = @body.key?(key) ? JSON.generate(@body[key]).bytesize : 0
57
+ end
58
+ end
59
+ end
@@ -10,12 +10,18 @@ module Principles
10
10
  # The domain logic, and the mediation of persistence. models/CLAUDE.md owns the boundary.
11
11
  module Models
12
12
  # The changes a correction declares it made to the map after the audit began: the members it moved,
13
- # and the members whose role or check a fix changed, which each fixed disposition lists in
13
+ # and the members whose role, check, name or reason a fix changed, which each fixed disposition lists in
14
14
  # changed_map_entries, and the members fixed dispositions removed. This tool checks them against the
15
15
  # map at the base commit, which may also hold
16
16
  # members added since, needing no declaration, as a fix maps a member a finding said was missing (T69); whether a
17
17
  # change fixes its finding is the agent's judgement.
18
18
  class DeclaredMapChanges
19
+ # The fields of a member's entry, beside its place, that say what it is, which a fix may claim it changed.
20
+ CLAIMED = %w[role check name reason].freeze #: Array[String]
21
+
22
+ # Those a fix sets, as change-member-name and change-member-reason do, and never removes.
23
+ SAID = %w[name reason].freeze #: Array[String]
24
+
19
25
  # The answer's moved_members and each disposition's changed_map_entries and removed_members.
20
26
  #: (untyped) -> DeclaredMapChanges
21
27
  def self.declared_in(response)
@@ -85,7 +91,7 @@ module Principles
85
91
  end
86
92
 
87
93
  # The map file, when the correction moved a member in it, even under its own id, a fix changed a
88
- # member's role or check in it, or added/removed members in it, so the agent commits it too.
94
+ # member's role, check, name or reason in it, or added/removed members in it, so the agent commits it too.
89
95
  #: (String, ?added: Array[String]) -> Array[String]
90
96
  def files_to_commit(map_file, added: [])
91
97
  empty? && added.empty? ? [] : [map_file]
@@ -93,7 +99,7 @@ module Principles
93
99
 
94
100
  private
95
101
 
96
- # Replay removals, then moves and role/check changes, then include members added during the correction.
102
+ # Replay removals, then moves and role, check, name and reason changes, then members added during the correction.
97
103
  #: (Principle, Principle) -> Principle
98
104
  def reconstructed(base, current)
99
105
  retained = @removals.applied(base, current)
@@ -124,16 +130,18 @@ module Principles
124
130
  end
125
131
  return replayed(map, id, current.member(id)) unless as_at_base?(map, current, id)
126
132
 
127
- raise Error.new("claimed_change_missing", "#{id}'s role and check did not change during this audit",
128
- "The role and check of #{id} are as they were at the base commit; remove it from " \
129
- "changed_map_entries.")
133
+ raise Error.new("claimed_change_missing", "#{id}'s role, check, name and reason did not change during this " \
134
+ "audit",
135
+ "The role, check, name and reason of #{id} are as they were at the base commit; remove it " \
136
+ "from changed_map_entries.")
130
137
  end
131
138
 
132
- # The map with the member's role and check changed to now's, as change-member-role, change-member-check
133
- # and remove-member-check changed them.
139
+ # The map with the member's role, name, reason and check changed to now's, as change-member-role, -name,
140
+ # -reason, change-member-check and remove-member-check changed them; no command removes a name or reason.
134
141
  #: (Principle, String, Hash[String, untyped]) -> Principle
135
142
  def replayed(map, id, now)
136
- roled = map.changing_role(id, now.fetch("role"))
143
+ said = (SAID & now.keys).reduce(map) { |each, field| each.saying(id, field, now.fetch(field)) }
144
+ roled = said.changing_role(id, now.fetch("role"))
137
145
  return roled.changing_check(id, now.fetch("check")) if now.key?("check")
138
146
 
139
147
  roled.member(id).key?("check") ? roled.removing_check(id) : roled
@@ -141,13 +149,13 @@ module Principles
141
149
 
142
150
  #: (String, Hash[String, untyped], Hash[String, untyped]) -> Hash[String, untyped]
143
151
  def changed_fields(id, was, now)
144
- changed = %w[role check].reject { |field| was[field] == now[field] }
152
+ changed = CLAIMED.reject { |field| was[field] == now[field] }
145
153
  { "member_id" => id, **changed.to_h { |field| [field, { "was" => was[field], "now" => now[field] }] } }
146
154
  end
147
155
 
148
156
  #: (Principle, Principle, String) -> bool
149
157
  def as_at_base?(map, current, id)
150
- map.member(id).slice("role", "check") == current.member(id).slice("role", "check")
158
+ CLAIMED.all? { |field| map.member(id)[field] == current.member(id)[field] }
151
159
  end
152
160
 
153
161
  #: (String, String) -> Error
@@ -160,8 +168,9 @@ module Principles
160
168
  Error.new("stale_map", "The map of #{principle_id} changed during this audit",
161
169
  "If you moved a member to fix a finding, declare it in the answer's moved_members as " \
162
170
  "{\"from\": OLD_ID, \"to\": NEW_ID}, and a move that kept its id, as narrowing or widening a " \
163
- "passage, as {\"from\": ID, \"to\": ID}; if a fix changed a member's role or check, list the " \
164
- "member's id in that fixed disposition's changed_map_entries. If a fix removed a member with " \
171
+ "passage, as {\"from\": ID, \"to\": ID}; if a fix changed a member's role, check, name or reason, " \
172
+ "list the member's id in that fixed disposition's changed_map_entries. If a fix removed a " \
173
+ "member with " \
165
174
  "remove-member, list its original id in that fixed disposition's removed_members. " \
166
175
  "In git, a member you added with " \
167
176
  "add-member needs no declaration, as long as nothing else changed.\n" \
@@ -0,0 +1,73 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ module Principles
5
+ # The domain logic, and the mediation of persistence. models/CLAUDE.md owns the boundary.
6
+ module Models
7
+ # The thinking blocks a response says the server dropped from its request, each by its path in the request, such
8
+ # as messages.10.content.0. A dropped block costs no tokens, so a request's context is measured without them.
9
+ class DroppedThinking
10
+ # response is the response as the host logged it, or nil for none.
11
+ #: (untyped) -> void
12
+ def initialize(response)
13
+ # Deepest and latest first, so leaving one out moves no index another names.
14
+ @paths = listed(response).map { it.split(".") }.sort_by { |keys| keys.map { sortable(it) } }
15
+ .reverse.freeze #: Array[Array[String]]
16
+ freeze
17
+ end
18
+
19
+ # body without each dropped block, body itself left as it was; a path naming nothing in it is passed over.
20
+ #: (untyped) -> untyped
21
+ def from(body) = @paths.reduce(body) { |kept, keys| without(kept, keys) }
22
+
23
+ private
24
+
25
+ # The path of each block response says was dropped.
26
+ #: (untyped) -> Array[String]
27
+ def listed(response)
28
+ transformations = response.is_a?(Hash) ? Array(response["input_transformations"]) : []
29
+ transformations.filter_map { it["path"] if it.is_a?(Hash) && it["type"] == "thinking_dropped" }.grep(String)
30
+ end
31
+
32
+ # A key as it sorts beside its siblings: an index by its number, before any name.
33
+ #: (String) -> [Integer, Integer, String]
34
+ def sortable(key)
35
+ index = index_of(key)
36
+ index ? [0, index, ""] : [1, 0, key]
37
+ end
38
+
39
+ # The array index key names, or nil for a key that is no index.
40
+ #: (String?) -> Integer?
41
+ def index_of(key) = key&.match?(/\A\d+\z/) ? key.to_i : nil
42
+
43
+ # value without what keys name in it, copied only along the way there; value itself where keys name nothing.
44
+ #: (untyped, Array[String]) -> untyped
45
+ def without(value, keys)
46
+ key, *rest = keys
47
+ case value
48
+ when Array then without_at(value, index_of(key), rest)
49
+ when Hash then without_key(value, key.to_s, rest)
50
+ else value
51
+ end
52
+ end
53
+
54
+ # hash without key, or without what rest names under it; hash itself where it has no key.
55
+ #: (Hash[untyped, untyped], String, Array[String]) -> Hash[untyped, untyped]
56
+ def without_key(hash, key, rest)
57
+ return hash unless hash.key?(key)
58
+
59
+ rest.empty? ? hash.except(key) : hash.merge(key => without(hash[key], rest))
60
+ end
61
+
62
+ # list without the element at index, or without what rest names inside it; list itself where index is none.
63
+ #: (Array[untyped], Integer?, Array[String]) -> Array[untyped]
64
+ def without_at(list, index, rest)
65
+ return list unless index && index < list.size
66
+
67
+ copy = list.dup
68
+ rest.empty? ? copy.delete_at(index) : copy[index] = without(list[index], rest)
69
+ copy
70
+ end
71
+ end
72
+ end
73
+ end
@@ -18,7 +18,8 @@ module Principles
18
18
  LOGGED_REQUEST_SCAN => {
19
19
  "jq" => "decodes each captured request into its text lines",
20
20
  "rg" => "finds mapped members' lines in the decoded requests"
21
- }
21
+ },
22
+ "show-context-budget" => { "jq" => "reads each captured request's shape, to find the turns it opened" }
22
23
  }.freeze #: Hash[String, Hash[String, String]]
23
24
 
24
25
  # The feature command runs, with on_path saying whether PATH holds a tool.
@@ -38,9 +38,9 @@ module Principles
38
38
  #: () -> Hash[String, untyped]
39
39
  def source = @reference.source(version)
40
40
 
41
- # Its entry in a map, playing role.
42
- #: (String) -> Hash[String, untyped]
43
- def member(role) = { "path" => member_path, "role" => role, "pinned" => pinned }
41
+ # Its entry in a map, playing the part played gives: its role, and any name, reason and check.
42
+ #: (Hash[String, untyped]) -> Hash[String, untyped]
43
+ def member(played) = { "path" => member_path, **played, "pinned" => pinned }
44
44
 
45
45
  # What add-member reports of it: its id, the lines it spans and where it comes from. No host's loading of a
46
46
  # plugin's file is derived yet.
@@ -13,31 +13,39 @@ module Principles
13
13
  # members is each member as the scan reports it, with its status and the places it was seen; scanned is how many
14
14
  # requests the scan read whole, and unreadable how many it could not, since what they held is unknown; carried
15
15
  # names each member a full audit carries forward, which is listed too, marked, since one that never loads still
16
- # fails its principle.
17
- #: (Array[Hash[String, untyped]], scanned: Integer, ?unreadable: Integer, ?carried: Array[String]) -> void
18
- def initialize(members, scanned:, unreadable: 0, carried: [])
16
+ # fails its principle; model_turns counts the model turns at each turn position, in all and by query_source,
17
+ # by the name each prints under.
18
+ #: (Array[Hash[String, untyped]], scanned: Integer,
19
+ #| model_turns: { model_turns_by_position: Hash[String, Integer],
20
+ #| model_turns_by_query_source: Hash[String, Hash[String, Integer]] },
21
+ #| ?unreadable: Integer, ?carried: Array[String]) -> void
22
+ def initialize(members, scanned:, model_turns:, unreadable: 0, carried: [])
19
23
  @members = members
20
24
  @carried = carried
25
+ @model_turns = model_turns
21
26
  @scanned = scanned
22
27
  @unreadable = unreadable
23
28
  freeze
24
29
  end
25
30
 
26
- # The requests scanned, any it could not read, and each member's status, the requests seen holding its lines and
27
- # its most bytes in one, and whether the audit carries it forward.
31
+ # The requests scanned, any it could not read, the model turns by turn position, each member's status, the
32
+ # requests seen holding its lines and its most bytes in one, and whether the audit carries it forward, and, while
33
+ # any is, the key of each member seen only where the agent read, sent or quoted it.
28
34
  #: () -> Hash[String, untyped]
29
35
  def to_h
36
+ reaches = @members.map { [it.fetch("member"), MemberReach.new(it)] }
37
+ read = reaches.select { |_, reach| reach.seen_only_as_read? }.map(&:first)
30
38
  { "requests" => @scanned, **({ "unreadable" => @unreadable } if @unreadable.positive?),
31
- "members" => @members.map { reach(it) } }
39
+ **@model_turns.transform_keys(&:to_s), "members" => reaches.map { |key, reach| shown(key, reach) },
40
+ **({ "seen_only_as_read" => read } unless read.empty?) }
32
41
  end
33
42
 
34
43
  private
35
44
 
36
- # member's reach, marked when the audit carries it forward.
37
- #: (Hash[String, untyped]) -> Hash[String, untyped]
38
- def reach(member)
39
- reach = MemberReach.new(member).to_h
40
- @carried.include?(member.fetch("member")) ? reach.merge("carried_forward" => true) : reach
45
+ # The reach of the member keyed key, marked when the audit carries it forward.
46
+ #: (String, MemberReach) -> Hash[String, untyped]
47
+ def shown(key, reach)
48
+ @carried.include?(key) ? reach.to_h.merge("carried_forward" => true) : reach.to_h
41
49
  end
42
50
  end
43
51
  end
@@ -0,0 +1,28 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ module Principles
5
+ module Models
6
+ # What saving a map does to its format, against the map as stored, and the first release of principles that
7
+ # reads the new format where an earlier release cannot, so a write locking out older copies can say so.
8
+ class MapFormatRaise
9
+ # The first release that reads each map format some earlier release cannot: every release reads formats 1 and
10
+ # 2, 0.1.3 reads up to 2 and 0.1.4 up to 4, as each tag's Data::MapFiles::NEWEST_FORMAT says (checked
11
+ # 2026-11-30 with git grep on v0.0.1, v0.1.3 and v0.1.4).
12
+ FIRST_READ_IN = { 4 => "0.1.4", 5 => "0.1.5" }.freeze #: Hash[Integer, String]
13
+
14
+ # principles are the project's mapped principles, holding map as stored, if it is; map is it as it will be saved.
15
+ #: (MappedPrinciples, Principle) -> void
16
+ def initialize(principles, map)
17
+ @from = principles.mapped?(map.id) ? principles.find(map.id).format : 1 #: Integer
18
+ @to = map.format #: Integer
19
+ freeze
20
+ end
21
+
22
+ # The format it was, the format it will be, and the release that first reads it where it rose to a format an
23
+ # earlier release cannot read, else nil.
24
+ #: () -> { from: Integer, to: Integer, release: String? }
25
+ def to_h = { from: @from, to: @to, release: (FIRST_READ_IN[@to] if @to > @from) }
26
+ end
27
+ end
28
+ end