principles 0.1.3 → 0.1.4

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 (237) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +120 -0
  3. data/README.md +10 -6
  4. data/lib/principles/command_line.rb +15 -6
  5. data/lib/principles/command_routes.rb +11 -1
  6. data/lib/principles/controllers/acknowledgement.rb +19 -4
  7. data/lib/principles/controllers/acknowledgements.rb +43 -12
  8. data/lib/principles/controllers/after_commit_report.rb +15 -2
  9. data/lib/principles/controllers/assessment.rb +7 -3
  10. data/lib/principles/controllers/audit.rb +17 -8
  11. data/lib/principles/controllers/audit_completion.rb +34 -9
  12. data/lib/principles/controllers/carrier_practices.rb +26 -0
  13. data/lib/principles/controllers/command.rb +29 -2
  14. data/lib/principles/controllers/correction.rb +15 -5
  15. data/lib/principles/controllers/full_audit_request.rb +38 -42
  16. data/lib/principles/controllers/inventory.rb +77 -71
  17. data/lib/principles/controllers/last_record_notice_beside.rb +51 -0
  18. data/lib/principles/controllers/member_addition.rb +19 -4
  19. data/lib/principles/controllers/member_entries.rb +25 -6
  20. data/lib/principles/controllers/member_problems_report.rb +26 -6
  21. data/lib/principles/controllers/members_a_commit_changed.rb +14 -5
  22. data/lib/principles/controllers/members_in_logged_requests.rb +52 -0
  23. data/lib/principles/controllers/members_to_assess.rb +24 -7
  24. data/lib/principles/controllers/meta_principle_setup.rb +2 -2
  25. data/lib/principles/controllers/open_correction.rb +3 -2
  26. data/lib/principles/controllers/parts_to_read.rb +46 -5
  27. data/lib/principles/controllers/plugin_member_addition.rb +48 -0
  28. data/lib/principles/controllers/principle_listing.rb +84 -0
  29. data/lib/principles/controllers/request_logging.rb +52 -0
  30. data/lib/principles/controllers/running_tool.rb +39 -13
  31. data/lib/principles/data/branches_bringing_in.rb +52 -0
  32. data/lib/principles/data/changes_since.rb +56 -0
  33. data/lib/principles/data/claude_code_home.rb +58 -0
  34. data/lib/principles/data/command-steps.json +91 -15
  35. data/lib/principles/data/decoded_leaf.rb +63 -0
  36. data/lib/principles/data/head_reflog.rb +13 -2
  37. data/lib/principles/data/kept_line.rb +32 -0
  38. data/lib/principles/data/known_marketplaces.rb +50 -0
  39. data/lib/principles/data/logged_request_matches.rb +138 -0
  40. data/lib/principles/data/logged_request_scan.rb +120 -0
  41. data/lib/principles/data/map_files.rb +18 -4
  42. data/lib/principles/data/plugin_folder.rb +85 -0
  43. data/lib/principles/data/plugin_registry.rb +73 -0
  44. data/lib/principles/data/principles_store.rb +49 -0
  45. data/lib/principles/data/ran.rb +25 -0
  46. data/lib/principles/data/raw_request_filter.rb +61 -0
  47. data/lib/principles/data/repository.rb +29 -27
  48. data/lib/principles/data/request_logging_folder.rb +167 -0
  49. data/lib/principles/data/running_version.rb +1 -1
  50. data/lib/principles/data/schemas/acknowledgement-answer.schema.json +16 -1
  51. data/lib/principles/data/schemas/acknowledgements-answer.schema.json +16 -1
  52. data/lib/principles/data/schemas/assessment-answer.schema.json +8 -0
  53. data/lib/principles/data/schemas/command-steps.schema.json +1 -1
  54. data/lib/principles/data/schemas/correction-answer-guide.schema.json +2 -1
  55. data/lib/principles/data/schemas/correction-answer.schema.json +14 -0
  56. data/lib/principles/data/schemas/member-map.schema.json +10 -1
  57. data/lib/principles/data/string_counts.rb +39 -0
  58. data/lib/principles/data/tools_on_path.rb +25 -0
  59. data/lib/principles/invocation_options.rb +4 -2
  60. data/lib/principles/launch.rb +14 -4
  61. data/lib/principles/models/acknowledged_check.rb +11 -1
  62. data/lib/principles/models/acknowledgement.rb +5 -0
  63. data/lib/principles/models/acknowledgement_refusal.rb +20 -11
  64. data/lib/principles/models/acknowledgements_to_offer.rb +86 -0
  65. data/lib/principles/models/after_commit_input.rb +5 -0
  66. data/lib/principles/models/answer_fields.rb +3 -0
  67. data/lib/principles/models/assessment_basis.rb +10 -3
  68. data/lib/principles/models/audit.rb +10 -10
  69. data/lib/principles/models/audit_record.rb +10 -0
  70. data/lib/principles/models/audit_records.rb +4 -3
  71. data/lib/principles/models/audit_start.rb +9 -0
  72. data/lib/principles/models/authored_locator.rb +33 -0
  73. data/lib/principles/models/candidate_files.rb +23 -3
  74. data/lib/principles/models/candidate_outline.rb +18 -125
  75. data/lib/principles/models/captured_sessions.rb +128 -0
  76. data/lib/principles/models/carrier_kind.rb +79 -0
  77. data/lib/principles/models/cited_files.rb +12 -3
  78. data/lib/principles/models/decided_prior_findings.rb +5 -0
  79. data/lib/principles/models/disposition.rb +37 -6
  80. data/lib/principles/models/disposition_placeholders.rb +12 -0
  81. data/lib/principles/models/disposition_text_field.rb +4 -0
  82. data/lib/principles/models/feature.rb +53 -0
  83. data/lib/principles/models/finding_outcomes.rb +55 -0
  84. data/lib/principles/models/findings_left_open.rb +9 -11
  85. data/lib/principles/models/head_moves.rb +27 -10
  86. data/lib/principles/models/installed_component.rb +55 -0
  87. data/lib/principles/models/installed_plugins.rb +174 -0
  88. data/lib/principles/models/kept_sessions.rb +34 -0
  89. data/lib/principles/models/locator.rb +8 -0
  90. data/lib/principles/models/logged_request_reach.rb +44 -0
  91. data/lib/principles/models/logged_request_scan_completeness.rb +43 -0
  92. data/lib/principles/models/mapped_baseline.rb +46 -0
  93. data/lib/principles/models/maps_holding_file_whole.rb +42 -0
  94. data/lib/principles/models/markdown_text.rb +143 -0
  95. data/lib/principles/models/member.rb +14 -1
  96. data/lib/principles/models/member_entry.rb +56 -0
  97. data/lib/principles/models/member_lines.rb +11 -0
  98. data/lib/principles/models/member_loads.rb +17 -2
  99. data/lib/principles/models/member_problems.rb +45 -42
  100. data/lib/principles/models/member_reach.rb +36 -0
  101. data/lib/principles/models/member_snapshots.rb +23 -4
  102. data/lib/principles/models/member_text_as_sent.rb +31 -0
  103. data/lib/principles/models/member_texts.rb +45 -0
  104. data/lib/principles/models/members_in_logged_requests.rb +240 -0
  105. data/lib/principles/models/missing_files.rb +41 -16
  106. data/lib/principles/models/nearly_matching_maps.rb +56 -0
  107. data/lib/principles/models/open_correction.rb +5 -0
  108. data/lib/principles/models/open_finding.rb +4 -3
  109. data/lib/principles/models/outline_budget.rb +10 -1
  110. data/lib/principles/models/outline_item.rb +25 -0
  111. data/lib/principles/models/outline_section.rb +15 -4
  112. data/lib/principles/models/part_named.rb +16 -2
  113. data/lib/principles/models/plugin_component.rb +37 -0
  114. data/lib/principles/models/plugin_install.rb +33 -0
  115. data/lib/principles/models/plugin_name.rb +23 -0
  116. data/lib/principles/models/plugin_reference.rb +53 -0
  117. data/lib/principles/models/principle_members.rb +15 -0
  118. data/lib/principles/models/prior_finding_decision.rb +1 -1
  119. data/lib/principles/models/prior_finding_outcomes.rb +12 -1
  120. data/lib/principles/models/problem_report.rb +14 -25
  121. data/lib/principles/models/project.rb +35 -29
  122. data/lib/principles/models/project_history.rb +19 -5
  123. data/lib/principles/models/recorded_members.rb +7 -0
  124. data/lib/principles/models/request_logging.rb +196 -0
  125. data/lib/principles/models/runs_from.rb +0 -5
  126. data/lib/principles/models/script_comments.rb +58 -0
  127. data/lib/principles/models/stale_request.rb +9 -0
  128. data/lib/principles/models/unfixed_part.rb +82 -0
  129. data/lib/principles/models/unresolved_plugin_members.rb +35 -0
  130. data/lib/principles/models/whole_file_member_read.rb +48 -0
  131. data/lib/principles/models/without_prose.rb +20 -0
  132. data/lib/principles/models/workflow_jobs.rb +92 -0
  133. data/lib/principles/show_members_in_logged_requests_options.rb +27 -0
  134. data/lib/principles/show_principle_options.rb +32 -0
  135. data/lib/principles/version.rb +2 -2
  136. data/lib/principles/views/acknowledged_result.rb +31 -12
  137. data/lib/principles/views/acknowledgement_result.rb +18 -13
  138. data/lib/principles/views/acknowledgement_template_alone.rb +55 -0
  139. data/lib/principles/views/acknowledgements_offered.rb +54 -0
  140. data/lib/principles/views/added_member.rb +22 -6
  141. data/lib/principles/views/answer_in_a_file.rb +15 -15
  142. data/lib/principles/views/assessed_members.rb +18 -7
  143. data/lib/principles/views/assessment_request.rb +8 -3
  144. data/lib/principles/views/audit_changes.rb +14 -8
  145. data/lib/principles/views/audit_findings.rb +34 -0
  146. data/lib/principles/views/audit_result.rb +14 -19
  147. data/lib/principles/views/carrier_checks.rb +40 -0
  148. data/lib/principles/views/carrier_practices_page.rb +49 -0
  149. data/lib/principles/views/completed_audit_findings.rb +33 -0
  150. data/lib/principles/views/completed_audit_next_step.rb +12 -4
  151. data/lib/principles/views/consecutive_sections_elsewhere.rb +4 -0
  152. data/lib/principles/views/context_parts.rb +129 -25
  153. data/lib/principles/views/correction_request.rb +21 -16
  154. data/lib/principles/views/disposition_template.rb +35 -0
  155. data/lib/principles/views/first_audit.rb +29 -15
  156. data/lib/principles/views/first_audit_line.rb +4 -5
  157. data/lib/principles/views/invocation.rb +14 -5
  158. data/lib/principles/views/last_record_notice.rb +41 -0
  159. data/lib/principles/views/lines_shared_with_member.rb +16 -22
  160. data/lib/principles/views/logged_request_status_meanings.rb +29 -0
  161. data/lib/principles/views/logged_requests_evidence.rb +69 -0
  162. data/lib/principles/views/map_added_to.rb +14 -12
  163. data/lib/principles/views/map_result.rb +39 -17
  164. data/lib/principles/views/member_change_since_baseline.rb +4 -0
  165. data/lib/principles/views/member_row.rb +13 -4
  166. data/lib/principles/views/member_sets_overlap.rb +31 -0
  167. data/lib/principles/views/members_a_commit_changed.rb +42 -25
  168. data/lib/principles/views/members_changed_during_audit.rb +27 -0
  169. data/lib/principles/views/members_in_logged_requests_result.rb +68 -0
  170. data/lib/principles/views/members_too_short_to_scan.rb +45 -0
  171. data/lib/principles/views/members_with_no_baseline.rb +6 -6
  172. data/lib/principles/views/meta_principle_result.rb +14 -2
  173. data/lib/principles/views/open_findings_line.rb +31 -92
  174. data/lib/principles/views/parts_index_result.rb +9 -5
  175. data/lib/principles/views/principle_read_result.rb +52 -11
  176. data/lib/principles/views/prior_findings_result.rb +9 -1
  177. data/lib/principles/views/problem_facts.rb +5 -3
  178. data/lib/principles/views/problem_lines.rb +32 -6
  179. data/lib/principles/views/problem_result.rb +7 -15
  180. data/lib/principles/views/prompts/assess-every-member/claim-an-earlier-first-raised-at.md +6 -6
  181. data/lib/principles/views/prompts/assess-every-member/read-a-compact-carried-member.md +9 -8
  182. data/lib/principles/views/prompts/assess-every-member/read-a-flagged-member-s-text-whole.md +3 -0
  183. data/lib/principles/views/prompts/assess-every-member/read-a-judged-member-s-text-whole.md +3 -0
  184. data/lib/principles/views/prompts/assess-every-member/turn-on-request-logging-to-see-what-reaches-context.md +2 -0
  185. data/lib/principles/views/prompts/assess-every-member/weigh-what-reached-the-context.md +7 -0
  186. data/lib/principles/views/prompts/dispose-of-each-finding/answer-guide.json +1 -0
  187. data/lib/principles/views/prompts/dispose-of-each-finding/fix-or-record-each-finding.md +5 -0
  188. data/lib/principles/views/prompts/find-a-principle-to-map/read-a-cut-section-back.md +1 -1
  189. data/lib/principles/views/prompts/follow-each-carriers-best-practices/practices-for-hook-configuration.md +41 -0
  190. data/lib/principles/views/prompts/follow-each-carriers-best-practices/practices-for-hook-scripts.md +35 -0
  191. data/lib/principles/views/prompts/follow-each-carriers-best-practices/practices-for-instruction-files.md +37 -0
  192. data/lib/principles/views/prompts/follow-each-carriers-best-practices/practices-for-other-text-an-agent-reads.md +38 -0
  193. data/lib/principles/views/prompts/follow-each-carriers-best-practices/practices-for-rule-files.md +34 -0
  194. data/lib/principles/views/prompts/follow-each-carriers-best-practices/practices-for-skills.md +35 -0
  195. data/lib/principles/views/prompts/follow-each-carriers-best-practices/practices-for-subagent-definitions.md +35 -0
  196. data/lib/principles/views/prompts/learn-what-a-command-does/add-member.md +50 -51
  197. data/lib/principles/views/prompts/learn-what-a-command-does/change-member-role.md +2 -1
  198. data/lib/principles/views/prompts/learn-what-a-command-does/list-candidate-files.md +1 -1
  199. data/lib/principles/views/prompts/learn-what-a-command-does/list-member-problems.md +32 -32
  200. data/lib/principles/views/prompts/learn-what-a-command-does/list-open-findings.md +10 -11
  201. data/lib/principles/views/prompts/learn-what-a-command-does/move-member.md +7 -6
  202. data/lib/principles/views/prompts/learn-what-a-command-does/remove-logged-requests.md +16 -0
  203. data/lib/principles/views/prompts/learn-what-a-command-does/remove-member.md +2 -1
  204. data/lib/principles/views/prompts/learn-what-a-command-does/report-at-session-start.md +2 -2
  205. data/lib/principles/views/prompts/learn-what-a-command-does/show-audit.md +7 -0
  206. data/lib/principles/views/prompts/learn-what-a-command-does/show-candidate-outlines.md +8 -2
  207. data/lib/principles/views/prompts/learn-what-a-command-does/show-carrier-practices.md +13 -0
  208. data/lib/principles/views/prompts/learn-what-a-command-does/show-logged-requests.md +20 -0
  209. data/lib/principles/views/prompts/learn-what-a-command-does/show-members-in-logged-requests.md +48 -0
  210. data/lib/principles/views/prompts/learn-what-a-command-does/show-principle.md +14 -14
  211. data/lib/principles/views/prompts/learn-what-a-command-does/start-audit.md +27 -27
  212. data/lib/principles/views/prompts/learn-what-a-command-does/submit-answer.md +10 -10
  213. data/lib/principles/views/prompts/learn-what-a-command-does/turn-off-request-logging.md +10 -0
  214. data/lib/principles/views/prompts/learn-what-a-command-does/turn-on-request-logging.md +32 -0
  215. data/lib/principles/views/prompts/read-requested-outlines/continue-the-survey.md +3 -2
  216. data/lib/principles/views/prompts/read-what-reached-the-context/explain-request-logging-to-the-user.md +11 -0
  217. data/lib/principles/views/prompts/read-what-reached-the-context/see-whether-members-reach-the-agent.md +2 -0
  218. data/lib/principles/views/prompts/read-what-reached-the-context/what-absent-means.md +2 -0
  219. data/lib/principles/views/prompts/read-what-reached-the-context/what-not-a-carrier-means.md +2 -0
  220. data/lib/principles/views/prompts/read-what-reached-the-context/what-present-but-not-loaded-means.md +2 -0
  221. data/lib/principles/views/prompts/read-what-reached-the-context/what-present-means.md +1 -0
  222. data/lib/principles/views/prompts/read-what-reached-the-context/what-unmeasurable-means.md +2 -0
  223. data/lib/principles/views/prompts/report-after-a-commit/plugin-members-are-still-listed.md +1 -0
  224. data/lib/principles/views/prompts/report-after-a-commit/the-commits-changed-these-members-waiting-on-an-upgrade.md +2 -2
  225. data/lib/principles/views/prompts/report-after-a-commit/the-commits-changed-these-members.md +2 -2
  226. data/lib/principles/views/prompts/report-after-a-commit/this-command-shows-what-each-needs-before-the-next-commit.md +1 -0
  227. data/lib/principles/views/prompts/set-principles-up/entry-file-passage.md +1 -1
  228. data/lib/principles/views/prompts/start-a-session/act-on-the-open-findings.md +2 -1
  229. data/lib/principles/views/prompts/start-a-session/hand-the-first-audit-to-a-subagent.md +2 -3
  230. data/lib/principles/views/prompts/start-a-session/raise-the-open-findings-waiting-on-no-one.md +1 -0
  231. data/lib/principles/views/request_logging_result.rb +62 -0
  232. data/lib/principles/views/request_part.rb +10 -4
  233. data/lib/principles/views/request_parts.rb +9 -0
  234. data/lib/principles/views/whole_file_elsewhere.rb +30 -0
  235. metadata +101 -4
  236. data/lib/principles/views/prompts/report-after-a-commit/the-principles-skill-is-where-to-start.md +0 -1
  237. data/lib/principles/views/prompts/report-after-a-commit/this-command-shows-each-one.md +0 -1
@@ -0,0 +1,50 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ require "json"
5
+ require_relative "../error"
6
+ require_relative "json_text"
7
+
8
+ module Principles
9
+ # Every file and process this tool reads or writes. data/CLAUDE.md owns the boundary.
10
+ module Data
11
+ # Claude Code's record of the marketplaces it knows, the text of known_marketplaces.json under its config folder:
12
+ # for each marketplace by name, where its plugins come from. A probe saw a local folder recorded as source
13
+ # "directory" without quoting how it nests, so this reads the kind either as source itself or as source.source.
14
+ class KnownMarketplaces
15
+ # The marketplaces text records, refused when it is not a JSON object.
16
+ #: (String) -> void
17
+ def initialize(text)
18
+ @marketplaces = parsed(text) #: Hash[String, untyped]
19
+ freeze
20
+ end
21
+
22
+ # The kind of source the marketplace named comes from, such as "directory" or "github", or nil when the record
23
+ # names no such marketplace or no kind this tool can read.
24
+ #: (String) -> String?
25
+ def source_kind(name)
26
+ marketplace = @marketplaces[name]
27
+ source = marketplace["source"] if marketplace.is_a?(Hash)
28
+ kind = source.is_a?(Hash) ? source["source"] : source
29
+ kind if kind.is_a?(String)
30
+ end
31
+
32
+ private
33
+
34
+ #: (String) -> Hash[String, untyped]
35
+ def parsed(text)
36
+ marketplaces = JsonText.new(text).parsed
37
+ marketplaces.is_a?(Hash) ? marketplaces : unreadable
38
+ rescue JSON::ParserError
39
+ unreadable
40
+ end
41
+
42
+ #: () -> bot
43
+ def unreadable
44
+ raise Error.new("unreadable_plugin_registry",
45
+ "Claude Code's record of its plugin marketplaces is not in the shape this tool reads",
46
+ "Reinstall the plugin with Claude Code, or map the project's own files instead.")
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,138 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ require "json"
5
+ require "open3"
6
+ require "tempfile"
7
+ require_relative "decoded_leaf"
8
+ require_relative "kept_line"
9
+ require_relative "raw_request_filter"
10
+ require_relative "string_counts"
11
+
12
+ module Principles
13
+ # Every file and process this tool reads or writes. data/CLAUDE.md owns the boundary.
14
+ module Data
15
+ # What a scan found in the captured requests. RawRequestFilter picks the request files that may hold a pattern,
16
+ # StringCounts counts the strings of the others, and only the picked ones are decoded: one jq run writes each
17
+ # string in them as one line, request<TAB>path<TAB>string, the path and string as JSON, and one rg run keeps those
18
+ # holding a pattern, escaped by the same jq, as fixed strings. Each distinct kept string is then split into its
19
+ # lines once. It holds each line holding a pattern as a KeptLine, how many strings each request it read through
20
+ # held, by request, and whether the scan was whole.
21
+ class LoggedRequestMatches
22
+ # Each string in a request, prefixed by the request file and its JSON path, both written as JSON, so no string
23
+ # can stop the run or split a line. After a request's strings comes its end line, request<TAB><TAB>strings,
24
+ # giving how many it held; only an end line has an empty path, so a request with none was not decoded to its
25
+ # end.
26
+ DECODE = <<~JQ
27
+ (input_filename | split("/") | last) as $request
28
+ | [paths(type == "string")] as $paths
29
+ | ($paths[] as $path | [$request, ($path | tojson), (getpath($path) | tojson)] | join("\\t")),
30
+ ([$request, "", ($paths | length | tostring)] | join("\\t"))
31
+ JQ
32
+ # The fixed string rg keeps each end line by: no other line holds two tabs together.
33
+ ENDING = "\t\t"
34
+ # Each pattern line as jq writes it inside a JSON string, so a pattern finds the strings DECODE wrote.
35
+ ESCAPE = "tojson | .[1:-1]"
36
+
37
+ # Runs jq and rg over files in the requests folder, keeping each line holding one of patterns, none of them
38
+ # empty.
39
+ #: (String, Array[String], Array[String]) -> LoggedRequestMatches
40
+ def self.run(requests, files, patterns)
41
+ listed, listing = RawRequestFilter.listing(requests, files, patterns)
42
+ counts, counting = StringCounts.of(requests, files - listed)
43
+ decoded = listed.empty? ? new(found: [], leaves: {}, whole: true) : decoded(requests, listed, patterns)
44
+ new(found: decoded.found, leaves: { **counts, **decoded.leaves }, whole: listing && counting && decoded.whole)
45
+ end
46
+
47
+ # One jq and rg run over files, keeping each line holding one of patterns.
48
+ #: (String, Array[String], Array[String]) -> LoggedRequestMatches
49
+ def self.decoded(requests, files, patterns)
50
+ written, escaping = escaped(patterns)
51
+ Tempfile.create("principles-patterns") do |listed|
52
+ listed.write([*written, ENDING].join("\n"))
53
+ listed.flush
54
+ Tempfile.create("principles-decode-errors") do |errors|
55
+ kept, statuses = decode_and_match(requests, files, listed.path, errors.path)
56
+ kept_lines(kept, patterns, escaping && whole?(statuses, errors.path))
57
+ end
58
+ end
59
+ end
60
+
61
+ # patterns as ESCAPE writes them, one a line, and whether jq wrote each of them and no error: a pattern it did
62
+ # not write finds nothing, so the run is not whole without it. capture3 reads while it writes, so many patterns
63
+ # cannot fill the pipes and stall, and it keeps jq's errors off this tool's output.
64
+ #: (Array[String]) -> [Array[String], bool]
65
+ def self.escaped(patterns)
66
+ written, errors, status = Open3.capture3("jq", "-rR", ESCAPE, stdin_data: patterns.join("\n"))
67
+ lines = written.split("\n")
68
+ [lines, status.success? == true && errors.empty? && lines.size == patterns.size]
69
+ end
70
+
71
+ # Each line rg kept, and both processes' exit statuses, their errors going to errors_path.
72
+ #: (String, Array[String], String, String) -> [Array[String], Array[Process::Status]]
73
+ def self.decode_and_match(requests, files, patterns_file, errors_path)
74
+ kept = [] #: Array[String]
75
+ statuses = [] #: Array[Process::Status]
76
+ Open3.pipeline_r(["jq", "-r", DECODE, *files], ["rg", "--no-config", "-F", "-f", patterns_file, "-"],
77
+ chdir: requests, err: errors_path) do |output, waits|
78
+ kept = output.each_line(chomp: true).to_a
79
+ statuses = waits.map(&:value)
80
+ end
81
+ [kept, statuses]
82
+ end
83
+
84
+ # Whether jq ran through every file, which its exit status alone does not say, as it names only the last file's
85
+ # error, so any error either process wrote counts too; and rg read all jq gave it, finding a line or none. The
86
+ # errors' words are never kept, since jq's can quote a value from a request.
87
+ #: (Array[Process::Status], String) -> bool
88
+ def self.whole?(statuses, errors_path)
89
+ case statuses.map(&:exitstatus)
90
+ in [0, 0 | 1] then File.empty?(errors_path)
91
+ else false
92
+ end
93
+ end
94
+
95
+ # The lines rg kept: the end lines count each request's strings, and each other names a string holding a pattern.
96
+ #: (Array[String], Array[String], bool) -> LoggedRequestMatches
97
+ def self.kept_lines(kept, patterns, whole)
98
+ endings, strings = kept.map { it.split("\t", 3).map(&:to_s) }.partition { |_, path, _| path.to_s.empty? }
99
+ leaves = endings.to_h { |request, _, count| [request.to_s, Integer(count)] }
100
+ new(found: lines_holding(strings, patterns), leaves:, whole:)
101
+ end
102
+
103
+ # Each line of strings, each as [request, path, string] in JSON, holding one of patterns, as [request, path,
104
+ # segment, line, offset], offset the byte in the string it starts at, each distinct string read once.
105
+ #: (Array[Array[String]], Array[String]) -> Array[KeptLine]
106
+ def self.lines_holding(strings, patterns)
107
+ held = strings.map(&:last).uniq.to_h { [it, DecodedLeaf.new(JSON.parse(it.to_s)).holding(patterns)] }
108
+ strings.flat_map { |request, path, leaf| kept_in(request.to_s, path.to_s, held.fetch(leaf)) }
109
+ end
110
+
111
+ # Each of lines, as DecodedLeaf#holding gives them, kept in request at path, the path in JSON.
112
+ #: (String, String, Array[[String, String, Integer]]) -> Array[KeptLine]
113
+ def self.kept_in(request, path, lines)
114
+ place = JSON.parse(path).join(".")
115
+ lines.map { |segment, line, at| KeptLine.new(request, place, segment, line, at) }
116
+ end
117
+ private_class_method :decoded, :escaped, :decode_and_match, :whole?, :kept_lines, :lines_holding, :kept_in
118
+
119
+ #: Array[KeptLine]
120
+ attr_reader :found
121
+ #: Hash[String, Integer]
122
+ attr_reader :leaves
123
+
124
+ # Whether the run read every file through: jq exited 0, neither process wrote an error, and rg read all it was
125
+ # given.
126
+ #: bool
127
+ attr_reader :whole
128
+
129
+ #: (found: Array[KeptLine], leaves: Hash[String, Integer], whole: bool) -> void
130
+ def initialize(found:, leaves:, whole:)
131
+ @found = found
132
+ @leaves = leaves
133
+ @whole = whole
134
+ freeze
135
+ end
136
+ end
137
+ end
138
+ end
@@ -0,0 +1,120 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ require "json"
5
+ require_relative "logged_request_matches"
6
+
7
+ module Principles
8
+ # Every file and process this tool reads or writes. data/CLAUDE.md owns the boundary.
9
+ module Data
10
+ # The requests the host captured in a request-logging folder, scanned by fast standard tools rather than Ruby:
11
+ # LoggedRequestMatches runs the jq and rg that decode and match them. A segment is reminder inside a
12
+ # system-reminder tag and plain outside one. jq and rg must be on PATH; Models::Feature refuses before a scan
13
+ # runs without them.
14
+ class LoggedRequestScan
15
+ REQUEST = "*.request.json"
16
+ INDEX = "index.jsonl"
17
+
18
+ # Each tool a request lists with defer_loading, as request<TAB>path: the host sends such a tool by name, and its
19
+ # definition reaches the model only once a tool search loads it.
20
+ DEFERRED = <<~'JQ'
21
+ (input_filename | split("/") | last) as $request
22
+ | (.tools // []) | to_entries[] | select(.value.defer_loading == true)
23
+ | "\($request)\ttools.\(.key)"
24
+ JQ
25
+
26
+ # DEFERRED, printing nothing, so a file it stops at fails it. It stands for both programs the other reads run:
27
+ # LoggedRequestMatches::DECODE reads any whole JSON through, so a file it stops at DEFERRED stops at too, and
28
+ # probing with it alone spares decoding every string of every request twice.
29
+ PROBE = "(#{DEFERRED}) | empty".freeze #: String
30
+
31
+ # Reads which request files the scan can read through once, here, so every read of this scan leaves the same ones
32
+ # out. That runs jq as the scan is built, which is fine as a command builds one scan per run.
33
+ #: (String) -> void
34
+ def initialize(requests)
35
+ @requests = requests
36
+ @unreadable = unreadable_files.freeze #: Array[Hash[String, String]]
37
+ freeze
38
+ end
39
+
40
+ # Each request file, by name, with the query_source its index line gives, or nil when the response failed and
41
+ # the host wrote it none.
42
+ #: () -> Array[Hash[String, String?]]
43
+ def requests
44
+ sources = index_sources
45
+ request_files.map { |name| { "file" => name, "query_source" => sources[name] } }
46
+ end
47
+
48
+ # Each decoded line holding one of patterns, and each request's count of strings. Each pattern is one line; an
49
+ # empty one is left out, since rg would match every line by it.
50
+ #: (Array[String]) -> LoggedRequestMatches
51
+ def matches(patterns)
52
+ patterns = patterns.reject(&:empty?)
53
+ files = readable_files
54
+ return LoggedRequestMatches.new(found: [], leaves: {}, whole: true) if files.empty? || patterns.empty?
55
+
56
+ LoggedRequestMatches.run(@requests, files, patterns)
57
+ end
58
+
59
+ # Each request file the scan cannot read through, by its request and its reason: not_whole_json for one that is
60
+ # not whole JSON, such as one a host left truncated, and not_decoded for whole JSON a read stops at, such as a
61
+ # list. jq stops at such a file, so the other reads leave these out rather than read it in part.
62
+ #: Array[Hash[String, String]]
63
+ attr_reader :unreadable
64
+
65
+ # Each tool a request defers loading, as [request, path].
66
+ #: () -> Array[[String, String]]
67
+ def deferred_tools
68
+ files = readable_files
69
+ return [] if files.empty?
70
+
71
+ listed = IO.popen(["jq", "-r", DEFERRED, *files], chdir: @requests, &:read)
72
+ listed.to_s.lines.map do |line|
73
+ request, path = line.chomp.split("\t", 2)
74
+ [request.to_s, path.to_s]
75
+ end
76
+ end
77
+
78
+ private
79
+
80
+ #: () -> Array[String]
81
+ def request_files = Dir.exist?(@requests) ? Dir.glob(REQUEST, base: @requests).sort : []
82
+
83
+ # One jq run probes every request file, and each is probed alone only when that run fails. The reason is a fixed
84
+ # code, never jq's message, which can quote a value from the request.
85
+ #: () -> Array[Hash[String, String]]
86
+ def unreadable_files
87
+ files = request_files
88
+ return [] if files.empty? || runs?(PROBE, files)
89
+
90
+ files.reject { runs?(PROBE, [it]) }
91
+ .map { { "request" => it, "reason" => runs?("empty", [it]) ? "not_decoded" : "not_whole_json" } }
92
+ end
93
+
94
+ #: () -> Array[String]
95
+ def readable_files = request_files - @unreadable.map { it.fetch("request") }
96
+
97
+ # Whether jq runs program, which prints nothing, through every one of files. jq's exit status tells only whether
98
+ # the last file failed, so an error it printed for any other file fails it too; its words are never kept.
99
+ #: (String, Array[String]) -> bool
100
+ def runs?(program, files)
101
+ printed = IO.popen(["jq", program, *files], chdir: @requests, err: %i[child out], &:read)
102
+ Process.last_status&.success? == true && printed.to_s.empty?
103
+ end
104
+
105
+ # The query_source of each request the index names, by its file name.
106
+ #: () -> Hash[String, String?]
107
+ def index_sources
108
+ index = File.join(@requests, INDEX)
109
+ return {} unless File.file?(index)
110
+
111
+ File.foreach(index).filter_map do |line|
112
+ entry = JSON.parse(line)
113
+ [File.basename(entry.fetch("request_file")), entry["query_source"]] if entry.is_a?(Hash)
114
+ rescue JSON::ParserError, KeyError, TypeError
115
+ nil
116
+ end.to_h
117
+ end
118
+ end
119
+ end
120
+ end
@@ -16,7 +16,11 @@ module Principles
16
16
  class MapFiles
17
17
  # The newest map format ordinary current-map reads accept. Models::Principle says which member fields need which
18
18
  # format, and a spec ties the two together.
19
- NEWEST_FORMAT = 2
19
+ NEWEST_FORMAT = 4
20
+
21
+ # The formats up to NEWEST_FORMAT a current read still refuses: 3 is an earlier map's history link, which only
22
+ # parse_history reads.
23
+ HISTORY_ONLY_FORMATS = [3].freeze #: Array[Integer]
20
24
 
21
25
  #: (PrinciplesSubfolder) -> void
22
26
  def initialize(directory)
@@ -111,15 +115,25 @@ module Principles
111
115
  #: (String, untyped, String?) -> void
112
116
  def refuse_newer(id, map, commit)
113
117
  format = map.is_a?(Hash) ? map["format"] : nil
114
- return unless format.is_a?(Integer) && format > NEWEST_FORMAT
118
+ return unless format.is_a?(Integer)
119
+ return unless format > NEWEST_FORMAT || HISTORY_ONLY_FORMATS.include?(format)
115
120
 
116
- raise Error.new("newer_format", "#{where(id, commit)} is format #{format}, written by a newer version " \
117
- "than this one; this one reads up to format #{NEWEST_FORMAT}",
121
+ raise Error.new("newer_format", "#{where(id, commit)} is format #{format}, #{unread_because(format)}",
118
122
  "Update the installed principles plugin or gem, then run the command again. " \
119
123
  "Leave the map as it is: it is not broken.",
120
124
  relative(id))
121
125
  end
122
126
 
127
+ # Why a current read cannot read a map at format.
128
+ #: (Integer) -> String
129
+ def unread_because(format)
130
+ if format > NEWEST_FORMAT
131
+ "written by a newer version than this one; this one reads up to format #{NEWEST_FORMAT}"
132
+ else
133
+ "which this version reads only as an earlier map's history"
134
+ end
135
+ end
136
+
123
137
  #: (String, String?) -> String
124
138
  def where(id, commit)
125
139
  commit ? "#{relative(id)} at commit #{commit[0, 12]}" : relative(id)
@@ -0,0 +1,85 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ require_relative "bounded_file"
5
+
6
+ module Principles
7
+ # Every file and process this tool reads or writes. data/CLAUDE.md owns the boundary.
8
+ module Data
9
+ # The folder Claude Code installed a copy of a plugin in. This tool only reads it, and walks no symbolic link, so
10
+ # every file it names is inside the folder as the disk holds it.
11
+ class PluginFolder
12
+ # The most entries a walk looks at, far above any plugin, so a vast folder cannot hang a run.
13
+ ENTRIES = 10_000 #: Integer
14
+
15
+ #: (String) -> void
16
+ def initialize(path)
17
+ @path = path
18
+ freeze
19
+ end
20
+
21
+ # Whether relative names a regular file in the folder, neither it nor any folder on the way a symbolic link.
22
+ #: (String) -> bool
23
+ def file?(relative)
24
+ *folders, name = relative.split("/")
25
+ inside = @path
26
+ folders.each do |folder|
27
+ inside = File.join(inside, folder)
28
+ return false unless File.lstat(inside).directory?
29
+ end
30
+ File.lstat(File.join(inside, name.to_s)).file?
31
+ rescue SystemCallError
32
+ false
33
+ end
34
+
35
+ # The text of the file at relative, which file? holds, refused when it is not UTF-8 or is larger than BoundedFile
36
+ # reads; a refusal names it by relative alone, never by where the host installed it.
37
+ #: (String) -> String
38
+ def read(relative)
39
+ BoundedFile.new(File.join(@path, relative), shown_as: relative, named: "#{relative} in the plugin").read_text
40
+ end
41
+
42
+ # Whether relative, or a folder on the way to it, or the plugin's folder itself, is a symbolic link, which this
43
+ # tool never follows.
44
+ #: (String) -> bool
45
+ def linked?(relative)
46
+ segments = relative.split("/")
47
+ (0..segments.size).any? { |count| File.lstat(File.join([@path] + segments.first(count))).symlink? }
48
+ rescue SystemCallError
49
+ false
50
+ end
51
+
52
+ # Each regular file in the folder by its path inside it, sorted, from a walk of at most ENTRIES entries that
53
+ # enters no symbolic link; none when the folder is gone.
54
+ #: () -> Array[String]
55
+ def files = walked.take(ENTRIES).select { |_, entry| entry.file? }.map(&:first).sort
56
+
57
+ private
58
+
59
+ # Every entry under the folder, by its path inside it, met one at a time, so taking the first few walks no
60
+ # further.
61
+ #: () -> Enumerator[[String, File::Stat]]
62
+ def walked = Enumerator.new { |found| visit("", found) }
63
+
64
+ #: (String, untyped) -> void
65
+ def visit(inside, found)
66
+ entries(inside).each do |relative, entry|
67
+ found << [relative, entry]
68
+ visit(relative, found) if entry.directory?
69
+ end
70
+ end
71
+
72
+ # Each entry directly in the folder at inside, by its path inside the plugin, as lstat sees it; none when it
73
+ # cannot be read.
74
+ #: (String) -> Array[[String, File::Stat]]
75
+ def entries(inside)
76
+ Dir.children(File.join(@path, inside)).sort.map do |name|
77
+ relative = inside.empty? ? name : "#{inside}/#{name}"
78
+ [relative, File.lstat(File.join(@path, relative))]
79
+ end
80
+ rescue SystemCallError
81
+ []
82
+ end
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,73 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ require "json"
5
+ require_relative "../error"
6
+ require_relative "json_text"
7
+
8
+ module Principles
9
+ # Every file and process this tool reads or writes. data/CLAUDE.md owns the boundary.
10
+ module Data
11
+ # Claude Code's record of the plugins installed on this machine, the text of installed_plugins.json under its
12
+ # config folder: for each plugin, by its install name NAME@MARKETPLACE, one row per install, in the order the host
13
+ # keeps them. Which row applies to a project is a model's rule; this reads the rows as the host wrote them.
14
+ class PluginRegistry
15
+ # The registry version this tool was written against, from a probe of Claude Code's own file.
16
+ VERSION = 2 #: Integer
17
+
18
+ # The registry text holds, refused when it is not a registry of the version this tool reads.
19
+ #: (String) -> void
20
+ def initialize(text)
21
+ @plugins = plugins_in(parsed(text)) #: Hash[String, Array[Hash[String, untyped]]]
22
+ freeze
23
+ end
24
+
25
+ # The rows for the plugin named, each with the fields a selection reads, in the host's order; none when the
26
+ # registry names no such plugin.
27
+ #: (String) -> Array[Hash[String, String?]]
28
+ def rows(name)
29
+ @plugins.fetch(name, []).map do |row|
30
+ { "scope" => row["scope"], "version" => row["version"], "project_path" => row["projectPath"],
31
+ "install_path" => row["installPath"] }
32
+ end
33
+ end
34
+
35
+ # Every plugin install name the registry holds, sorted.
36
+ #: () -> Array[String]
37
+ def names = @plugins.keys.sort
38
+
39
+ private
40
+
41
+ #: (Hash[String, untyped]) -> Hash[String, Array[Hash[String, untyped]]]
42
+ def plugins_in(registry)
43
+ unless registry["version"].eql?(VERSION)
44
+ raise Error.new("unsupported_plugin_registry",
45
+ "Claude Code's plugin registry is version #{registry["version"].inspect}; this tool reads " \
46
+ "version #{VERSION}",
47
+ "Map the project's own files instead; this copy cannot read this Claude Code's plugins.")
48
+ end
49
+
50
+ plugins = registry["plugins"]
51
+ plugins.is_a?(Hash) && plugins.each_value.all? { |rows| rows?(rows) } ? plugins : unreadable
52
+ end
53
+
54
+ #: (untyped) -> bool
55
+ def rows?(rows) = rows.is_a?(Array) ? rows.all?(Hash) : false
56
+
57
+ #: (String) -> Hash[String, untyped]
58
+ def parsed(text)
59
+ registry = JsonText.new(text).parsed
60
+ registry.is_a?(Hash) ? registry : unreadable
61
+ rescue JSON::ParserError
62
+ unreadable
63
+ end
64
+
65
+ #: () -> bot
66
+ def unreadable
67
+ raise Error.new("unreadable_plugin_registry",
68
+ "Claude Code's plugin registry is not in the shape this tool reads",
69
+ "Reinstall the plugin with Claude Code, or map the project's own files instead.")
70
+ end
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,49 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ require_relative "principles_directory"
5
+ require_relative "principles_subfolder"
6
+ require_relative "map_files"
7
+ require_relative "audit_files"
8
+ require_relative "guidance_search_paths_file"
9
+ require_relative "request_logging_folder"
10
+
11
+ module Principles
12
+ # Every file and process this tool reads or writes. data/CLAUDE.md owns the boundary.
13
+ module Data
14
+ # The files this tool keeps for a project under .principles: its member maps, its audit records, its recorded
15
+ # guidance search paths and its git-ignored logged requests, which a project is handed together.
16
+ class PrinciplesStore
17
+ # The store of the project at root.
18
+ #: (String) -> PrinciplesStore
19
+ def self.at(root)
20
+ new(maps: MapFiles.new(PrinciplesSubfolder.new(root, "maps")),
21
+ audits: AuditFiles.new(PrinciplesSubfolder.new(root, "audits")),
22
+ guidance_search_paths: GuidanceSearchPathsFile.new(PrinciplesDirectory.new(root)),
23
+ request_logging: RequestLoggingFolder.new(root))
24
+ end
25
+
26
+ #: MapFiles
27
+ attr_reader :maps
28
+
29
+ #: AuditFiles
30
+ attr_reader :audits
31
+
32
+ #: GuidanceSearchPathsFile
33
+ attr_reader :guidance_search_paths
34
+
35
+ #: RequestLoggingFolder
36
+ attr_reader :request_logging
37
+
38
+ #: (maps: MapFiles, audits: AuditFiles, guidance_search_paths: GuidanceSearchPathsFile,
39
+ #| request_logging: RequestLoggingFolder) -> void
40
+ def initialize(maps:, audits:, guidance_search_paths:, request_logging:)
41
+ @maps = maps
42
+ @audits = audits
43
+ @guidance_search_paths = guidance_search_paths
44
+ @request_logging = request_logging
45
+ freeze
46
+ end
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,25 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ require "open3"
5
+
6
+ module Principles
7
+ # Every file and process this tool reads or writes. data/CLAUDE.md owns the boundary.
8
+ module Data
9
+ # One run of a command in a folder: what it printed, and its exit status.
10
+ module Ran
11
+ # What command printed, run in folder with its errors going to errors_path, and its exit status, nil for one
12
+ # stopped by a signal.
13
+ #: (Array[String], String, String) -> [String, Integer?]
14
+ def self.run(command, folder, errors_path)
15
+ printed = ""
16
+ status = nil #: Integer?
17
+ Open3.pipeline_r(command, chdir: folder, err: errors_path) do |output, waits|
18
+ printed = output.read
19
+ status = waits.fetch(0).value.exitstatus
20
+ end
21
+ [printed, status]
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,61 @@
1
+ # typed: strict
2
+ # frozen_string_literal: true
3
+
4
+ require "json"
5
+ require "tempfile"
6
+ require_relative "ran"
7
+
8
+ module Principles
9
+ # Every file and process this tool reads or writes. data/CLAUDE.md owns the boundary.
10
+ module Data
11
+ # The request files that may hold one of some patterns, found by one rg run over the files as the host wrote them,
12
+ # so only those are decoded. The JSON writers of the hosts it captures, Node's among them, and jq and Ruby's, agree
13
+ # on writing a quote, a backslash and a control character, and differ on a slash, a DEL and a non-ASCII character,
14
+ # each written raw or as an escape, so each pattern is looked for in every one of those forms. A writer escaping
15
+ # < > & as Go's HTML-safe form does is not covered.
16
+ class RawRequestFilter
17
+ # rg's options for listing each file holding a fixed string, one a line, ignore files left unread, since git
18
+ # ignores the folder the requests are in.
19
+ SEARCH = %w[--no-config --no-ignore -F -l].freeze #: Array[String]
20
+ # A character outside ASCII, which a writer may write as itself or as \u escapes, in either case of hex digit.
21
+ NON_ASCII = /[^\x00-\x7f]/
22
+
23
+ # Each of files, in the requests folder, that may hold one of patterns, none of them empty, and whether rg read
24
+ # every file, finding one or none, and wrote no error.
25
+ #: (String, Array[String], Array[String]) -> [Array[String], bool]
26
+ def self.listing(requests, files, patterns)
27
+ Tempfile.create("principles-raw-patterns") do |listed|
28
+ listed.write(patterns.flat_map { written_forms(it) }.uniq.join("\n"))
29
+ listed.flush
30
+ search = ["rg", *SEARCH, "-f", listed.path]
31
+ Tempfile.create("principles-raw-errors") { listed_by(requests, search, files, it) }
32
+ end
33
+ end
34
+
35
+ # Each of files the command lists, run with them in the requests folder, and whether it found one or none and
36
+ # wrote no error to errors.
37
+ #: (String, Array[String], Array[String], File) -> [Array[String], bool]
38
+ def self.listed_by(requests, command, files, errors)
39
+ printed, status = Ran.run([*command, "--", *files], requests, errors.path)
40
+ [files & printed.split("\n"), [0, 1].include?(status) && File.empty?(errors.path)]
41
+ end
42
+
43
+ # Each form a JSON writer may write pattern in inside a string.
44
+ #: (String) -> Array[String]
45
+ def self.written_forms(pattern)
46
+ [JSON.generate(pattern)[1..-2].to_s]
47
+ .flat_map { [it, it.gsub("/", "\\/")] }
48
+ .flat_map { [it, it.gsub("\u007f", "\\u007f")] }
49
+ .flat_map { |form| [form, *%w[%04x %04X].map { |hex| form.gsub(NON_ASCII) { escaped(it, hex) } }] }
50
+ .uniq
51
+ end
52
+
53
+ # character as \u escapes, a surrogate pair beyond the first plane, with hex digits as hex writes them.
54
+ #: (String, String) -> String
55
+ def self.escaped(character, hex)
56
+ character.encode("UTF-16BE").unpack("n*").map { "\\u#{format(hex, it)}" }.join
57
+ end
58
+ private_class_method :listed_by, :written_forms, :escaped
59
+ end
60
+ end
61
+ end