textus 0.54.0 → 0.54.2

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.
@@ -1,316 +1,46 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Textus
2
4
  class Manifest
3
5
  module Schema
4
- # The manifest validation walk. Extracted from Schema (ADR 0107); the
5
- # schema data now lives in Schema::Vocabulary (coordination vocabulary,
6
- # LANES + derived) and Schema::Keys (key whitelists / FIELD_REGISTRY),
7
- # re-exported on Schema — while the validation *logic* lives here.
8
- # Lexically nested under Schema, so bare constant references
9
- # (ROOT_KEYS, LANES, FIELD_REGISTRY, …) resolve to Schema's constants.
6
+ # Orchestrates structural validation (dry-schema Contract) then cross-field
7
+ # semantic checks (Semantics). Public interface unchanged: Validator.validate!(raw).
10
8
  module Validator
11
9
  module_function
12
10
 
13
11
  def validate!(raw)
14
12
  raise BadManifest.new("manifest must be a hash") unless raw.is_a?(Hash)
15
13
 
16
- walk(raw, ROOT_KEYS, "$")
17
- raise BadManifest.new("manifest must declare lanes:") if Array(raw["lanes"]).empty?
18
-
19
- validate_roles!(raw["roles"])
20
- validate_lanes!(raw["lanes"])
21
- validate_entries!(raw["entries"])
22
- validate_owners!(raw["lanes"], raw["entries"])
23
- validate_rules!(raw["rules"])
24
- walk(raw["audit"], AUDIT_KEYS, "$.audit") if raw["audit"].is_a?(Hash)
25
- validate_single_queue!(raw)
26
- validate_single_machine!(raw)
27
- validate_lane_kind_consistency!(raw)
28
- end
29
-
30
- def validate_lanes!(lanes)
31
- Array(lanes).each_with_index do |z, i|
32
- walk(z, LANE_KEYS, "$.lanes[#{i}]")
33
- if z["kind"].nil?
34
- raise BadManifest.new("lane '#{z["name"]}' at '$.lanes[#{i}]' must declare a kind (one of: #{LANE_KINDS.join(", ")})")
35
- end
36
- next if LANE_KINDS.include?(z["kind"])
37
-
38
- if %w[quarantine derived].include?(z["kind"])
39
- raise BadManifest.new(
40
- "lane kind '#{z["kind"]}' at '$.lanes[#{i}]' was folded into 'machine' (ADR 0091) — " \
41
- "use `kind: machine`",
42
- )
43
- end
44
-
45
- raise BadManifest.new(
46
- "unknown lane kind '#{z["kind"]}' at '$.lanes[#{i}]' (known: #{LANE_KINDS.join(", ")})",
47
- )
48
- end
49
- end
50
-
51
- def validate_entries!(entries)
52
- Array(entries).each_with_index do |e, i|
53
- path = "$.entries[#{i}]"
54
- reject_retired_publish_keys!(e, path)
55
- reject_retired_render_keys!(e, path)
56
- walk(e, ENTRY_KEYS, path)
57
- validate_publish_block!(e, path)
58
- walk(e["source"], SOURCE_KEYS, "#{path}.source") if e["source"]
59
- end
60
- end
61
-
62
- # Retired keys are no longer allowed, so `walk` would reject them as merely
63
- # "unknown"; intercept first with the migration path so a pre-0.43 manifest
64
- # gets a useful error. `publish_each` was removed (ADR 0051); `publish_to`/
65
- # `publish_tree` were folded into the `publish:` block (ADR 0052);
66
- # `index_filename` was removed (ADR 0053).
67
- def reject_retired_publish_keys!(entry, path)
68
- return unless entry.is_a?(Hash)
69
-
70
- if entry.key?("publish_each")
71
- raise BadManifest.new(
72
- "publish_each was removed in 0.42.0 (ADR 0051) at '#{path}' — " \
73
- "mirror the subtree with `publish: { tree: \"...\" }`.",
74
- )
75
- end
76
-
77
- if entry.key?("publish_to")
78
- raise BadManifest.new(
79
- "publish_to was replaced by the publish: block in 0.43.0 (ADR 0052) at '#{path}' — " \
80
- "use `publish: { to: [...] }`.",
81
- )
82
- end
83
-
84
- if entry.key?("publish_tree")
85
- raise BadManifest.new(
86
- "publish_tree was replaced by the publish: block in 0.43.0 (ADR 0052) at '#{path}' — " \
87
- "use `publish: { tree: \"...\" }`.",
88
- )
89
- end
90
-
91
- return unless entry.key?("index_filename")
92
-
93
- raise BadManifest.new(
94
- "index_filename was removed in 0.43.0 (ADR 0053) at '#{path}' — a nested entry now enumerates " \
95
- "each file as a key; to mirror a directory of files to a consumer path use `publish: { tree: \"...\" }`.",
96
- )
97
- end
98
-
99
- # ADR 0094: rendering is a publish concern. An entry no longer
100
- # declares a build-time template or render flags — they move onto publish
101
- # targets. Provenance lives in the data's `_meta`, not a flag.
102
- def reject_retired_render_keys!(entry, path)
103
- return unless entry.is_a?(Hash)
104
-
105
- if entry.key?("template")
106
- raise BadManifest.new(
107
- "entry-level `template:` was removed at '#{path}' (ADR 0094): rendering is a " \
108
- "publish concern — `publish: [{ to:, template: }]`.",
109
- )
110
- end
111
- if entry.key?("inject_boot")
112
- raise BadManifest.new(
113
- "entry-level `inject_boot:` was removed at '#{path}' (ADR 0094): it is a render " \
114
- "flag — `publish: [{ to:, inject_boot: }]`.",
115
- )
116
- end
117
- return unless entry.key?("provenance")
118
-
119
- raise BadManifest.new("entry-level `provenance:` was removed at '#{path}' (ADR 0094): provenance lives in the data's `_meta`.")
120
- end
121
-
122
- # ADR 0094: publish is a LIST of target objects. The old
123
- # `{ to: [...] }` / `{ tree: … }` map forms are retired (fold hint).
124
- def validate_publish_block!(entry, path)
125
- return unless entry.is_a?(Hash) && entry.key?("publish")
126
-
127
- block = entry["publish"]
128
- if block.is_a?(Hash)
129
- raise BadManifest.new(
130
- "publish: at '#{path}.publish' must be a list of targets " \
131
- "[{ to:, template:? } | { tree: }] (ADR 0094); the map form was retired.",
132
- )
133
- end
134
- raise BadManifest.new("publish: must be a list of targets at '#{path}.publish'") unless block.is_a?(Array)
135
-
136
- block.each_with_index do |t, i|
137
- raise BadManifest.new("publish target ##{i} must be a mapping at '#{path}.publish'") unless t.is_a?(Hash)
138
-
139
- walk(t, %w[to tree template inject_boot], "#{path}.publish[#{i}]")
140
- end
141
- end
142
-
143
- def validate_rules!(rules)
144
- Array(rules).each_with_index do |r, i|
145
- path = "$.rules[#{i}]"
146
- reject_retired_rule_keys!(r, path)
147
- if r.is_a?(Hash) && r.key?("upkeep")
148
- raise BadManifest.new(
149
- "rule key `upkeep:` was removed (ADR 0093): move age-GC to `retention:` " \
150
- "and production (handler/template) to the entry's `source:`",
151
- )
152
- end
153
- walk(r, RULE_KEYS, path)
154
- FIELD_REGISTRY.each_value do |meta|
155
- next unless meta[:sub_keys]
156
-
157
- value = r[meta[:yaml_key]]
158
- walk(value, meta[:sub_keys], "#{path}.#{meta[:yaml_key]}") if value.is_a?(Hash)
159
- end
160
- end
161
- end
162
-
163
- # ADR 0093 split production from age-GC: age-GC moved to the `retention:`
164
- # rule; intake cadence + production (handler/template) moved to the
165
- # entry's `source:` block. Legacy `lifecycle:`/`materialize:` rule keys
166
- # are rejected with a migration hint toward the new shape.
167
- def reject_retired_rule_keys!(rule, path)
168
- return unless rule.is_a?(Hash)
169
-
170
- hints = {
171
- "lifecycle" => "age GC moved to the `retention:` rule ({ ttl, action: drop|archive }); " \
172
- "intake cadence to the entry's `source: { ttl }`",
173
- "materialize" => "removed — materialization is automatic (a write enqueues a job; run `drain`)",
174
- }
175
- hints.each do |old, hint|
176
- next unless rule.key?(old)
177
-
178
- raise BadManifest.new("`#{old}:` was removed at '#{path}' (ADR 0093) — #{hint}.")
179
- end
180
- end
181
-
182
- def validate_roles!(roles)
183
- return if roles.nil?
184
- raise BadManifest.new("roles: must be a list") unless roles.is_a?(Array)
185
-
186
- roles.each_with_index do |r, i|
187
- path = "$.roles[#{i}]"
188
- walk(r, ROLE_KEYS, path)
189
- name = r["name"] or raise BadManifest.new("role at '#{path}' missing name")
190
- unless Textus::Role::NAMES.include?(name)
191
- raise BadManifest.new(
192
- "unknown role name '#{name}' at '#{path}' " \
193
- "(allowed: #{Textus::Role::NAMES.join(", ")})",
194
- )
195
- end
196
- Array(r["can"]).each do |verb|
197
- next if CAPABILITIES.include?(verb)
14
+ # Root unknown-key check before Contract so it fires even when lanes: is empty.
15
+ Semantics.walk(raw, ROOT_KEYS, "$")
198
16
 
199
- # The quarantine capability folded into the converge capability (ADR 0090); a
200
- # manifest still naming the old quarantine capability (`ingest`, or
201
- # legacy `fetch`) gets a pointed hint rather than a bare error.
202
- hint = %w[ingest fetch].include?(verb) ? " — the quarantine capability folded into 'converge' (ADR 0090)" : ""
203
- raise BadManifest.new(
204
- "unknown capability '#{verb}' for role '#{name}' at '#{path}' " \
205
- "(known: #{CAPABILITIES.join(", ")})#{hint}",
206
- )
207
- end
208
- end
17
+ result = Contract.call(raw)
18
+ raise BadManifest.new(format_first_error(result.errors.messages)) unless result.success?
209
19
 
210
- author_holders = roles.count { |r| Array(r["can"]).include?("author") }
211
- return if author_holders <= 1
212
-
213
- raise BadManifest.new(
214
- "manifest declares #{author_holders} roles with the author capability; at most one is allowed",
215
- )
216
- end
217
-
218
- # Owners are validated against the SAME closed archetype set as role names
219
- # (ADR 0045 D1) so attribution can't bypass the closed-name guarantee.
220
- # Applies to both zone owners and entry owners; owner is optional, so a
221
- # nil owner is not an error.
222
- def validate_owners!(lanes, entries)
223
- Array(lanes).each_with_index do |z, i|
224
- check_owner!(z["owner"], "$.lanes[#{i}]")
225
- end
226
- Array(entries).each_with_index do |e, i|
227
- check_owner!(e["owner"], "$.entries[#{i}]")
228
- end
229
- end
230
-
231
- def check_owner!(owner, path)
232
- return if owner.nil?
233
- return if valid_owner?(owner)
234
-
235
- raise BadManifest.new(
236
- "invalid owner '#{owner}' at '#{path}' " \
237
- "(expected <archetype> or <archetype>:<subject>, " \
238
- "archetype one of: #{Textus::Role::NAMES.join(", ")})",
239
- )
240
- end
241
-
242
- # The owner-validation rule: an `owner:` token is either a bare archetype
243
- # (`agent`) or `<archetype>:<subject>` (`human:patrick`). The archetype is
244
- # gated against the closed Role::NAMES set (so attribution can't smuggle in
245
- # a name the role side rejects, ADR 0045 D1); the subject is the free-form
246
- # principal, validated by OWNER_SUBJECT_PATTERN. Split on the FIRST ':'
247
- # only — a subject may not itself contain ':' (the pattern excludes it), so
248
- # `human:a:b` is rejected.
249
- def valid_owner?(token)
250
- return false unless token.is_a?(String) && !token.empty?
251
-
252
- archetype, subject = token.split(":", 2)
253
- return false unless Textus::Role::NAMES.include?(archetype)
254
- return true if subject.nil?
20
+ raise BadManifest.new("manifest must declare lanes:") if Array(raw["lanes"]).empty?
255
21
 
256
- OWNER_SUBJECT_PATTERN.match?(subject)
22
+ Semantics.check!(raw)
257
23
  end
258
24
 
259
- def walk(hash, allowed, path)
260
- return unless hash.is_a?(Hash)
25
+ # Format the first dry-schema error to match the legacy path-prefixed style:
26
+ # "unknown key 'x' at '$.lanes[0]'" for extra-key errors;
27
+ # "manifest structure error at <path>: <msg>" for type/value errors.
28
+ def format_first_error(messages)
29
+ msg = messages.first
30
+ return "manifest structure error: unknown" unless msg
261
31
 
262
- hash.each_key do |k|
263
- next if allowed.include?(k)
32
+ parent = format_path(msg.path[0..-2])
33
+ key = msg.path.last
264
34
 
265
- raise BadManifest.new("unknown key '#{k}' at '#{path}'")
35
+ if msg.text == "is not allowed"
36
+ "unknown key '#{key}' at '#{parent}'"
37
+ else
38
+ "manifest structure error at #{format_path(msg.path)}: #{msg.text}"
266
39
  end
267
40
  end
268
41
 
269
- def validate_single_queue!(raw)
270
- queues = Array(raw["lanes"]).select { |z| z["kind"] == "queue" }.map { |z| z["name"] }
271
- return if queues.size <= 1
272
-
273
- raise BadManifest.new(
274
- "at most one lane may declare kind: queue (found: #{queues.join(", ")})",
275
- )
276
- end
277
-
278
- def validate_single_machine!(raw)
279
- machines = Array(raw["lanes"]).select { |z| z["kind"] == "machine" }.map { |z| z["name"] }
280
- return if machines.size <= 1
281
-
282
- raise BadManifest.new(
283
- "at most one lane may declare kind: machine (found: #{machines.join(", ")})",
284
- )
285
- end
286
-
287
- # ADR 0093: retention (drop/archive) is age-based GC; it is invalid on a
288
- # derived entry (a derived entry regenerates from its source, it isn't aged
289
- # out). Per ADR 0095 the produce-method is read from source.from on the one
290
- # Produced kind, so there is no longer a kind to agree against the source.
291
- # (Replaces validate_upkeep_kinds!.)
292
- def validate_source_and_retention!(_manifest)
293
- # No-op: from: derive is removed; retention + produced entries are
294
- # always valid (retention drives age-GC on workflow-produced entries).
295
- end
296
-
297
- # Write authority is derived from capabilities (ADR 0030): a lane of a
298
- # given kind can only be written by a role that holds the kind's required
299
- # verb. Reject a manifest declaring a lane whose required verb is held by
300
- # no role. Capabilities.resolve returns the defaults when `roles:` is nil,
301
- # so the capability union is all four verbs and every kind is satisfied.
302
- def validate_lane_kind_consistency!(raw)
303
- held = Capabilities.resolve(raw["roles"]).values.flatten.uniq
304
-
305
- Array(raw["lanes"]).each_with_index do |z, i|
306
- verb = KIND_REQUIRES_VERB[z["kind"]]
307
- next if verb.nil? || held.include?(verb)
308
-
309
- raise BadManifest.new(
310
- "lane '#{z["name"]}' (#{z["kind"]}) at '$.lanes[#{i}]' " \
311
- "needs a role with capability '#{verb}'; none declared",
312
- )
313
- end
42
+ def format_path(parts)
43
+ "$" + Array(parts).map { |p| p.is_a?(Integer) ? "[#{p}]" : ".#{p}" }.join
314
44
  end
315
45
  end
316
46
  end
@@ -23,11 +23,8 @@ module Textus
23
23
  RULE_KEYS = Keys::RULE_KEYS
24
24
  OWNER_SUBJECT_PATTERN = Keys::OWNER_SUBJECT_PATTERN
25
25
 
26
- # Public entry points — the validation walk lives in Schema::Validator
27
- # (ADR 0107). Kept here so callers keep speaking to `Schema`.
26
+ # Public entry point — the validation walk lives in Schema::Validator (ADR 0107).
28
27
  def self.validate!(raw) = Validator.validate!(raw)
29
-
30
- def self.validate_source_and_retention!(manifest) = Validator.validate_source_and_retention!(manifest)
31
28
  end
32
29
  end
33
30
  end
@@ -44,14 +44,12 @@ module Textus # rubocop:disable Style/OneClassPerFile
44
44
 
45
45
  def build(raw, root)
46
46
  data = Manifest::Data.parse(raw, root: root)
47
- manifest = new(
47
+ new(
48
48
  data: data,
49
49
  resolver: Manifest::Resolver.new(data),
50
50
  policy: data.policy,
51
51
  rules: Manifest::Rules.parse(raw["rules"] || []),
52
52
  )
53
- Manifest::Schema.validate_source_and_retention!(manifest) # ADR 0093
54
- manifest
55
53
  end
56
54
 
57
55
  def check_version!(raw, source)
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "yaml"
4
+ require "fileutils"
5
+
6
+ module Textus
7
+ module Ports
8
+ # Content-addressable index for the raw lane. Maps content hashes and URLs
9
+ # to their current canonical key. Lives under <root>/.state/indexes/raw.yaml
10
+ # (gitignored, regenerable — truth is in the on-disk raw entries).
11
+ class RawIndex
12
+ def initialize(root:)
13
+ @root = root
14
+ @path = Layout.raw_index(root)
15
+ end
16
+
17
+ attr_reader :path
18
+
19
+ def load
20
+ return empty_index unless File.exist?(@path)
21
+
22
+ YAML.safe_load_file(@path) || empty_index
23
+ rescue StandardError
24
+ empty_index
25
+ end
26
+
27
+ def save(index)
28
+ FileUtils.mkdir_p(File.dirname(@path))
29
+ File.write(@path, YAML.dump(index))
30
+ index
31
+ end
32
+
33
+ def find_by_hash(content_hash)
34
+ index = load
35
+ index["hashes"]&.fetch(content_hash, nil)
36
+ end
37
+
38
+ def find_by_url(url)
39
+ return nil unless url
40
+
41
+ index = load
42
+ index["urls"]&.fetch(url, nil)
43
+ end
44
+
45
+ def upsert(content_hash:, url:, key:)
46
+ index = load
47
+ index["hashes"] ||= {}
48
+ index["urls"] ||= {}
49
+ index["hashes"][content_hash] = key
50
+ index["urls"][url] = key if url
51
+ save(index)
52
+ end
53
+
54
+ private
55
+
56
+ def empty_index
57
+ { "hashes" => {}, "urls" => {} }
58
+ end
59
+ end
60
+ end
61
+ end
@@ -1,4 +1,6 @@
1
- require "mustache"
1
+ # frozen_string_literal: true
2
+
3
+ require "erb"
2
4
 
3
5
  module Textus
4
6
  module Produce
@@ -11,7 +13,7 @@ module Textus
11
13
  raise ArgumentError.new("Produce::Render called for a verbatim target #{target.to.inspect}") unless target.renders?
12
14
 
13
15
  ctx = target.inject_boot ? data.merge("boot" => boot) : data
14
- Mustache.render(@template_loader.call(target.template), ctx)
16
+ ERB.new(@template_loader.call(target.template), trim_mode: "-").result_with_hash(ctx)
15
17
  end
16
18
  end
17
19
  end
@@ -1,11 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dry-struct"
4
+
1
5
  module Textus
2
6
  # The agent session: per-connection (MCP), per-process (CLI), or per-loop
3
7
  # (Ruby) orientation state — the audit cursor plus the contract etag and
4
- # propose_lane captured at boot. Immutable Data value; advance_cursor
5
- # returns a new instance. ADR 0036; contract_etag widened in ADR 0074.
6
- Session = Data.define(:role, :cursor, :propose_lane, :contract_etag) do
7
- # Back-compat reader while lane terminology migrates.
8
- def propose_zone = propose_lane
8
+ # propose_lane captured at boot. Immutable Dry::Struct::Value; advance_cursor
9
+ # and with return new instances. ADR 0036; contract_etag widened in ADR 0074.
10
+ class Session < Dry::Struct
11
+ attribute :role, Types::RoleName
12
+ attribute :cursor, Types::Cursor
13
+ attribute :propose_lane, Types::String.optional
14
+ attribute :contract_etag, Types::String
15
+
16
+ def with(**attrs) = self.class.new(to_h.merge(attrs))
9
17
 
10
18
  def advance_cursor(new_cursor) = with(cursor: new_cursor)
11
19
 
@@ -21,8 +29,7 @@ module Textus
21
29
  private
22
30
 
23
31
  # First 8 hex chars after the "sha256:" prefix — a stable short id for
24
- # the drift diagnostic. Tolerates non-prefixed values (delete_prefix is
25
- # a no-op when the prefix is absent).
32
+ # the drift diagnostic.
26
33
  def short_etag(etag) = etag.to_s.delete_prefix("sha256:")[0, 8]
27
34
  end
28
35
  end
data/lib/textus/store.rb CHANGED
@@ -5,9 +5,9 @@ module Textus
5
5
  attr_reader :container
6
6
 
7
7
  # Readers are derived from the Container's schema, so the field set lives
8
- # in exactly one place (Container's Data.define). A new capability added
9
- # there is automatically exposed on the Store.
10
- Textus::Container.members.each do |field|
8
+ # in exactly one place (Container). A new capability added there is
9
+ # automatically exposed on the Store.
10
+ Textus::Container.attribute_names.each do |field|
11
11
  define_method(field) { @container.public_send(field) }
12
12
  end
13
13
 
@@ -50,7 +50,7 @@ module Textus
50
50
  # Ruby equivalent of an MCP `initialize`. ADR 0036.
51
51
  def session(role:)
52
52
  Textus::Session.new(
53
- role: role,
53
+ role: role.to_s,
54
54
  cursor: audit_log.latest_seq,
55
55
  propose_lane: manifest.policy.propose_lane_for(role),
56
56
  contract_etag: Textus::Etag.for_contract(root),
@@ -1,11 +1,10 @@
1
1
  module Textus
2
2
  module Surfaces
3
3
  module MCP
4
- # Derives the entire MCP tool surface from the per-verb contracts
5
- # (ADR 0039). `tool_schemas` feeds tools/list; `call` is the generic
6
- # tools/call dispatch: map JSON args -> (positional, keyword) per the
7
- # contract, invoke the verb through the role scope, then shape the
8
- # return value with the contract's default view. No per-tool code.
4
+ # Derives the entire MCP tool surface from the per-verb contracts (ADR 0039).
5
+ # `build_tools` builds MCP::Tool instances for the SDK; `call` is the generic
6
+ # dispatch: map JSON args -> (positional, keyword) per the contract, invoke
7
+ # the verb through the role scope, then shape the return value. No per-tool code.
9
8
  module Catalog
10
9
  module_function
11
10
 
@@ -24,14 +23,27 @@ module Textus
24
23
  .map(&:contract)
25
24
  end
26
25
 
27
- def tool_schemas
28
- specs.map do |s|
29
- { name: s.verb.to_s, description: s.summary, inputSchema: s.input_schema }
30
- end.freeze
26
+ # Builds MCP::Tool instances for the SDK, bound to mcp_server.dispatch.
27
+ def build_tools(mcp_server)
28
+ Textus::Action::VERBS
29
+ .select { |_, klass| mcp_surfaced?(klass) }
30
+ .map do |name, action|
31
+ schema = action.contract.input_schema
32
+ schema = schema.reject { |k, v| k == :required && Array(v).empty? }
33
+ ::MCP::Tool.define(
34
+ name: name.to_s,
35
+ description: action.contract.summary,
36
+ input_schema: schema,
37
+ ) do |server_context:, **args|
38
+ mcp_server.dispatch(name, args, server_context)
39
+ end
40
+ end
31
41
  end
32
42
 
33
43
  def names
34
- specs.map { |s| s.verb.to_s }
44
+ Textus::Action::VERBS
45
+ .select { |_, klass| mcp_surfaced?(klass) }
46
+ .keys.map(&:to_s)
35
47
  end
36
48
 
37
49
  # MCP-surfaced read verbs, by Dispatcher class namespace — the agent's