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
@@ -0,0 +1,84 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ require_relative "../error"
5
+ require_relative "../data/request_logging_folder"
6
+ require_relative "../data/project_files"
7
+
8
+ module Principles
9
+ # The domain logic, and the mediation of persistence. models/CLAUDE.md owns the boundary.
10
+ module Models
11
+ # The one guard every request-logging command shares: git must confirm it ignores the folder and every file in it,
12
+ # since a logged request holds the session's whole working context and must never be committed.
13
+ class RequestLoggingGuard
14
+ FOLDER = Data::RequestLoggingFolder
15
+ # The paths each command checks git ignores, beside every file already in the folder.
16
+ GUARDED = [FOLDER::IGNORE, FOLDER::SETTINGS, "#{FOLDER::REQUESTS}/"].freeze #: Array[String]
17
+
18
+ #: (Data::RequestLoggingFolder, Data::ProjectFiles) -> void
19
+ def initialize(folder, files)
20
+ @folder = folder
21
+ @files = files
22
+ freeze
23
+ end
24
+
25
+ # Refuses while the folder exists unguarded: its .gitignore gone, or git not ignoring every path there. Every
26
+ # read of the folder asks this first, since a logged request git does not ignore can be committed.
27
+ #: () -> void
28
+ def refuse_while_unguarded
29
+ refusal = unguarded_refusal
30
+ raise refusal if refusal
31
+ end
32
+
33
+ # The refusal every read of the folder gives while it exists unguarded, or nil while git ignores it or it is
34
+ # not there; for a read that carries on without the logged requests, such as a full audit's request.
35
+ #: () -> Error?
36
+ def unguarded_refusal
37
+ return unless @folder.exist?
38
+ return unguarded unless @folder.files.include?(FOLDER::IGNORE)
39
+
40
+ not_ignored unless ignored?
41
+ end
42
+
43
+ # Removes what turning logging on wrote, and the folder when it made it, then refuses, unless git confirms it
44
+ # ignores the folder.
45
+ #: (Array[String], bool) -> void
46
+ def refuse_unignored(written, created)
47
+ return if ignored?
48
+
49
+ written.each { |name| @folder.remove(name) }
50
+ @folder.remove_if_empty if created
51
+ raise not_ignored
52
+ end
53
+
54
+ private
55
+
56
+ # Whether git confirms it ignores the folder's own paths and every file already in it.
57
+ #: () -> bool
58
+ def ignored?
59
+ paths = (GUARDED | @folder.files).map { |name| @folder.relative(name) }
60
+ ignored = @files.ignored_paths(paths)
61
+ !ignored.nil? && (paths - ignored).empty?
62
+ end
63
+
64
+ #: () -> Error
65
+ def unguarded
66
+ Error.new("request_logging_unguarded",
67
+ "#{@folder.relative(FOLDER::IGNORE)} is missing, so git may not ignore the logged requests beside it",
68
+ "A logged request holds the session's whole working context, so it must never reach git. Restore " \
69
+ "#{@folder.relative(FOLDER::IGNORE)} holding the one line *, then run this again.")
70
+ end
71
+
72
+ #: () -> Error
73
+ def not_ignored
74
+ Error.new("request_logging_not_ignored",
75
+ "git does not confirm that it ignores #{FOLDER::FOLDER}/, so logged requests there could be " \
76
+ "committed",
77
+ "A logged request holds the session's whole working context, so it must never reach git. Make this " \
78
+ "project a git repository with git init if it is not one. If git tracks a file under " \
79
+ "#{FOLDER::FOLDER}/, stop tracking it with git rm -r --cached #{FOLDER::FOLDER}. Then run this " \
80
+ "command again.")
81
+ end
82
+ end
83
+ end
84
+ end
@@ -0,0 +1,46 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ require "time"
5
+
6
+ module Principles
7
+ # The domain logic, and the mediation of persistence. models/CLAUDE.md owns the boundary.
8
+ module Models
9
+ # When a captured request was sent, as its index line gives it, in ISO 8601 UTC to the millisecond, the form the
10
+ # host writes, so a time written with an offset sorts beside the rest as text. A timestamp that is not ISO 8601
11
+ # gives none rather than a guess. Times compare as they were sent, one with none after every one with a time.
12
+ class RequestTime
13
+ include Comparable
14
+
15
+ #: (String?) -> void
16
+ def initialize(timestamp)
17
+ @timestamp = timestamp
18
+ freeze
19
+ end
20
+
21
+ # The time in ISO 8601 UTC, or nil for none or one that does not parse.
22
+ #: () -> String?
23
+ def utc
24
+ timestamp = @timestamp
25
+ return unless timestamp
26
+
27
+ Time.iso8601(timestamp).utc.iso8601(3)
28
+ rescue ArgumentError
29
+ nil
30
+ end
31
+
32
+ # Earlier first, and none after every time.
33
+ #: (RequestTime) -> Integer
34
+ def <=>(other) = sort_key <=> other.sort_key
35
+
36
+ protected
37
+
38
+ # A time with one, as its UTC text sorts, before one without.
39
+ #: () -> [Integer, String]
40
+ def sort_key
41
+ sent = utc
42
+ sent ? [0, sent] : [1, ""]
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,61 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ require "json"
5
+ require_relative "../data/request_logging_folder"
6
+ require_relative "../data/user_request_logging_folder"
7
+ require_relative "../data/repository"
8
+ require_relative "request_logging"
9
+
10
+ module Principles
11
+ # The domain logic, and the mediation of persistence. models/CLAUDE.md owns the boundary.
12
+ module Models
13
+ # The sessions registered to this project while request logging is on in the user's own settings, which write
14
+ # every project's requests to one user-level folder: a scan keeps a request only when its session is registered
15
+ # here. The session-start hook registers each session from the session_id and cwd its documented input gives,
16
+ # never from a request's text (022 F4, F5). The registry is the repository's main checkout's, so a worktree's
17
+ # sessions stay registered once it is removed, and every checkout reads the same one (022 F8).
18
+ class SessionRegistry
19
+ #: (Data::UserRequestLoggingFolder, Data::Repository) -> void
20
+ def initialize(user_folder, repository)
21
+ @user_folder = user_folder
22
+ @repository = repository
23
+ freeze
24
+ end
25
+
26
+ # Records session_id, started in cwd, once, while the user-level folder exists, writing the folder's .gitignore
27
+ # first so the registry is never where git could commit it. A write that fails registers nothing and says
28
+ # nothing, since the hook running this prints nothing of it.
29
+ #: (session_id: String?, cwd: String?) -> void
30
+ def register(session_id:, cwd:)
31
+ return unless session_id && cwd && @user_folder.exist?
32
+
33
+ root = @repository.main_checkout_root
34
+ folder = @user_folder.registry_folder(root)
35
+ guard(folder)
36
+ @user_folder.add_project_root(root) unless @user_folder.project_roots.include?(root)
37
+ return if session_ids(folder).include?(session_id)
38
+
39
+ folder.append_to_registry(JSON.generate("session_id" => session_id, "cwd" => cwd))
40
+ rescue SystemCallError
41
+ nil
42
+ end
43
+
44
+ # Each session registered, in the order it was.
45
+ #: (?Data::RequestLoggingFolder) -> Array[String]
46
+ def session_ids(folder = registry_folder) = folder.registered_session_ids
47
+
48
+ private
49
+
50
+ # The main checkout's request-logging folder, asking git for it only when called.
51
+ #: () -> Data::RequestLoggingFolder
52
+ def registry_folder = @user_folder.registry_folder(@repository.main_checkout_root)
53
+
54
+ #: (Data::RequestLoggingFolder) -> void
55
+ def guard(folder)
56
+ ignore = Data::RequestLoggingFolder::IGNORE
57
+ folder.write(ignore, RequestLogging::IGNORE_EVERYTHING) unless folder.files.include?(ignore)
58
+ end
59
+ end
60
+ end
61
+ end
@@ -17,16 +17,25 @@ module Principles
17
17
  #: String
18
18
  attr_reader :source
19
19
 
20
+ # The session and the directory it started in, as the hook's input names them; nil when it names none.
21
+ #: String?
22
+ attr_reader :session_id, :cwd
23
+
20
24
  #: (String) -> void
21
25
  def initialize(text)
22
26
  given = parsed(text)
23
- given = given["source"] if given.is_a?(Hash)
24
- @source = SOURCES.include?(given) ? given.to_s : "startup" #: String
27
+ fields = given.is_a?(Hash) ? given : {} #: Hash[String, untyped]
28
+ @source = SOURCES.include?(fields["source"]) ? fields["source"].to_s : "startup" #: String
29
+ @session_id = named(fields["session_id"]) #: String?
30
+ @cwd = named(fields["cwd"]) #: String?
25
31
  freeze
26
32
  end
27
33
 
28
34
  private
29
35
 
36
+ #: (untyped) -> String?
37
+ def named(value) = value.is_a?(String) && !value.empty? ? value : nil
38
+
30
39
  #: (String) -> untyped
31
40
  def parsed(text)
32
41
  JSON.parse(text)
@@ -0,0 +1,36 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ require_relative "turn_opening"
5
+
6
+ module Principles
7
+ # The domain logic, and the mediation of persistence. models/CLAUDE.md owns the boundary.
8
+ module Models
9
+ # How one session's context moved from its first turn opening to its last, as sent: when each was sent, how many
10
+ # there were, and the bytes and input tokens at each end with their change, so a session whose context grew is
11
+ # seen without reading every opening (034).
12
+ class SessionTrend
13
+ # openings are the session's turn openings, in the order sent, at least one.
14
+ #: (Array[TurnOpening]) -> void
15
+ def initialize(openings)
16
+ @openings = openings
17
+ freeze
18
+ end
19
+
20
+ #: () -> Hash[String, untyped]
21
+ def to_h
22
+ first = @openings.fetch(0)
23
+ last = @openings.fetch(-1)
24
+ { "from" => first.request_at, "to" => last.request_at, "turn_openings" => @openings.size,
25
+ "bytes" => moved(first.parts.bytes, last.parts.bytes),
26
+ "input_tokens" => moved(first.input_tokens, last.input_tokens) }
27
+ end
28
+
29
+ private
30
+
31
+ # A count at each end, and its change, null where either end is.
32
+ #: (Integer?, Integer?) -> Hash[String, Integer?]
33
+ def moved(first, last) = { "first" => first, "last" => last, "change" => first && last && (last - first) }
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,83 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ require_relative "../data/logged_request_scan"
5
+ require_relative "context_parts"
6
+ require_relative "dropped_thinking"
7
+ require_relative "members_by_part"
8
+ require_relative "part_token_estimates"
9
+ require_relative "request_time"
10
+
11
+ module Principles
12
+ # The domain logic, and the mediation of persistence. models/CLAUDE.md owns the boundary.
13
+ module Models
14
+ # A captured request that opens one of the agent's turns, whose body is the whole context the host loaded before
15
+ # the turn's work started, and the host's own count of the tokens it took. A request continuing a thread sends
16
+ # only what it adds, so only a turn opening's body is its context (034, F7). It gives counts alone, never text.
17
+ class TurnOpening
18
+ # The usage fields that together count every input token the request took, cached or not.
19
+ INPUT_TOKENS = %w[input_tokens cache_read_input_tokens cache_creation_input_tokens].freeze #: Array[String]
20
+
21
+ # The turn openings among scan's requests, as RequestKind labels them, grouped by session in the order their
22
+ # first was sent, each session's in the order they were sent.
23
+ # members gives, by request file, the mapped members each sent.
24
+ #: (Array[Hash[String, String?]], Data::LoggedRequestScan, ?Hash[String, MembersByPart])
25
+ #| -> Array[[String?, Array[TurnOpening]]]
26
+ def self.by_session(requests, scan, members = {})
27
+ openings = requests.select { it["turn_position"] == "turn_opening" }
28
+ .map { new(it, scan, members.fetch(it.fetch("file").to_s) { MembersByPart.new([]) }) }
29
+ openings.sort_by { RequestTime.new(it.request_at) }.group_by(&:session_id).to_a
30
+ end
31
+
32
+ # request is its row as the scan lists it; its body and response are read from scan; members are the mapped
33
+ # members it sent.
34
+ #: (Hash[String, String?], Data::LoggedRequestScan, MembersByPart) -> void
35
+ def initialize(request, scan, members)
36
+ @request = request
37
+ @members = members
38
+ response = request["response_file"]
39
+ @response = response && scan.response(response) #: untyped
40
+ sent = scan.body(request.fetch("file").to_s)
41
+ @body = DroppedThinking.new(@response).from(sent) #: untyped
42
+ @dropped_bytes = ContextParts.new(sent).bytes - parts.bytes #: Integer
43
+ freeze
44
+ end
45
+
46
+ #: () -> String?
47
+ def session_id = @request["session_id"]
48
+
49
+ # When it was sent, in UTC, from its index line.
50
+ #: () -> String?
51
+ def request_at = RequestTime.new(@request["timestamp"]).utc
52
+
53
+ # Its context's parts, as ContextParts splits them, without the thinking blocks its response says the server
54
+ # dropped; any other key of the request, such as its metadata, is not context.
55
+ #: () -> ContextParts
56
+ def parts = ContextParts.new(@body)
57
+
58
+ # Every input token its response counted, cached or not.
59
+ #: () -> Integer?
60
+ def input_tokens
61
+ usage = @response.is_a?(Hash) ? @response["usage"] : nil
62
+ INPUT_TOKENS.sum { usage.fetch(it, 0) } if usage.is_a?(Hash)
63
+ end
64
+
65
+ # The mapped members it sent, by principle and part.
66
+ #: MembersByPart
67
+ attr_reader :members
68
+
69
+ # Its counts, with the members it sent, as --session lists each turn opening.
70
+ #: () -> Hash[String, untyped]
71
+ def with_members = to_h.merge("members" => @members.to_a)
72
+
73
+ #: () -> Hash[String, untyped]
74
+ def to_h
75
+ split = parts
76
+ estimates = PartTokenEstimates.new(split.to_a, input_tokens)
77
+ { "request" => @request.fetch("file"), "request_at" => request_at, "bytes" => split.bytes,
78
+ "dropped_bytes" => @dropped_bytes, "input_tokens" => input_tokens,
79
+ "bytes_per_token" => estimates.bytes_per_token, "parts" => estimates.to_a }
80
+ end
81
+ end
82
+ end
83
+ end
@@ -0,0 +1,43 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ require_relative "../data/request_shape"
5
+
6
+ module Principles
7
+ # The domain logic, and the mediation of persistence. models/CLAUDE.md owns the boundary.
8
+ module Models
9
+ # Whether a model turn's request opens a turn of the agent's or continues one after a tool result; only a model
10
+ # turn has one. The host does not say; this is a heuristic from how the request's last message ends: user or
11
+ # system text with no tool result opens a turn, and a tool result continues one. Text the host adds mid-turn
12
+ # with no tool result would read as opening one. A request ending any other way is unclassified.
13
+ class TurnPosition
14
+ # Every position, in the order counts of them print.
15
+ NAMES = %w[turn_opening mid_turn unclassified].freeze #: Array[String]
16
+ # The position each ending the scan reads names.
17
+ BY_ENDING = { "text" => "turn_opening", "tool_result" => "mid_turn" }.freeze #: Hash[String, String]
18
+
19
+ # How many of requests, as RequestKind labels them, are at each position, every position counted.
20
+ #: (Array[Hash[String, String?]]) -> Hash[String, Integer]
21
+ def self.counted(requests) = NAMES.to_h { |name| [name, requests.count { it["turn_position"] == name }] }
22
+
23
+ # How many of each query_source's model turns, as RequestKind labels them, are at each position, every
24
+ # position counted, by query_source in name order; a request the index gives no query_source is under orphan.
25
+ #: (Array[Hash[String, String?]]) -> Hash[String, Hash[String, Integer]]
26
+ def self.counted_by_query_source(requests)
27
+ turns = requests.select { it["turn_position"] }.group_by { it["query_source"] || "orphan" }
28
+ turns.sort.to_h { |source, those| [source, counted(those)] }
29
+ end
30
+
31
+ # shape is the model turn's request's, as Data::RequestShape gives it.
32
+ #: (Data::RequestShape) -> void
33
+ def initialize(shape)
34
+ @shape = shape
35
+ freeze
36
+ end
37
+
38
+ # Its position's name.
39
+ #: () -> String
40
+ def to_s = @shape.continues_thread? ? "mid_turn" : BY_ENDING.fetch(@shape.ending, "unclassified")
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,90 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ require_relative "../error"
5
+ require_relative "../data/user_request_logging_folder"
6
+ require_relative "captured_sessions"
7
+
8
+ module Principles
9
+ # The domain logic, and the mediation of persistence. models/CLAUDE.md owns the boundary.
10
+ module Models
11
+ # The requests in the user-level folder, where the host writes every project's while request logging is on in
12
+ # the user's own settings: each session in it belongs to a project only once that project's hook registered it,
13
+ # so a session no listed project registered is pruned, and only counted (022 F8).
14
+ class UserLoggedRequests
15
+ # What a prune removed: how many sessions, and their files and bytes.
16
+ class Pruned
17
+ #: Integer
18
+ attr_reader :sessions
19
+ #: CapturedSessions::Tally
20
+ attr_reader :tally
21
+
22
+ # sessions is how many sessions lost a file, and files each file removed.
23
+ #: (Integer, Array[Data::CapturedRequests::CapturedFile]) -> void
24
+ def initialize(sessions, files)
25
+ @sessions = sessions
26
+ @tally = CapturedSessions::Tally.new(files: files.size, bytes: files.sum(&:bytes)) #: CapturedSessions::Tally
27
+ freeze
28
+ end
29
+
30
+ #: () -> Hash[String, Integer]
31
+ def to_h = { "sessions" => @sessions, **@tally.to_h }
32
+ end
33
+
34
+ NONE = Pruned.new(0, []) #: Pruned
35
+
36
+ #: (Data::UserRequestLoggingFolder) -> void
37
+ def initialize(user_folder)
38
+ @user_folder = user_folder
39
+ freeze
40
+ end
41
+
42
+ # Removes the files of each session the host's index names that no listed project registered, leaving a file
43
+ # a registered session's line also names, and every request no index line names, since one may be a running
44
+ # session's request in flight. It prunes nothing while no project is listed, and nothing at all while any
45
+ # listed registry cannot be read, since a session it holds would be removed as no one's.
46
+ # A file it cannot remove stops it, and it counts only what it removed.
47
+ #: () -> Pruned
48
+ def prune
49
+ registered = registered_sessions or return NONE
50
+ requests = @user_folder.requests
51
+ everything = CapturedSessions.new(requests.captured_files, requests.index_lines)
52
+ unregistered = everything.session_ids - registered
53
+ removed = removed(requests, everything.of(unregistered).files_apart_from(everything.of(registered)))
54
+ Pruned.new(losing_a_file(everything, unregistered, removed), removed)
55
+ rescue Error, SystemCallError
56
+ NONE
57
+ end
58
+
59
+ private
60
+
61
+ # How many of sessions lost one of the files removed.
62
+ #: (CapturedSessions, Array[String], Array[Data::CapturedRequests::CapturedFile]) -> Integer
63
+ def losing_a_file(everything, sessions, removed)
64
+ names = removed.map(&:name)
65
+ sessions.count { |id| everything.of([id]).file_names.intersect?(names) }
66
+ end
67
+
68
+ # Each of files removed from requests, in order, until one cannot be.
69
+ #: (Data::CapturedRequests, Array[Data::CapturedRequests::CapturedFile])
70
+ #| -> Array[Data::CapturedRequests::CapturedFile]
71
+ def removed(requests, files)
72
+ done = [] #: Array[Data::CapturedRequests::CapturedFile]
73
+ files.each do |file|
74
+ requests.remove_request(file.name)
75
+ done << file
76
+ end
77
+ done
78
+ rescue SystemCallError
79
+ done || []
80
+ end
81
+
82
+ # Every session a listed project registered, or nil while no project is listed.
83
+ #: () -> Array[String]?
84
+ def registered_sessions
85
+ roots = @user_folder.exist? ? @user_folder.project_roots : []
86
+ roots.flat_map { |root| @user_folder.registry_folder(root).registered_session_ids } unless roots.empty?
87
+ end
88
+ end
89
+ end
90
+ end
@@ -0,0 +1,49 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ require_relative "../data/claude_code_home"
5
+ require_relative "../data/user_request_logging_folder"
6
+
7
+ module Principles
8
+ # The domain logic, and the mediation of persistence. models/CLAUDE.md owns the boundary.
9
+ module Models
10
+ # The env entries in the user's own Claude Code settings that turn request logging on for every session they
11
+ # start, from the Desktop app and IDEs as from a terminal. This tool prints them and never writes those settings:
12
+ # they are the user's to edit (022 F1).
13
+ class UserSettingsEntries
14
+ # The entries that switch the host's telemetry on and its exporters off, which the user may have set for
15
+ # telemetry of their own, so only they know whether one was added for request logging.
16
+ TELEMETRY_AND_EXPORTERS = %w[CLAUDE_CODE_ENABLE_TELEMETRY OTEL_METRICS_EXPORTER OTEL_LOGS_EXPORTER
17
+ OTEL_TRACES_EXPORTER].freeze #: Array[String]
18
+
19
+ #: (Data::ClaudeCodeHome, Data::UserRequestLoggingFolder) -> void
20
+ def initialize(claude_code, user_folder)
21
+ @claude_code = claude_code
22
+ @user_folder = user_folder
23
+ freeze
24
+ end
25
+
26
+ # The user's settings file, under CLAUDE_CONFIG_DIR when set.
27
+ #: () -> String
28
+ def settings_file = @claude_code.settings_file
29
+
30
+ # The entry that is request logging's alone: the host writes each request's body to the user-level folder.
31
+ #: () -> Hash[String, String]
32
+ def own = { "OTEL_LOG_RAW_API_BODIES" => "file:#{@user_folder.requests_path}" }
33
+
34
+ # The entries that turn request logging on: telemetry on, so the host logs each request's body, the entry of its
35
+ # own, and each exporter none, so nothing leaves the machine, apart from an exporter the user's settings set,
36
+ # which stays theirs; every exporter when those settings cannot be read.
37
+ #: () -> Hash[String, String]
38
+ def to_add
39
+ set = @claude_code.settings_env_keys || []
40
+ { "CLAUDE_CODE_ENABLE_TELEMETRY" => "1", **own,
41
+ **(TELEMETRY_AND_EXPORTERS.drop(1) - set).to_h { [it, "none"] } }
42
+ end
43
+
44
+ # Whether the user's settings file is there but cannot be read as settings, so every exporter entry is printed.
45
+ #: () -> bool
46
+ def settings_unreadable? = @claude_code.settings_env_keys.nil?
47
+ end
48
+ end
49
+ end
@@ -3,9 +3,9 @@
3
3
 
4
4
  module Principles
5
5
  # The next production release, as major.minor.patch. A production build is versioned with this alone.
6
- RELEASE = "0.1.4"
6
+ RELEASE = "0.1.5"
7
7
  # The version a built gem prints. `rake build[production]` stamps RELEASE here, in the copy of lib/ it
8
8
  # packages, and `rake build[development]` stamps RELEASE.g<short sha>. A checkout leaves it nil, and
9
9
  # Data::RunningVersion reads the commit this tool runs from instead.
10
- BUILT_VERSION = "0.1.4" #: String?
10
+ BUILT_VERSION = "0.1.5" #: String?
11
11
  end
@@ -11,9 +11,9 @@ module Principles
11
11
  # request shows of each, the template entry each starts with, and what they carry that the request explains.
12
12
  class AssessedMembers
13
13
  # What the request shows of each member.
14
- SHOWN = %w[id role first_line last_line source check check_since_last_audit check_hidden_characters
15
- acknowledged_since_last_audit carried_forward open_finding_ids judge_because moved_from read_the_change
16
- changed_lines mapped_elsewhere].freeze #: Array[String]
14
+ SHOWN = %w[name id role reason carrier first_line last_line source check check_since_last_audit
15
+ check_hidden_characters acknowledged_since_last_audit carried_forward open_finding_ids judge_because
16
+ moved_from read_the_change changed_lines mapped_elsewhere].freeze #: Array[String]
17
17
 
18
18
  # reviewed_check_placeholders is the text a checked member's template prints in each field it may leave as
19
19
  # printed to give none, for a check reviewed before it runs; unchanged_check_placeholders, for one the
@@ -36,7 +36,7 @@ module Principles
36
36
 
37
37
  # What the request shows of a carried member no flag fires on: what names it and its check, whose result
38
38
  # the template still asks for, and of its carried assessment only its dates and flags.
39
- COMPACT = %w[id role source check check_since_last_audit check_hidden_characters
39
+ COMPACT = %w[name id role reason carrier source check check_since_last_audit check_hidden_characters
40
40
  carried_forward].freeze #: Array[String]
41
41
  # What a compact member shows of its carried assessment.
42
42
  CARRIED_COMPACTLY = %w[assessed_at observed_at observed_at_from_assessed_at evidence_changed
@@ -153,13 +153,16 @@ module Principles
153
153
  end
154
154
 
155
155
  # The question, defining observed only when a member is judged afresh, whose delivery it guides, then whether
156
- # each rule is enforced, which the set's assessment answers afresh at every audit. A record digests the question
157
- # without it, so asking it still carries forward each member's last assessment, which never answered it.
156
+ # each member's reason holds, and each rule is enforced, which the set's assessment answers afresh at every
157
+ # audit. A record digests the question without those two, so asking them still carries forward each member's
158
+ # last assessment, which never answered them, rather than judging every member of every principle again.
158
159
  #: () -> Instruction
159
160
  def question
160
161
  assess, observed = AssessmentRequest.question_paragraphs
162
+ reasons = Prompts.text("assess-every-member/ask-whether-each-reason-holds")
161
163
  enforced = Prompts.text("assess-every-member/ask-whether-each-rule-is-enforced")
162
- Instruction.new("question", [[assess, true], [observed, @members.judged_afresh?], [enforced, true]])
164
+ Instruction.new("question", [[assess, true], [observed, @members.judged_afresh?], [reasons, true],
165
+ [enforced, true]])
163
166
  end
164
167
 
165
168
  # Why each member with judge_because is judged afresh, explaining only the values the members carry, so the
@@ -140,14 +140,21 @@ module Principles
140
140
  "full_record" => @invocation.in_project("show-audit", principle_id))
141
141
  end
142
142
 
143
- # completed, a completed audit's result, offering to set principles up after its next_action, as it does
144
- # while nothing keeps them held between audits, and with hooks, the hook entries that report between them.
143
+ # completed, a completed audit's result, as it is while nothing in the project has every session check the
144
+ # principles: with set_up_offer, the question the agent puts to its user and the command a yes runs, in a field
145
+ # of its own, since a line among next_action's went unasked (019 F6), and with hooks, the hook entries that
146
+ # report between audits after its next_action. The offer holds no state, so each later audit asks the same
147
+ # (019 F7).
145
148
  #: (Hash[String, untyped], hooks: bool) -> Hash[String, untyped]
146
149
  def offering_set_up(completed, hooks:)
147
- offers = [Prompts.text("set-principles-up/keep-them-held-between-audits",
148
- command: @invocation.in_project("show-meta-principle-passage"))]
149
- offers << ReportHooksOffer.new(@invocation).to_s if hooks
150
- completed.merge("next_action" => [completed.fetch("next_action"), *offers].join("\n"))
150
+ why = Prompts.text("set-principles-up/why-set-principles-up")
151
+ offer = { "ask_the_user" => Prompts.text("set-principles-up/ask-to-set-principles-up-after-an-audit", why:),
152
+ "on_yes" => @invocation.in_project("show-meta-principle-passage") }
153
+ offered = completed.merge("set_up_offer" => offer)
154
+ return offered unless hooks
155
+
156
+ hooks_offer = ReportHooksOffer.new(@invocation).to_s
157
+ offered.merge("next_action" => [completed.fetch("next_action"), hooks_offer].join("\n"))
151
158
  end
152
159
 
153
160
  # completed, a completed first full audit's result, with the line after its next_action that names the command
@@ -107,7 +107,7 @@ module Principles
107
107
  create = @invocation.in_project("create-principle", usage: CREATE_PRINCIPLE_USAGE)
108
108
  return create if existing_maps.empty?
109
109
 
110
- add = @invocation.in_project("add-member", usage: "ID PATH --role ROLE")
110
+ add = @invocation.in_project("add-member", usage: "ID PATH --role ROLE --name NAME --reason REASON")
111
111
  "To add a member to an existing principle: #{add}\nTo map a distinct principle: #{create}"
112
112
  end
113
113
 
@@ -0,0 +1,36 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ require "json"
5
+ require_relative "invocation"
6
+ require_relative "prompts"
7
+ require_relative "problem_lines"
8
+
9
+ module Principles
10
+ # What this tool prints, from plain values a controller hands it. views/CLAUDE.md owns the boundary.
11
+ module Views
12
+ # report-before-carrier-edit's output: the PreToolUse hook's JSON denying an edit once, its reason naming the
13
+ # kind's practices page and asking for the same edit again, since a denial's reason reaches the model before it
14
+ # retries, where added context arrives only after the tool ran; or nothing, which lets the edit through.
15
+ class CarrierEditDenial
16
+ # Nothing on stdout, exit 0: the edit goes ahead.
17
+ NOTHING = Lines.new(stdout: "", stderr: "", status: 0).freeze #: Lines
18
+
19
+ #: (Invocation) -> void
20
+ def initialize(invocation)
21
+ @invocation = invocation
22
+ freeze
23
+ end
24
+
25
+ # The denial of an edit of a file of kind.
26
+ #: (String) -> Lines
27
+ def denied(kind)
28
+ reason = Prompts.text("edit-a-carrier/read-the-page-before-the-first-edit",
29
+ kind:, command: @invocation.in_project("show-carrier-practices", kind))
30
+ output = { "hookSpecificOutput" => { "hookEventName" => "PreToolUse", "permissionDecision" => "deny",
31
+ "permissionDecisionReason" => reason } }
32
+ Lines.new(stdout: "#{JSON.generate(output)}\n", stderr: "", status: 0)
33
+ end
34
+ end
35
+ end
36
+ end