@zalom/plastic 1.0.0-beta.17 → 1.0.0-beta.18

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.
package/PLASTIC.md CHANGED
@@ -256,20 +256,29 @@ hygiene after each intent. Advisory self-check, not hard-verifiable.
256
256
  ## Retrieval Gate
257
257
 
258
258
  A single capability-aware PreToolUse gate enforces retrieval-first routing on the agent's own
259
- Bash/Read/Grep/Glob calls (and on subagents, since PreToolUse binds them). Detection is binary:
260
- present means enforce, absent or down means off, with no warning and no advisory tier.
261
-
262
- - Store markdown (under a Plastic store) routes to QMD when QMD is present and the index is
263
- fresh: the raw grep/find/Read is blocked and you use `qmd search`/`qmd query` (or
264
- `scripts/qmd-sync search`) instead. When QMD is present but stale, the read is allowed this
265
- turn and a background reindex is fired so the next turn enforces against a fresh index;
266
- reindex is never synchronous. When QMD is absent or down, raw reads are allowed.
267
- - Serena-supported code and data files route to Serena symbolic tools when Serena is present;
268
- absent means allowed.
269
- - Images, binaries, and everything else are allowed.
270
- - Bypass: append a trailing `# qmd-ok` shell comment to a Bash command for the rare case where
271
- QMD is healthy but you genuinely need the raw read. A quoted or echoed occurrence does not
272
- bypass. Bypasses are logged.
259
+ Bash/Read/Grep/Glob calls (and on subagents, since PreToolUse binds them). The gate is
260
+ OPERATION-based: it separates searching from reading, and it never stands between you and
261
+ reading something you have already located.
262
+
263
+ - Only CONTENT SEARCH over a Plastic store is gated. The Grep tool and bash `grep`/`rg`/`ag`
264
+ whose target is at or under a store route to QMD when QMD is present and the index is fresh:
265
+ the raw scan is blocked and you use `qmd search`/`qmd query` (or `scripts/qmd-sync search`)
266
+ instead. When QMD is present but stale, the search is allowed this turn and a background
267
+ reindex is fired so the next turn enforces against a fresh index; reindex is never
268
+ synchronous. When QMD is absent, the search is allowed.
269
+ - Reading a known target (the Read tool, bash `cat`/`head`/`tail`) and structural discovery
270
+ (the Glob tool, bash `find`/`ls`) are always allowed, including over the store. QMD cannot
271
+ list directories or hand back one specific file, so these are never gated.
272
+ - Code is never hard-gated here. Symbolic code navigation via Serena is a soft prompt mandate
273
+ (the UserPromptSubmit power-tools hook), not a block: content grep over code is allowed,
274
+ because Serena navigates symbols and cannot grep arbitrary strings.
275
+ - QMD failure model. Absent or stale degrades to allow (stale also fires the background
276
+ reindex). A broken QMD, where the freshness probe errors or times out, also fails open, and
277
+ the hook emits a one-line warning so a degraded QMD is visible rather than silent.
278
+ - Bypass: append a trailing `# qmd-ok` shell comment to a Bash command when you attempted
279
+ discovery and it did not serve you (no hits, or results that do not answer your need by your
280
+ reading of the snippets, not their score). A quoted or echoed occurrence does not bypass.
281
+ Bypasses are logged. The gate enforces that discovery was attempted, never that it succeeded.
273
282
  - Scope: only the agent's tool calls. Ruby `File.read` inside a script is invisible to the gate
274
283
  and is out of scope by design.
275
284
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zalom/plastic",
3
- "version": "1.0.0-beta.17",
3
+ "version": "1.0.0-beta.18",
4
4
  "description": "Intent-driven idea development system for AI coding agents",
5
5
  "type": "module",
6
6
  "bin": {
@@ -2,14 +2,19 @@
2
2
  # encoding: UTF-8
3
3
  # frozen_string_literal: true
4
4
 
5
- # PreToolUse retrieval gate (intent 84, Lever 2). Reads the tool call (JSON on
6
- # stdin: tool_name + tool_input), computes capabilities (QMD detect+freshness,
7
- # Serena detect), delegates the decision to RetrievalGate, and enforces:
5
+ # PreToolUse retrieval gate (intent 84, Lever 2; operation-based redesign 89a).
6
+ # Reads the tool call (JSON on stdin: tool_name + tool_input), computes
7
+ # capabilities (QMD detect + freshness), delegates the decision to RetrievalGate,
8
+ # and enforces:
8
9
  # ALLOW = exit 0 ; BLOCK = exit 2 with reason on stderr (shown to the agent).
9
10
  # Fail-open: any parse error, timeout, or unexpected exception exits 0. On the
10
11
  # STALE QMD path RetrievalGate fires QmdSync.reindex_async (NEVER synchronous).
11
12
  # Binds subagents (PreToolUse hooks apply to subagent tool calls too).
12
13
  #
14
+ # Only CONTENT SEARCH over store markdown is gated; reads and structural ops are
15
+ # allowed. Code navigation is a soft prompt mandate (UserPromptSubmit power-tools),
16
+ # not enforced here, so this hook no longer detects Serena.
17
+ #
13
18
  # Scope: only the agent's own Bash/Read/Grep/Glob calls. Ruby `File.read` inside
14
19
  # scripts is invisible to a PreToolUse hook and is out of scope (no exemptions).
15
20
  #
@@ -19,15 +24,14 @@ require "json"
19
24
  require "timeout"
20
25
  require_relative "lib/retrieval_gate"
21
26
  require_relative "lib/qmd_sync"
22
- require_relative "lib/power_tools"
23
27
 
24
28
  module RetrievalGateHook
25
29
  module_function
26
30
 
27
31
  # Pure-ish core: capabilities and reindex are injected so this is unit-testable
28
- # with no real qmd/serena. Returns [exit_code, stderr_string].
32
+ # with no real qmd. Returns [exit_code, stderr_string].
29
33
  # stdin: raw PreToolUse JSON
30
- # capabilities: { qmd:, qmd_fresh:, serena: }
34
+ # capabilities: { qmd:, qmd_fresh: }
31
35
  # reindex: callable fired on the STALE path
32
36
  def run(stdin:, plastic_home:, cwd:, capabilities:, reindex: -> {})
33
37
  payload = parse(stdin)
@@ -62,23 +66,33 @@ module RetrievalGateHook
62
66
  nil
63
67
  end
64
68
 
65
- # Detect real capabilities for the live executable. A slow `qmd status` cannot
66
- # stall a tool call: a Timeout around the freshness probe degrades to "absent
67
- # for this turn" (allow, no reindex), staying fail-open and non-blocking.
68
- def detect_capabilities(cwd:)
69
- qmd = QmdSync.detect
69
+ # Detect real capabilities for the live executable. Probes are injected so the
70
+ # three-tier QMD failure model is unit-testable:
71
+ # - absent : QMD not on PATH -> allow, no warn.
72
+ # - broken : QMD present but freshness probe -> tier-b: WARN once, then treat
73
+ # raises/times out as absent this turn (allow).
74
+ # - fresh : probe returns truthy -> gate is live.
75
+ # A slow `qmd status` cannot stall a tool call: a 2s Timeout bounds the probe.
76
+ def detect_capabilities(cwd:,
77
+ detect: -> { QmdSync.detect },
78
+ fresh: -> { QmdSync.fresh? },
79
+ warn: ->(m) { $stderr.puts(m) })
80
+ qmd = detect.call
70
81
  qmd_fresh = false
71
82
  if qmd
72
- qmd_fresh = begin
73
- Timeout.timeout(2) { QmdSync.fresh? }
83
+ begin
84
+ qmd_fresh = Timeout.timeout(2) { fresh.call }
74
85
  rescue StandardError
75
- # Probe stalled/failed: treat as absent this turn (allow, no reindex).
86
+ # Tier-b: QMD is present but its freshness probe broke/stalled. Distinct
87
+ # from QMD being absent — warn so a degraded QMD is visible, then fail open
88
+ # (allow this turn, no reindex).
89
+ warn.call("PLASTIC GATE — QMD is present but its freshness probe failed; " \
90
+ "allowing this turn without routing search to QMD (check qmd).")
76
91
  qmd = false
77
- false
92
+ qmd_fresh = false
78
93
  end
79
94
  end
80
- serena = PowerTools.serena?(cwd: cwd)
81
- { qmd: qmd, qmd_fresh: qmd_fresh, serena: serena }
95
+ { qmd: qmd, qmd_fresh: qmd_fresh }
82
96
  end
83
97
 
84
98
  # Best-effort reindex callable for the STALE path. Resolves the collection from
@@ -3,62 +3,57 @@
3
3
 
4
4
  require_relative "bridge"
5
5
 
6
- # RetrievalGate — the single, pure decision for Lever 2 of intent 84.
6
+ # RetrievalGate — the single, pure decision for Lever 2 of intent 84, redesigned
7
+ # operation-based in intent 89a.
7
8
  #
8
9
  # Given an agent tool call (Bash/Read/Grep/Glob) and injected capability signals,
9
- # it decides whether to BLOCK the call (returning a redirect-to-QMD/Serena reason
10
- # String) or ALLOW it (returning nil). All capability and freshness signals are
11
- # injected by the caller (the hook); this module shells out to nothing, reads no
12
- # globals, and runs no binaries. Mirrors bridge.rb's decision-fn convention
13
- # (reason String to block, nil to allow).
10
+ # it decides whether to BLOCK the call (returning a redirect-to-QMD reason String)
11
+ # or ALLOW it (returning nil). All capability/freshness signals are injected by the
12
+ # caller (the hook); this module shells out to nothing, reads no globals, and runs
13
+ # no binaries. Mirrors bridge.rb's decision-fn convention (reason String to block,
14
+ # nil to allow).
14
15
  #
15
- # Classification (per target path):
16
- # - store `*.md` (under <plastic_home>/store or .../projects/<slug>/store) -> QMD
17
- # - Serena-supported code/data file (NOT a store markdown) -> SERENA
18
- # - images / binary / other -> ALLOWED
16
+ # Operation-based policy (intent 89, ## Redesign):
17
+ # - The gate distinguishes DISCOVERY (content search) from READING a known target.
18
+ # - Only CONTENT SEARCH over store markdown is hard-gated -> QMD.
19
+ # - Reading a known target (Read, cat/head/tail) and structural discovery (Glob,
20
+ # find, ls) are ALWAYS allowed, including over the store.
21
+ # - Code navigation is a soft prompt MANDATE (PowerTools / UserPromptSubmit), not a
22
+ # hard gate here. Content grep over code is allowed (Serena cannot grep strings).
19
23
  #
20
- # Capability enforcement is BINARY (no advisory tier):
21
- # - QMD class: detected+fresh -> BLOCK; detected+stale -> fire reindex, ALLOW
22
- # this turn; absent/down -> ALLOW (no warning).
23
- # - SERENA class: detected -> BLOCK; absent -> ALLOW.
24
+ # Content-search vectors (the only ones that can be gated):
25
+ # - the Grep tool (its `path` search root)
26
+ # - bash `grep`/`rg`/`ag` (their path args; the first bareword is the PATTERN)
24
27
  #
25
- # Bypass: a TRAILING `# qmd-ok` shell comment on a Bash command (not a substring;
26
- # a quoted/echoed occurrence does not bypass).
28
+ # QMD enforcement is BINARY (no advisory tier):
29
+ # - store-md content search: QMD detected+fresh -> BLOCK; detected+stale -> fire
30
+ # reindex, ALLOW this turn; absent/broken -> ALLOW (the hook warns on broken).
27
31
  #
28
- # Scope: only the agent's own tool calls. Ruby `File.read` inside scripts is
29
- # invisible to a PreToolUse hook and is explicitly out of scope (no exemptions).
32
+ # Bypass: a TRAILING `# qmd-ok` shell comment on a Bash command (not a substring; a
33
+ # quoted/echoed occurrence does not bypass). It is the auditable seam for "I tried
34
+ # discovery and it did not serve me" (empty, low, or wrongly-scored results).
35
+ #
36
+ # Scope: only the agent's own tool calls. Ruby `File.read` inside scripts is invisible
37
+ # to a PreToolUse hook and is explicitly out of scope (no exemptions).
30
38
  module RetrievalGate
31
39
  module_function
32
40
 
33
- # Serena LSP covers many languages incl. JSON/YAML/TOML/Markdown/Ruby. Keep a
34
- # small, conservative allowlist of code/data extensions. Markdown is listed but
35
- # store markdown is reclassified to QMD before Serena ever sees it.
36
- SERENA_EXTENSIONS = %w[
37
- rb js jsx ts tsx mjs cjs py go rs java kt scala c h cpp hpp cc
38
- cs php rb swift sh bash zsh lua ex exs erl clj sql
39
- json yaml yml toml
40
- ].freeze
41
-
42
- # Image / binary extensions that are always allowed (plain read is fine).
43
- BINARY_EXTENSIONS = %w[
44
- png jpg jpeg gif webp svg ico bmp tiff pdf
45
- zip gz tar tgz bz2 xz 7z
46
- mp3 mp4 mov avi wav flac ogg
47
- woff woff2 ttf otf eot
48
- bin exe dll so dylib o a class jar wasm
49
- ].freeze
50
-
51
41
  # A `# qmd-ok` token that is a real TRAILING shell comment, after stripping a
52
42
  # trailing newline. The token must be preceded by whitespace (or start the
53
- # command) and run to end-of-string. `echo "# qmd-ok"` does NOT match: the
54
- # token there is followed by a closing quote, not end-of-string.
43
+ # command) and run to end-of-string. `echo "# qmd-ok"` does NOT match: the token
44
+ # there is followed by a closing quote, not end-of-string.
55
45
  BYPASS_RE = /(?:\A|\s)#\s*qmd-ok\s*\z/.freeze
56
46
 
47
+ # Bash utilities that perform CONTENT SEARCH (scan file CONTENT for a pattern).
48
+ # These are the only bash read-vectors that can be gated; readers (cat/head/tail)
49
+ # and structural tools (find/ls) are never gated.
50
+ CONTENT_SEARCH_UTILS = %w[grep rg ag].freeze
51
+
57
52
  # Decide. Returns nil to ALLOW, or a reason String to BLOCK.
58
- # capabilities: { qmd:, qmd_fresh:, serena: } (booleans).
53
+ # capabilities: { qmd:, qmd_fresh: } (booleans).
59
54
  # reindex: no-arg callable fired once when a QMD-class target is STALE.
60
- # When bypassed, returns nil and (if given) yields :bypass to the optional
61
- # block so the caller can log it.
55
+ # When bypassed, returns nil and (if given) yields :bypass to the optional block
56
+ # so the caller can log it.
62
57
  def decision(tool_name:, tool_input:, plastic_home:, cwd:,
63
58
  capabilities:, reindex: -> {})
64
59
  targets = extract_targets(tool_name, tool_input, cwd: cwd)
@@ -71,17 +66,14 @@ module RetrievalGate
71
66
 
72
67
  stale_seen = false
73
68
  targets.each do |path|
74
- case classify(path, plastic_home: plastic_home)
75
- when :qmd
76
- if capabilities[:qmd] && capabilities[:qmd_fresh]
77
- return qmd_reason(path)
78
- elsif capabilities[:qmd] # present but stale
79
- stale_seen = true
80
- end
81
- # absent/down -> allow this target
82
- when :serena
83
- return serena_reason(path) if capabilities[:serena]
69
+ next unless classify(path, plastic_home: plastic_home) == :qmd
70
+
71
+ if capabilities[:qmd] && capabilities[:qmd_fresh]
72
+ return qmd_reason(path)
73
+ elsif capabilities[:qmd] # present but stale
74
+ stale_seen = true
84
75
  end
76
+ # absent/broken -> allow this target
85
77
  end
86
78
 
87
79
  reindex.call if stale_seen
@@ -90,27 +82,21 @@ module RetrievalGate
90
82
 
91
83
  # --- classification ---
92
84
 
85
+ # Operation-based: the store tree is the only gated class (content search whose
86
+ # target is at/under a store routes to QMD). Everything else is allowed.
93
87
  def classify(path, plastic_home:)
94
88
  return :allow if path.nil? || path.empty?
95
- ext = extension(path)
96
-
97
- if store_markdown?(path, plastic_home: plastic_home)
98
- return :qmd
99
- end
100
- return :allow if BINARY_EXTENSIONS.include?(ext)
101
- return :serena if SERENA_EXTENSIONS.include?(ext)
102
-
103
- :allow
89
+ store_path?(path, plastic_home: plastic_home) ? :qmd : :allow
104
90
  end
105
91
 
106
- # A markdown file under the global store or a project store. QMD owns store
107
- # markdown even though Serena could also read markdown (QMD wins for the store).
108
- def store_markdown?(path, plastic_home:)
109
- return false unless %w[md markdown].include?(extension(path))
92
+ # A path AT or UNDER the global store or a project store. We gate the whole store
93
+ # tree (not just `*.md`) because a content search root is usually a directory:
94
+ # grepping the store scans its markdown, which is exactly what QMD should serve.
95
+ def store_path?(path, plastic_home:)
110
96
  abs = absolutize(path)
111
97
  home = File.expand_path(plastic_home)
112
98
  global = File.join(home, "store")
113
- return true if abs.start_with?("#{global}/")
99
+ return true if abs == global || abs.start_with?("#{global}/")
114
100
 
115
101
  projects = File.join(home, "projects")
116
102
  return false unless abs.start_with?("#{projects}/")
@@ -118,19 +104,14 @@ module RetrievalGate
118
104
  tail.length >= 2 && tail[1] == "store"
119
105
  end
120
106
 
121
- def extension(path)
122
- File.extname(path.to_s).sub(/\A\./, "").downcase
123
- end
124
-
125
107
  def absolutize(path)
126
108
  File.absolute_path?(path) ? path : File.expand_path(path)
127
109
  end
128
110
 
129
111
  # --- bypass ---
130
112
 
131
- # Only Bash commands carry a trailing `# qmd-ok` comment. The token must be a
132
- # real trailing comment (BYPASS_RE), so a quoted/echoed occurrence does not
133
- # bypass.
113
+ # Only Bash commands carry a trailing `# qmd-ok` comment. The token must be a real
114
+ # trailing comment (BYPASS_RE), so a quoted/echoed occurrence does not bypass.
134
115
  def bypass?(tool_name, tool_input)
135
116
  return false unless tool_name.to_s == "Bash"
136
117
  cmd = tool_input.is_a?(Hash) ? tool_input["command"].to_s : ""
@@ -139,40 +120,36 @@ module RetrievalGate
139
120
 
140
121
  # --- target extraction ---
141
122
 
142
- # Paths the call reads/scans. Conservative: missing an exotic form is fine;
143
- # never flag /dev/null or pure pipes. Read vectors only (this is a READ gate),
144
- # not the write vectors bridge.rb already covers.
123
+ # Paths a CONTENT-SEARCH operation scans. Reads (Read, cat/head/tail) and
124
+ # structural discovery (Glob, find, ls) are NOT content search -> no targets ->
125
+ # always allowed. Only the Grep tool and bash grep/rg/ag can be gated. Read
126
+ # vectors only (this is a READ gate); write vectors are bridge.rb's job.
145
127
  def extract_targets(tool_name, tool_input, cwd:)
146
128
  input = tool_input.is_a?(Hash) ? tool_input : {}
147
129
  case tool_name.to_s
148
- when "Read"
149
- [input["file_path"]].compact.reject(&:empty?)
150
- when "Glob"
151
- [input["path"], input["pattern"]].compact.reject { |s| s.to_s.empty? }
152
130
  when "Grep"
153
131
  # The search root is the target; the query text is not a path.
154
132
  [input["path"]].compact.reject { |s| s.to_s.empty? }
155
133
  when "Bash"
156
- bash_read_targets(input["command"].to_s)
134
+ bash_search_targets(input["command"].to_s)
157
135
  else
136
+ # Read, Glob, and every other tool: read / structural op -> never gated.
158
137
  []
159
138
  end
160
139
  end
161
140
 
162
- # READ utilities that take file/dir path arguments. Conservative parse: split
163
- # on shell separators, identify the utility, collect its non-flag path args.
164
- READ_UTILS = %w[grep rg ag find cat head tail less more bat ls wc nl sort uniq].freeze
165
-
166
- def bash_read_targets(command)
141
+ # CONTENT-SEARCH path args across a compound command. Conservative: missing an
142
+ # exotic form is fine; never flag /dev/null or pure pipes.
143
+ def bash_search_targets(command)
167
144
  return [] unless command.is_a?(String) && !command.empty?
168
145
  targets = []
169
146
  command.split(/[;\n]|&&|\|\||\|/).each do |segment|
170
- targets.concat(segment_read_targets(segment))
147
+ targets.concat(segment_search_targets(segment))
171
148
  end
172
149
  targets.reject { |t| t.nil? || t.empty? || dev_path?(t) }.uniq
173
150
  end
174
151
 
175
- def segment_read_targets(segment)
152
+ def segment_search_targets(segment)
176
153
  tokens = tokenize(segment)
177
154
  return [] if tokens.empty?
178
155
 
@@ -180,21 +157,20 @@ module RetrievalGate
180
157
  idx = 0
181
158
  idx += 1 while tokens[idx] && tokens[idx].include?("=") && tokens[idx] !~ /\A-/
182
159
  util = File.basename(tokens[idx].to_s)
183
- return [] unless READ_UTILS.include?(util)
160
+ return [] unless CONTENT_SEARCH_UTILS.include?(util)
184
161
 
185
162
  args = tokens[(idx + 1)..] || []
186
- path_args_for(util, args)
163
+ path_args_for(args)
187
164
  end
188
165
 
189
- # Collect path-shaped arguments for a read utility. Flags and flag-values are
190
- # skipped; for grep/rg the first non-flag bareword is the PATTERN, not a path.
191
- def path_args_for(util, args)
192
- skip_pattern = %w[grep rg ag].include?(util)
166
+ # Collect path-shaped arguments for a content-search util. Flags are skipped; the
167
+ # first non-flag bareword is the PATTERN, not a path.
168
+ def path_args_for(args)
193
169
  paths = []
194
170
  pattern_consumed = false
195
171
  args.each do |a|
196
172
  next if a.start_with?("-")
197
- if skip_pattern && !pattern_consumed
173
+ unless pattern_consumed
198
174
  pattern_consumed = true
199
175
  next
200
176
  end
@@ -225,14 +201,11 @@ module RetrievalGate
225
201
  # --- reasons ---
226
202
 
227
203
  def qmd_reason(path)
228
- "retrieval gate: search the store via QMD, not raw grep/Read. " \
229
- "Use `qmd search`/`qmd query` over the `plastic-*` collections (or " \
230
- "`scripts/qmd-sync search`) instead of reading #{path}. " \
231
- "If you genuinely need the raw read, append a trailing `# qmd-ok` to a Bash command."
232
- end
233
-
234
- def serena_reason(path)
235
- "retrieval gate: navigate code via Serena's symbolic tools (find_symbol / " \
236
- "get_symbols_overview / find_referencing_symbols), not raw grep/Read of #{path}."
204
+ "retrieval gate: search the store via QMD, not a raw content scan. Reading a " \
205
+ "known file and listing/globbing the store are fine; only CONTENT SEARCH over " \
206
+ "store markdown routes through QMD. Use `qmd search`/`qmd query` over the " \
207
+ "`plastic-*` collections (or `scripts/qmd-sync search`) instead of scanning " \
208
+ "#{path}. If QMD's results do not answer your need (your reading of the " \
209
+ "snippets, not their score), append a trailing `# qmd-ok` to a Bash command."
237
210
  end
238
211
  end