hecks 3.2.1 → 3.3.0

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 (111) hide show
  1. checksums.yaml +4 -4
  2. data/lib/hecks/bluebook/assembly/contracts.rb +2 -1
  3. data/lib/hecks/bluebook/dsl/bootstrap_table.rb +1 -0
  4. data/lib/hecks/bluebook/dsl/command_builder.rb +2 -39
  5. data/lib/hecks/bluebook/dsl/hecksagon_builder.rb +1 -1
  6. data/lib/hecks/bluebook/dsl/need_word.rb +50 -0
  7. data/lib/hecks/bluebook/dsl/query_builder.rb +6 -1
  8. data/lib/hecks/bluebook/query.rb +8 -5
  9. data/lib/hecks/cli/interview_draft.rb +86 -31
  10. data/lib/hecks/cli/interview_session.rb +77 -26
  11. data/lib/hecks/cli/interview_shape.rb +179 -0
  12. data/lib/hecks/doors/cli_runner.rb +14 -1
  13. data/lib/hecks/doors/launcher_options.rb +13 -3
  14. data/lib/hecks/doors/mcp_door_scope.rb +2 -1
  15. data/lib/hecks/doors.rb +1 -1
  16. data/lib/hecks/embryonaut_bluebook/manifest.rb +117 -0
  17. data/lib/hecks/embryonaut_bluebook/registry.rb +209 -0
  18. data/lib/hecks/embryonaut_bluebook/vendor.rb +1 -1
  19. data/lib/hecks/embryonaut_bluebook.rb +2 -0
  20. data/lib/hecks/fuzzing/qa_settings.rb +15 -34
  21. data/lib/hecks/gate/stages.yml +113 -8
  22. data/lib/hecks/hecks/adapters/codebase/regeneration.rb +10 -1
  23. data/lib/hecks/hecks/adapters/first_admin.rb +108 -0
  24. data/lib/hecks/hecks/adapters/git.rb +59 -0
  25. data/lib/hecks/hecks/adapters/in_process_access.rb +25 -0
  26. data/lib/hecks/hecks/adapters/in_process_boot.rb +2 -0
  27. data/lib/hecks/hecks/adapters/rust_toolchain.rb +18 -3
  28. data/lib/hecks/hecks/adapters/site_toolchain.rb +67 -0
  29. data/lib/hecks/hecks/codebase.behaviors +6 -0
  30. data/lib/hecks/hecks/codebase.bluebook +21 -0
  31. data/lib/hecks/hecks/custodian.behaviors +6 -0
  32. data/lib/hecks/hecks/custodian.bluebook +217 -0
  33. data/lib/hecks/hecks/hecks.hecksagon +24 -0
  34. data/lib/hecks/hecks/hecks.world +8 -3
  35. data/lib/hecks/hecks/site.world +5 -2
  36. data/lib/hecks/language/bluebook/query.bluebook +25 -0
  37. data/lib/hecks/language/bluebook/vocabulary.bluebook +213 -0
  38. data/lib/hecks/language/hecksagon/hecksagon.bluebook +1 -1
  39. data/lib/hecks/language/oidc.json +5 -0
  40. data/lib/hecks/projections/deploy/box/hosting.rb +170 -0
  41. data/lib/hecks/projections/deploy/box/hosting_settings.rb +123 -0
  42. data/lib/hecks/projections/deploy/box/settings.rb +17 -4
  43. data/lib/hecks/projections/deploy/box/templates/deploy-service.services-roll.part +33 -0
  44. data/lib/hecks/projections/deploy/box/templates/deploy-service.sh.tmpl +79 -0
  45. data/lib/hecks/projections/deploy/box/templates/deploy-service.taskdef-roll.part +77 -0
  46. data/lib/hecks/projections/deploy/box/templates/deploy-service.taskdef.part +12 -0
  47. data/lib/hecks/projections/deploy/box/templates/hosting.mk.tmpl +24 -0
  48. data/lib/hecks/projections/deploy/box/templates/smoke-after-deploy.sh.tmpl +271 -0
  49. data/lib/hecks/projections/deploy/box.rb +15 -2
  50. data/lib/hecks/projections/deploy/fargate.rb +3 -3
  51. data/lib/hecks/projections/deploy/lambda.rb +8 -8
  52. data/lib/hecks/projections/model/deviations.rb +1 -1
  53. data/lib/hecks/projections/site/live_edge.rb +162 -0
  54. data/lib/hecks/quality_control/adapters/git_pr.rb +0 -14
  55. data/lib/hecks/quality_control/cli/qa_discover_external_domains.rb +1 -1
  56. data/lib/hecks/quality_control/cli/qa_open_pr.rb +32 -16
  57. data/lib/hecks/quality_control/cli/qa_seed_angles.rb +2 -2
  58. data/lib/hecks/quality_control/cli/qa_seed_targets.rb +1 -2
  59. data/lib/hecks/quality_control/quality_control.bluebook +76 -124
  60. data/lib/hecks/runtime/interpreting.rb +3 -22
  61. data/lib/hecks/runtime/needs.rb +48 -0
  62. data/lib/hecks/runtime/query_interpreter.rb +3 -0
  63. data/lib/hecks/runtime/registry/verification.rb +3 -3
  64. data/lib/hecks/rust_build/host.rb +147 -0
  65. data/lib/hecks/rust_build/kernel_input.rb +40 -18
  66. data/lib/hecks/rust_build/project_rust/codegen_run.rb +0 -18
  67. data/lib/hecks/rust_build/project_rust.rb +3 -10
  68. data/lib/hecks/rust_build.rb +1 -0
  69. data/lib/hecks/site/bluebook/site.bluebook +53 -1
  70. data/lib/hecks/site/bluebook/site.ports.hecksagon +6 -0
  71. data/lib/hecks/sme/bluebook/sme.bluebook +128 -1
  72. data/lib/hecks/tools/gate.rb +1 -1
  73. data/lib/hecks/tools/rust_comment_style.rb +1 -3
  74. data/lib/hecks/tools/tools_doc.rb +204 -0
  75. data/lib/hecks/tools.rb +1 -0
  76. data/lib/hecks/version.rb +1 -1
  77. data/lib/hecks/vocabulary.rb +151 -0
  78. data/qa/settings.yml +1 -2
  79. data/rust/build/src/lineage_pass.rs +30 -15
  80. data/rust/build/src/main.rs +4 -2
  81. data/rust/build/src/pipeline.rs +8 -19
  82. data/rust/codegen/src/bridging.rs +7 -7
  83. data/rust/codegen/src/json.rs +214 -23
  84. data/rust/codegen/src/literal.rs +6 -3
  85. data/rust/codegen/src/main.rs +20 -9
  86. data/rust/codegen/src/naming.rs +4 -2
  87. data/rust/codegen/src/optional_pass.rs +226 -0
  88. data/rust/{build → codegen}/src/sidecars.rs +9 -5
  89. data/rust/host/HECKS_RELEASE +1 -1
  90. data/rust/host/src/api.rs +1 -1
  91. data/rust/host/src/dispatch.rs +5 -0
  92. data/rust/host/src/needs.rs +99 -2
  93. data/rust/host/src/resend.rs +4 -4
  94. data/rust/host/src/ui_schema.rs +1 -1
  95. data/rust/parser/src/emit.rs +12 -0
  96. data/rust/parser/src/ir.rs +2 -0
  97. data/rust/parser/src/keywords.rs +2 -0
  98. data/rust/parser/src/main.rs +1 -0
  99. data/rust/parser/src/parse/command.rs +2 -44
  100. data/rust/parser/src/parse/mod.rs +1 -0
  101. data/rust/parser/src/parse/needs.rs +60 -0
  102. data/rust/parser/src/parse/query.rs +3 -0
  103. data/rust/src/kernel/cli.rs +16 -6
  104. data/rust/src/kernel/needs.rs +104 -9
  105. metadata +22 -8
  106. data/lib/hecks/rust_build/append_optionals.rb +0 -79
  107. data/lib/hecks/rust_build/rust_literal.rb +0 -33
  108. data/lib/hecks/three_zero/forms.yml +0 -127
  109. data/lib/hecks/three_zero.rb +0 -12
  110. data/rust/build/src/json.rs +0 -421
  111. data/rust/build/src/optional_pass.rs +0 -150
@@ -0,0 +1,226 @@
1
+ //! Marks value-object and entity fields `optional` when an `append` mutation binds them to an
2
+ //! optional command argument, so the generated struct field is an `Option`.
3
+ //!
4
+ //! Resolves the appended element as `Hecks::RustBuild::AppendOptionals` does in Ruby: a local
5
+ //! entity wins over any value object of the same name, a local value object over a domain-wide one,
6
+ //! and an `append` into another aggregate's value object marks that value object.
7
+
8
+ use std::collections::HashMap;
9
+
10
+ use crate::json::Json;
11
+
12
+ /// Where an appended element lives: its aggregate's index, then its own index in that aggregate.
13
+ #[derive(Clone, Copy)]
14
+ enum Element {
15
+ ValueObject(usize, usize),
16
+ Entity(usize, usize),
17
+ }
18
+
19
+ struct Mark {
20
+ element: Element,
21
+ field: String,
22
+ }
23
+
24
+ pub fn run(ir: &mut Json) {
25
+ let marks = collect_marks(ir);
26
+ apply_marks(ir, &marks);
27
+ }
28
+
29
+ fn list<'a>(node: &'a Json, key: &str) -> &'a [Json] {
30
+ node.get(key).map(Json::each).unwrap_or(&[])
31
+ }
32
+
33
+ fn name_of(node: &Json) -> Option<&str> {
34
+ node.get("name").and_then(Json::as_str)
35
+ }
36
+
37
+ // Every value object in the domain by name; the last one declared wins, as a Ruby `to_h` does.
38
+ fn domain_wide_value_objects(aggregates: &[Json]) -> HashMap<&str, (usize, usize)> {
39
+ let mut by_name = HashMap::new();
40
+ for (a, aggregate) in aggregates.iter().enumerate() {
41
+ for (v, value_object) in list(aggregate, "value_objects").iter().enumerate() {
42
+ if let Some(name) = name_of(value_object) {
43
+ by_name.insert(name, (a, v));
44
+ }
45
+ }
46
+ }
47
+ by_name
48
+ }
49
+
50
+ fn find_element(aggregates: &[Json], a: usize, domain_wide: &HashMap<&str, (usize, usize)>, type_name: &str) -> Option<Element> {
51
+ let aggregate = &aggregates[a];
52
+ if let Some(e) = list(aggregate, "entities").iter().position(|entity| name_of(entity) == Some(type_name)) {
53
+ return Some(Element::Entity(a, e));
54
+ }
55
+ if let Some(v) = list(aggregate, "value_objects").iter().rposition(|value_object| name_of(value_object) == Some(type_name)) {
56
+ return Some(Element::ValueObject(a, v));
57
+ }
58
+ domain_wide.get(type_name).map(|&(owner, v)| Element::ValueObject(owner, v))
59
+ }
60
+
61
+ // Read first, write after: the commands are read while the elements they mark are mutated.
62
+ fn collect_marks(ir: &Json) -> Vec<Mark> {
63
+ let aggregates = list(ir, "aggregates");
64
+ let domain_wide = domain_wide_value_objects(aggregates);
65
+ let mut marks = Vec::new();
66
+
67
+ for (a, aggregate) in aggregates.iter().enumerate() {
68
+ for attribute in list(aggregate, "attributes") {
69
+ let (Some(attr_name), Some(type_name)) = (name_of(attribute), attribute.get("type").and_then(Json::as_str)) else { continue };
70
+ let Some(element) = find_element(aggregates, a, &domain_wide, type_name) else { continue };
71
+
72
+ for field in collect_fields_to_mark(aggregate, attr_name) {
73
+ marks.push(Mark { element, field });
74
+ }
75
+ }
76
+ }
77
+ marks
78
+ }
79
+
80
+ fn collect_fields_to_mark(aggregate: &Json, target_attr_name: &str) -> Vec<String> {
81
+ let mut out = Vec::new();
82
+
83
+ for command in list(aggregate, "commands") {
84
+ let command_attrs = list(command, "attributes");
85
+
86
+ for mutation in list(command, "mutations") {
87
+ let op = mutation.get("op").and_then(Json::as_str).unwrap_or("");
88
+ let target = mutation.get("target").and_then(Json::as_str).unwrap_or("");
89
+ if op != "append" || target != target_attr_name {
90
+ continue;
91
+ }
92
+
93
+ let Some(fields) = mutation.get("fields").and_then(Json::as_object) else { continue };
94
+ for (field_name, source) in fields {
95
+ // Only a Symbol (an argument name) renders with a leading `:` in `Literal.render`.
96
+ let Some(source_text) = source.as_str() else { continue };
97
+ let Some(arg_name) = source_text.strip_prefix(':') else { continue };
98
+
99
+ let source_is_optional = command_attrs
100
+ .iter()
101
+ .any(|a| name_of(a) == Some(arg_name) && a.get("optional").map(Json::as_bool).unwrap_or(false));
102
+ if source_is_optional {
103
+ out.push(field_name.clone());
104
+ }
105
+ }
106
+ }
107
+ }
108
+
109
+ out
110
+ }
111
+
112
+ fn apply_marks(ir: &mut Json, marks: &[Mark]) {
113
+ let Some(aggregates) = ir.get_mut("aggregates").and_then(Json::as_array_mut) else { return };
114
+
115
+ for mark in marks {
116
+ let (a, key, index) = match mark.element {
117
+ Element::ValueObject(a, v) => (a, "value_objects", v),
118
+ Element::Entity(a, e) => (a, "entities", e),
119
+ };
120
+ let element = aggregates.get_mut(a).and_then(|aggregate| aggregate.get_mut(key)).and_then(Json::as_array_mut).and_then(|elements| elements.get_mut(index));
121
+ let Some(attrs) = element.and_then(|element| element.get_mut("attributes")).and_then(Json::as_array_mut) else { continue };
122
+
123
+ if let Some(field_attr) = attrs.iter_mut().find(|a| name_of(a) == Some(mark.field.as_str())) {
124
+ field_attr.set_bool("optional", true);
125
+ }
126
+ }
127
+ }
128
+
129
+ #[cfg(test)]
130
+ mod tests {
131
+ use super::*;
132
+
133
+ fn aggregate_with(entities: &str, value_objects: &str, attribute_type: &str) -> String {
134
+ format!(
135
+ r#"{{
136
+ "attributes": [
137
+ {{"name": "ledger", "type": "{attribute_type}", "list": true, "default": null, "optional": false, "pattern": null, "admits": null}}
138
+ ],
139
+ "value_objects": [{value_objects}],
140
+ "entities": [{entities}],
141
+ "commands": [
142
+ {{
143
+ "name": "Credit",
144
+ "attributes": [
145
+ {{"name": "amount", "type": "PositiveMoney", "list": false, "default": null, "optional": true, "pattern": null, "admits": null}}
146
+ ],
147
+ "mutations": [
148
+ {{"target": "ledger", "op": "append", "fields": {{"amount": ":amount", "direction": "{{value: \"credit\"}}"}}}}
149
+ ]
150
+ }}
151
+ ]
152
+ }}"#
153
+ )
154
+ }
155
+
156
+ fn element(amount_optional: bool) -> String {
157
+ format!(
158
+ r#"{{"name": "LedgerEntry", "attributes": [
159
+ {{"name": "amount", "type": "Money", "list": false, "default": null, "optional": {amount_optional}, "pattern": null, "admits": null}},
160
+ {{"name": "direction", "type": "Direction", "list": false, "default": null, "optional": false, "pattern": null, "admits": null}}
161
+ ]}}"#
162
+ )
163
+ }
164
+
165
+ fn domain(aggregates: &[String]) -> Json {
166
+ Json::parse(&format!(r#"{{"aggregates": [{}]}}"#, aggregates.join(","))).expect("fixture parses")
167
+ }
168
+
169
+ fn amount_optional(ir: &Json, aggregate: usize, key: &str) -> bool {
170
+ let element = &list(&list(ir, "aggregates")[aggregate], key)[0];
171
+ let amount = list(element, "attributes").iter().find(|a| name_of(a) == Some("amount")).unwrap();
172
+ amount.get("optional").unwrap().as_bool()
173
+ }
174
+
175
+ // The input and expectation `spec/rust_build_generation_helpers_spec.rb` holds the Ruby pass to,
176
+ // recorded from it. Read at test time, not compiled in: an installed gem has no `spec/`.
177
+ #[test]
178
+ fn marks_what_the_ruby_pass_marks_on_the_shared_fixture() {
179
+ let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../spec/fixtures/append_optionals");
180
+ let read = |name: &str| Json::parse(&std::fs::read_to_string(dir.join(name)).expect("reads the fixture")).expect("parses");
181
+
182
+ let mut ir = read("input.json");
183
+ run(&mut ir);
184
+
185
+ assert_eq!(ir, read("expected.json"));
186
+ }
187
+
188
+ // Banking's `Account.Credit` shape: entity list `ledger`, one `append` binding `amount` from
189
+ // an optional argument and `direction` from a literal Hash.
190
+ #[test]
191
+ fn marks_the_argument_sourced_field_optional() {
192
+ let mut ir = domain(&[aggregate_with(&element(false), "", "LedgerEntry")]);
193
+ run(&mut ir);
194
+
195
+ assert!(amount_optional(&ir, 0, "entities"));
196
+ }
197
+
198
+ #[test]
199
+ fn marks_a_value_object_another_aggregate_declares() {
200
+ let owner = r#"{"attributes": [], "value_objects": [LEDGER], "entities": [], "commands": []}"#.replace("LEDGER", &element(false));
201
+ let appender = aggregate_with("", "", "LedgerEntry");
202
+ let mut ir = domain(&[appender, owner]);
203
+ run(&mut ir);
204
+
205
+ assert!(amount_optional(&ir, 1, "value_objects"), "the value object lives in the second aggregate");
206
+ }
207
+
208
+ #[test]
209
+ fn prefers_a_local_entity_over_a_value_object_of_the_same_name() {
210
+ let local = aggregate_with(&element(false), "", "LedgerEntry");
211
+ let owner = r#"{"attributes": [], "value_objects": [LEDGER], "entities": [], "commands": []}"#.replace("LEDGER", &element(false));
212
+ let mut ir = domain(&[local, owner]);
213
+ run(&mut ir);
214
+
215
+ assert!(amount_optional(&ir, 0, "entities"), "the local entity is the one marked");
216
+ assert!(!amount_optional(&ir, 1, "value_objects"), "the domain-wide value object is left alone");
217
+ }
218
+
219
+ #[test]
220
+ fn leaves_a_field_alone_when_its_argument_is_required() {
221
+ let mut ir = domain(&[aggregate_with(&element(false), "", "LedgerEntry").replace("\"optional\": true", "\"optional\": false")]);
222
+ run(&mut ir);
223
+
224
+ assert!(!amount_optional(&ir, 0, "entities"));
225
+ }
226
+ }
@@ -1,4 +1,6 @@
1
- //! Writes each chapter's `ir.json` and `metadata.rs` sidecars.
1
+ //! Writes each chapter's `ir.json` and `metadata.rs` sidecars, from the IR as generated (marked).
2
+
3
+ use crate::json::{self, Json};
2
4
 
3
5
  /// Renders `text` as a Rust string literal. Not Ruby's `String#inspect`, whose `\#{` and bare
4
6
  /// `\uXXXX` escapes are not valid Rust.
@@ -22,22 +24,24 @@ pub fn rust_string_literal(text: &str) -> String {
22
24
  out
23
25
  }
24
26
 
25
- pub fn write(mod_dir: &std::path::Path, ir_text: &str, source_label: &str) -> Result<(std::path::PathBuf, std::path::PathBuf), String> {
27
+ /// `ir.json` is what `rust/host` reads at runtime, and `metadata.rs` embeds the same text.
28
+ pub fn write(mod_dir: &std::path::Path, ir: &Json, source_label: &str) -> Result<(std::path::PathBuf, std::path::PathBuf), String> {
26
29
  std::fs::create_dir_all(mod_dir).map_err(|e| format!("creating {}: {e}", mod_dir.display()))?;
27
30
 
31
+ let ir_text = json::write(ir);
28
32
  let ir_json_path = mod_dir.join("ir.json");
29
- std::fs::write(&ir_json_path, ir_text).map_err(|e| format!("writing {}: {e}", ir_json_path.display()))?;
33
+ std::fs::write(&ir_json_path, &ir_text).map_err(|e| format!("writing {}: {e}", ir_json_path.display()))?;
30
34
 
31
35
  let metadata_path = mod_dir.join("metadata.rs");
32
36
  let mut contents = String::new();
33
- // Attribution text matches both Ruby pipelines so generated trees diff clean.
37
+ // The header every generated `metadata.rs` carries; `regenerate_corpus --check` diffs it.
34
38
  contents.push_str("// GENERATED by hecks project_rust — ");
35
39
  contents.push_str(source_label);
36
40
  contents.push_str("'s own canonical IR,\n");
37
41
  contents.push_str("// embedded for runtime self-description. Not read by any dispatch\n");
38
42
  contents.push_str("// function in this module — introspection only.\n");
39
43
  contents.push_str("pub const IR_JSON: &str = ");
40
- contents.push_str(&rust_string_literal(ir_text));
44
+ contents.push_str(&rust_string_literal(&ir_text));
41
45
  contents.push_str(";\n");
42
46
  std::fs::write(&metadata_path, contents).map_err(|e| format!("writing {}: {e}", metadata_path.display()))?;
43
47
 
@@ -1 +1 @@
1
- 3.2.1
1
+ 3.3.0
data/rust/host/src/api.rs CHANGED
@@ -823,7 +823,7 @@ mod tests {
823
823
  }
824
824
 
825
825
  // app.rb: `get "/api/me" { json(session[:member] || {}) }`, where
826
- // session[:member] is embryonaut_access_control.rb's own
826
+ // session[:member] is the access-control module's own
827
827
  // `{ "email" =>, "name" =>, "identity_id" =>, "role" => }`.
828
828
  #[test]
829
829
  fn me_is_the_ruby_engines_own_member_hash() {
@@ -611,6 +611,11 @@ pub async fn query(
611
611
  question: &str,
612
612
  args: serde_json::Value,
613
613
  ) -> anyhow::Result<serde_json::Value> {
614
+ // A fact the query `needs` is answered before the kernel checks its arguments (ADR 0081).
615
+ let mut args = args;
616
+ if let Some(domain_ir) = crate::ir::ir() {
617
+ crate::needs::fill_query_needs(domain_ir, question, &mut args, &crate::needs::ProcessClock);
618
+ }
614
619
  let state = read(client, wasm_path).await?;
615
620
  let seed = state.get("instances").cloned().unwrap_or_else(|| serde_json::json!({}));
616
621
  let input = serde_json::json!({ "seed": seed, "steps": [{ "query": question, "args": args }] }).to_string();
@@ -186,9 +186,11 @@ fn facts_mut(args: &mut Value) -> Option<&mut serde_json::Map<String, Value>> {
186
186
 
187
187
  fn answer(fact: &str, attribute_type: Option<&str>, clock: &dyn Clock) -> Option<Value> {
188
188
  match fact {
189
- "now" => {
189
+ // `now` is epoch seconds; `today` the day those fall in, whole days since the epoch (UTC).
190
+ "now" | "today" => {
190
191
  let secs = clock.now_secs();
191
- Some(if attribute_type == Some("Integer") { json!(secs) } else { json!({ "value": secs }) })
192
+ let answer = if fact == "today" { secs.div_euclid(86_400) } else { secs };
193
+ Some(if attribute_type == Some("Integer") { json!(answer) } else { json!({ "value": answer }) })
192
194
  }
193
195
  _ => None,
194
196
  }
@@ -212,6 +214,49 @@ pub fn fill_needs(domain_ir: &Value, verb: &str, args: &mut Value, clock: &dyn C
212
214
  }
213
215
  }
214
216
 
217
+ /// The facts the query `question` (`Domain::Aggregate.Query`) needs, each with the type of the
218
+ /// argument of the same name. An entity's query is not looked up here.
219
+ fn declared_query_needs<'a>(domain_ir: &'a Value, question: &str) -> Vec<(&'a str, Option<&'a str>)> {
220
+ let Some((qualified_aggregate, query_name)) = question.rsplit_once('.') else { return Vec::new() };
221
+ let aggregate = qualified_aggregate.rsplit("::").next().unwrap_or(qualified_aggregate);
222
+ let Some(query) = list(domain_ir, "aggregates")
223
+ .iter()
224
+ .find(|a| named(a, aggregate))
225
+ .and_then(|a| list(a, "queries").iter().find(|q| named(q, query_name)))
226
+ else {
227
+ return Vec::new();
228
+ };
229
+ let attributes = list(query, "attributes");
230
+ list(query, "needs")
231
+ .iter()
232
+ .filter_map(|n| n.get("fact").and_then(Value::as_str))
233
+ .map(|fact| {
234
+ let attribute_type =
235
+ attributes.iter().find(|a| named(a, fact)).and_then(|a| a.get("type")).and_then(Value::as_str);
236
+ (fact, attribute_type)
237
+ })
238
+ .collect()
239
+ }
240
+
241
+ /// Fills each fact the query `question` needs that `args` leaves out, before the kernel checks the
242
+ /// arguments. A key the caller supplied (even a null) is kept; a query that needs nothing, or whose
243
+ /// arguments are not an object, is untouched.
244
+ pub fn fill_query_needs(domain_ir: &Value, question: &str, args: &mut Value, clock: &dyn Clock) {
245
+ let needs = declared_query_needs(domain_ir, question);
246
+ if needs.is_empty() {
247
+ return;
248
+ }
249
+ let Some(facts) = args.as_object_mut() else { return };
250
+ for (fact, attribute_type) in needs {
251
+ if facts.contains_key(fact) {
252
+ continue;
253
+ }
254
+ if let Some(value) = answer(fact, attribute_type, clock) {
255
+ facts.insert(fact.to_string(), value);
256
+ }
257
+ }
258
+ }
259
+
215
260
  /// Gives each argument `verb` declares a default for, and `args` leaves out, that default, after
216
261
  /// `fill_needs` and before any gate reads the arguments. A key the caller supplied (even a null)
217
262
  /// is kept, as is a fact `fill_needs` already answered.
@@ -408,6 +453,58 @@ mod tests {
408
453
  assert_eq!(args, json!({"number": 1}));
409
454
  }
410
455
 
456
+ // An aggregate with a query that needs `now` and one that needs `today`.
457
+ fn query_ir() -> Value {
458
+ json!({"name": "Lease", "aggregates": [{"name": "Slot", "commands": [], "queries": [
459
+ {"name": "Expired", "attributes": [{"name": "now", "type": "LeaseInstant"}],
460
+ "needs": [{"fact": "now"}]},
461
+ {"name": "IssuedToday", "attributes": [{"name": "today", "type": "Integer"}],
462
+ "needs": [{"fact": "today"}]},
463
+ {"name": "Plain", "attributes": [{"name": "now", "type": "LeaseInstant"}]}
464
+ ]}]})
465
+ }
466
+
467
+ #[test]
468
+ fn a_needed_query_fact_the_caller_left_out_is_filled_from_the_clock() {
469
+ let mut args = json!({});
470
+ fill_query_needs(&query_ir(), "Lease::Slot.Expired", &mut args, &FixedClock(1_700_000_000));
471
+ assert_eq!(args["now"], json!({"value": 1_700_000_000}));
472
+ }
473
+
474
+ #[test]
475
+ fn a_query_value_the_caller_supplied_is_kept_even_when_null() {
476
+ let mut args = json!({"now": null});
477
+ fill_query_needs(&query_ir(), "Lease::Slot.Expired", &mut args, &FixedClock(5));
478
+ assert!(args["now"].is_null());
479
+ let mut named = json!({"now": {"value": 9}});
480
+ fill_query_needs(&query_ir(), "Lease::Slot.Expired", &mut named, &FixedClock(5));
481
+ assert_eq!(named["now"], json!({"value": 9}));
482
+ }
483
+
484
+ #[test]
485
+ fn a_query_that_needs_nothing_or_names_nothing_is_untouched() {
486
+ let mut args = json!({});
487
+ fill_query_needs(&query_ir(), "Lease::Slot.Plain", &mut args, &FixedClock(5));
488
+ fill_query_needs(&query_ir(), "Lease::Slot.Missing", &mut args, &FixedClock(5));
489
+ fill_query_needs(&query_ir(), "Lease::Shelf.Expired", &mut args, &FixedClock(5));
490
+ assert_eq!(args, json!({}));
491
+ }
492
+
493
+ #[test]
494
+ fn today_is_whole_days_since_the_epoch_shaped_for_its_argument() {
495
+ let mut args = json!({});
496
+ fill_query_needs(&query_ir(), "Lease::Slot.IssuedToday", &mut args, &FixedClock((19_000 * 86_400) + 86_399));
497
+ assert_eq!(args["today"], json!(19_000));
498
+
499
+ let mut command = json!({"with": {}});
500
+ let ir = json!({"name": "D", "aggregates": [{"name": "A", "commands": [
501
+ {"name": "Open", "attributes": [{"name": "day", "type": "Day"}], "needs": [{"fact": "day"}]},
502
+ {"name": "Take", "attributes": [{"name": "today", "type": "Day"}], "needs": [{"fact": "today"}]}
503
+ ]}]});
504
+ fill_needs(&ir, "D::A.Take", &mut command, &FixedClock(19_001 * 86_400));
505
+ assert_eq!(command["with"]["today"], json!({"value": 19_001}));
506
+ }
507
+
411
508
  #[test]
412
509
  fn the_kernel_table_lists_entity_commands_under_their_full_path() {
413
510
  assert_eq!(
@@ -256,8 +256,8 @@ mod tests {
256
256
 
257
257
  #[test]
258
258
  fn a_reply_to_address_rides_in_the_payload_and_is_absent_without_one() {
259
- let with = payload("f", Some("lifeadelics@gmail.com"), &email("a@b.com", "x"));
260
- assert_eq!(with["reply_to"], "lifeadelics@gmail.com");
259
+ let with = payload("f", Some("replies@example.com"), &email("a@b.com", "x"));
260
+ assert_eq!(with["reply_to"], "replies@example.com");
261
261
  assert!(payload("f", None, &email("a@b.com", "x")).get("reply_to").is_none());
262
262
  }
263
263
 
@@ -273,11 +273,11 @@ mod tests {
273
273
  #[tokio::test]
274
274
  async fn a_live_send_carries_the_reply_to_address_to_resend() {
275
275
  let fake = FakeResend::start(vec![("200 OK", "", r#"{"id":"em_9"}"#)]);
276
- let mailer = Mailer::live("re_x", "News <n@mail.example.com>", &fake.base).replying_to("lifeadelics@gmail.com");
276
+ let mailer = Mailer::live("re_x", "News <n@mail.example.com>", &fake.base).replying_to("replies@example.com");
277
277
 
278
278
  mailer.deliver(&email("a@b.com", "x")).await;
279
279
 
280
- assert!(fake.requests()[0].contains(r#""reply_to":"lifeadelics@gmail.com""#), "{}", fake.requests()[0]);
280
+ assert!(fake.requests()[0].contains(r#""reply_to":"replies@example.com""#), "{}", fake.requests()[0]);
281
281
  }
282
282
 
283
283
  #[test]
@@ -860,7 +860,7 @@ fn humanize(key: &str) -> String {
860
860
  mod tests {
861
861
  use super::*;
862
862
 
863
- // Embryonaut-shaped, because that's the domain the Ruby engine
863
+ // Shaped like a real member-gated app, the kind the Ruby engine
864
864
  // actually serves. Each test below pins one rule of ui_schema.rb.
865
865
 
866
866
  fn domain() -> Value {
@@ -463,6 +463,18 @@ fn query_json(q: &ir::Query) -> JsonValue {
463
463
  if let Some(returns) = &q.returns {
464
464
  pairs.push(("returns".to_string(), JsonValue::str(returns.clone())));
465
465
  }
466
+ // `needs` follows `returns`, only when declared, so a query that needs nothing keeps its shape.
467
+ if !q.needs.is_empty() {
468
+ pairs.push((
469
+ "needs".to_string(),
470
+ JsonValue::Array(
471
+ q.needs
472
+ .iter()
473
+ .map(|fact| JsonValue::Object(vec![("fact".to_string(), JsonValue::str(fact.clone()))]))
474
+ .collect(),
475
+ ),
476
+ ));
477
+ }
466
478
  JsonValue::Object(pairs)
467
479
  }
468
480
 
@@ -133,6 +133,8 @@ pub struct Query {
133
133
  pub options: QueryOptions,
134
134
  /// `returns Name` or `returns list_of(Name)`, spelled as `Query#returns` holds it.
135
135
  pub returns: Option<String>,
136
+ /// Outside facts the runtime supplies before the filter reads the arguments (`needs :now`).
137
+ pub needs: Vec<String>,
136
138
  }
137
139
 
138
140
  /// `AuthorizationSpec#to_h`: both fields are bare `.to_s`, never Literal-rendered.
@@ -161,6 +161,7 @@ pub static KEYWORDS: &[KeywordRow] = &[
161
161
  KeywordRow { word: "authorize", context: "Query", body: "none", inner: "", opens: "", fills: "options", status: "admitted", was: "", resolves_via: "", disambiguator: "" },
162
162
  KeywordRow { word: "inspect_query", context: "Query", body: "none", inner: "", opens: "", fills: "options", status: "admitted", was: "", resolves_via: "", disambiguator: "" },
163
163
  KeywordRow { word: "returns", context: "Query", body: "none", inner: "", opens: "", fills: "returns", status: "admitted", was: "", resolves_via: "", disambiguator: "" },
164
+ KeywordRow { word: "needs", context: "Query", body: "none", inner: "", opens: "", fills: "needs", status: "admitted", was: "", resolves_via: "", disambiguator: "" },
164
165
  KeywordRow { word: "attribute", context: "ValueObject", body: "none", inner: "", opens: "", fills: "attributes", status: "admitted", was: "", resolves_via: "", disambiguator: "" },
165
166
  KeywordRow { word: "one_of", context: "ValueObject", body: "rows", inner: "OneOf", opens: "", fills: "rows", status: "admitted", was: "", resolves_via: "", disambiguator: "" },
166
167
  KeywordRow { word: "invariant", context: "ValueObject", body: "source", inner: "", opens: "", fills: "invariants", status: "admitted", was: "", resolves_via: "sibling_scan", disambiguator: "" },
@@ -437,6 +438,7 @@ pub static ARGUMENTS: &[ArgumentRow] = &[
437
438
  ArgumentRow { keyword: "authorize", context: "Query", at: "", named: "tenant", kind: "symbol", required: "false", fills: "tenant", selects: "", pair_key_fills: "", pair_value_fills: "", pairs_shape: "", status: "admitted", variadic: "", minimum: "" },
438
439
  ArgumentRow { keyword: "inspect_query", context: "Query", at: "1", named: "", kind: "symbol", required: "false", fills: "mode", selects: "", pair_key_fills: "", pair_value_fills: "", pairs_shape: "", status: "admitted", variadic: "", minimum: "" },
439
440
  ArgumentRow { keyword: "returns", context: "Query", at: "1", named: "", kind: "constant", required: "true", fills: "type", selects: "", pair_key_fills: "", pair_value_fills: "", pairs_shape: "", status: "admitted", variadic: "", minimum: "" },
441
+ ArgumentRow { keyword: "needs", context: "Query", at: "1", named: "", kind: "symbol", required: "true", fills: "fact", selects: "", pair_key_fills: "", pair_value_fills: "", pairs_shape: "", status: "admitted", variadic: "", minimum: "" },
440
442
  ArgumentRow { keyword: "attribute", context: "ValueObject", at: "1", named: "", kind: "symbol", required: "true", fills: "name", selects: "", pair_key_fills: "", pair_value_fills: "", pairs_shape: "", status: "admitted", variadic: "", minimum: "" },
441
443
  ArgumentRow { keyword: "attribute", context: "ValueObject", at: "2", named: "", kind: "constant", required: "true", fills: "type", selects: "", pair_key_fills: "", pair_value_fills: "", pairs_shape: "", status: "admitted", variadic: "", minimum: "" },
442
444
  ArgumentRow { keyword: "attribute", context: "ValueObject", at: "", named: "default", kind: "literal", required: "false", fills: "default", selects: "", pair_key_fills: "", pair_value_fills: "", pairs_shape: "", status: "admitted", variadic: "", minimum: "" },
@@ -205,6 +205,7 @@ const COVERED_PAIRS: &[(&str, &str)] = &[
205
205
  ("limit", "Query"),
206
206
  ("authorize", "Query"),
207
207
  ("returns", "Query"),
208
+ ("needs", "Query"),
208
209
  ("on", "Policy"),
209
210
  ("trigger", "Policy"),
210
211
  ("across", "Policy"),
@@ -164,7 +164,7 @@ pub fn parse_body(
164
164
  owner_entities,
165
165
  );
166
166
  refuse_duplicate_targets(file, *pos, &command)?;
167
- refuse_undeclared_needs(file, *pos, &command)?;
167
+ super::needs::refuse_undeclared(file, *pos, &command.name, &command.needs, &command.attributes)?;
168
168
  return Ok((command, pending));
169
169
  };
170
170
  let line = gated.line.number;
@@ -206,27 +206,7 @@ pub fn parse_body(
206
206
  canonical: canonical::apply(&raw),
207
207
  });
208
208
  }
209
- "needs" => {
210
- let fact = super::positional_symbol(file, line, "needs", &gated.args, 1)?;
211
- if !NEEDABLE_FACTS.contains(&fact.as_str()) {
212
- return Err(Diagnostic::new(
213
- file,
214
- line,
215
- format!(
216
- "{} needs :{fact}, which the runtime cannot supply — it supplies :now",
217
- command.name
218
- ),
219
- ));
220
- }
221
- if command.needs.contains(&fact) {
222
- return Err(Diagnostic::new(
223
- file,
224
- line,
225
- format!("{} declares needs :{fact} twice", command.name),
226
- ));
227
- }
228
- command.needs.push(fact);
229
- }
209
+ "needs" => super::needs::declare(file, line, &command.name, &gated.args, &mut command.needs)?,
230
210
  "provenance" => {
231
211
  let raw = super::named_raw(&gated.args, "from")
232
212
  .ok_or_else(|| Diagnostic::new(file, line, "'provenance' requires a from:"))?;
@@ -319,28 +299,6 @@ fn state_ref(raw: &str) -> Option<String> {
319
299
  Some(inner.to_string())
320
300
  }
321
301
 
322
- /// The outside facts a command may declare it needs; mirrors `CommandBuilder::NEEDABLE_FACTS`.
323
- const NEEDABLE_FACTS: &[&str] = &["now"];
324
-
325
- /// A need names the attribute the runtime fills, so the command must declare it.
326
- fn refuse_undeclared_needs(file: &str, line: usize, command: &ir::Command) -> ParseResult<()> {
327
- match command
328
- .needs
329
- .iter()
330
- .find(|fact| !command.attributes.iter().any(|a| &a.name == *fact))
331
- {
332
- Some(fact) => Err(Diagnostic::new(
333
- file,
334
- line,
335
- format!(
336
- "{} needs :{fact} but declares no attribute :{fact} for the runtime to fill — add `attribute :{fact}, <type>`",
337
- command.name
338
- ),
339
- )),
340
- None => Ok(()),
341
- }
342
- }
343
-
344
302
  /// Refuses a field written twice: a command's effects are one update set (C4.2).
345
303
  /// `delegates_to`/`corrects` name no field and are not counted.
346
304
  fn refuse_duplicate_targets(file: &str, line: usize, command: &ir::Command) -> ParseResult<()> {
@@ -9,6 +9,7 @@ pub mod entity;
9
9
  pub mod file;
10
10
  pub mod hecksagon;
11
11
  pub mod lifecycle;
12
+ pub mod needs;
12
13
  pub mod policy;
13
14
  pub mod process_manager;
14
15
  pub mod query;
@@ -0,0 +1,60 @@
1
+ //! The `needs` word, shared by the two declarations that may use it: a command and a query
2
+ //! (ADR 0081). Mirrors `Hecks::Bluebook::DSL::NeedWord`.
3
+
4
+ use crate::diag::{Diagnostic, ParseResult};
5
+ use crate::ir;
6
+ use crate::parse::ArgumentGateResult;
7
+
8
+ /// The outside facts a declaration may need, each the name of the attribute the runtime fills;
9
+ /// mirrors `NeedWord::NEEDABLE_FACTS`. `now` is the clock port's reading in epoch seconds and
10
+ /// `today` the day it falls in, whole days since the epoch in UTC.
11
+ const NEEDABLE_FACTS: &[&str] = &["now", "today"];
12
+
13
+ /// Reads one `needs :fact` line into `needs`.
14
+ ///
15
+ /// Refuses a fact the runtime cannot supply and a fact declared twice, as the Ruby builder does.
16
+ pub fn declare(
17
+ file: &str,
18
+ line: usize,
19
+ owner: &str,
20
+ args: &ArgumentGateResult,
21
+ needs: &mut Vec<String>,
22
+ ) -> ParseResult<()> {
23
+ let fact = super::positional_symbol(file, line, "needs", args, 1)?;
24
+ if !NEEDABLE_FACTS.contains(&fact.as_str()) {
25
+ let supplied: Vec<String> = NEEDABLE_FACTS.iter().map(|known| format!(":{known}")).collect();
26
+ return Err(Diagnostic::new(
27
+ file,
28
+ line,
29
+ format!(
30
+ "{owner} needs :{fact}, which the runtime cannot supply — it supplies {}",
31
+ supplied.join(", ")
32
+ ),
33
+ ));
34
+ }
35
+ if needs.contains(&fact) {
36
+ return Err(Diagnostic::new(file, line, format!("{owner} declares needs :{fact} twice")));
37
+ }
38
+ needs.push(fact);
39
+ Ok(())
40
+ }
41
+
42
+ /// A need names the attribute the runtime fills, so the declaration must have one.
43
+ pub fn refuse_undeclared(
44
+ file: &str,
45
+ line: usize,
46
+ owner: &str,
47
+ needs: &[String],
48
+ attributes: &[ir::Attribute],
49
+ ) -> ParseResult<()> {
50
+ match needs.iter().find(|fact| !attributes.iter().any(|a| &a.name == *fact)) {
51
+ Some(fact) => Err(Diagnostic::new(
52
+ file,
53
+ line,
54
+ format!(
55
+ "{owner} needs :{fact} but declares no attribute :{fact} for the runtime to fill — add `attribute :{fact}, <type>`"
56
+ ),
57
+ )),
58
+ None => Ok(()),
59
+ }
60
+ }