@cratis/pi 7.137.1 → 7.138.1

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 (24) hide show
  1. package/package/corpus/harnesses/copilot/instructions/glossary.instructions.md +4 -0
  2. package/package/corpus/hooks/README.md +14 -4
  3. package/package/corpus/hooks/scripts/cratis-guard-shell-writes.sh +24 -6
  4. package/package/corpus/hooks/scripts/cratis-guard-writes.sh +48 -14
  5. package/package/corpus/product-sync.json +1 -0
  6. package/package/corpus/rules/glossary.md +4 -0
  7. package/package/corpus/skills/cratis-arc-neo4j/LICENSE +2 -0
  8. package/package/corpus/skills/cratis-arc-neo4j/SKILL.md +166 -0
  9. package/package/corpus/skills/cratis-arc-neo4j/references/connection-resolution-and-single-mode.md +51 -0
  10. package/package/corpus/skills/cratis-chronicle-client-elixir/SKILL.md +12 -1
  11. package/package/corpus/skills/cratis-chronicle-client-elixir/references/graphs.md +123 -0
  12. package/package/corpus/skills/cratis-chronicle-projection/SKILL.md +18 -1
  13. package/package/corpus/skills/cratis-chronicle-projection/references/graph-projections.md +159 -0
  14. package/package/corpus/skills/cratis-screenplay-projections/SKILL.md +15 -2
  15. package/package/corpus/skills/cratis-screenplay-projections/references/graphs.md +150 -0
  16. package/package/corpus/skills/cratis-screenplay-specifications/SKILL.md +25 -23
  17. package/package/corpus/skills/cratis-screenplay-specifications/references/graph-steps.md +90 -0
  18. package/package/corpus/skills/cratis-screenplay-specifications/references/vocabulary.md +6 -0
  19. package/package/corpus/skills/cratis-screenplay-toolchain/references/screenplay-contract.json +7212 -1834
  20. package/package/corpus/skills/cratis-screenplay-toolchain/references/screenplay-contract.version +1 -1
  21. package/package/corpus/skills/cratis-stage-rendering-and-sandbox/SKILL.md +2 -0
  22. package/package/corpus/skills/cratis-stage-rendering-and-sandbox/references/graphs.md +52 -0
  23. package/package/profile-catalog.json +1 -0
  24. package/package.json +1 -1
@@ -41,6 +41,10 @@ One precise line per load-bearing term, so the same word means the same thing ev
41
41
  - **Observer** — Chronicle's umbrella for anything consuming an event sequence (projection, reducer, reactor); carries subscription / replay / **quarantine** state. Projection replay and catch-up each walk the sequence in one globally ordered job step; a new catch-up failure stops that step. Full replay is inactive and completion does not resume a quarantined observer (Chronicle v19.50.1, `Documentation/concepts/observers.mdx`, `Observation/Jobs/{CatchUpObserver,ReplayObserver}.cs` under `Source/Kernel/Core/`).
42
42
  - **Sink** — where a read model is persisted (MongoDB, EF Core).
43
43
  - **AutoMap** — Chronicle's on-by-default mapping of matching event→read-model property names; **never call `.AutoMap()`**.
44
+ - **Graph** — a named property graph that events build through a graph projection: nodes, edges and their properties. Derived state like a read model; nothing writes to it directly.
45
+ - **Node** — a graph element with a label, one unique key and primitive properties. The label is the type name.
46
+ - **Edge** — a directed, typed graph relationship from a source node to a target node, identified by type, source key and target key (plus an identifying property when several edges of one type may join the same pair).
47
+ - **Graph sink** — where a graph is persisted (Neo4j, or the in-memory graph); it applies the five idempotent graph operations, separate from the `ISink` of document read models.
44
48
  - **Query** — a `static` method on a `[ReadModel]`; returns derived state, **snapshot** (one-shot) or **observable** (live).
45
49
 
46
50
  ## Write side
@@ -189,7 +189,8 @@ Dependency manifests, including `package.json`, retain their origin/opt-in allow
189
189
  **every simple command must be on this read-only allowlist**:
190
190
 
191
191
  Only the following **exact options** are exempt, because they select/present reads rather
192
- than create files or invoke helpers. Any other option denies, including long-option
192
+ than create files or name helpers. Repository configuration can still run helpers for
193
+ allowed Git verbs. Any other option denies, including long-option
193
194
  abbreviations and unlisted `--option=value` forms. `--` ends option checking; remaining
194
195
  arguments are operands. A lone `-` is a stdin operand. Value-free short flags may combine
195
196
  (e.g. `grep -ni`); value-taking forms must use the explicitly listed spelling.
@@ -200,24 +201,33 @@ arguments are operands. A lone `-` is a stdin operand. Value-free short flags ma
200
201
  | `head`, `tail` | `-n N`, `-nN`, `-c N`, `-N` (numeric counts); no `-f` |
201
202
  | `wc` | `-l -w -c -m` |
202
203
  | `ls` | `-l -a -A -1 -h -d -R -t -r -F` |
204
+ | `rg` | `-n` only; no long options |
203
205
  | `grep`, `egrep`, `fgrep` | `-n -i -r -R -l -L -c -v -w -x -F -E -H -h -o -q -s`; `-e PATTERN`, `-A N`, `-B N`, `-C N`; no long options |
204
206
  | `echo` | `-n -e -E` |
205
207
  | `printf`, `test`, `[`, `true`, `false`, `pwd` | None (in particular, no `printf -v`) |
206
208
  | `git status` | `-s -b --short --porcelain` |
207
- | `git diff` | `--stat --name-only --name-status --cached --staged --check -p -U<N> --no-color` |
209
+ | `git diff` | `--stat --numstat --name-only --name-status --cached --staged --check -p -U<N> --no-color` |
208
210
  | `git log` | `--oneline --stat --name-only -n N -nN -<N> -p --no-color --format=<fmt> --pretty=<fmt> --follow` |
209
211
  | `git show` | `--stat --name-only -p --no-color --format=<fmt>` |
210
212
  | `git add` | `-A -u -p` |
211
213
  | `git commit` | `-m MSG`, `-mMSG`, `-a`, `-q`; `-F FILE` only for a literal non-protected file; no `--no-verify` |
212
214
  | `git blame`, `ls-files`, `rev-parse`, `check-ignore`, `grep` | None |
213
215
 
214
- No global git options are exempt (`-C`, `-c`, `--no-pager` etc. deny before the subcommand).
216
+ The only global Git option exemption is a single separate `-C <dir>` with a literal,
217
+ non-empty directory word not starting with `-`, followed by exactly one of these tails:
218
+ `status --short`, `rev-parse HEAD`, `branch --show-current`, or `tag --list <pattern>`.
219
+ The tag tail takes exactly one pattern not starting with `-` (for example, `'*7.321*'`).
220
+ No extra words are accepted. Attached `-Cdir`/`-C=dir`, repeated `-C`, other verbs and
221
+ all other global options (`-c`, `--git-dir`, `--work-tree`, `--no-pager`, `--exec-path`, etc.)
222
+ remain denied. `-C` gives **no protection** from a hostile repository's configuration:
223
+ fsmonitor, hooks, pager and diff/textconv helpers can still run. This is a syntax filter,
224
+ not a repository sandbox.
215
225
  Git format values containing `%(` are not accepted. Index/commit operations are deliberate
216
226
  allowances, not general shell execution permission. Output-to-file options such as
217
227
  `git diff --output=...` are never exempt, even with a non-protected destination on a line
218
228
  that references a protected file.
219
229
 
220
- `gh` (all subcommands), `rg`, `ag`, `sort`, `uniq`, `cut`, `jq`, `yq`, `less`, `more`, `stat`,
230
+ `gh` (all subcommands), `ag`, `sort`, `uniq`, `cut`, `jq`, `yq`, `less`, `more`, `stat`,
221
231
  `file`, `diff`, `cmp`, checksum tools, `realpath`, `dirname`, `basename`, `which` and `type`
222
232
  are not on this list: their option surfaces are deliberately not analysed here.
223
233
 
@@ -42,14 +42,16 @@ function candidate(s) {
42
42
  # A generic attached option prefix must not hide a path spelling (-t.pi/...).
43
43
  if (s ~ /^-/ && match(s, /[.\/]/) && RSTART > 1) candidate(substr(s, RSTART))
44
44
  }
45
- function scan(s, n, i, c, word) {
45
+ function scan(s, n, i, c, word, whole) {
46
46
  n = length(s)
47
47
  for (i = 1; i <= n; i++) {
48
48
  c = substr(s, i, 1)
49
49
  if (c ~ /[ \t\n\r;|&<>()\047"`$=\\]/) { candidate(word); word = "" }
50
50
  else word = word c
51
+ if (c ~ /[ \t\n\r;|&<>()\047"`$]/) { candidate(whole); whole = "" }
52
+ else whole = whole c
51
53
  }
52
- candidate(word)
54
+ candidate(word); candidate(whole)
53
55
  # Braces have a second boundary view; retain the original pattern above too.
54
56
  if (s ~ /[{}]/) { gsub(/[{}]/, " ", s); scan(s) }
55
57
  }
@@ -98,8 +100,9 @@ function endword() {
98
100
  } else {
99
101
  if (++argc > 256) bad = 1
100
102
  W[argc] = word
103
+ globbed[argc] = glob
101
104
  }
102
- word = ""; inword = 0
105
+ word = ""; inword = glob = 0
103
106
  }
104
107
  # Each exemption permits only the reviewed read/presentation options below. No unknown
105
108
  # options, long-option abbreviations or implicit value-taking short clusters are accepted.
@@ -152,15 +155,27 @@ function options_allowed(verb, first, i, w) {
152
155
  }
153
156
  return 1
154
157
  }
158
+ # Only git -C <literal-dir> status --short, rev-parse HEAD, branch --show-current,
159
+ # or tag --list <pattern> are exempt, with exact arity; no other global option is.
160
+ # -C gives no protection from hostile repository config (fsmonitor, hooks, pager,
161
+ # diff/textconv helpers). This filter checks syntax, not repository trust.
162
+ function directory_metadata() {
163
+ if (argc < 5 || W[3] == "" || W[3] ~ /^-/ || globbed[3]) return 0
164
+ if (argc == 5) return (W[4] == "status" && W[5] == "--short") || (W[4] == "rev-parse" && W[5] == "HEAD") || (W[4] == "branch" && W[5] == "--show-current")
165
+ return argc == 6 && W[4] == "tag" && W[5] == "--list" && W[6] !~ /^-/
166
+ }
155
167
  function allow_command( verb, first) {
156
168
  if (!argc) return
157
169
  if (++commands > 64) { bad = 1; return }
158
170
  verb = W[1]; first = 2
159
- # No global git option is exempt, including -C, -c and --no-pager.
171
+ if (verb == "git" && W[2] == "-C") {
172
+ if (!directory_metadata()) bad = 1
173
+ return
174
+ }
160
175
  if (verb == "git") { verb = verb " " W[2]; first = 3 }
161
176
  if (!(verb in verbs) || !options_allowed(verb, first)) bad = 1
162
177
  }
163
- function command_end() { endword(); allow_command(); delete W; argc = 0 }
178
+ function command_end() { endword(); allow_command(); delete W; delete globbed; argc = 0 }
164
179
  function readonly(s, i, c, c2, sq, dq) {
165
180
  for (i = 1; i <= length(s); i++) {
166
181
  c = substr(s, i, 1); c2 = substr(s, i + 1, 1)
@@ -171,6 +186,8 @@ function readonly(s, i, c, c2, sq, dq) {
171
186
  # Expansions and globs can supply option words the per-verb tables never see.
172
187
  if (c == "`" || c == "$") bad = 1
173
188
  if (dq) { word = word c; continue }
189
+ # Directory metadata requires a literal -C operand, not a pathname expansion.
190
+ if (c == "*" || c == "?" || c == "[") glob = 1
174
191
  # A glob that starts a word, or follows a leading dash, may expand to an option word.
175
192
  if ((c == "*" || c == "?" || c == "[") && (word == "" ? !(c == "[" && c2 ~ /[ \t]/) : substr(word, 1, 1) == "-")) bad = 1
176
193
  if (c == "#" && !inword) { while (i <= length(s) && substr(s, i, 1) != "\n") i++; c = "\n" }
@@ -196,13 +213,14 @@ BEGIN {
196
213
  policy("cat", "nAvetsb", "")
197
214
  policy("head", "", ""); policy("tail", "", "")
198
215
  policy("wc", "lwcm", ""); policy("ls", "laA1hdRtrF", "")
216
+ policy("rg", "n", "")
199
217
  policy("grep", "nirRlLcvwxFEHhoqs", "")
200
218
  policy("egrep", "nirRlLcvwxFEHhoqs", ""); policy("fgrep", "nirRlLcvwxFEHhoqs", "")
201
219
  policy("echo", "neE", "")
202
220
  policy("printf", "", ""); policy("test", "", ""); policy("[", "", "")
203
221
  policy("true", "", ""); policy("false", "", ""); policy("pwd", "", "")
204
222
  policy("git status", "sb", "--short --porcelain")
205
- policy("git diff", "p", "--stat --name-only --name-status --cached --staged --check --no-color")
223
+ policy("git diff", "p", "--stat --numstat --name-only --name-status --cached --staged --check --no-color")
206
224
  policy("git log", "p", "--oneline --stat --name-only --no-color --follow")
207
225
  policy("git show", "p", "--stat --name-only --no-color")
208
226
  policy("git add", "Aup", ""); policy("git commit", "aq", "")
@@ -193,30 +193,63 @@ control_patterns=('.claude/settings.json' '.claude/settings.local.json' '.mcp.js
193
193
 
194
194
  # Glob-language intersection, not expansion/eval. A star has an epsilon transition and
195
195
  # a character loop. The product automaton accepts iff the two patterns share a spelling.
196
- # Braces conservatively become a star; bracket classes retain their ordinary meaning.
196
+ # In a reference, everything from the first '{' to the last '}' becomes one star: brace
197
+ # expansion, however nested, quoted or escaped, only rewrites text inside that span. A
198
+ # reference bracket is never parsed: it is either a literal '[' or one any-character step
199
+ # to any later ']' in the same segment. Bash's reading is always one of those alternatives,
200
+ # so the class contents can only widen the match. References that mix braces with brackets,
201
+ # whose brace span holds '/', with anything but plain path characters outside the brace
202
+ # span (quoting, substitution and expansion syntax), or with dense brackets are not modeled at all: they fail closed (exit 2) so the work stays
203
+ # bounded.
197
204
  IFS= read -r -d '' glob_program <<'AWK' || true
198
- function tokens(s, side, i, c, j, t, n) {
205
+ function tokens(s, side, i, c, j, k, t, copy, jumps, first, closing) {
199
206
  s = tolower(s)
207
+ if (side == 1) {
208
+ copy = s
209
+ if (index(s, "{") && index(s, "[")) exit 2
210
+ if (gsub(/\[/, "[", copy) > 64) exit 2
211
+ first = index(s, "{")
212
+ for (k = length(s); k > first; k--) if (substr(s, k, 1) == "}") { closing = k; break }
213
+ if (first && closing) {
214
+ if (index(substr(s, first, closing - first + 1), "/")) exit 2
215
+ if (substr(s, 1, first - 1) substr(s, closing + 1) ~ /[^a-z0-9._\/*?,+=:@%-]/) exit 2
216
+ s = substr(s, 1, first) substr(s, closing)
217
+ }
218
+ }
200
219
  for (i = 1; i <= length(s); i++) {
201
- c = substr(s, i, 1); t = c
202
- if (c == "{") { j = index(substr(s, i), "}"); if (j) i += j - 1; t = "*" }
203
- else if (c == "[") {
204
- j = index(substr(s, i + 1), "]")
205
- if (j) { t = substr(s, i, j + 1); i += j; sub(/^\[!/, "[^", t) }
220
+ c = substr(s, i, 1); t = c; j = i
221
+ if (c == "{") {
222
+ j = index(substr(s, i), "}"); j = j ? i + j - 1 : i; t = "*"
223
+ if (side == 1 && index(substr(s, i, j - i + 1), "/")) exit 2
206
224
  }
207
225
  N[side]++; A[side, N[side]] = t
226
+ for (k = i; k <= j; k++) TOKEN[side, k] = N[side]
227
+ if (c == "[" && side == 1) START[N[side]] = i
228
+ i = j
229
+ }
230
+ TOKEN[side, length(s) + 1] = N[side] + 1
231
+ for (t = 1; t <= N[side]; t++) {
232
+ if (side != 1 || !(t in START)) continue
233
+ for (k = START[t] + 2; k <= length(s); k++) {
234
+ c = substr(s, k, 1)
235
+ if (c == "/") break
236
+ if (c != "]") continue
237
+ # A ']' inside a brace star re-enters that star, which covers the rest of it.
238
+ j = TOKEN[1, k] == TOKEN[1, k + 1] ? TOKEN[1, k] : TOKEN[1, k + 1]
239
+ if (++jumps > 4096) exit 2
240
+ JUMP[t, ++JUMPS[t]] = j
241
+ }
208
242
  }
209
243
  }
210
244
  function push(i, j, key) { key = i SUBSEP j; if (!(key in seen)) { seen[key] = 1; L[++last] = i; R[last] = j } }
211
245
  function accepts(t, c, side) {
212
- if (side == 1 && c == "/" && (t == "*" || t == "?" || length(t) > 1)) return 0
213
- return t == "*" || t == "?" || (length(t) > 1 && substr(t, 1, 1) == "[" ? c ~ ("^" t "$") : t == c)
246
+ if (side == 1 && c == "/" && (t == "*" || t == "?")) return 0
247
+ return t == "*" || t == "?" || t == c
214
248
  }
215
- function compatible(a, b, k, c) {
216
- if (length(a) == 1 && a != "*" && a != "?") return accepts(b, a, 2)
217
- if (length(b) == 1 && b != "*" && b != "?") return accepts(a, b, 1)
218
- for (k = 1; k < 256; k++) { c = sprintf("%c", k); if (accepts(a, c, 1) && accepts(b, c, 2)) return 1 }
219
- return 0
249
+ function compatible(a, b) {
250
+ if (a != "*" && a != "?") return accepts(b, a, 2)
251
+ if (b != "*" && b != "?") return accepts(a, b, 1)
252
+ return 1
220
253
  }
221
254
  BEGIN {
222
255
  tokens(ENVIRON["REF_LEFT"], 1); tokens(ENVIRON["REF_RIGHT"], 2); push(1, 1)
@@ -228,6 +261,7 @@ BEGIN {
228
261
  if (a == "*") push(i + 1, j)
229
262
  if (b == "*") push(i, j + 1)
230
263
  if (i <= N[1] && j <= N[2] && compatible(a, b)) push(i + (a != "*"), j + (b != "*"))
264
+ if (i <= N[1] && j <= N[2] && compatible("?", b)) for (k = 1; k <= JUMPS[i]; k++) push(JUMP[i, k], j + (b != "*"))
231
265
  }
232
266
  exit 1
233
267
  }
@@ -78,6 +78,7 @@
78
78
  "cratis-arc-command-validation",
79
79
  "cratis-arc-ef-core-migration",
80
80
  "cratis-arc-hosting",
81
+ "cratis-arc-neo4j",
81
82
  "cratis-arc-observable-query-http",
82
83
  "cratis-arc-query-paging",
83
84
  "cratis-arc-react-page",
@@ -40,6 +40,10 @@ One precise line per load-bearing term, so the same word means the same thing ev
40
40
  - **Observer** — Chronicle's umbrella for anything consuming an event sequence (projection, reducer, reactor); carries subscription / replay / **quarantine** state. Projection replay and catch-up each walk the sequence in one globally ordered job step; a new catch-up failure stops that step. Full replay is inactive and completion does not resume a quarantined observer (Chronicle v19.50.1, `Documentation/concepts/observers.mdx`, `Observation/Jobs/{CatchUpObserver,ReplayObserver}.cs` under `Source/Kernel/Core/`).
41
41
  - **Sink** — where a read model is persisted (MongoDB, EF Core).
42
42
  - **AutoMap** — Chronicle's on-by-default mapping of matching event→read-model property names; **never call `.AutoMap()`**.
43
+ - **Graph** — a named property graph that events build through a graph projection: nodes, edges and their properties. Derived state like a read model; nothing writes to it directly.
44
+ - **Node** — a graph element with a label, one unique key and primitive properties. The label is the type name.
45
+ - **Edge** — a directed, typed graph relationship from a source node to a target node, identified by type, source key and target key (plus an identifying property when several edges of one type may join the same pair).
46
+ - **Graph sink** — where a graph is persisted (Neo4j, or the in-memory graph); it applies the five idempotent graph operations, separate from the `ISink` of document read models.
43
47
  - **Query** — a `static` method on a `[ReadModel]`; returns derived state, **snapshot** (one-shot) or **observable** (live).
44
48
 
45
49
  ## Write side
@@ -0,0 +1,2 @@
1
+ Copyright (c) Cratis. All rights reserved.
2
+ Licensed under the MIT license. See LICENSE file in the project root for full license information.
@@ -0,0 +1,166 @@
1
+ ---
2
+ name: cratis-arc-neo4j
3
+ description: Use when an Arc C# query or command must read a Neo4j graph, inject the tenant-aware IGraphSession, run Cypher, or choose the graph database per tenant. Not for projecting events onto a graph or for MongoDB documents.
4
+ license: MIT
5
+ ---
6
+
7
+ <!-- Copyright (c) Cratis. All rights reserved. -->
8
+ <!-- Licensed under the MIT license. See LICENSE file in the project root for full license information. -->
9
+
10
+ # Read a Neo4j graph from Arc
11
+
12
+ `Cratis.Arc.Neo4j` gives a model-bound query, a command's `Provide()` method or any
13
+ scoped service a session on the Neo4j database of the current tenant. It reads the
14
+ graph; it does not build it. A graph is what events leave behind: a graph projection
15
+ (`cratis-chronicle-projection`, or `cratis-screenplay-projections` in a model) writes
16
+ nodes and relationships through Chronicle's Neo4j sink, and nothing writes to the
17
+ graph from a query. Arc does not need Chronicle or event sourcing to read a graph.
18
+
19
+ Requires `Cratis.Arc.Neo4j` 22.168.0 (`dotnet list package`); older Arc releases have
20
+ no graph session, so read the graph with the Neo4j driver directly.
21
+
22
+ - An accepted `.play` model under the model root covers the behavior, or the
23
+ repository is opted in (per `general.md` "Model first"): change the model first
24
+ with `cratis-screenplay-event-modeling`. The graph shape comes from the model's
25
+ `graph` declaration; this skill covers only the read side in code.
26
+
27
+ ## When a graph read fits
28
+
29
+ Use a graph query for traversals: who belongs to which group, nested groups,
30
+ paths, "everyone who reaches this node". Use a document read model
31
+ (`cratis-chronicle-read-model`, MongoDB or EF Core) for lookups by key, lists and
32
+ anything shaped like one row per entity. Do not read a graph for what one document
33
+ read already answers.
34
+
35
+ ## Set it up
36
+
37
+ ```bash
38
+ dotnet add package Cratis.Arc.Neo4j
39
+ ```
40
+
41
+ ```json
42
+ {
43
+ "Cratis": {
44
+ "Neo4j": {
45
+ "Server": "bolt://localhost:7687",
46
+ "EventStore": "Organization",
47
+ "UserName": "neo4j",
48
+ "PasswordSecret": "NEO4J_PASSWORD"
49
+ }
50
+ }
51
+ }
52
+ ```
53
+
54
+ `Server` and `EventStore` are required. `EventStore` is the event store whose graph
55
+ Chronicle's sink writes; it is the first part of the database name. `PasswordSecret`
56
+ names a configuration key (environment variable, user secrets, key vault), so the
57
+ password is never written in options. `Password` exists for local development only
58
+ and loses to `PasswordSecret`. Other options: `DatabasePrefix`, `DatabaseMode`,
59
+ `SingleDatabase`, `ConnectionResolution`.
60
+
61
+ ```csharp
62
+ builder.AddCratisArc(configureBuilder: arc => arc.WithNeo4j());
63
+ ```
64
+
65
+ Use `WithNeo4j()` on the Arc builder, or `AddCratisNeo4j()` on the service
66
+ collection for existing host code, never both. Starting the host does not connect;
67
+ the first query checks connectivity and permissions.
68
+
69
+ ## Query
70
+
71
+ ```csharp
72
+ [ReadModel]
73
+ public record GroupMember(PersonId PersonId, PersonName Name)
74
+ {
75
+ public static Task<IReadOnlyList<GroupMember>> MembersOf(GroupId groupId, IGraphSession graph) =>
76
+ graph.Query<GroupMember>(
77
+ "MATCH (p:Person)-[:MEMBER_OF]->(g:Group { groupId: $groupId }) RETURN p.personId AS personId, p.name AS name ORDER BY p.name",
78
+ new { groupId });
79
+ }
80
+ ```
81
+
82
+ - `Query<T>` maps every row; `QuerySingle<T>` maps the first row or gives `null`.
83
+ - Parameters are an object's public properties or a dictionary.
84
+ - One returned column maps to a primitive, concept or list of those. Several
85
+ columns match constructor parameters or settable properties by name, ignoring
86
+ case. `RETURN p` maps a node's properties.
87
+ - `Run` returns the driver's `IResultCursor` and `Session` exposes `IAsyncSession`
88
+ for transaction functions. Pass `graph.Parameters(new { ... })` so the converted
89
+ parameters, including `$namespace`, are used.
90
+ - Concepts bind as their inner value and are rebuilt from results. A `Guid` is
91
+ bound and read as its string, a `decimal` as `double`, an enum by name. This is
92
+ what the Chronicle sink stores, so a key written from an event is found by the
93
+ same parameter.
94
+
95
+ ## The session is a read session
96
+
97
+ The scoped `IGraphSession` opens with `AccessMode.Read`; the server refuses a query
98
+ that writes. Change the graph by appending events. For data no projection owns, open
99
+ a write session with `IGraphSessionFactory.Open(AccessMode.Write)` and dispose it.
100
+ `IGraphSession` is scoped: a singleton that captures it keeps the database of an
101
+ earlier scope.
102
+
103
+ ## Pick the tenant's database
104
+
105
+ `IGraphNamespaceResolver` maps the tenant to a namespace like the Chronicle
106
+ integration: a named tenant is the namespace of the same name, and `TenantId.NotSet`
107
+ and `TenantId.Default` are `Default`. The database is `[prefix-]eventStore[-namespace]`
108
+ and must equal what Chronicle's sink writes, so use the shipped algorithm
109
+ (`GraphDatabaseName.For(prefix, eventStore, namespace)`) rather than hand-building
110
+ names:
111
+
112
+ 1. Compose the name; the `Default` namespace (exact, case-sensitive), `null` or empty adds no segment.
113
+ 2. Lower-case it and replace every character outside `[a-z0-9-]` with `-`.
114
+ 3. Prefix `g-` when it does not start with a letter.
115
+ 4. When step 2 changed the lower-cased name, or the result is over 63 or under 3
116
+ characters, cut to 54 and append `-` and the first 8 lower-case hex of the SHA-256
117
+ of the unsanitized UTF-8 name.
118
+
119
+ | Event store | Namespace | Database |
120
+ | --- | --- | --- |
121
+ | `Orders` | `Default` | `orders` |
122
+ | `Orders` | `acme` or `Acme` | `orders-acme` |
123
+ | `Orders` | `Acme Corp` | `orders-acme-corp-` plus 8 hex of the hash |
124
+ | `1Orders` | `Default` | `g-1orders` |
125
+
126
+ Lower-casing alone adds no hash, so namespaces that differ only by case share a
127
+ database. Replace the naming only when you also change what writes the database:
128
+ `WithDatabaseNameResolver<T>()` and `WithNamespaceResolver<T>()` on the Neo4j builder.
129
+
130
+ Read references/connection-resolution-and-single-mode.md when tenants need their
131
+ own server, database or credentials, or when the host runs against Neo4j Community
132
+ Edition.
133
+
134
+ ## Test
135
+
136
+ `Cratis.Arc.Neo4j.Testing` replaces the session without a server:
137
+
138
+ ```csharp
139
+ var services = new ServiceCollection();
140
+ var graph = services.UseGraphSessionSubstitute();
141
+ graph.Returns("MATCH (p:Person)", new GroupMember(personId, new PersonName("Ada")));
142
+
143
+ var members = await GroupMember.MembersOf(groupId, graph);
144
+ ```
145
+
146
+ `Executions` lists the Cypher run with its converted parameters; assert on it to
147
+ prove a query was bound and filtered. `Run` and `Session` throw on the substitute,
148
+ so keep row mapping on `Query` and `QuerySingle`, and cover driver calls with an
149
+ integration test against Neo4j.
150
+
151
+ ## Pitfalls
152
+
153
+ - A query leaves out `_namespace` in `Single` database mode and reads across tenants.
154
+ - A resolved `Database` (template or endpoint) bypasses the naming algorithm, so
155
+ Arc reads a database nothing writes to unless the sink resolves the same one.
156
+ - A property starting with an underscore is the sink's own; never return it as data.
157
+ - A key keeps its type in the graph: `1` and `"1"` are different nodes.
158
+ - Reading the graph from a command to decide an invariant is advisory only; a
159
+ graph is eventually consistent with the event log.
160
+
161
+ ## Verify
162
+
163
+ Run the host with a query against a development graph: it returns the expected
164
+ rows, and with `DatabaseMode` `PerNamespace` another tenant's request returns none
165
+ of them. A specification using `UseGraphSessionSubstitute` passes, and `Executions`
166
+ shows the `$namespace` parameter. `dotnet build` finishes with zero warnings.
@@ -0,0 +1,51 @@
1
+ <!-- Copyright (c) Cratis. All rights reserved. -->
2
+ <!-- Licensed under the MIT license. See LICENSE file in the project root for full license information. -->
3
+
4
+ # Connection resolution and single-database mode
5
+
6
+ ## Single-database mode
7
+
8
+ `DatabaseMode` `Single` puts every namespace in `SingleDatabase` (`neo4j` by
9
+ default), the only user database on Neo4j Community Edition. Chronicle stamps the
10
+ namespace as `_namespace` on every node and relationship, and nothing else separates
11
+ tenants. Use it for development and tests, never production. Filter every pattern
12
+ with the `$namespace` parameter the session adds to each query:
13
+
14
+ ```cypher
15
+ MATCH (p:Person)-[:MEMBER_OF]->(g:Group)
16
+ WHERE p._namespace = $namespace AND g._namespace = $namespace
17
+ RETURN p.name AS name, g.name AS group
18
+ ```
19
+
20
+ In `PerNamespace` mode the parameter is still given and harmless, so one query can
21
+ carry the filter in both modes. `GraphParameters.Namespace` and
22
+ `GraphParameters.NamespaceProperty` name the parameter and the property.
23
+
24
+ ## Connection resolution
25
+
26
+ Resolution lets the platform choose server, database or credentials per tenant.
27
+ Arc resolves once per service scope, and the scoped `IGraphSession` and
28
+ `IGraphSessionFactory` share it. A resolved part applies as follows:
29
+
30
+ | Resolved part | Effect |
31
+ | --- | --- |
32
+ | `ConnectionString` | A Bolt URI that replaces `Server` |
33
+ | `Database` | Replaces the computed database name |
34
+ | `Identity.UserName` and `Identity.Password` | Basic authentication |
35
+ | `Identity.AccessToken` | Bearer token |
36
+
37
+ With no resolved identity the configured user and password apply. Drivers are shared
38
+ per server and resolution, never across credentials. When the server rejects a
39
+ credential or token, Arc drops the cached resolution and resolves again.
40
+
41
+ To resolve only the identity over HTTP and keep the shared server and naming:
42
+
43
+ ```csharp
44
+ builder.AddCratisArc(configureBuilder: arc => arc.WithNeo4j(
45
+ configureOptions: neo4j => neo4j.ConnectionResolution.Identity.UseHttp(new Uri("https://platform.example/connections"))));
46
+ ```
47
+
48
+ A template placing tenants by rule goes in the `ConnectionResolution` section with
49
+ `"Resolver": "Template"` and a `Template` holding a `Database` such as
50
+ `graph-{tenant}`. The default tenant then resolves to `graph-Default`, so point the
51
+ Chronicle sink at the same destination.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: cratis-chronicle-client-elixir
3
- description: Use when adding Chronicle to an Elixir OTP application, defining its event structs or handling client append outcomes. Not for JVM or Node.js clients; use the corresponding Chronicle client sibling.
3
+ description: Use when adding Chronicle to an Elixir OTP application, defining its event structs, declaring a graph with the node and edge DSL, or handling client append outcomes. Not for JVM or Node.js clients; use the corresponding Chronicle client sibling.
4
4
  license: MIT
5
5
  ---
6
6
 
@@ -276,6 +276,17 @@ registered definitions.
276
276
 
277
277
  **Live updates arrive as messages, not as a stream.** `ReadModels.watch/2` and `subscribe/2` send `{:chronicle_read_model_changed, module, %Changeset{}}` and error messages to the calling process, which needs a `handle_info` for each. Read [references/read-models.md](references/read-models.md) when subscribing, filtering, observing collections, previewing or waiting for a projection.
278
278
 
279
+ #### Graph projections — `node` and `edge`
280
+
281
+ A graph is a module with `use Chronicle.Graphs.Graph, id: "Organization"`; its nodes
282
+ and edges are structs with `use Chronicle.Graphs.Node` and `use Chronicle.Graphs.Edge,
283
+ type: "MEMBER_OF"`. Inside the graph, `node Mod, key: :field do ... end` and
284
+ `edge Mod, source: A, target: B do ... end` hold `from/2` and `removed_with/2`
285
+ (`detach: true` on a node). Register it with `graphs: [Mod]` on `Chronicle.Client`.
286
+ Requires cratis_chronicle 3.20.0 (check `mix deps`). Read
287
+ [references/graphs.md](references/graphs.md) for the options, counters, edge identity,
288
+ compiler checks and sink choice. Pin `id:`; renaming it registers a different projection.
289
+
279
290
  ## Guarding decisions, testing and more
280
291
 
281
292
  Read the reference that matches the task:
@@ -0,0 +1,123 @@
1
+ # Graph projections with the node and edge DSL
2
+
3
+ ## Contents
4
+
5
+ - Declaring a graph
6
+ - Options
7
+ - Counters and edge identity
8
+ - Compiler checks
9
+ - Registering and choosing the sink
10
+ - Not supported yet
11
+
12
+ ## Declaring a graph
13
+
14
+ ```elixir
15
+ defmodule MyApp.Graphs.Person do
16
+ use Chronicle.Graphs.Node
17
+ defstruct person_id: "", name: ""
18
+ end
19
+
20
+ defmodule MyApp.Graphs.Group do
21
+ use Chronicle.Graphs.Node
22
+ defstruct group_id: "", name: ""
23
+ end
24
+
25
+ defmodule MyApp.Graphs.MemberOf do
26
+ use Chronicle.Graphs.Edge, type: "MEMBER_OF"
27
+ defstruct since: ""
28
+ end
29
+
30
+ defmodule MyApp.Graphs.Organization do
31
+ use Chronicle.Graphs.Graph, id: "Organization"
32
+
33
+ node MyApp.Graphs.Person, key: :person_id do
34
+ from MyApp.Events.PersonRegistered, key: :person_id, set: [name: :name]
35
+ removed_with MyApp.Events.PersonRemoved, key: :person_id, detach: true
36
+ end
37
+
38
+ node MyApp.Graphs.Group, key: :group_id do
39
+ from MyApp.Events.GroupCreated, key: :group_id
40
+ end
41
+
42
+ edge MyApp.Graphs.MemberOf, source: MyApp.Graphs.Person, target: MyApp.Graphs.Group do
43
+ from MyApp.Events.MemberAdded,
44
+ source_key: :person_id,
45
+ target_key: :group_id,
46
+ set: [since: {:event_context, :occurred}]
47
+
48
+ removed_with MyApp.Events.MemberRemoved, source_key: :person_id, target_key: :group_id
49
+ end
50
+ end
51
+ ```
52
+
53
+ The struct fields are the properties, typed by their `defstruct` defaults; a property
54
+ is a primitive or a list of primitives. A node's label and an edge's type default to the
55
+ last segment of the module name (`label:` / `type:` choose another). Property names are
56
+ the `camelCase` of the field names, as in the .NET client, so both register the same definition.
57
+ `node/3` names the unique key field with `key:`; `edge/3` names its `source:` and
58
+ `target:` nodes, both declared with `node` in the same graph. The end nodes are not
59
+ properties of the edge.
60
+
61
+ ## Options
62
+
63
+ - `from/2`: a node takes `key:`, an edge `source_key:` and `target_key:` (event
64
+ properties; each defaults to the event source id). `update_only: true` on a node's
65
+ `from` changes the node only when it exists.
66
+ - `removed_with/2`: deletes the node or edge. A node accepts `detach: true` (deletes
67
+ its edges too; without it a node that still has edges cannot be deleted). An edge
68
+ cannot detach.
69
+ - Property options as for read models: `set:` (event property, `:event_source_id`,
70
+ `{:event_context, :occurred}`, `{:value, v}`), `add:`, `subtract:`, `increment:`,
71
+ `decrement:`, `count:`, `clear:`.
72
+
73
+ ## Counters and edge identity
74
+
75
+ ```elixir
76
+ node MyApp.Graphs.Team, key: :team_id do
77
+ from MyApp.Events.TeamFormed, key: :team_id
78
+ from MyApp.Events.TeamMemberJoined, key: :team_id, increment: :member_count
79
+ from MyApp.Events.TeamMemberLeft, key: :team_id, decrement: :member_count
80
+ end
81
+ ```
82
+
83
+ `identified_by:` on an edge names a struct field that distinguishes several edges of
84
+ one type between the same two nodes. Every `from` and `removed_with` of that edge
85
+ must then name the identity event property with `identity:` or have one of the same
86
+ name as the field. A sink that cannot hold several edges between one pair rejects it.
87
+
88
+ ```elixir
89
+ edge MyApp.Graphs.Visited,
90
+ source: MyApp.Graphs.Customer,
91
+ target: MyApp.Graphs.Shop,
92
+ identified_by: :visit_id do
93
+ from MyApp.Events.ShopVisited, source_key: :customer_id, target_key: :shop_id, count: :times
94
+ end
95
+ ```
96
+
97
+ ## Compiler checks
98
+
99
+ A graph that cannot work raises a `CompileError` naming the declaration line when an
100
+ edge names a source or target that is not a node of the graph; a node has no `key:` or
101
+ the key is not a struct field; an edge's `removed_with` asks to `detach`; a node or edge
102
+ struct has a nested struct or map property; an identified edge has an event with no
103
+ identity; or a mapped field, option or module is unknown.
104
+
105
+ ## Registering and choosing the sink
106
+
107
+ ```elixir
108
+ {Chronicle.Client,
109
+ connection_string: "chronicle://localhost:35000",
110
+ event_store: "my-store",
111
+ default_graph_sink_type_id: :in_memory_graph,
112
+ graphs: [MyApp.Graphs.Organization]}
113
+ ```
114
+
115
+ The client registers the graph as a read model stored by the graph sink and as the
116
+ projection that fills it, with `id:` as read model name and projection identifier.
117
+ `:default_graph_sink_type_id` defaults to `:neo4j`; use `:in_memory_graph` for development
118
+ and tests. `:default_sink_type_id` still chooses the sink of document read models only.
119
+
120
+ ## Not supported yet
121
+
122
+ The client does not read a graph (use the engine driver) and `Chronicle.Testing` has no
123
+ graph scenario, so test a graph by asserting the definition it registers.