@cratis/pi 8.4.0 → 8.5.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 (138) hide show
  1. package/package/corpus/harnesses/copilot/instructions/ai-distribution.instructions.md +2 -1
  2. package/package/corpus/harnesses/copilot/instructions/exit-codes-and-wrappers.instructions.md +1 -1
  3. package/package/corpus/harnesses/copilot/instructions/scripting.instructions.md +2 -1
  4. package/package/corpus/hooks/scripts/cratis-cleanup-worktrees.sh +5 -1
  5. package/package/corpus/hooks/scripts/cratis-guard-secrets.sh +131 -9
  6. package/package/corpus/rules/ai-distribution.md +2 -1
  7. package/package/corpus/rules/exit-codes-and-wrappers.md +1 -1
  8. package/package/corpus/rules/scripting.md +2 -1
  9. package/package/corpus/skills/cratis-application-growth/references/csharp.md +1 -1
  10. package/package/corpus/skills/cratis-arc-authorize-request/SKILL.md +3 -3
  11. package/package/corpus/skills/cratis-arc-authorize-request/references/authproxy.md +28 -3
  12. package/package/corpus/skills/cratis-arc-authorize-request/references/csharp-query-security.md +3 -3
  13. package/package/corpus/skills/cratis-arc-authorize-request/references/csharp.md +1 -1
  14. package/package/corpus/skills/cratis-arc-authorize-request/references/typescript.md +2 -0
  15. package/package/corpus/skills/cratis-arc-connect-storage/references/csharp.md +1 -0
  16. package/package/corpus/skills/cratis-arc-connect-storage/references/elixir.md +9 -2
  17. package/package/corpus/skills/cratis-arc-declare-command/references/csharp-chronicle.md +1 -1
  18. package/package/corpus/skills/cratis-arc-declare-command/references/csharp-history.md +2 -2
  19. package/package/corpus/skills/cratis-arc-declare-command/references/csharp.md +7 -7
  20. package/package/corpus/skills/cratis-arc-declare-operation/references/csharp-abilities.md +2 -2
  21. package/package/corpus/skills/cratis-arc-declare-operation/references/csharp-recovery.md +6 -4
  22. package/package/corpus/skills/cratis-arc-declare-operation/references/csharp.md +2 -2
  23. package/package/corpus/skills/cratis-arc-diagnose-live-query/SKILL.md +1 -1
  24. package/package/corpus/skills/cratis-arc-diagnose-live-query/references/csharp.md +6 -6
  25. package/package/corpus/skills/cratis-arc-diagnose-live-query/references/java.md +1 -1
  26. package/package/corpus/skills/cratis-arc-diagnose-live-query/references/kotlin.md +1 -1
  27. package/package/corpus/skills/cratis-arc-expose-mcp-operation/references/csharp-diagnose-tool-call.md +9 -7
  28. package/package/corpus/skills/cratis-arc-expose-mcp-operation/references/csharp.md +3 -1
  29. package/package/corpus/skills/cratis-arc-expose-query/SKILL.md +1 -1
  30. package/package/corpus/skills/cratis-arc-expose-query/references/csharp.md +10 -7
  31. package/package/corpus/skills/cratis-arc-expose-query/references/go.md +2 -2
  32. package/package/corpus/skills/cratis-arc-expose-query/references/typescript.md +6 -3
  33. package/package/corpus/skills/cratis-arc-generate-proxies/references/csharp.md +7 -5
  34. package/package/corpus/skills/cratis-arc-host-application/references/csharp-identity.md +3 -2
  35. package/package/corpus/skills/cratis-arc-host-application/references/csharp.md +7 -0
  36. package/package/corpus/skills/cratis-arc-invoke-command/references/csharp-extensions.md +4 -0
  37. package/package/corpus/skills/cratis-arc-isolate-tenant/SKILL.md +1 -1
  38. package/package/corpus/skills/cratis-arc-isolate-tenant/references/csharp.md +4 -2
  39. package/package/corpus/skills/cratis-arc-react-bind-slice/SKILL.md +17 -22
  40. package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-commands.md +11 -1
  41. package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-host.md +10 -3
  42. package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-identity.md +7 -3
  43. package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-queries.md +1 -1
  44. package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript.md +1 -1
  45. package/package/corpus/skills/cratis-arc-testing-typescript/references/typescript.md +2 -2
  46. package/package/corpus/skills/cratis-arc-validation-typescript/SKILL.md +1 -0
  47. package/package/corpus/skills/cratis-chronicle-cli-operations/SKILL.md +5 -5
  48. package/package/corpus/skills/cratis-chronicle-cli-operations/references/inspection.md +11 -3
  49. package/package/corpus/skills/cratis-chronicle-cli-operations/references/project-tooling.md +22 -0
  50. package/package/corpus/skills/cratis-chronicle-cli-operations/references/recovery-and-comparison.md +17 -3
  51. package/package/corpus/skills/cratis-chronicle-cli-operations/references/setup-and-target.md +8 -2
  52. package/package/corpus/skills/cratis-chronicle-connect-application/references/python.md +2 -2
  53. package/package/corpus/skills/cratis-chronicle-constrain-append/SKILL.md +1 -1
  54. package/package/corpus/skills/cratis-chronicle-deploy-kernel/SKILL.md +4 -3
  55. package/package/corpus/skills/cratis-chronicle-deploy-kernel/references/configuration.md +86 -16
  56. package/package/corpus/skills/cratis-chronicle-deploy-kernel/references/kernel-options.md +3 -3
  57. package/package/corpus/skills/cratis-chronicle-deploy-kernel/references/network-and-tls.md +14 -6
  58. package/package/corpus/skills/cratis-chronicle-deploy-kernel/references/storage.md +33 -1
  59. package/package/corpus/skills/cratis-chronicle-deploy-kernel/references/upgrade-and-recovery.md +27 -1
  60. package/package/corpus/skills/cratis-chronicle-evolve-event/references/csharp.md +2 -2
  61. package/package/corpus/skills/cratis-chronicle-inspect-observer/SKILL.md +4 -4
  62. package/package/corpus/skills/cratis-chronicle-inspect-observer/references/csharp.md +8 -7
  63. package/package/corpus/skills/cratis-chronicle-inspect-observer/references/go.md +2 -2
  64. package/package/corpus/skills/cratis-chronicle-mcp-inspection/SKILL.md +1 -1
  65. package/package/corpus/skills/cratis-chronicle-mcp-inspection/references/deployment.md +1 -1
  66. package/package/corpus/skills/cratis-chronicle-project-view/SKILL.md +1 -1
  67. package/package/corpus/skills/cratis-chronicle-project-view/references/csharp-fluent.md +1 -1
  68. package/package/corpus/skills/cratis-chronicle-project-view/references/csharp-model-bound.md +1 -1
  69. package/package/corpus/skills/cratis-chronicle-project-view/references/csharp-reading.md +2 -0
  70. package/package/corpus/skills/cratis-chronicle-project-view/references/java.md +1 -1
  71. package/package/corpus/skills/cratis-chronicle-project-view/references/kotlin.md +3 -3
  72. package/package/corpus/skills/cratis-chronicle-project-view/references/typescript.md +2 -0
  73. package/package/corpus/skills/cratis-chronicle-protect-decision/SKILL.md +1 -1
  74. package/package/corpus/skills/cratis-chronicle-protect-decision/references/csharp-scopes.md +1 -1
  75. package/package/corpus/skills/cratis-chronicle-protect-decision/references/csharp.md +2 -2
  76. package/package/corpus/skills/cratis-chronicle-protect-personal-data/SKILL.md +1 -1
  77. package/package/corpus/skills/cratis-chronicle-protect-personal-data/references/csharp.md +4 -2
  78. package/package/corpus/skills/cratis-chronicle-publish-contract/SKILL.md +6 -5
  79. package/package/corpus/skills/cratis-chronicle-publish-contract/references/elixir-integrations.md +3 -3
  80. package/package/corpus/skills/cratis-chronicle-react-to-fact/SKILL.md +2 -1
  81. package/package/corpus/skills/cratis-chronicle-react-to-fact/references/csharp-pages.md +1 -1
  82. package/package/corpus/skills/cratis-chronicle-react-to-fact/references/csharp.md +3 -3
  83. package/package/corpus/skills/cratis-chronicle-react-to-fact/references/java.md +1 -1
  84. package/package/corpus/skills/cratis-chronicle-record-event/SKILL.md +2 -2
  85. package/package/corpus/skills/cratis-chronicle-reduce-state/references/typescript.md +1 -1
  86. package/package/corpus/skills/cratis-chronicle-web-workbench/SKILL.md +1 -1
  87. package/package/corpus/skills/cratis-ci-pipeline-performance/SKILL.md +4 -3
  88. package/package/corpus/skills/cratis-ci-pipeline-performance/references/publish-pipelines.md +19 -4
  89. package/package/corpus/skills/cratis-code-review/SKILL.md +6 -2
  90. package/package/corpus/skills/cratis-code-review/references/csharp.md +3 -3
  91. package/package/corpus/skills/cratis-commits-and-pull-requests/SKILL.md +6 -38
  92. package/package/corpus/skills/cratis-commits-and-pull-requests/references/pr-description.md +2 -0
  93. package/package/corpus/skills/cratis-commits-and-pull-requests/references/pr-labels-and-release.md +5 -4
  94. package/package/corpus/skills/cratis-commits-and-pull-requests/references/workflow-inputs.md +39 -0
  95. package/package/corpus/skills/cratis-components-submit-form/SKILL.md +6 -6
  96. package/package/corpus/skills/cratis-components-submit-form/references/typescript-commanddialog.md +21 -1
  97. package/package/corpus/skills/cratis-components-submit-form/references/typescript.md +2 -2
  98. package/package/corpus/skills/cratis-fundamentals-concept/references/csharp-serialization.md +2 -1
  99. package/package/corpus/skills/cratis-fundamentals-concept/references/csharp.md +1 -0
  100. package/package/corpus/skills/cratis-fundamentals-concept/references/go.md +1 -1
  101. package/package/corpus/skills/cratis-fundamentals-concept/references/java-json.md +3 -2
  102. package/package/corpus/skills/cratis-fundamentals-concept/references/kotlin-json.md +3 -2
  103. package/package/corpus/skills/cratis-fundamentals-concept/references/typescript-serialization.md +8 -2
  104. package/package/corpus/skills/cratis-fundamentals-name-value/SKILL.md +8 -7
  105. package/package/corpus/skills/cratis-fundamentals-type-discovery/SKILL.md +3 -3
  106. package/package/corpus/skills/cratis-fundamentals-type-discovery/references/csharp-diagnostics.md +3 -0
  107. package/package/corpus/skills/cratis-fundamentals-type-discovery/references/csharp.md +2 -2
  108. package/package/corpus/skills/cratis-platform-deliver-slice/references/typescript.md +14 -1
  109. package/package/corpus/skills/cratis-platform-prepare-release-pr/SKILL.md +8 -8
  110. package/package/corpus/skills/cratis-platform-prepare-release-pr/references/product-release-checks.md +16 -2
  111. package/package/corpus/skills/cratis-release-notes/SKILL.md +1 -1
  112. package/package/corpus/skills/cratis-release-notes/references/publish-repair.md +6 -3
  113. package/package/corpus/skills/cratis-screenplay-accept-model/references/csharp.md +5 -3
  114. package/package/corpus/skills/cratis-screenplay-accept-model/references/read-the-evidence.md +2 -2
  115. package/package/corpus/skills/cratis-screenplay-declare-slice/SKILL.md +6 -10
  116. package/package/corpus/skills/cratis-screenplay-declare-slice/references/commands.md +8 -4
  117. package/package/corpus/skills/cratis-screenplay-declare-slice/references/projections.md +2 -0
  118. package/package/corpus/skills/cratis-screenplay-declare-slice/references/structure-and-imports.md +19 -1
  119. package/package/corpus/skills/cratis-screenplay-edit-workspace/SKILL.md +2 -1
  120. package/package/corpus/skills/cratis-screenplay-edit-workspace/references/mcp-tools.md +1 -1
  121. package/package/corpus/skills/cratis-screenplay-handoff-slice/references/csharp.md +13 -1
  122. package/package/corpus/skills/cratis-screenplay-model-translation/SKILL.md +1 -1
  123. package/package/corpus/skills/cratis-screenplay-model-translation/references/boundary-diagnostics.md +1 -1
  124. package/package/corpus/skills/cratis-screenplay-onboard-workspace/SKILL.md +26 -48
  125. package/package/corpus/skills/cratis-screenplay-onboard-workspace/references/studio.md +5 -0
  126. package/package/corpus/skills/cratis-screenplay-specify-outcome/SKILL.md +8 -12
  127. package/package/corpus/skills/cratis-screenplay-specify-outcome/references/running-mcp.md +12 -0
  128. package/package/corpus/skills/cratis-screenplay-specify-outcome/references/scenarios.md +2 -2
  129. package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-command-results.md +1 -1
  130. package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-events.md +6 -0
  131. package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-integration.md +3 -2
  132. package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-reactors.md +15 -2
  133. package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-read-models.md +4 -2
  134. package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp.md +1 -1
  135. package/package/corpus/skills/cratis-specifications-exercise-backend/references/typescript.md +4 -2
  136. package/package/corpus/skills/cratis-stage-render-slice/SKILL.md +6 -0
  137. package/package/corpus/skills/cratis-stage-render-slice/references/semantic-conformance.md +64 -0
  138. package/package.json +1 -1
@@ -9,7 +9,8 @@ paths:
9
9
 
10
10
  - Author shared corpus changes in `Cratis/AI`, generalized and free of private facts; never copy one consumer's `.cratis/ai` or native assistant folders into another repository, and keep consumer settings, private skills and repository knowledge local.
11
11
  - Never hand-edit installed managed files, generated adapters or a marketplace wrapper, because the next update overwrites or flags them; install, update, roll back and remove through the channel that installed them (`cratis ai install`, `update`, `uninstall`), previewing with `--dry-run`.
12
- - Use `cratis ai update --force` only after reviewing the modified managed files it will overwrite; `cratis ai status` exits nonzero when a managed file was modified, so CI can gate on it.
12
+ - Use `cratis ai update --force` only after reviewing the modified managed files it will overwrite; `cratis ai status` exits nonzero when a managed file was modified, so CI can gate on it. In CI, install a pinned `Cratis.Cli` .NET tool with a .NET SDK that supports the package's target framework (currently .NET 11), with the .NET and ASP.NET Core runtimes it needs; a runtime-only image cannot run `dotnet tool install`. On macOS or Linux (x64 or arm64) you can instead use the matching pinned, self-contained native release binary, which needs no .NET runtime; there is no native Windows binary.
13
+ - When stdin is redirected, pass `--profiles` and `--harnesses` to `cratis ai install` (`--languages` is optional), or it exits 5 before downloading the corpus. `cratis ai update` takes no selection options and reuses `.cratis/ai.json`; run `install` again to change the selection. Both take whatever the corpus source currently holds and the installed revision pins nothing; to reproduce a reviewed revision, point `--source` or `CRATIS_AI_SOURCE` at a fresh, full `Cratis/AI` checkout of that commit with no extra files, including ignored ones such as a `.env`, and supply it on every run. The CLI reads the selected corpus files from disk, not from Git's tracked tree, so extra files in selected directories are installed even when ignored and a clean `git status` is not enough; it asks Git only for `HEAD` to record the revision, and the source is not saved for later runs.
13
14
  - Never merge, overwrite or remove project context (repository documentation, `.cratis/ai/rules/project.md`, local bootstraps, user prompts) while installing, updating, rolling back or uninstalling, and never delete a project-owned prompt because an old corpus supplied one.
14
15
  - Treat `mcp-servers.json` as launch capability, not permission: enable an optional server only once authorized, and opt out with `mcpServers.<id>.enabled: false` in `.cratis/ai.json`.
15
16
  - Audit by reporting missing, stale, modified and dangling paths separately with the smallest repair, and change nothing unless asked; never remove user-owned or legacy adapters as a side effect of a canary.
@@ -14,7 +14,7 @@ paths:
14
14
  An exit code is the verdict; a wrapper that loses it turns a red run green.
15
15
 
16
16
  - Exit our checkers `0` for ran clean, `1` for found defects and `2` for could not run, and report `2` as "not run", never as clean or as defects. Interpret an external tool by its documented codes; never map failure, interruption or unknown to success.
17
- - Preserve the child's status before filtering output: `pipefail`, or `PIPESTATUS` captured immediately, in Bash; `$LASTEXITCODE` immediately after a native command in PowerShell. Accumulate failures across a loop instead of trusting its last iteration.
17
+ - Preserve the child's status before filtering output: `pipefail`, or `PIPESTATUS` captured immediately, in Bash; `$LASTEXITCODE` immediately after a native command in PowerShell. Accumulate failures across a loop instead of trusting its last iteration. Under `-e` (GitHub Actions' `shell: bash` enables `errexit` and `pipefail`, and `set -uo pipefail` does not turn it off), capture an external command's code with `status=0; tool || status=$?` before branching on it, because a failing `tool; status=$?` exits before the capture. Bash ignores `-e` inside a function or compound command on the left of `||`, so such a wrapper must propagate each failure explicitly or a failed step falls through to a later success and reads as `0`: `step || return $?` inside a function, `( step || exit $?; … ) || status=$?` for a subshell group.
18
18
  - Ship a `--self-test` that plants known violations and fails unless it detects every one, because a checker that cannot fail proves nothing (non-vacuity: `guards-and-fuses`).
19
19
  - Never add `|| true`, discard stderr or swallow an error to quiet a gate, because that silently stops checking.
20
20
  - Keep wrappers thin and name the failing subject (path, id, rule) in the failure line, so the failure is actionable without a rerun.
@@ -15,8 +15,9 @@ paths:
15
15
 
16
16
  # Scripts and tooling
17
17
 
18
+ - These rules choose the language of scripts and tooling you add to a repository. When asked to fix an existing script, workflow step or snippet, fix it in its own language and do not rewrite it in another language unless asked, because the person asked for that script. The only exception is porting Python that is not part of a Python package, including inline Python in a shell step, described below. In Bash, check exit codes explicitly; use strict mode (`set -euo pipefail`) only where it keeps the script's intended behaviour, and do not change the caller's shell options in sourced or interactive snippets.
18
19
  - Write repository scripts, CI helpers and tooling in Node with only `node:` built-ins (`.mjs`, or `.ts` limited to erasable syntax: no enums or parameter properties), because Node and the .NET SDK are the only runtimes every Cratis build machine and runner has.
19
20
  - Use a C# file-based app (`dotnet run --file tool.cs`, pinned `#:package`) only when the script needs .NET, Cratis libraries or product types, and never in hooks or per-call hot paths, because of its startup cost.
20
21
  - Write hooks under `.cratis/ai/hooks` in Bash 3.2-compatible shell or Node, because macOS ships Bash 3.2. Read a hook's small stdin payload with `IFS= read -r -d '' x || true`, not `$(</dev/stdin)`.
21
- - Add no Python scripts or `python3` workflow steps unless the project itself is Python; port an existing Python script to Node in the change that substantially edits it.
22
+ - Add no Python scripts or `python`/`python3` workflow steps except in a Python package and its build tooling, such as a Python client package and the steps that generate, test and publish it, even when the rest of the repository is not Python. Keep a Python package's existing Python scripts in Python and its existing shell steps in shell unless asked to rewrite them. Port any other existing Python script to Node in the change that substantially edits it. This includes inline Python in a shell step: port only the inline Python and leave the surrounding shell as it is.
22
23
  - As an agent, edit files with the edit or write tools, query JSON with `gh --jq` or `jq`, and run ad-hoc logic with `node -e` or `node --input-type=module`. Never use `python3 -c` or rewrite files by script, because a scripted rewrite escapes per-edit review.
@@ -391,7 +391,7 @@ lsof_matches() {
391
391
  /^f./ { kind = substr($0, 2); type = ""; next }
392
392
  /^t./ { type = substr($0, 2); next }
393
393
  /^n/ {
394
- seen_name = 1; path = substr($0, 2)
394
+ seen_name = 1; path = substr($0, 2); name = path
395
395
  if (ignored || path == "(revoked)") next
396
396
  # A diagnostic suffix can follow the target directory itself, not just a child path.
397
397
  sub(/ (\(stat:|\(FD info error:|FD info error:).*/, "", path)
@@ -414,6 +414,10 @@ lsof_matches() {
414
414
  if (path ~ /^(anon_inode:)?\[[[:alnum:]_]+(:[0-9]+(,[0-9]+)*)?\]$/) next
415
415
  # lsof truncates long names, leaving a digit/comma list ending in `...` with no closing bracket.
416
416
  if (path ~ /^(anon_inode:)?\[[[:alnum:]_]+:[0-9,]*\.\.\.$/) next
417
+ # Some lsof builds keep the closing bracket after the ellipsis. Only an a_inode record qualifies,
418
+ # because a Unix socket can be bound to that literal file name, and the unstripped name must
419
+ # match, so no diagnostic suffix can hide behind it.
420
+ if (type == "a_inode" && name ~ /^(anon_inode:)?\[[[:alnum:]_]+:[0-9,]*\.\.\.\]$/) next
417
421
  if (type == "a_inode" && path ~ /^(anon_inode:)?[[:alnum:]_]+$/) next
418
422
  if (type == "unix" && path ~ /^type=[[:upper:]]+( \([[:upper:]]+\))?$/) next
419
423
  if (type == "netlink" && path ~ /^[[:upper:]_]+$/) next
@@ -117,7 +117,7 @@ linked_targets_word() {
117
117
  }
118
118
  unset CDPATH
119
119
  cwd_available=1
120
- cd -- "$1" 2>/dev/null || cwd_available=0
120
+ cd -P -- "$1" 2>/dev/null || cwd_available=0
121
121
  physical_cwd="$(pwd -P && printf '.')" || { printf 'E\n'; exit 0; }
122
122
  physical_cwd="${physical_cwd%$'\n.'}"
123
123
  if [ "$cwd_available" = 0 ]; then
@@ -200,6 +200,12 @@ function enqueue(text, k) {
200
200
  queue[++queued] = text
201
201
  QUEUE_COUNT[queued] = ncd
202
202
  for (k = 1; k <= ncd; k++) QUEUE_DIR[queued, k] = cwd_at(k)
203
+ for (k = 1; k <= nlink_possible; k++) QUEUE_LINK[queued, k] = wrapped_link_dir(LINK_POSSIBLE[k])
204
+ QUEUE_LINKS[queued] = nlink_possible
205
+ }
206
+ function wrapped_link_dir(dir, j) {
207
+ for (j = 1; j <= nwrap; j++) dir = literal_directory(WRAP_DIR[j], dir)
208
+ return dir
203
209
  }
204
210
  function base(word) { word = tolower(word); sub(/.*\//, "", word); return word }
205
211
 
@@ -778,9 +784,108 @@ function nonreader(A, M, n, i, w, first, read, nexti) {
778
784
  }
779
785
  return 1
780
786
  }
781
- function check_links(A, n, k, cmd, line, kind) {
787
+ # Relative operands resolve against every directory the command may run in. A cd or pushd that
788
+ # fails leaves the shell where it was, so every directory reached so far stays a candidate. The
789
+ # candidates are tracked lexically, as the shell's logical cd does; a physical directory change
790
+ # (cd -P, set -P, an env -C value with ..) can diverge from that, so it is not modeled but refused.
791
+ function add_link_dir(dir) {
792
+ if (dir !~ /^\// || (dir in LINK_SEEN)) return
793
+ if (nlink_dir >= 17) { link_overflow = 1; return }
794
+ LINK_SEEN[dir] = 1; LINK_DIR[++nlink_dir] = dir
795
+ }
796
+ function add_link_candidate(CAND, CAND_SEEN, count, dir) {
797
+ if (dir in CAND_SEEN) return count
798
+ if (count >= 16) { link_candidates_overflow = 1; return count }
799
+ CAND_SEEN[dir] = 1; CAND[++count] = dir
800
+ return count
801
+ }
802
+ function note_link_wrap(w) {
803
+ LINK_WRAP[++nlink_wrap] = w
804
+ if (w ~ /(^|\/)\.\.(\/|$)/) link_physical = 1
805
+ }
806
+ function note_link_dirs( d) {
807
+ for (d = 1; d <= ncd; d++) add_link_dir(CWD[d])
808
+ for (d = 1; d <= nlink_possible; d++) add_link_dir(LINK_POSSIBLE[d])
809
+ nlink_wrap = 0
810
+ }
811
+ # The first unquoted redirection operator in a word (set LINK_OP_AT and LINK_OP_LEN); quoted characters
812
+ # before it, such as a quoted digit, stay a separate argument while the operator still redirects.
813
+ function link_operator(w, m, i, c) {
814
+ if (length(m) != length(w)) return 0
815
+ for (i = 1; i <= length(w); i++) {
816
+ c = substr(w, i, 1)
817
+ if ((c != "<" && c != ">" && c != "&") || tolower(substr(m, i, 1)) != "u") continue
818
+ if (!match(substr(w, i), /^(<>|>>|>\||&>>|&>|<|>)/)) continue
819
+ if (tolower(substr(m, i, RLENGTH)) !~ /^u+$/) continue
820
+ LINK_OP_AT = i; LINK_OP_LEN = RLENGTH
821
+ return 1
822
+ }
823
+ return 0
824
+ }
825
+ function add_link_word(OP, ABS, nop, w) {
826
+ if (relative_link_word(w)) OP[++nop] = w
827
+ else ABS[++ABS[0]] = w
828
+ return nop
829
+ }
830
+ function relative_link_word(w) {
831
+ if (w ~ /^--/) return 0
832
+ if (w ~ /^-./) w = substr(w, 3)
833
+ return w != "" && w !~ /^\//
834
+ }
835
+ # Redirections open in the caller's directory before env changes it, so they resolve against the
836
+ # directories reached so far. Command operands resolve where the command runs: with env -C, each
837
+ # value on its own and the chain, since implementations differ on whether repeated values chain or
838
+ # the last one wins. Absolute operands resolve the same everywhere and are checked once.
839
+ function check_links(A, n, d, j, k, w, m, before, pending_redirect, chained, nabs, nop, nredir, ABS, OP, REDIR, ncall, CALLER, CALLER_SEEN, nrun, RUN, RUN_SEEN) {
782
840
  if (ENVIRON["GS_CWD"] == "") return
783
- cmd = "bash -c " shell_quote(ENVIRON["GS_LINK_PROGRAM"]) " guard-links " shell_quote(ENVIRON["GS_CWD"])
841
+ # A plain command name is found on PATH, not in the working directory. Every other word is an
842
+ # operand of the run directory; one that follows an unquoted redirection operator is opened by
843
+ # the shell in the caller's directory as well.
844
+ k = (A[1] ~ /^[[:alnum:]_.+-]+$/ && A[1] !~ /^-/) ? 2 : 1
845
+ for (; k <= n; k++) {
846
+ nop = add_link_word(OP, ABS, nop, A[k])
847
+ if (k > 1 && pending_redirect && relative_link_word(A[k])) REDIR[++nredir] = A[k]
848
+ pending_redirect = 0
849
+ # Split the word at each unquoted operator: the text before it is an argument (or a file
850
+ # descriptor), the text after it is opened by the shell in the caller's directory.
851
+ w = A[k]; m = WM[k]
852
+ while (link_operator(w, m)) {
853
+ before = substr(w, 1, LINK_OP_AT - 1)
854
+ if (before != "" && before !~ /^[0-9]+$/) nop = add_link_word(OP, ABS, nop, before)
855
+ w = substr(w, LINK_OP_AT + LINK_OP_LEN); m = substr(m, LINK_OP_AT + LINK_OP_LEN)
856
+ if (w == "") { pending_redirect = 1; break }
857
+ nop = add_link_word(OP, ABS, nop, w)
858
+ if (relative_link_word(w)) REDIR[++nredir] = w
859
+ }
860
+ }
861
+ nabs = ABS[0] + 0; delete ABS[0]
862
+ if (nabs > 0) check_links_in(ABS, nabs, LINK_DIR[1])
863
+ if (nop + nredir == 0) return
864
+ if (link_physical) {
865
+ report("a physical directory change hides where symbolic links resolve", "run the read from its own directory with literal paths, without cd -P, set -P or env -C ..")
866
+ return
867
+ }
868
+ link_candidates_overflow = link_overflow
869
+ for (d = 1; d <= nlink_dir && !link_candidates_overflow; d++) {
870
+ if (nredir > 0) ncall = add_link_candidate(CALLER, CALLER_SEEN, ncall, LINK_DIR[d])
871
+ if (nop == 0) continue
872
+ if (nlink_wrap == 0) { nrun = add_link_candidate(RUN, RUN_SEEN, nrun, LINK_DIR[d]); continue }
873
+ chained = LINK_DIR[d]
874
+ for (j = 1; j <= nlink_wrap; j++) {
875
+ nrun = add_link_candidate(RUN, RUN_SEEN, nrun, literal_directory(LINK_WRAP[j], LINK_DIR[d]))
876
+ chained = literal_directory(LINK_WRAP[j], chained)
877
+ nrun = add_link_candidate(RUN, RUN_SEEN, nrun, chained)
878
+ }
879
+ }
880
+ if (link_candidates_overflow) {
881
+ report("too many possible working directories to check symbolic links", "run the read from its own directory with literal paths, without chained cd, pushd or env -C")
882
+ return
883
+ }
884
+ for (d = 1; d <= ncall; d++) check_links_in(REDIR, nredir, CALLER[d])
885
+ for (d = 1; d <= nrun; d++) check_links_in(OP, nop, RUN[d])
886
+ }
887
+ function check_links_in(A, n, dir, k, cmd, line, kind) {
888
+ cmd = "bash -c " shell_quote(ENVIRON["GS_LINK_PROGRAM"]) " guard-links " shell_quote(dir)
784
889
  for (k = 1; k <= n; k++) cmd = cmd " " shell_quote(A[k])
785
890
  while ((cmd | getline line) > 0) {
786
891
  kind = substr(line, 1, 2) == "P:" ? sensitive_path(substr(line, 3)) : "an unresolved link target"
@@ -791,7 +896,7 @@ function check_links(A, n, k, cmd, line, kind) {
791
896
  function end_cmd( k, m, w, j, hit, exempt, path_git, paths_only, test_filter) {
792
897
  flush_word()
793
898
  if (nw > 0) {
794
- check_links(W, nw)
899
+ note_link_dirs()
795
900
  commands++
796
901
  delete PROBE_WORDS; PROBE_COUNT = nw
797
902
  for (k = 1; k <= nw; k++) PROBE_WORDS[k] = W[k]
@@ -839,6 +944,7 @@ function end_cmd( k, m, w, j, hit, exempt, path_git, paths_only, test_filter)
839
944
  V[++m] = w; VM[m] = WM[k]; VT[m] = WT[k]
840
945
  }
841
946
  if (m > 0) { check_inputs(V, 1, m); analyze(V, 1, m) }
947
+ if (nw > 0) check_links(W, nw)
842
948
  nwrap = 0
843
949
  delete W; delete WP; delete WM; delete WU; delete WT; delete V; delete VM; delete VT; nw = 0
844
950
  }
@@ -946,6 +1052,8 @@ function read_heredocs(s, i, n, h, e, line, cmp, body) {
946
1052
  function tokenize(s, i, n, c, c2, j, dash, delim) {
947
1053
  delete CWD; ncd = QUEUE_COUNT[qi]
948
1054
  for (i = 1; i <= ncd; i++) CWD[i] = QUEUE_DIR[qi, i]
1055
+ for (i = 1; i <= ncd; i++) add_link_possible(CWD[i])
1056
+ for (i = 1; i <= QUEUE_LINKS[qi]; i++) add_link_possible(QUEUE_LINK[qi, i])
949
1057
  effective_dir = CWD[1]; cwd_depth = 0; cwd_conditional = 0; nwrap = 0
950
1058
  clear_pipeline(); pipe_input = 0; filter_compound = 0
951
1059
  n = length(s); i = 1; nw = 0; word = ""; wmask = ""; inword = 0; wquoted = 0; wplain = 0; wunquoted = 0; wtranslated = 0; nheredoc = 0; hd_shell = 0; hd_interp = 0; quote_boundary = 0
@@ -2016,16 +2124,28 @@ function pop_cwd_scope( k) {
2016
2124
  function change_directory(A, s, n, b, k, j, w, dir, count, nextdir, seen) {
2017
2125
  if (b == "popd") return
2018
2126
  k = s + 1
2019
- while (k <= n && A[k] ~ /^(-[LP]|--)$/) k++
2127
+ while (k <= n && A[k] ~ /^-[[:alnum:]@]+$/ && A[k] !~ /^-[0-9]+$/) { if (A[k] !~ /^-[L]+$/) link_physical = 1; k++ }
2128
+ if (k <= n && A[k] == "--") k++
2020
2129
  w = k <= n ? A[k] : ENVIRON["HOME"]
2130
+ if (w !~ /^(\/|\.\.?(\/|$)|~|[-+])/ && (ENVIRON["CDPATH"] != "" || cdpath_set)) link_physical = 1
2021
2131
  for (k = 1; k <= ncd; k++) {
2022
2132
  if (cwd_conditional && !(CWD[k] in seen)) { seen[CWD[k]] = 1; nextdir[++count] = CWD[k] }
2023
2133
  dir = literal_directory(w, CWD[k])
2024
2134
  if (!(dir in seen)) { seen[dir] = 1; nextdir[++count] = dir }
2135
+ if (count >= 64) { report("too many possible working directories", "run the command from its own directory without chained cd or pushd"); break }
2025
2136
  }
2026
2137
  delete CWD; ncd = count
2027
2138
  for (j = 1; j <= ncd; j++) CWD[j] = nextdir[j]
2028
2139
  effective_dir = CWD[1]
2140
+ count = nlink_possible
2141
+ for (k = 1; k <= count; k++) add_link_possible(literal_directory(w, LINK_POSSIBLE[k]))
2142
+ }
2143
+ # Any cd or pushd may fail and leave the shell where it was, so every combination of the
2144
+ # changes so far is a directory a later read may run in.
2145
+ function add_link_possible(dir) {
2146
+ if (dir in LINK_POSSIBLE_SEEN) return
2147
+ if (nlink_possible >= 17) { link_overflow = 1; return }
2148
+ LINK_POSSIBLE_SEEN[dir] = 1; LINK_POSSIBLE[++nlink_possible] = dir
2029
2149
  }
2030
2150
  function clear_pipeline() {
2031
2151
  if (cwd_depth > 0 && PIPE_SCOPE[cwd_depth]) return
@@ -2314,9 +2434,9 @@ function analyze(A, s, n, w, b, k, names, p, config, get, show, first) {
2314
2434
  w = A[s]
2315
2435
  if (is_assign(w)) { if (protected_config(w)) config_report(); s++ }
2316
2436
  else if (w ~ /^[0-9]*[<>]/) s += (w ~ /^[0-9]*[<>]+&?-?$/) ? 2 : 1
2317
- else if (w == "-C" || w == "--chdir") { WRAP_DIR[++nwrap] = A[s + 1]; s += 2 }
2318
- else if (w ~ /^--chdir=/) { WRAP_DIR[++nwrap] = substr(w, 9); s++ }
2319
- else if (w ~ /^-C./) { WRAP_DIR[++nwrap] = substr(w, 3); s++ }
2437
+ else if (w == "-C" || w == "--chdir") { WRAP_DIR[++nwrap] = A[s + 1]; note_link_wrap(A[s + 1]); s += 2 }
2438
+ else if (w ~ /^--chdir=/) { WRAP_DIR[++nwrap] = substr(w, 9); note_link_wrap(substr(w, 9)); s++ }
2439
+ else if (w ~ /^-C./) { WRAP_DIR[++nwrap] = substr(w, 3); note_link_wrap(substr(w, 3)); s++ }
2320
2440
  else if (w == "-u" || w == "-S" || w == "--unset" || w == "--split-string") s += 2
2321
2441
  else if (substr(w, 1, 1) == "-") s++
2322
2442
  else break
@@ -2433,8 +2553,10 @@ BEGIN {
2433
2553
  nstem = split(".env .pem .key .p12 .pfx .jks .keystore .kdbx id_rsa id_ed25519 id_ecdsa id_dsa .netrc .npmrc .pgpass .pypirc .git-credentials .kube/ kubeconfig credentials credential secrets.yaml secrets.yml .docker/ /environ run/secrets", STEM, " ")
2434
2554
  CMD = ENVIRON["GS_COMMAND"]
2435
2555
  for (pass = 1; pass <= 2; pass++) {
2436
- delete queue; delete QUEUE_DIR; delete QUEUE_COUNT; queued = 0; qi = 0; delete seen; reports = ""
2556
+ delete queue; delete QUEUE_DIR; delete QUEUE_COUNT; delete QUEUE_LINK; delete QUEUE_LINKS; queued = 0; qi = 0; delete seen; reports = ""
2437
2557
  delete CWD; ncd = 1; nwrap = 0; CWD[1] = ENVIRON["GS_CWD_FALLBACK"]; effective_dir = CWD[1]
2558
+ delete LINK_DIR; delete LINK_SEEN; nlink_dir = 0; nlink_wrap = 0
2559
+ delete LINK_POSSIBLE; delete LINK_POSSIBLE_SEEN; nlink_possible = 0; link_overflow = 0; link_physical = 0; cdpath_set = CMD ~ /CDPATH=/ || CMD ~ /(export|declare|typeset|readonly|local|read|printf[ \t]+-v)[^;&|\n]*CDPATH/; add_link_possible(CWD[1])
2438
2560
  nheredoc = 0; hd_shell = 0; hd_interp = 0; INLINE = 0; INLINE_HIT = interpreter_hit(CMD) != ""; commands = 0; complex = 0; simple_ok = 1; TAINT = ""
2439
2561
  enqueue(CMD)
2440
2562
  while (qi < queued) { qi++; tokenize(queue[qi]) }
@@ -8,7 +8,8 @@ paths:
8
8
 
9
9
  - Author shared corpus changes in `Cratis/AI`, generalized and free of private facts; never copy one consumer's `.cratis/ai` or native assistant folders into another repository, and keep consumer settings, private skills and repository knowledge local.
10
10
  - Never hand-edit installed managed files, generated adapters or a marketplace wrapper, because the next update overwrites or flags them; install, update, roll back and remove through the channel that installed them (`cratis ai install`, `update`, `uninstall`), previewing with `--dry-run`.
11
- - Use `cratis ai update --force` only after reviewing the modified managed files it will overwrite; `cratis ai status` exits nonzero when a managed file was modified, so CI can gate on it.
11
+ - Use `cratis ai update --force` only after reviewing the modified managed files it will overwrite; `cratis ai status` exits nonzero when a managed file was modified, so CI can gate on it. In CI, install a pinned `Cratis.Cli` .NET tool with a .NET SDK that supports the package's target framework (currently .NET 11), with the .NET and ASP.NET Core runtimes it needs; a runtime-only image cannot run `dotnet tool install`. On macOS or Linux (x64 or arm64) you can instead use the matching pinned, self-contained native release binary, which needs no .NET runtime; there is no native Windows binary.
12
+ - When stdin is redirected, pass `--profiles` and `--harnesses` to `cratis ai install` (`--languages` is optional), or it exits 5 before downloading the corpus. `cratis ai update` takes no selection options and reuses `.cratis/ai.json`; run `install` again to change the selection. Both take whatever the corpus source currently holds and the installed revision pins nothing; to reproduce a reviewed revision, point `--source` or `CRATIS_AI_SOURCE` at a fresh, full `Cratis/AI` checkout of that commit with no extra files, including ignored ones such as a `.env`, and supply it on every run. The CLI reads the selected corpus files from disk, not from Git's tracked tree, so extra files in selected directories are installed even when ignored and a clean `git status` is not enough; it asks Git only for `HEAD` to record the revision, and the source is not saved for later runs.
12
13
  - Never merge, overwrite or remove project context (repository documentation, `.cratis/ai/rules/project.md`, local bootstraps, user prompts) while installing, updating, rolling back or uninstalling, and never delete a project-owned prompt because an old corpus supplied one.
13
14
  - Treat `mcp-servers.json` as launch capability, not permission: enable an optional server only once authorized, and opt out with `mcpServers.<id>.enabled: false` in `.cratis/ai.json`.
14
15
  - Audit by reporting missing, stale, modified and dangling paths separately with the smallest repair, and change nothing unless asked; never remove user-owned or legacy adapters as a side effect of a canary.
@@ -13,7 +13,7 @@ paths:
13
13
  An exit code is the verdict; a wrapper that loses it turns a red run green.
14
14
 
15
15
  - Exit our checkers `0` for ran clean, `1` for found defects and `2` for could not run, and report `2` as "not run", never as clean or as defects. Interpret an external tool by its documented codes; never map failure, interruption or unknown to success.
16
- - Preserve the child's status before filtering output: `pipefail`, or `PIPESTATUS` captured immediately, in Bash; `$LASTEXITCODE` immediately after a native command in PowerShell. Accumulate failures across a loop instead of trusting its last iteration.
16
+ - Preserve the child's status before filtering output: `pipefail`, or `PIPESTATUS` captured immediately, in Bash; `$LASTEXITCODE` immediately after a native command in PowerShell. Accumulate failures across a loop instead of trusting its last iteration. Under `-e` (GitHub Actions' `shell: bash` enables `errexit` and `pipefail`, and `set -uo pipefail` does not turn it off), capture an external command's code with `status=0; tool || status=$?` before branching on it, because a failing `tool; status=$?` exits before the capture. Bash ignores `-e` inside a function or compound command on the left of `||`, so such a wrapper must propagate each failure explicitly or a failed step falls through to a later success and reads as `0`: `step || return $?` inside a function, `( step || exit $?; … ) || status=$?` for a subshell group.
17
17
  - Ship a `--self-test` that plants known violations and fails unless it detects every one, because a checker that cannot fail proves nothing (non-vacuity: `guards-and-fuses`).
18
18
  - Never add `|| true`, discard stderr or swallow an error to quiet a gate, because that silently stops checking.
19
19
  - Keep wrappers thin and name the failing subject (path, id, rule) in the failure line, so the failure is actionable without a rerun.
@@ -14,8 +14,9 @@ paths:
14
14
 
15
15
  # Scripts and tooling
16
16
 
17
+ - These rules choose the language of scripts and tooling you add to a repository. When asked to fix an existing script, workflow step or snippet, fix it in its own language and do not rewrite it in another language unless asked, because the person asked for that script. The only exception is porting Python that is not part of a Python package, including inline Python in a shell step, described below. In Bash, check exit codes explicitly; use strict mode (`set -euo pipefail`) only where it keeps the script's intended behaviour, and do not change the caller's shell options in sourced or interactive snippets.
17
18
  - Write repository scripts, CI helpers and tooling in Node with only `node:` built-ins (`.mjs`, or `.ts` limited to erasable syntax: no enums or parameter properties), because Node and the .NET SDK are the only runtimes every Cratis build machine and runner has.
18
19
  - Use a C# file-based app (`dotnet run --file tool.cs`, pinned `#:package`) only when the script needs .NET, Cratis libraries or product types, and never in hooks or per-call hot paths, because of its startup cost.
19
20
  - Write hooks under `.cratis/ai/hooks` in Bash 3.2-compatible shell or Node, because macOS ships Bash 3.2. Read a hook's small stdin payload with `IFS= read -r -d '' x || true`, not `$(</dev/stdin)`.
20
- - Add no Python scripts or `python3` workflow steps unless the project itself is Python; port an existing Python script to Node in the change that substantially edits it.
21
+ - Add no Python scripts or `python`/`python3` workflow steps except in a Python package and its build tooling, such as a Python client package and the steps that generate, test and publish it, even when the rest of the repository is not Python. Keep a Python package's existing Python scripts in Python and its existing shell steps in shell unless asked to rewrite them. Port any other existing Python script to Node in the change that substantially edits it. This includes inline Python in a shell step: port only the inline Python and leave the surrounding shell as it is.
21
22
  - As an agent, edit files with the edit or write tools, query JSON with `gh --jq` or `jq`, and run ad-hoc logic with `node -e` or `node --input-type=module`. Never use `python3 -c` or rewrite files by script, because a scripted rewrite escapes per-edit review.
@@ -34,7 +34,7 @@
34
34
  | Job type | simple type name | no | yes | `[JobType("name")]` |
35
35
  | Convention DI binding | `IName`→`Name` in the same namespace | breaks if the pair splits | breaks | keep the pair together or register explicitly |
36
36
 
37
- The observer ID, read-model identifier and container are independent. When the full model type name must change, plan the new definition and verify the successor against historical events and the chosen sink. Full-set registration can retire the old projection across namespaces without deleting its data. A successor projection sharing the container can get a replay recommendation; apply and verify the replay as needed. Do not expect this to rebuild a successor reducer. For an intentional container-only change, coordinate readers/writers and explicitly update the definition (`UpdateDefinition` in Workbench when saving an existing model); deploy matching declarations. This changes routing metadata, not rows or table names. Ordinary registration refuses a different container for the same identifier (even a case-only change or new generation), and clients declaring the old container after the update are refused too. Migrate/rebuild separately before cutting readers over.
37
+ The observer ID, read-model identifier and container are independent. When the full model type name must change, plan the new definition and verify the successor against historical events and the chosen sink. Full-set registration can retire the old projection across namespaces without deleting its data. A successor projection sharing the container can get a replay recommendation; apply and verify the replay as needed. Do not expect this to rebuild a successor reducer. For an intentional container-only change, coordinate readers/writers and explicitly update the definition (`UpdateDefinition` in Workbench when saving an existing model); deploy matching declarations. This changes routing metadata, not rows or table names. Ordinary registration refuses a different container for the same identifier with `FailedPrecondition`, even when the names differ only in case (such as after switching naming policy). If any container conflicts, Chronicle rejects the entire read-model registration batch before applying any of its definitions, so none of them is registered or updated. Dropping or renaming collections does not help: the check compares against the stored definition. Clients declaring the old container after the update are refused too. Migrate/rebuild separately before cutting readers over.
38
38
 
39
39
  ## Identity pinning
40
40
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: cratis-arc-authorize-request
3
- description: Use when restricting who may execute an Arc command or query on the server, including writing a custom authorization policy or a command/query filter that denies a request, or a rule that depends on who acts on behalf of a user. Not for selecting a tenant (use cratis-arc-isolate-tenant).
3
+ description: Use when restricting who may execute an Arc command or query on the server, including writing a custom authorization policy or a command/query filter that denies a request, a rule that depends on who acts on behalf of a user, or configuring what Cratis AuthProxy admits (identity verification, bearer routes, anonymous paths, a sign-in shared across hosts). Not for selecting a tenant (use cratis-arc-isolate-tenant).
4
4
  compatibility: Requires an Arc backend with a trusted source of caller identity.
5
5
  ---
6
6
 
@@ -10,13 +10,13 @@ Authorization decides whether the caller may invoke an operation. Authentication
10
10
 
11
11
  Read `references/<language>.md` for the project's SDK (`.csproj` → csharp, Node server `package.json` → typescript, `*.kt` → kotlin, `*.java` → java, `go.mod` → go, `mix.exs` → elixir); only the project's languages are installed.
12
12
 
13
- When the application runs behind Cratis AuthProxy, read [who authenticates what](references/authproxy.md) before opening a path to anonymous or token-bearing callers.
13
+ When the application runs behind Cratis AuthProxy, read [who authenticates what](references/authproxy.md) before opening a path to anonymous or token-bearing callers, changing how a service takes part in identity verification, or sharing a sign-in across hosts.
14
14
 
15
15
  ## Default path: require sign-in on the operation
16
16
 
17
17
  1. Verify that the host supplies an authenticated principal for a real credential and does not accept a caller's assertion of identity. If it cannot distinguish that credential from an anonymous request, fix authentication first.
18
18
  2. Declare sign-in on the command or query, not inside its handler. For example, a shift-swap request (names are illustrative) might be open to any signed-in employee **if** the host authenticates only employees. If other callers can sign in, declare the employee role instead. Apply the requirement to the read model only when its queries share the same rule.
19
- 3. Exercise the server pipeline with and without the credential. The denied request must not mutate state, append events or reveal protected rows. For a role or policy, also try a signed-in caller who fails it. Inspect the authorization verdict: an HTTP challenge at the host and an Arc denial need not have the same status. A direct handler test exercises neither gate.
19
+ 3. Exercise the server pipeline with and without the credential. The denied request must not mutate state, append events or reveal protected rows. For a role or policy, also try a signed-in caller who fails it. Repeat each case on every transport that reaches the operation (such as direct HTTP, WebSocket and the live-query hub), because they can pass different gates. Inspect the authorization verdict: an HTTP challenge at the host and an Arc denial need not have the same status. A direct handler test exercises neither gate.
20
20
 
21
21
  ## Capability catalog
22
22
 
@@ -1,13 +1,24 @@
1
1
  # Behind Cratis AuthProxy: who authenticates what
2
2
 
3
+ ## Contents
4
+
5
+ - The boundary
6
+ - Choose how a path is admitted
7
+ - Bearer routes
8
+ - Anonymous paths
9
+ - Sign-in providers
10
+ - Sessions across tenant hosts
11
+ - Verify
12
+
3
13
  Read this when the application is deployed behind Cratis AuthProxy. It is deployment configuration under `Cratis:AuthProxy:Services:<service>` and applies to every backend language. Names below are illustrative.
4
14
 
5
15
  ## The boundary
6
16
 
7
17
  - AuthProxy decides who the caller is before the request reaches the application. The application trusts the principal and tenant AuthProxy forwards and authorizes that identity; it does not check passwords, session cookies or issuer tokens itself. The one exception is a personal access token, which AuthProxy passes on unverified (see Bearer routes).
8
18
  - The boundary holds only when nothing reaches the application around AuthProxy. Restrict the application's listener to the proxy at the network level. AuthProxy removes caller-supplied identity and tenant headers and writes its own; a route that bypasses it does neither.
9
- - Forwarded identity is not authorization. The application still declares sign-in, roles and policies on each operation and still checks tenant membership.
19
+ - Forwarded identity is not authorization. The application still declares sign-in, roles and policies on each operation and must still check tenant membership on tenant-scoped operations.
10
20
  - Identity verification is `Required` by default for a service with a `Backend`: after sign-in AuthProxy asks the application's `/.cratis/me` and admits a browser caller only on an explicit positive verdict. A refusal, an error, a timeout or an answer without a verdict denies. The application must therefore answer that endpoint with whether this person may use it.
21
+ - To take a service out of verification, set `ResolveIdentityDetails: false` on it, for example a static-file server that cannot answer `/.cratis/me`: AuthProxy then skips only that service's `/.cratis/me`; every other participating service is still asked and can still deny. The supported `IdentityVerification` modes are `Required` (default) and `BestEffort`. A `BestEffort` service causes a denial only when it answers 403, or when AuthProxy is configured to sign the call to it and cannot sign it. A 200 that says "not authorized", an error, a timeout or an unreachable service causes no denial from that service, but another service or a later gate can still deny the request. Use it only for a service that merely adds display details, never for the service that decides who may enter.
11
22
 
12
23
  ## Choose how a path is admitted
13
24
 
@@ -83,14 +94,28 @@ Declare the identity providers in one place only. For a Screenplay deployment, l
83
94
 
84
95
  ## Sessions across tenant hosts
85
96
 
86
- `Session:CookieDomain` shares one sign-in across hosts under a parent domain. It cannot be combined with `SubHost` tenant resolution: AuthProxy refuses to start, because one session would then be valid on every tenant's host. With a tenant per sub-host, leave `CookieDomain` empty so each tenant host keeps its own session.
97
+ `Session:CookieDomain` shares one sign-in across hosts under a parent domain. With `SubHost` tenant resolution AuthProxy refuses to start, and no setting overrides that: the host-only session cookie is what keeps one tenant's session off the next tenant's host, and AuthProxy's tenant verification only confirms that the tenant exists, not that the person belongs to it. Choose one:
98
+
99
+ - Keep `SubHost` and leave `CookieDomain` empty, so each tenant host signs in separately.
100
+ - Resolve tenants another way, such as the `Claim` strategy, and then set the cookie domain.
101
+
102
+ With a cookie domain:
103
+
104
+ - Use the narrowest domain that covers every service host. AuthProxy refuses to start when a host listed in a service's `Hosts` is outside it, or when the domain is an IP address, a top-level domain, a wildcard or has a port.
105
+ - `SameSite=Lax` does not separate sibling subdomains, so treat every host under the domain as one trust boundary.
106
+
107
+ Cookie scope only decides what a browser sends. AuthProxy does not bind a session to a host, so a session cookie copied to another host of the same AuthProxy still authenticates there, with or without a cookie domain. Authenticating does not grant that host's tenant; separate gates decide that:
108
+
109
+ - **Credential binding:** a session bound to another tenant, through a bound tenant-selection cookie or a `Claim` tenant, is refused with 403 before any membership lookup, even for a member of both tenants.
110
+ - **Membership confirmation:** when `Selection` is configured, AuthProxy confirms through the tenants endpoint that the person belongs to a tenant addressed by `Host`, `SubHost` or `Route`, and trusts that confirmation until `Session:TenantRevalidationInterval` passes. A zero or negative interval remembers nothing: AuthProxy skips the check only for a request carrying a bound tenant-selection cookie for that tenant, and confirmation of a `Route` tenant does not issue one, so without it AuthProxy checks membership again. Without `Selection`, AuthProxy leaves membership to the application.
111
+ - **The application:** it must enforce tenant membership on every tenant-scoped operation; Arc's sign-in and role checks do not do that.
87
112
 
88
113
  ## Verify
89
114
 
90
115
  1. Without a credential, a bearer-route path answers 401 and an ordinary path does not reach the application.
91
116
  2. An issuer token for another tenant, or one missing a required scope, is refused before the application.
92
117
  3. Forged `x-cratis-tenant-id` and `x-ms-client-principal*` values never survive. On an authenticated request the application sees AuthProxy's values, not the forged ones. On an anonymous path, and on a personal-access-token request, it sees none of these headers.
93
- 4. A browser caller for whom `/.cratis/me` answers "not authorized", or does not answer, is not admitted.
118
+ 4. For a service with `Required` verification, a browser caller whose fresh `/.cratis/me` check answers "not authorized", or gets no answer, is not admitted. A remembered positive answer skips the fresh check only for the same account and tenant, while the set of `Required` services is unchanged and the answer has not expired. Every other gate still applies.
94
119
  5. On a route that accepts personal access tokens, the application refuses a well-formed but unknown or revoked token, and a valid token used for another tenant.
95
120
  6. A request that skips the proxy cannot reach the application's listener.
96
121
  7. No path that serves a credential-bearing endpoint appears in `AnonymousPaths`, and none appears in `PassCallerAuthorizationPaths` unless the application authenticates that credential itself.
@@ -31,15 +31,15 @@ public sealed class StaffCommands(ICurrentPrincipalAccessor callers) : IAuthoriz
31
31
  Register `builder.Services.AddScoped<IQueryRowNarrowing, VisibleShifts>();` with a scoped access store. In `Cratis.Arc.Queries`, the typed base builds a membership predicate for the read model; it applies to every query of that model unless `AppliesTo(QueryContext)` is overridden.
32
32
 
33
33
  ```csharp
34
- public sealed class VisibleShifts(IShiftAccess access) : QueryRowNarrowing<Shift, Guid>
34
+ public sealed class VisibleShifts(IShiftAccess access, ICurrentPrincipalAccessor callers) : QueryRowNarrowing<Shift, Guid>
35
35
  {
36
36
  protected override Expression<Func<Shift, Guid>> Key => shift => shift.Id;
37
37
  protected override ValueTask<IEnumerable<Guid>> GetAllowedKeys(QueryContext context) =>
38
- access.VisibleIds(context.AuthorizedPrincipal, context.CancellationToken);
38
+ access.VisibleIds(callers.Current, context.CancellationToken);
39
39
  }
40
40
  ```
41
41
 
42
- Have the store return an empty set for no access and throw on lookup failure. For a different predicate implement `IQueryRowNarrowing.GetPredicate(Type, QueryContext)` returning `ValueTask<LambdaExpression?>`: null means **not applicable**, never “no access”. Test that totals as well as rows exclude another caller's shifts. Scope the underlying producer too, especially for streams; a delivery guard decides on the whole emission, not individual rows.
42
+ Read the caller from `ICurrentPrincipalAccessor.Current`. `QueryContext.AuthorizedPrincipal` is set only when scheme authentication selected a different principal and is `null` otherwise, so do not use it to read the caller. Have the store return an empty set for no access and throw on lookup failure. For a different predicate implement `IQueryRowNarrowing.GetPredicate(Type, QueryContext)` returning `ValueTask<LambdaExpression?>`: null means **not applicable**, never “no access”. Test that totals as well as rows exclude another caller's shifts. Scope the underlying producer too, especially for streams; a delivery guard decides on the whole emission, not individual rows.
43
43
 
44
44
  ## Recheck access on delivery
45
45
 
@@ -114,7 +114,7 @@ This denies when there is no actor; allow `!context.Principal.IsActedOnBehalfOf(
114
114
 
115
115
  ## Trusted background work
116
116
 
117
- Outside HTTP use the injected `ISystemExecution` for a bounded scope: `using (systemExecution.AsSystem("dispatcher")) { var result = await pipeline.Execute(command); /* inspect result */ }`. With no roles the actor satisfies sign-in only. Use `As(trustedPrincipal)` for an explicit server-selected identity. Await inside the scope so disposal restores the previous actor. The system actor is authenticated with `SystemPrincipal.AuthenticationType` (`"System"`) and `SystemPrincipal.Subject` (`"[System]"`), which is what audit trails show. The scoped principal is used only when there is no HTTP request, so it cannot elevate an HTTP caller. Keep the scope as narrow as the work. Do not take roles from request or event payloads. In the Chronicle integration put `[Cratis.Arc.Chronicle.Reactors.ExecuteCommandsAsSystem("dispatcher")]` on a reactor class for its **returned** commands only; separately invoked commands need their own principal.
117
+ Outside HTTP use the injected `ISystemExecution` for a bounded scope: `using (systemExecution.AsSystem("dispatcher")) { var result = await pipeline.Execute(command); /* inspect result */ }`. With no roles the actor satisfies sign-in only. Use `As(trustedPrincipal)` for an explicit server-selected identity. Await inside the scope so disposal restores the previous actor. The system actor is authenticated with `SystemPrincipal.AuthenticationType` (`"System"`) and `SystemPrincipal.Subject` (`"[System]"`), which is what audit trails show. The scoped principal is used only when there is no HTTP request, so it cannot elevate an HTTP caller. With the Chronicle integration, events a command appends inside `As(principal)` record that principal as their `causedBy`, unless the current Chronicle identity's subject is not System, in which case that identity wins. A System identity is replaced, and its `OnBehalfOf` chain is kept after the principal. Claim `sub` becomes the subject, `name` the name and `preferred_username` the user name, with `Identity.Name` as the fallback for the last two. A principal acting on behalf of someone records the actor with the represented user as `OnBehalfOf` when both carry a subject, name or user name; otherwise it records only the one that does. Give its `ClaimsIdentity` an authentication type; an unauthenticated principal leaves the recorded identity unchanged. The same principal is authorized, so it must hold at least one role from each role-restricted attribute on the command. Keep the scope as narrow as the work. Do not take roles from request or event payloads. In the Chronicle integration put `[Cratis.Arc.Chronicle.Reactors.ExecuteCommandsAsSystem("dispatcher")]` on a reactor class for its **returned** commands only; separately invoked commands need their own principal.
118
118
 
119
119
  ## Not supported in this SDK
120
120
 
@@ -77,6 +77,8 @@ builder.addAuthorizationCommandFilter(CommandGate).addAuthorizationQueryFilter(Q
77
77
 
78
78
  Alternatively use discovered classes marked `@authorizationCommandFilter()` or `@authorizationQueryFilter()`. The blanket filters above also deny anonymous operations; explicitly account for any intended exceptions.
79
79
 
80
+ To limit a gate to some operations, match `operationName` exactly. It is the declared namespace and the name joined with a dot, skipping an empty part; a model-bound query's name includes its read-model class. Query introspection shows it as `fullyQualifiedName`; command introspection shows `namespace` and `name` separately, so join them. For example, a command without a namespace is `AcknowledgeShift`, and the query `byName` on read model `Item` is `Item.byName`. Deny when `operationName` is absent, as it may be on a manually built context. Never infer the operation from the `command`/`query` input. Register a filter token in one group per operation kind: a token in both the authorization and the pipeline group for commands, or for queries, makes `build()` throw.
81
+
80
82
  ## Guard ongoing delivery
81
83
 
82
84
  Admission at subscription is not a continuing entitlement. Register a scoped service in the server options and include its token in `query.observableEmissionGuards`. For example, with an application lookup that checks the current entitlement for the indicated query and input:
@@ -63,6 +63,7 @@ For application-owned documents only: `await shipments.InsertOneAsync(item)`, `R
63
63
  - For a named sink configure `Cratis:MongoDB:Sinks:reporting:Server` or `ServerFile` (secret file). Use Chronicle's `[Sink("reporting")]` or Arc's `[ReadModelSink("reporting")]` from `Cratis.Arc.Sinks` (Arc wins). Inject the model's collection normally. Lower-level code uses `IMongoDBReadModelDatabases.GetFor(typeof(Shipment))` or `IMongoDBSinks.GetClientFor("reporting")`. Unknown named sinks fail rather than falling back.
64
64
  - Leave `DirectConnection` unset to preserve the URI setting; true pins a server, not a change-stream capability. `EnableResilience` defaults on: async collection-not-found may return empty/default or wait on a stream. Set false for native driver failure behavior. `LogCommandBodies` is off; enable only in a controlled environment without sensitive data.
65
65
  - Concepts serialize as their underlying values; use nested mapped types for actual subdocuments. Arc supplies serializers for temporal and geospatial values and polymorphic discrimination. Match stored IDs and discriminators, not just the apparent JSON shape.
66
+ - Arc's default serializer stores a `DateTimeOffset` as a BSON date holding its `ToUnixTimeMilliseconds()` value. The offset and sub-millisecond ticks are lost, and the value reads back as `+00:00`. When local time matters, store the offset or time-zone ID in its own field. For equality with a stored value, compare the `ToUnixTimeMilliseconds()` results of both values rather than trimming ticks yourself; use a stable key if distinct instants can share a millisecond. That serializer accepts only `BsonType.DateTime` (default) and `BsonType.String`; `Int64` throws. `String` is not a lossless alternative: its format does not round-trip. For a different storage contract, set an application-owned serializer on that member in a class map (`SetSerializer`).
66
67
  - Configure maps **before first use** (driver maps freeze). For example:
67
68
 
68
69
  ```csharp
@@ -86,7 +86,7 @@ A watch invalidates the collection, not just matching IDs; rerun the scoped sele
86
86
 
87
87
  ## Override placement only when necessary
88
88
 
89
- For simple overrides, `database_resolver: Dispatch.Databases` implements `Cratis.Arc.MongoDB.DatabaseNameResolver.resolve(tenant, options)` (handle nil); `server_resolver: Dispatch.Servers` implements `Cratis.Arc.MongoDB.ServerResolver.resolve(options)`. For tenant-specific servers or rotating identities, add this option inside `mongodb:`:
89
+ For simple overrides, `database_resolver: Dispatch.Databases` implements `Cratis.Arc.MongoDB.DatabaseNameResolver.resolve(tenant, options)` and returns the database name. `options` is the `Cratis.Arc.MongoDB.Options` struct, not a keyword list: read `options.database`, and return it unchanged when `Cratis.Arc.Tenancy.default?(tenant)` is true (`nil`, `""`, or `"Default"` or `"[notset]"` in any letter case); `server_resolver: Dispatch.Servers` implements `Cratis.Arc.MongoDB.ServerResolver.resolve(options)`. For tenant-specific servers or rotating identities, add this option inside `mongodb:`:
90
90
 
91
91
  ```elixir
92
92
  connection_resolution: [
@@ -97,7 +97,14 @@ connection_resolution: [
97
97
  ]
98
98
  ```
99
99
 
100
- Both slots default to `:default`; connection applies first, then identity. A resolved database replaces tenant suffixing. Templates accept `:database` and `:connection_string` with `{tenant}` (`Default` if unset), `{storage}` and `{purpose}`; missing substitutions fail. HTTP POST sends storage `MongoDB`, purpose `Runtime` or `Schema`, and `scope.tenant`; `timeout:` defaults to 10000 ms. Return 200 with the chosen `connectionString`, `database`, `identity` or `expiresAt` fields, or 204 for unchanged. Keep endpoint credentials separate from database credentials. Alternatively implement `Cratis.Arc.MongoDB.ConnectionResolver.resolve/1`, e.g. `def resolve(%{scope: %{"tenant" => t}}), do: {:ok, %Cratis.Arc.MongoDB.ResolvedConnection{database: "dispatch-" <> t}}`. Cache duration defaults to 300 seconds; answers are keyed by purpose and tenant, refreshed ahead of expiry and invalidated on authentication rejection. Schema purpose selects permissions, not a migration.
100
+ Both slots default to `:default`; connection applies first, then identity. A resolved database replaces tenant suffixing. Templates accept `:database` and `:connection_string` with `{tenant}` (`Default` for the default tenant), `{storage}` and `{purpose}`; missing substitutions fail. HTTP POST sends storage `MongoDB`, purpose `Runtime` or `Schema`, and `scope.tenant`; `timeout:` defaults to 10000 ms. Return 200 with the chosen `connectionString`, `database`, `identity` or `expiresAt` fields, or 204 to leave this slot unchanged. Keep endpoint credentials separate from database credentials. For rules a template cannot express, set `connection: Dispatch.Connections` to a module implementing `Cratis.Arc.MongoDB.ConnectionResolver.resolve/1`. It receives `%{storage: "MongoDB", purpose: :runtime | :schema, scope: %{"tenant" => t}}` (`t` is `"Default"` for every default tenant: unset, empty, `Default` or `[NotSet]` in any case) and returns `{:ok, %Cratis.Arc.MongoDB.ResolvedConnection{...}}`, `:unchanged` (this slot changes nothing; the identity slot still runs) or `{:error, reason}`. A resolved database applies to the default tenant too, and a database from the identity slot wins over one from the connection slot. Only when neither slot returns a database does the database-name resolver choose it. So the `:unchanged` clause below keeps the bare `database:` name for the default tenant only if the identity slot returns no database for it and the database-name resolver returns the base name:
101
+
102
+ ```elixir
103
+ def resolve(%{scope: %{"tenant" => "Default"}}), do: :unchanged
104
+ def resolve(%{scope: %{"tenant" => t}}), do: {:ok, %Cratis.Arc.MongoDB.ResolvedConnection{database: "dispatch-" <> t}}
105
+ ```
106
+
107
+ Cache duration defaults to 300 seconds; answers are cached per purpose and tenant. Nothing refreshes in the background. Without a returned expiry, the next lookup resolves again once the cache duration passes. With `expiresAt`, the expiry replaces the cache duration: the next lookup from one minute before the earliest returned expiry resolves again. A MongoDB authorization or authentication error (code 13 or 18) from an Arc write or index call (`insert`, `insert_many`, `save`, `update`, `update_many`, `delete`, `delete_many`, `create_index`) drops the cached answer. Read failures, for example from `find` or `count`, do not drop it, and neither does an unreachable server. Pass `purpose: :schema` to `collection/3` (for example before creating indexes) so a configured resolver can return a more privileged identity; the flag itself grants no permissions and runs no migration.
101
108
 
102
109
  ## Test against a real server
103
110
 
@@ -179,7 +179,7 @@ The generated identity is guarded: the whole event source has to be empty when r
179
179
  Use `ICanProvideSubject.GetSubject()` on the command for a compliance identity known before handling, or return `(fact, new Subject(customerId.ToString()))` when the decision supplies it. The subject need not own the event source.
180
180
 
181
181
  - `[EventTag("account", nameof(AccountId))]` tags from an input; `[EventTag("origin", Value = "import")]` adds a constant.
182
- - For computed tags implement `ICanProvideEventTags.GetEventTags()` on the command, e.g. `=> [new NamedTag("channel", Channel)]`. For a convention shared across commands implement `ICanProvideCommandEventTags.GetEventTags(object command)` on a discovered service; return an empty sequence when not applicable.
182
+ - For computed tags implement `ICanProvideEventTags.GetEventTags()` on the command, e.g. `=> [new NamedTag("channel", Channel)]`. For a convention shared across commands implement `ICanProvideCommandEventTags.GetEventTags(object command)` on a discovered service; return an empty sequence when not applicable. `[EventTag]`, `ICanProvideEventTags`, `ICanProvideCommandEventTags` and `EventTags` live in `Cratis.Arc.Chronicle.Commands`; `NamedTag` lives in `Cratis.Chronicle`.
183
183
  - Arc discovers command tag providers by convention and resolves them from the command's service scope, so they may inject scoped tenant or user services. Keep them transient or scoped; a singleton must not capture request values. They run once per command at the first returned-event append, after authorization and validation, and never for validation-only calls or commands that return no events.
184
184
  - Every command tag source (attributes, `ICanProvideEventTags`, providers, returned `EventTags`) applies only to events the handler returns. Aggregate-root commits and events appended directly to an event log or sequence get none of them; a direct append must pass its own named tags.
185
185
  - Return `(fact, new EventTags(new NamedTag("batch", batchId)))` to tag all returned events after handling. Set `NamedTags = [new NamedTag("leg", "credit")]` on an `EventForEventSourceId` to tag only that event. Arc merges by name/value pair at append, not during preflight.
@@ -55,7 +55,7 @@ public record ApproveReport(ReportId ReportId, string Owner, string Month)
55
55
 
56
56
  ## Aggregate root
57
57
 
58
- Use it when an entity's rules read best as methods over its own history. Derive from `AggregateRoot` (`Cratis.Arc.Chronicle.Aggregates`), keep state in `On` methods, and take the aggregate as a `Handle` parameter. Arc loads it for the command's event source and replays its handled events first.
58
+ Use it when an entity's rules read best as methods over its own history. Derive from `AggregateRoot` (`Cratis.Arc.Chronicle.Aggregates`), keep state in `On` methods, and take the aggregate as a `Handle` parameter. Arc loads it for the command's event source and replays its handled events first. Every injected aggregate parameter uses the command's event source: a second parameter of the same type is the same instance, with the same state and `Failed` results, not another identity. Load any other identity with `IAggregateRootFactory.Get<T>(…)`.
59
59
 
60
60
  ```csharp
61
61
  using Cratis.Arc.Chronicle.Aggregates;
@@ -122,4 +122,4 @@ A constructor may take registered services. A read model injected there is a dep
122
122
  | `StreamDecisionRequiresSpecificRoute` | The read has an unspecified event source ID, every stream type, or the default stream ID | Declare the stream type and stream ID on the command or route. |
123
123
  | `EventRoutingContradictsEventSource` | A stream name the event source definition does not declare, or metadata contradicting it | Use a declared stream. |
124
124
  | `UnableToResolveAggregateRootFromCommandContext` | The command's event source ID is declared but unusable, for example unspecified | Supply a usable identity before the aggregate is resolved. |
125
- | `ReadAndAggregateOnSameSource` | Under read protection, a protected read model and an aggregate guard the same source | Decide from the aggregate, or mark an advisory read `[Unprotected("reason")]`. |
125
+ | `ReadAndAggregateOnSameSource` (analyzer `ARCCHR0033`) | Under read protection `On`, a protected read model and an aggregate guard the same source | Decide from the aggregate, or mark an advisory read `[Unprotected("reason")]`. A protected read of a different source is allowed beside the aggregate and adds its own guard. |