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
@@ -6,14 +6,12 @@ require_relative "../data/project_root"
6
6
  require_relative "../data/principles_store"
7
7
  require_relative "../data/repository"
8
8
  require_relative "../data/claude_code_home"
9
+ require_relative "../data/user_request_logging_folder"
9
10
  require_relative "candidate_inventory"
10
11
  require_relative "entry_files"
11
12
  require_relative "member"
12
13
  require_relative "member_file"
13
- require_relative "hook_commands"
14
- require_relative "loaded_files"
15
14
  require_relative "located_text"
16
- require_relative "member_loads"
17
15
  require_relative "member_lines"
18
16
  require_relative "mapped_principles"
19
17
  require_relative "member_snapshots"
@@ -25,9 +23,12 @@ require_relative "principles_folder_move"
25
23
  require_relative "sent_answer"
26
24
  require_relative "guidance_search_paths"
27
25
  require_relative "request_logging"
26
+ require_relative "session_registry"
27
+ require_relative "user_settings_entries"
28
28
  require_relative "survey_search_paths"
29
29
  require_relative "installed_plugins"
30
30
  require_relative "plugin_reference"
31
+ require_relative "project_harness"
31
32
 
32
33
  module Principles
33
34
  # The domain logic, and the mediation of persistence. models/CLAUDE.md owns the boundary.
@@ -46,12 +47,13 @@ module Principles
46
47
  def self.at(root)
47
48
  files = Data::ProjectFiles.new(root)
48
49
  new(files: files, store: Data::PrinciplesStore.at(files.root), repository: Data::Repository.new(files.root),
49
- claude_code: Data::ClaudeCodeHome.from_environment)
50
+ claude_code: Data::ClaudeCodeHome.from_environment,
51
+ user_request_logging: Data::UserRequestLoggingFolder.from_environment)
50
52
  end
51
53
 
52
54
  #: (files: Data::ProjectFiles, store: Data::PrinciplesStore, repository: Data::Repository,
53
- #| claude_code: Data::ClaudeCodeHome) -> void
54
- def initialize(files:, store:, repository:, claude_code:)
55
+ #| claude_code: Data::ClaudeCodeHome, user_request_logging: Data::UserRequestLoggingFolder) -> void
56
+ def initialize(files:, store:, repository:, claude_code:, user_request_logging:)
55
57
  @files = files
56
58
  @maps = store.maps #: Data::MapFiles
57
59
  @audits = store.audits #: Data::AuditFiles
@@ -59,6 +61,7 @@ module Principles
59
61
  @guidance_search_paths = store.guidance_search_paths #: Data::GuidanceSearchPathsFile
60
62
  @request_logging = store.request_logging #: Data::RequestLoggingFolder
61
63
  @claude_code = claude_code
64
+ @user_request_logging = user_request_logging
62
65
  @history = nil #: ProjectHistory?
63
66
  @principle_histories = {} #: Hash[[String, PrincipleMappingHistory?], PrincipleHistory]
64
67
  end
@@ -89,9 +92,16 @@ module Principles
89
92
 
90
93
  # The requests the host sent, captured into a folder git must ignore.
91
94
  #: () -> RequestLogging
92
- def request_logging = RequestLogging.new(@request_logging, @files)
95
+ def request_logging
96
+ RequestLogging.new(@request_logging, @files, registry: SessionRegistry.new(@user_request_logging, @repository),
97
+ user_folder: @user_request_logging)
98
+ end
93
99
 
94
100
  # The plugins Claude Code installed that a session in the project loads, as installed for its main checkout.
101
+ # The entries in the user's own settings that turn request logging on for every session they start.
102
+ #: () -> UserSettingsEntries
103
+ def user_settings_entries = UserSettingsEntries.new(@claude_code, @user_request_logging)
104
+
95
105
  #: () -> InstalledPlugins
96
106
  def installed_plugins = InstalledPlugins.new(@claude_code, main_checkout: @repository.main_checkout_root)
97
107
 
@@ -178,16 +188,6 @@ module Principles
178
188
  @files.file?(OLDER_STATE) ? [OLDER_STATE] : []
179
189
  end
180
190
 
181
- # Each member's hash now by key, or the refusal that says why its text cannot be found or read.
182
- #: (PrincipleMembers) -> Hash[String, untyped]
183
- def current_by_key(members)
184
- members.to_h do |member|
185
- [member.key, located_text(member.locator).sha256]
186
- rescue Error => e
187
- [member.key, e.payload]
188
- end
189
- end
190
-
191
191
  # A member's text now and how fresh it is, which the block says from its hash. A member whose place
192
192
  # in its file is gone is locator_lost; one whose file cannot be read is unavailable. Both keep the
193
193
  # refusal. A plugin member no installed plugin gives, for any reason, is plugin_unresolved with that reason, a
@@ -204,20 +204,9 @@ module Principles
204
204
  { "freshness" => LocateRefusal.new(e.payload).member_state, "error" => e.payload }
205
205
  end
206
206
 
207
- # Each member's MemberLoads by id: when each host loads it into context, with the size of what loads, and
208
- # the project hooks whose commands name its file, read once for them all unless the caller already read them.
209
- #: (PrincipleMembers, ?HookCommands) -> Hash[String, MemberLoads]
210
- def member_loads(members, hooks = hook_commands)
211
- members.to_h { |member| [member.id, MemberLoads.read(@files, member.locator, hooks: hooks)] }
212
- end
213
-
214
- # The files members load, each read whole once, with the project's hooks as hooks read them.
215
- #: (PrincipleMembers, HookCommands) -> LoadedFiles
216
- def loaded_files(members, hooks) = LoadedFiles.read(@files, members, hooks: hooks)
217
-
218
- # The command hooks in each of paths present, the project settings files unless others are given.
219
- #: (?Array[String]) -> HookCommands
220
- def hook_commands(paths = HookCommands::SETTINGS) = HookCommands.read(@files, paths)
207
+ # What a host's harness reads from the project's files.
208
+ #: () -> ProjectHarness
209
+ def harness = ProjectHarness.new(@files)
221
210
 
222
211
  # The root entry files every session of a host loads, whether one links the other and which git does not
223
212
  # track.
@@ -0,0 +1,48 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ require_relative "../data/project_files"
5
+ require_relative "hook_commands"
6
+ require_relative "loaded_files"
7
+ require_relative "member_loads"
8
+ require_relative "plugin_enabled_in_project_settings"
9
+
10
+ module Principles
11
+ # The domain logic, and the mediation of persistence. models/CLAUDE.md owns the boundary.
12
+ module Models
13
+ # What a host's harness reads from the project's files: the hooks its settings name, when each member loads,
14
+ # the files members load, the settings line that enables the principles plugin, and where a file a hook names
15
+ # sits in the project.
16
+ class ProjectHarness
17
+ #: (Data::ProjectFiles) -> void
18
+ def initialize(files)
19
+ @files = files
20
+ freeze
21
+ end
22
+
23
+ # Each member's MemberLoads by id: when each host loads it into context, with the size of what loads, and
24
+ # the project hooks whose commands name its file, read once for them all unless the caller already read them.
25
+ #: (PrincipleMembers, ?HookCommands) -> Hash[String, MemberLoads]
26
+ def member_loads(members, hooks = hook_commands)
27
+ members.to_h { |member| [member.id, MemberLoads.read(@files, member.locator, hooks: hooks)] }
28
+ end
29
+
30
+ # The files members load, each read whole once, with the project's hooks as hooks read them.
31
+ #: (PrincipleMembers, HookCommands) -> LoadedFiles
32
+ def loaded_files(members, hooks) = LoadedFiles.read(@files, members, hooks: hooks)
33
+
34
+ # The command hooks in each of paths present, the project settings files unless others are given.
35
+ #: (?Array[String]) -> HookCommands
36
+ def hook_commands(paths = HookCommands::SETTINGS) = HookCommands.read(@files, paths)
37
+
38
+ # The project settings line that enables the principles plugin for the team, or nil.
39
+ #: () -> PluginEnabledInProjectSettings?
40
+ def plugin_enabled_in_project_settings = PluginEnabledInProjectSettings.read(@files)
41
+
42
+ # absolute's path inside the project, as a hook names the file a call edits, or nil when it is not a full path
43
+ # into it.
44
+ #: (String) -> String?
45
+ def path_in_project(absolute) = @files.path_in_project(absolute)
46
+ end
47
+ end
48
+ end
@@ -4,9 +4,10 @@
4
4
  module Principles
5
5
  # The domain logic, and the mediation of persistence. models/CLAUDE.md owns the boundary.
6
6
  module Models
7
- # The hooks that run this tool's two hook commands for a project without the principles plugin, on each host: the
7
+ # The hooks that run this tool's hook commands for a project without the principles plugin, on each host: the
8
8
  # file the project's own hooks go in, and the command each event runs. Claude Code runs a hook after a failed shell
9
- # call under an event of its own; Codex has none, its PostToolUse running after every call.
9
+ # call under an event of its own; Codex has none, its PostToolUse running after every call. Codex has no Edit or
10
+ # Write tool either, which the hook before a carrier edit matches, so that hook is Claude Code's alone.
10
11
  class ReportHooks
11
12
  # One hook: the event that runs it, the matcher that picks which of the event's runs, and its command.
12
13
  class Hook
@@ -52,14 +53,18 @@ module Principles
52
53
  SESSION_START = Hook.new("SessionStart", "startup|resume|clear|compact", "report-at-session-start") #: Hook
53
54
  AFTER_A_CALL = Hook.new("PostToolUse", "Bash", "report-after-commit") #: Hook
54
55
 
56
+ # The hook before each file edit, which points the first edit of each carrier kind at its practices page.
57
+ BEFORE_AN_EDIT = Hook.new("PreToolUse", "Edit|Write", "report-before-carrier-edit") #: Hook
58
+
55
59
  # The commands the hooks run, once each.
56
- COMMANDS = [SESSION_START.command, AFTER_A_CALL.command].freeze #: Array[String]
60
+ COMMANDS = [SESSION_START.command, BEFORE_AN_EDIT.command, AFTER_A_CALL.command].freeze #: Array[String]
57
61
 
58
62
  # Claude Code first, its file the gitignored local one, since a committed one would run for a teammate without
59
63
  # this tool and fail every session start of theirs.
60
64
  HOSTS = [
61
65
  Host.new("Claude Code", ".claude/settings.local.json",
62
- [SESSION_START, AFTER_A_CALL, Hook.new("PostToolUseFailure", "Bash", "report-after-commit")],
66
+ [SESSION_START, BEFORE_AN_EDIT, AFTER_A_CALL,
67
+ Hook.new("PostToolUseFailure", "Bash", "report-after-commit")],
63
68
  offered: "always, as the host this tool serves first"),
64
69
  Host.new("Codex", ".codex/hooks.json", [SESSION_START, AFTER_A_CALL],
65
70
  offered: "always, since this command does not tell which host runs this project's sessions",
@@ -0,0 +1,62 @@
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 channel by which a string reached a captured request, from its JSON path, segment and the role of the
8
+ # message it sits in, so the agent tells the host's own load from the agent reading or quoting a file. The system
9
+ # prompt and the tool definitions are the host's; within a message, a tool's input is what the agent sent, a
10
+ # reminder tag is the host's, wherever it sits, and a tool's result is what came back. Plain text in a message
11
+ # whose role is system is the host's too, as its skill listing is; plain text in any other message is
12
+ # message_text, since neither says whose it is. Printed output has no channel of its own: it arrives as a tool
13
+ # result or a reminder.
14
+ class RequestChannel
15
+ # The channel each top-level key of a request names by itself.
16
+ TOP_LEVEL = { "system" => "system", "tools" => "tool_definition" }.freeze #: Hash[String, String]
17
+ # Every channel, in the order counts of them print: the host's own first, then what the agent sent and got back.
18
+ NAMES = %w[system system_message tool_definition reminder tool_input tool_result message_text other]
19
+ .freeze #: Array[String]
20
+ # The channels by which the host itself loads text; any other is the agent reading, sending or quoting it.
21
+ HOST = %w[system system_message tool_definition reminder].freeze #: Array[String]
22
+
23
+ # path is the string's JSON path, its keys joined by dots, such as messages.2.content.0.content; segment is
24
+ # reminder or plain; role is that of the message it sits in, or nil outside one.
25
+ #: (String, String, role: String?) -> void
26
+ def initialize(path, segment, role:)
27
+ @keys = path.split(".").freeze #: Array[String]
28
+ @segment = segment
29
+ @role = role
30
+ freeze
31
+ end
32
+
33
+ # Its channel's name.
34
+ #: () -> String
35
+ def to_s
36
+ top = @keys.first.to_s
37
+ return TOP_LEVEL.fetch(top) if TOP_LEVEL.key?(top)
38
+ return "other" unless top == "messages"
39
+
40
+ in_message
41
+ end
42
+
43
+ private
44
+
45
+ # The channel of a string inside a message: what the agent sent a tool, a reminder, what a tool gave back, or
46
+ # plain text, the host's in a system message.
47
+ #: () -> String
48
+ def in_message
49
+ return "tool_input" if block_key == "input"
50
+ return "reminder" if @segment == "reminder"
51
+ return "tool_result" if block_key == "content"
52
+
53
+ @role == "system" ? "system_message" : "message_text"
54
+ end
55
+
56
+ # The key under a message's content block, such as input, content or text, or nil for a message whose content
57
+ # is one string.
58
+ #: () -> String?
59
+ def block_key = @keys[4]
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,62 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ require_relative "../data/logged_request_scan"
5
+ require_relative "../data/request_shape"
6
+ require_relative "turn_position"
7
+
8
+ module Principles
9
+ # The domain logic, and the mediation of persistence. models/CLAUDE.md owns the boundary.
10
+ module Models
11
+ # Whether a captured request was a model turn of a thread or a side call made on its behalf, such as a summary
12
+ # or a permission check, which the host sends under the same query_source. The host does not say. A request
13
+ # continuing a thread is a model turn. Any other request under one of the host's side-call sources is a side call,
14
+ # since it can carry the thread's whole context and tools. Any other request still is told by a heuristic from its
15
+ # shape alone: a model turn lists tools, and a side call lists none and holds one or two messages. A request that
16
+ # is neither is unclassified rather than guessed at.
17
+ class RequestKind
18
+ # Every kind, in the order counts of them print.
19
+ NAMES = %w[model_turn side_call unclassified].freeze #: Array[String]
20
+ # The most messages a side call holds.
21
+ SIDE_CALL_MESSAGES = 2
22
+ # The query_sources whose requests that continue no thread are the host's side calls, a label-based exception to
23
+ # the shape rule from one log: on 2026-11-28 this project's held 21, 10, 9 and 1 of them, each with tools, none
24
+ # in a thread and none continued. sdk is left out, since a headless run's own model turns go under it.
25
+ SIDE_CALL_SOURCES = %w[away_summary compact prompt_suggestion web_search_tool].freeze #: Array[String]
26
+
27
+ # Each of scan's requests with its kind, from its shape, and a model turn with its
28
+ # TurnPosition too; one the scan read no shape of, as it could not read it through, is left without.
29
+ #: (Data::LoggedRequestScan) -> Array[Hash[String, String?]]
30
+ def self.labelled(scan)
31
+ shapes = scan.request_shapes
32
+ scan.requests.map do |request|
33
+ shape = shapes[request.fetch("file").to_s]
34
+ next request unless shape
35
+
36
+ kind = new(shape, query_source: request["query_source"]).to_s
37
+ next request.merge("kind" => kind) unless kind == "model_turn"
38
+
39
+ request.merge("kind" => kind, "turn_position" => TurnPosition.new(shape).to_s)
40
+ end
41
+ end
42
+
43
+ # shape is the request's, as Data::RequestShape gives it, and query_source the one its index line gives, if any.
44
+ #: (Data::RequestShape, ?query_source: String?) -> void
45
+ def initialize(shape, query_source: nil)
46
+ @shape = shape
47
+ @query_source = query_source
48
+ freeze
49
+ end
50
+
51
+ # Its kind's name.
52
+ #: () -> String
53
+ def to_s
54
+ return "model_turn" if @shape.continues_thread?
55
+ return "side_call" if SIDE_CALL_SOURCES.include?(@query_source)
56
+ return "model_turn" if @shape.tools.positive?
57
+
58
+ (1..SIDE_CALL_MESSAGES).cover?(@shape.messages) ? "side_call" : "unclassified"
59
+ end
60
+ end
61
+ end
62
+ end
@@ -2,14 +2,19 @@
2
2
  # frozen_string_literal: true
3
3
 
4
4
  require_relative "../error"
5
+ require_relative "request_logging_guard"
6
+ require_relative "user_logged_requests"
5
7
  require_relative "../data/request_logging_folder"
6
8
  require_relative "../data/project_files"
9
+ require_relative "../data/user_request_logging_folder"
7
10
  require_relative "captured_sessions"
8
11
  require_relative "logged_request_scan_completeness"
9
12
  require_relative "logged_request_reach"
10
13
  require_relative "member_reach"
14
+ require_relative "request_kind"
11
15
  require_relative "kept_sessions"
12
16
  require_relative "members_in_logged_requests"
17
+ require_relative "turn_opening"
13
18
 
14
19
  module Principles
15
20
  # The domain logic, and the mediation of persistence. models/CLAUDE.md owns the boundary.
@@ -18,15 +23,27 @@ module Principles
18
23
  # request holds the session's whole working context. Each command here checks first that git ignores the folder
19
24
  # and every file in it, and refuses otherwise; this is the one guard they share.
20
25
  class RequestLogging
26
+ # What a scan reports: how many members have each status, each member with where it was seen, the requests
27
+ # with no query_source, those quoting a logged request, the requests by kind, the model turns by turn
28
+ # position, the requests it could not read, and how complete it was.
29
+ #: type report = { members_by_status: Hash[String, Integer], members: Array[Hash[String, untyped]],
30
+ #| orphans: Integer, quoting_requests: Array[String], requests_by_kind: Hash[String, Integer],
31
+ #| model_turns_by_position: Hash[String, Integer],
32
+ #| model_turns_by_query_source: Hash[String, Hash[String, Integer]],
33
+ #| unreadable: Array[Hash[String, String]], completeness: Hash[String, untyped] }
34
+
21
35
  FOLDER = Data::RequestLoggingFolder
22
36
  IGNORE_EVERYTHING = "*\n"
23
- # The paths each command checks git ignores, beside every file already in the folder.
24
- GUARDED = [FOLDER::IGNORE, FOLDER::SETTINGS, "#{FOLDER::REQUESTS}/"].freeze #: Array[String]
25
37
 
26
- #: (Data::RequestLoggingFolder, Data::ProjectFiles) -> void
27
- def initialize(folder, files)
38
+ # registry is the sessions registered here while request logging is on in the user's own settings, which have
39
+ # the host write every project's requests to user_folder.
40
+ #: (Data::RequestLoggingFolder, Data::ProjectFiles, ?registry: SessionRegistry?,
41
+ #| ?user_folder: Data::UserRequestLoggingFolder?) -> void
42
+ def initialize(folder, files, registry: nil, user_folder: nil)
28
43
  @folder = folder
29
- @files = files
44
+ @guard = RequestLoggingGuard.new(folder, files) #: RequestLoggingGuard
45
+ @registry = registry
46
+ @user_folder = user_folder
30
47
  freeze
31
48
  end
32
49
 
@@ -38,7 +55,7 @@ module Principles
38
55
  created = !@folder.exist?
39
56
  written = @folder.files.include?(FOLDER::IGNORE) ? [] : [FOLDER::IGNORE]
40
57
  written.each { |name| @folder.write(name, IGNORE_EVERYTHING) }
41
- refuse_unignored(written, created)
58
+ @guard.refuse_unignored(written, created)
42
59
  @folder.write_settings("env" => capturing)
43
60
  [*written, FOLDER::SETTINGS].map { |name| @folder.relative(name) }
44
61
  end
@@ -71,7 +88,9 @@ module Principles
71
88
  #: () -> CapturedSessions
72
89
  def captured
73
90
  refuse_while_unguarded
74
- CapturedSessions.new(@folder.captured_files, @folder.index_lines)
91
+ requests, kept = read
92
+ everything = CapturedSessions.new(requests.captured_files, requests.index_lines)
93
+ kept ? everything.of(kept) : everything
75
94
  end
76
95
 
77
96
  # Removes the host's files of every session but the newest keep_sessions, 5 unless given, and gives the paths it
@@ -80,44 +99,52 @@ module Principles
80
99
  def remove(keep_sessions:)
81
100
  refuse_while_unguarded
82
101
  names = captured.older_than_newest(KeptSessions.new(keep_sessions).count)
83
- names.each { |name| @folder.remove_request(name) }
84
- names.map { |name| @folder.relative("#{Data::RequestLoggingFolder::REQUESTS}/#{name}") }
102
+ requests, = read
103
+ names.each { |name| requests.remove_request(name) }
104
+ names.map { |name| requests.shown(name) }
85
105
  end
86
106
 
87
- # Refuses while the folder exists unguarded: its .gitignore gone, or git not ignoring every path there. Every
88
- # read of the folder asks this first, since a logged request git does not ignore can be committed.
89
- #: () -> void
90
- def refuse_while_unguarded
91
- refusal = unguarded_refusal
92
- raise refusal if refusal
107
+ # Makes the user-level folder the host writes every project's requests to, readable only by the user, and gives
108
+ # it when it was new; none while there is no user-level folder to make.
109
+ #: () -> Array[String]
110
+ def make_user_folder
111
+ user = @user_folder or return []
112
+ user.create ? [user.path] : []
93
113
  end
94
114
 
95
- # The refusal every read of the folder gives while it exists unguarded, or nil while git ignores it or it is
96
- # not there; for a read that carries on without the logged requests, such as a full audit's request.
97
- #: () -> Error?
98
- def unguarded_refusal
99
- return unless @folder.exist?
100
- return unguarded unless @folder.files.include?(FOLDER::IGNORE)
101
-
102
- not_ignored unless ignored?
115
+ # Registers session_id, started in cwd, to the project while request logging is on in the user's own settings,
116
+ # as SessionRegistry says.
117
+ #: (session_id: String?, cwd: String?) -> void
118
+ def register_session(session_id:, cwd:) = @registry&.register(session_id: session_id, cwd: cwd)
119
+
120
+ # Removes the user-level folder's sessions no listed project registered, as UserLoggedRequests says; none while
121
+ # there is no user-level folder to read.
122
+ #: () -> UserLoggedRequests::Pruned
123
+ def prune_unregistered
124
+ user = @user_folder
125
+ user ? UserLoggedRequests.new(user).prune : UserLoggedRequests::NONE
103
126
  end
104
127
 
128
+ # Refuses while the folder exists unguarded, as RequestLoggingGuard says.
129
+ #: () -> void
130
+ def refuse_while_unguarded = @guard.refuse_while_unguarded
131
+
132
+ # The refusal a read gives while the folder exists unguarded, or nil, as RequestLoggingGuard says.
133
+ #: () -> Error?
134
+ def unguarded_refusal = @guard.unguarded_refusal
135
+
105
136
  # Where each of members' text was seen in the captured requests, scanned by jq and rg, once the folder is
106
137
  # guarded.
107
138
  # Each request that is not whole JSON is named under unreadable, with its reason, since what it held is unknown,
108
139
  # and completeness says how many requests and strings the scan read, and whether it read every request through.
109
140
  #: (MembersInLoggedRequests)
110
- #| -> { members_by_status: Hash[String, Integer], members: Array[Hash[String, untyped]], orphans: Integer,
111
- #| quoting_requests: Array[String], unreadable: Array[Hash[String, String]],
112
- #| completeness: Hash[String, untyped] }
141
+ #| -> report
113
142
  def members_seen(members) = scanned(members).first
114
143
 
115
144
  # The report members_seen gives, but each member's reach in place of its places, as MemberReach lists it, so
116
145
  # the report is bounded by the members mapped rather than growing with every request that holds them.
117
146
  #: (MembersInLoggedRequests)
118
- #| -> { members_by_status: Hash[String, Integer], members: Array[Hash[String, untyped]], orphans: Integer,
119
- #| quoting_requests: Array[String], unreadable: Array[Hash[String, String]],
120
- #| completeness: Hash[String, untyped] }
147
+ #| -> report
121
148
  def members_reached(members)
122
149
  seen = members_seen(members)
123
150
  seen.merge(members: seen[:members].map { MemberReach.new(it).listed })
@@ -128,20 +155,64 @@ module Principles
128
155
  #: (MembersInLoggedRequests, ?carried: Array[String]) -> LoggedRequestReach
129
156
  def reach(members, carried: [])
130
157
  seen, read_whole = scanned(members)
131
- LoggedRequestReach.new(seen[:members], scanned: read_whole, unreadable: seen[:unreadable].size, carried:)
158
+ turns = { model_turns_by_position: seen[:model_turns_by_position],
159
+ model_turns_by_query_source: seen[:model_turns_by_query_source] }
160
+ LoggedRequestReach.new(seen[:members], scanned: read_whole, unreadable: seen[:unreadable].size, carried:,
161
+ model_turns: turns)
162
+ end
163
+
164
+ # Each captured turn opening, by session, as TurnOpening gives them, with the bytes of members' text each sent,
165
+ # from one scan, once the folder is guarded.
166
+ #: (MembersInLoggedRequests) -> Array[[String?, Array[TurnOpening]]]
167
+ def turn_openings(members)
168
+ scan = captured_scan
169
+ requests = RequestKind.labelled(scan)
170
+ seen, deferred = members_opening(requests, members)
171
+ TurnOpening.by_session(requests, scan, MembersByPart.by_request(seen, deferred))
132
172
  end
133
173
 
134
174
  private
135
175
 
176
+ # The scan of the requests read, those of the kept sessions alone when the folder holds other sessions', once
177
+ # the guard passes.
178
+ #: () -> Data::LoggedRequestScan
179
+ def captured_scan
180
+ refuse_while_unguarded
181
+ requests, kept = read
182
+ return requests.scan unless kept
183
+
184
+ requests.scan(only: CapturedSessions.new(requests.captured_files, requests.index_lines).of(kept).file_names)
185
+ end
186
+
187
+ # Where each of members' text was seen in the turn openings among requests, as members_seen gives it, and each
188
+ # tool they defer loading, from a scan of those requests alone, since the rest are not measured and scanning
189
+ # them took most of the read's time.
190
+ #: (Array[Hash[String, String?]], MembersInLoggedRequests)
191
+ #| -> [Array[Hash[String, untyped]], Array[[String, String]]]
192
+ def members_opening(requests, members)
193
+ opened = requests.select { it["turn_position"] == "turn_opening" }
194
+ scan = read.first.scan(only: opened.map { it.fetch("file").to_s })
195
+ deferred = scan.deferred_tools
196
+ [members.report(opened, scan.matches(members.patterns).found, deferred).fetch(:members), deferred]
197
+ end
198
+
199
+ # The requests the commands here read, and the sessions they keep: the user-level folder's, kept to the
200
+ # sessions registered here, once the registry names one; this project's own folder's, all kept, otherwise.
201
+ #: () -> [Data::CapturedRequests, Array[String]?]
202
+ def read
203
+ user = @user_folder
204
+ registered = user&.exist? ? @registry&.session_ids || [] : []
205
+ return [@folder.requests, nil] if user.nil? || registered.empty?
206
+
207
+ [user.requests, registered]
208
+ end
209
+
136
210
  # Where each of members' text was seen, as members_seen gives it, and how many requests the scan read whole.
137
211
  #: (MembersInLoggedRequests)
138
- #| -> [{ members_by_status: Hash[String, Integer], members: Array[Hash[String, untyped]], orphans: Integer,
139
- #| quoting_requests: Array[String], unreadable: Array[Hash[String, String]],
140
- #| completeness: Hash[String, untyped] }, Integer]
212
+ #| -> [report, Integer]
141
213
  def scanned(members)
142
- refuse_while_unguarded
143
- scan = @folder.scan
144
- requests = scan.requests
214
+ scan = captured_scan
215
+ requests = RequestKind.labelled(scan)
145
216
  matched = scan.matches(members.patterns)
146
217
  read = LoggedRequestScanCompleteness.of(scan, matched)
147
218
  report = members.report(requests, matched.found, scan.deferred_tools)
@@ -155,42 +226,6 @@ module Principles
155
226
  { "CLAUDE_CODE_ENABLE_TELEMETRY" => "1", "OTEL_METRICS_EXPORTER" => "none", "OTEL_LOGS_EXPORTER" => "none",
156
227
  "OTEL_TRACES_EXPORTER" => "none", "OTEL_LOG_RAW_API_BODIES" => "file:#{@folder.absolute(FOLDER::REQUESTS)}" }
157
228
  end
158
-
159
- #: (Array[String], bool) -> void
160
- def refuse_unignored(written, created)
161
- return if ignored?
162
-
163
- written.each { |name| @folder.remove(name) }
164
- @folder.remove_if_empty if created
165
- raise not_ignored
166
- end
167
-
168
- # Whether git confirms it ignores the folder's own paths and every file already in it.
169
- #: () -> bool
170
- def ignored?
171
- paths = (GUARDED | @folder.files).map { |name| @folder.relative(name) }
172
- ignored = @files.ignored_paths(paths)
173
- !ignored.nil? && (paths - ignored).empty?
174
- end
175
-
176
- #: () -> Error
177
- def unguarded
178
- Error.new("request_logging_unguarded",
179
- "#{@folder.relative(FOLDER::IGNORE)} is missing, so git may not ignore the logged requests beside it",
180
- "A logged request holds the session's whole working context, so it must never reach git. Restore " \
181
- "#{@folder.relative(FOLDER::IGNORE)} holding the one line *, then run this again.")
182
- end
183
-
184
- #: () -> Error
185
- def not_ignored
186
- Error.new("request_logging_not_ignored",
187
- "git does not confirm that it ignores #{FOLDER::FOLDER}/, so logged requests there could be " \
188
- "committed",
189
- "A logged request holds the session's whole working context, so it must never reach git. Make this " \
190
- "project a git repository with git init if it is not one. If git tracks a file under " \
191
- "#{FOLDER::FOLDER}/, stop tracking it with git rm -r --cached #{FOLDER::FOLDER}. Then run this " \
192
- "command again.")
193
- end
194
229
  end
195
230
  end
196
231
  end