@cratis/pi 7.148.0 → 7.149.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 (20) hide show
  1. package/package/corpus/skills/cratis-screenplay-reverse-engineering/SKILL.md +22 -4
  2. package/package/corpus/skills/cratis-screenplay-reverse-engineering/references/behavior-catalog.md +5 -0
  3. package/package/corpus/skills/cratis-screenplay-reverse-engineering/references/evidence-format.md +23 -0
  4. package/package/corpus/skills/cratis-screenplay-reverse-engineering/references/executable-intake.md +13 -0
  5. package/package/corpus/skills/cratis-screenplay-reverse-engineering/references/fidelity-check.md +13 -2
  6. package/package/corpus/skills/cratis-screenplay-reverse-engineering/references/probing-and-naming.md +29 -4
  7. package/package/corpus/skills/cratis-screenplay-reverse-engineering/references/process-drift.md +56 -0
  8. package/package/corpus/skills/cratis-screenplay-reverse-engineering/references/provenance.md +1 -1
  9. package/package/corpus/skills/cratis-screenplay-reverse-engineering/references/scoping.md +6 -0
  10. package/package/corpus/skills/cratis-screenplay-reverse-engineering/references/synthesis-rules.md +38 -3
  11. package/package/corpus/skills/cratis-screenplay-reverse-engineering/references/target-and-first-validation.md +3 -0
  12. package/package/corpus/skills/cratis-screenplay-reverse-engineering/scripts/drift-scope-self-test.mjs +87 -0
  13. package/package/corpus/skills/cratis-screenplay-reverse-engineering/scripts/drift-scope.mjs +155 -0
  14. package/package/corpus/skills/cratis-screenplay-reverse-engineering/scripts/fixtures/solocrm-drift/README.md +23 -0
  15. package/package/corpus/skills/cratis-screenplay-reverse-engineering/scripts/fixtures/solocrm-drift/change.diff +131 -0
  16. package/package/corpus/skills/cratis-screenplay-reverse-engineering/scripts/fixtures/solocrm-drift/evidence-map.json +39 -0
  17. package/package/corpus/skills/cratis-screenplay-reverse-engineering/scripts/fixtures/solocrm-drift/expected.json +52 -0
  18. package/package/corpus/skills/cratis-screenplay-reverse-engineering/verification.json +3 -1
  19. package/package.json +1 -1
  20. package/src/index.ts +47 -35
@@ -28,6 +28,7 @@ it scores observable behavior, with names reported separately.
28
28
  | A running app from the system and its executable, no source required | this skill |
29
29
  | Faithful migration or documentation with the source, `file:line` evidence, loss report and expert verification | `cratis-screenplay-legacy-extraction` |
30
30
  | A new system from interviews, workshops or process documents | `cratis-screenplay-discovery` |
31
+ | An accepted model whose observed system has since changed | this skill, [references/process-drift.md](references/process-drift.md) |
31
32
 
32
33
  When source exists and the goal is migration, switch to legacy extraction. When both goals hold,
33
34
  run this skill for the walk and the run, and legacy extraction for the source-backed claims.
@@ -60,7 +61,8 @@ Work area: `.ai-work/screenplay/<slug>/re/` (`captures/`, `EVIDENCE.md`, optiona
60
61
 
61
62
  1. **Intake.** Reuse the brief; ask only what is missing, at most the two discovery questions of
62
63
  the UI walk (start URL and actor, then guidance), one per turn. Record the inputs, the
63
- environment, the approvals, the walk budget and the scope. Scope is the key areas wanted, in
64
+ environment, the approvals, the walk budget and the scope, and a watermark per source
65
+ (version, hash or capture date; `references/evidence-format.md`). Scope is the key areas wanted, in
64
66
  and explicitly out; with none given, inventory first, then propose one and ask once. Read
65
67
  [references/scoping.md](references/scoping.md) for a focused run. Unattended: assume read-only, no hosted
66
68
  model, no writes, no executable runs, and record each assumption. Order of sources: the
@@ -74,7 +76,9 @@ Work area: `.ai-work/screenplay/<slug>/re/` (`captures/`, `EVIDENCE.md`, optiona
74
76
  - **L0 feature inventory**: list what the system lets users do, before any modeling: features
75
77
  and their entry points (screens, navigation, forms, routes in the OpenAPI document or HAR,
76
78
  executable commands and menus, documented jobs and emails), each with the source that covers
77
- it, tagged in / out / boundary against the scope. Modeling starts only from this list; out of
79
+ it, tagged in / out / boundary against the scope. Break each in-scope feature into flows and take
80
+ them one at a time, each small enough to review in one sitting
81
+ (`references/scoping.md`). Modeling starts only from this list; out of
78
82
  scope features are listed, never walked or modeled.
79
83
  - **L1 static**: OpenAPI, product docs and the static inventory of the executable
80
84
  (`references/executable-intake.md`). Source code, if offered, is one more optional input
@@ -92,11 +96,14 @@ Work area: `.ai-work/screenplay/<slug>/re/` (`captures/`, `EVIDENCE.md`, optiona
92
96
  the UI, the time rule recipe, client versus server rules, naming fidelity, observed defects
93
97
  and opaque queries. An API probe batch counts as one walk state per command. **Probe
94
98
  coverage gate:** record every command and probe class in `re/PROBES.md` (accepted, rejected or
95
- `not probed: <reason>`); `not probed` counts as unknown, never as no rule.
99
+ `not probed: <reason>`) and close the file with a per-class coverage check (rule, rejection,
100
+ flow, time, authorization, query shape); `not probed` counts as unknown, never as no rule.
96
101
  3. **Synthesis.** Start only after the probe coverage gate. Write `event-model.md` first (readout before `.play`, see the synthesis rules), then turn evidence rows into candidate elements with the signal rules in
97
102
  [references/synthesis-rules.md](references/synthesis-rules.md). Every write goes through the
98
103
  Screenplay MCP loop of `cratis-screenplay-model-authoring`: propose, read the proposal, apply.
99
- Each step validates; never hand-edit around a diagnostic. Without the MCP server, first-pass
104
+ Before validating, cross-walk every finding to the construct that encodes it or a `GAP` with
105
+ its cause (`references/synthesis-rules.md`, Finding crosswalk). Each step validates; never
106
+ hand-edit around a diagnostic. Without the MCP server, first-pass
100
107
  traps and the run recipe are in
101
108
  [references/target-and-first-validation.md](references/target-and-first-validation.md). Follow the phase skills for craft
102
109
  (`cratis-screenplay-discovery`, `cratis-screenplay-slice-design`,
@@ -127,6 +134,10 @@ Work area: `.ai-work/screenplay/<slug>/re/` (`captures/`, `EVIDENCE.md`, optiona
127
134
  (pass signal: exit 0 and the score block; exit 2 means an invalid catalog). Run
128
135
  `scripts/score-fidelity.mjs --self-test` to check the arithmetic; it executes
129
136
  `scripts/score-fidelity-self-test.mjs` and prints the checked count.
137
+ For process-drift scoping, run `scripts/drift-scope.mjs --self-test`, which executes
138
+ `scripts/drift-scope-self-test.mjs`. The [SoloCrm case](scripts/fixtures/solocrm-drift/README.md)
139
+ uses `scripts/fixtures/solocrm-drift/change.diff`, `scripts/fixtures/solocrm-drift/evidence-map.json`
140
+ and `scripts/fixtures/solocrm-drift/expected.json`; see [process drift](references/process-drift.md).
130
141
 
131
142
  When the sources are only a website, user docs or a description document, or the run must feel
132
143
  like a product on Stage, read
@@ -166,6 +177,13 @@ The model may be offered for acceptance only when each item is a result or "not
166
177
 
167
178
  - The inventory lists every observable entry point with its source or "not covered".
168
179
  - Every slice cites evidence ids; every row has a classification; every unknown has a question.
180
+ - Every finding is encoded or carries a `GAP` cause; the probe coverage check has no empty class.
181
+ - `screenplay test` ran with executed equal to discovered and none failed; its summary line is
182
+ in the report. "Needs an occurrence supplied by the execution request" means the
183
+ specification lacks a `given clock` line.
184
+ - `cratis run` admitted the model: `GET /stage/status` reads `ready`, the admission list is
185
+ empty and the detailed admission lists no artifact as unsupported. One admission issue refuses
186
+ every route; one unsupported command answers 501, and so does every flow that needs it first.
169
187
  - V1 clean on the candidate (`cratis-screenplay-toolchain`), warnings as errors.
170
188
  - The independent review ran, and each slice has a keep, change or remove decision.
171
189
  - Safety: approvals named, captures scrubbed, captures untracked.
@@ -77,6 +77,11 @@ item weights default to 1, and 1.5 for `time` (hardest to infer). A scorer may o
77
77
  weight with a reason in `note`. Never change the split or the catalog after the first score is
78
78
  seen.
79
79
 
80
+ Score a `time` item as a pair: the positive probe and the negative probe of the same rule must
81
+ both hold; an unfiltered list passing only the positive half is a fail. Performer-held time
82
+ rules run only in the rendered app (`cratis run --engine eventmodel`, or render), because the
83
+ semantic sandbox leaves performer bodies out.
84
+
80
85
  ## Naming fidelity is separate
81
86
 
82
87
  Keep the inventory of names (commands, events, read models and queries, screens, constraints,
@@ -19,6 +19,23 @@ combines it with the legacy rows. For the richer table used with source code, se
19
19
  resource, and `RUN-<n>` for an approved run. A `binary` row from assembly reading is `Declared`.
20
20
  - A person or document row cites the section or the person and date.
21
21
 
22
+ ## Watermark
23
+
24
+ Record per feature and per source which state of the system the rows describe, in `STATE.md`
25
+ and, at acceptance, in the feature's `note`:
26
+
27
+ | Source | Watermark |
28
+ |---|---|
29
+ | source code, if offered | source identity (commit plus input digest, legacy extraction) |
30
+ | OpenAPI or docs | sha256 of the fetched file, its stated version and the fetch date |
31
+ | shipped binary or package | sha256, version string and build date |
32
+ | running app (walk, HAR) | version or build id the system shows, environment and capture date |
33
+
34
+ A source with no readable version gets its fetch date and the word `unversioned`. A later run
35
+ compares watermarks per feature before walking: unchanged means "unchanged since <watermark>"
36
+ and the feature is left alone; changed or `unversioned` means re-intake that feature only, with
37
+ stable ids (`process-drift.md`).
38
+
22
39
  ## Probe budget and table
23
40
 
24
41
  A batch of API probes against one command counts as one L2 walk state, not one per case, so
@@ -41,3 +58,9 @@ in `captures/` and cite its file from the rule rows:
41
58
  - Every candidate element cites at least one evidence id; a slice with none is removed or sent
42
59
  back to intake.
43
60
  - Cite ids in a slice `description` ("Evidence: RE-E1, RE-E2") and keep the detail in the table.
61
+ - Each candidate row carries a one-sentence `rationale`: why this evidence became this element
62
+ and name ("two writes in one POST and a 409 on the second: one command with a guard, not two
63
+ events"). At acceptance, promote the rationale with the evidence ids and the watermark into
64
+ the slice `documentation` and the feature `note`, as legacy extraction does
65
+ (`../../cratis-screenplay-legacy-extraction/references/re-entry-and-passes.md`); otherwise the
66
+ evidence is lost when `.ai-work` is discarded.
@@ -7,6 +7,7 @@
7
7
  - Techniques per kind
8
8
  - Managed assembly intake (own .NET app)
9
9
  - Trace one feature end to end
10
+ - Driving a live web app from scripts
10
11
  - Optional external tooling
11
12
  - Locators and evidence rows
12
13
  - Feature coverage
@@ -125,6 +126,18 @@ Write each hop as an evidence row with its locator. A static trace names candida
125
126
  node is not proven to take part. Confirm the path with one observed run before stating it as a
126
127
  rule. A feature with no observed effect stays a candidate.
127
128
 
129
+ ## Driving a live web app from scripts
130
+
131
+ For an owned or test-permitted web app, script the observation instead of clicking by hand:
132
+
133
+ - **Query subscriptions.** A read model the UI shows live is an event stream (SSE). Open the
134
+ query's stream with `curl -N` or a small Node script, run a command in another call, and
135
+ record the pushed rows: that is the observable effect of the command on that view.
136
+ - **Browser driver.** Drive a headless browser over the DevTools protocol (CDP) from a script
137
+ to fill forms, click and read page text; one script per flow, output as a probe table.
138
+ - Both run against the sandbox or approved target only, with fresh marker ids, and write their
139
+ output to `captures/`. Redact tokens from scripts and logs.
140
+
128
141
  ## Optional external tooling
129
142
 
130
143
  A dedicated reverse-engineering MCP server or CLI (for example REA, `https://github.com/morluto/rea`)
@@ -62,7 +62,13 @@ flows; rules and rejections are scored by the catalog probes
62
62
 
63
63
  Passing `screenplay test` does not show that Stage can run the model. After `cratis run`:
64
64
 
65
- 1. Read `GET /stage/status`; the state must not be `unsupported`.
65
+ 1. Read `GET /stage/status`; the state must be `ready`. A refused model serves
66
+ `/stage/semantic/admission` instead and answers every `/api` route with 501, so one issue
67
+ (for example a specification missing a `$context.occurred` field) blocks the whole walk.
68
+ Fix every admission issue before walking or scoring; a refused model scores zero. A `ready`
69
+ state can still list single artifacts as unsupported: that command answers 501, and every
70
+ flow that needs it first fails with it (one in round 3 lost 38 of 91 cases). Read the whole
71
+ admission output, not its first entries, and fix each unsupported artifact.
66
72
  2. Execute one command over HTTP. A refusal naming an unsupported model format version means the
67
73
  toolchain is out of range: update it before changing the model. Send date-time values in the
68
74
  full round-trip form with fractional seconds and offset.
@@ -144,5 +150,10 @@ knows the original product would. A script or HTTP harness does not replace this
144
150
  query filters). The model carries it in a query performer body, fixture-dated specifications
145
151
  and a platform gap row. The body runs only in a rendered app, never in the executable model.
146
152
  Walk it on the rendered app with backdated data, and on the sandbox mark the journey as
147
- not run.
153
+ not run. Time items are scored as pairs: the positive probe (the item appears) and the
154
+ negative probe (a non-matching item does not appear) must both hold. An unfiltered list
155
+ passes every positive half and fails every negative one, so a pass whose twin fails is not
156
+ evidence. Report time fidelity as the paired score. Performer-held rules are verified against
157
+ the rendered app (`cratis run --engine eventmodel`, or render), since the semantic sandbox
158
+ leaves performer bodies out.
148
159
  - A pass list is not a coverage claim: report what was not walked.
@@ -37,6 +37,17 @@ exact response and `validationResults[].message`). The eight probe classes:
37
37
  (at-least-one-of, mutually dependent fields) never shows in per-field probes. Probe all
38
38
  fields empty, each one empty alone, and all filled;
39
39
  - a duplicate is a second, distinct id with the same value, sent sequentially; read the body.
40
+ Do this for every name-like field of a create command: a uniqueness rule is confirmed or
41
+ refuted only by this probe, never by a UI success;
42
+ - **toggle commands** (complete and reopen, archive and restore, assign and unassign): probe
43
+ the inverse and read back the whole read-model row before and after, field by field, not only
44
+ the headline flag; a timestamp or reason the inverse should clear is a rule.
45
+
46
+ Budget: about ten probes per command, written as a script that sends the whole batch for one
47
+ command and prints one table (`evidence-format.md`, probe table); the batch counts as one walk
48
+ state. Classify each result of a free-form probe as **intent** (a consistent, deliberate
49
+ rejection or message), **defect** (coercion, crash, HTTP 500, silent wrap) or `unconfirmed`
50
+ (one observation) before it becomes a row; defects follow "Observed defects" below.
40
51
 
41
52
  Read the command schema as well as the form: concept names (`x-concept`), enums, required flags
42
53
  and formats show value types the screen hides. When the first call is unknown, request the
@@ -46,7 +57,11 @@ request envelope and auth shape; if none exists, record that and make one read c
46
57
  **Probe coverage gate.** Keep `re/PROBES.md`: one row per command and probe class, each
47
58
  accepted, rejected or `not probed: <reason>` (write scope not approved, destructive, no id
48
59
  available). Synthesis does not start until every in-scope command has all eight classes
49
- recorded or explicitly `not probed`. A `not probed` class counts as unknown in the report,
60
+ recorded or explicitly `not probed`. End the file with a coverage check by catalog class: rule,
61
+ rejection, flow (read-model effect of each command), time, authorization (each role or
62
+ anonymous, when approved) and query shape (every argument of every query). Each class lists at
63
+ least one probe row or an explicit reason it was skipped; an empty class blocks synthesis.
64
+ A command with two or more optional text fields always has a row for all fields empty together. A `not probed` class counts as unknown in the report,
50
65
  never as "no rule". Ask for the write approval once, with the matrix attached. Each rule the
51
66
  assemblies declare (`executable-intake.md`) gets a probe that tries to violate it; a mismatch
52
67
  between assembly and server is an observed defect or dead code, recorded either way.
@@ -67,7 +82,10 @@ becomes a row; until then it is `unconfirmed`. A wrong `Confirmed` row is worse
67
82
  The UI shows only the queries its screens use. On a system the team owns or is authorized to
68
83
  probe (the owned-only limit above holds), also enumerate the surface from your own traffic and
69
84
  the schema: by-id lookups, filters and argument variants of each query, and the routes seen in
70
- the capture. Read the error text for required arguments. A query that returns HTTP 202 or
85
+ the capture. Probe every argument of every list query as true, false and omitted, and record
86
+ each one that changes the result as an optional filter (`synthesis-rules.md`, Intent in the mapping);
87
+ an argument seen in traffic but not probed is a gap, not an absent argument. Read the error text
88
+ for required arguments. A query that returns HTTP 202 or
71
89
  `isReady: false` is warming up: retry after a few seconds before recording it empty.
72
90
 
73
91
  ## Time-based views
@@ -78,14 +96,21 @@ has a threshold that only data can reveal. Seed records through the commands' ow
78
96
  0, 1, N-1, N and N+1 days, today plus and minus one, near local midnight, done and not done.
79
97
  Diff the result sets to find the boundary and whether the edge is inclusive; where assemblies
80
98
  are available, confirm that the decompiled threshold and the observed one agree. If the server
81
- refuses backdated writes, record that as its own rule.
99
+ refuses backdated writes, record that as its own rule. Also probe an item whose reference is
100
+ undefined (a stage or status never created) to see whether it counts as open or is excluded.
82
101
  How to model the result, and what the Screenplay surface cannot run, is in
83
102
  `synthesis-rules.md` ("Time facts"). If a threshold could not be exercised, record the
84
103
  placeholder value as an `unknown` with a question; never ship a guessed number unrecorded.
104
+ When the server clock cannot be set, seed relative dates from the host clock (`today`,
105
+ `today±N`), run well away from local and UTC midnight, and record the zone assumption and run
106
+ time in PROBES.md. Probe each state filter (completed, archived, stage open, won, lost,
107
+ undefined) as its own row.
85
108
  The server's time zone and its "today" are standing unknowns: seed near midnight and with
86
109
  backdated dates, and look for a zone setting or response header. A today-relative rule the
87
110
  declarative dialect cannot express goes in a query performer body plus an `event-model.md` gap
88
- row (`synthesis-rules.md`, Time facts). Never use a comment or a guessed filter.
111
+ row (`synthesis-rules.md`, Time facts), with specs on fixed dates. Record the zone as an
112
+ explicit assumption and add a spec near midnight. A probed time rule is never left as a `GAP`
113
+ comment or prose, and never as a guessed filter.
89
114
 
90
115
  ## Client-side or server-side
91
116
 
@@ -0,0 +1,56 @@
1
+ # Process drift
2
+
3
+ Use when a model is accepted and the observed system has since changed. Do not rebuild the
4
+ model. The question is whether the system still does what the model says (process drift), not
5
+ whether its structure changed (architecture drift).
6
+
7
+ **Input:** the watermark recorded with the model (`evidence-format.md`, Watermark) and the
8
+ current state of the same sources: two OpenAPI documents, two binary or app versions, two
9
+ capture sets, or, when source is offered, `<commit>..HEAD` (`cratis-screenplay-legacy-extraction`,
10
+ `re-entry-and-passes.md`). The diff between the two states is the work list.
11
+
12
+ ## Source-diff scope helper
13
+
14
+ Run `node scripts/drift-scope.mjs change.diff evidence-map.json` for JSON work lists;
15
+ `node scripts/drift-scope.mjs --self-test` checks the SoloCrm case and rejection rules.
16
+ The map projects evidence rows into `flows: [{id, evidenceIds, paths}]` and carries
17
+ `watermarks: {from: {revision, inputDigest}, to: {revision, inputDigest}}`. Paths are
18
+ repository-relative, case-sensitive exact paths or globs (`*` within a segment,
19
+ `**` across segments); include shared dependencies in every affected flow's paths.
20
+ This map is an index of evidence, not a replacement for the evidence rows.
21
+
22
+ The helper accepts Git unified diffs with unquoted `diff --git a/... b/...` headers
23
+ (and trimmed hunk bodies). It preserves hunk locators and checks both old and new paths.
24
+ Artifact hints take precedence: Cratis-generated TypeScript with both `@generated by
25
+ Cratis` and `DO NOT EDIT` markers in the diff, lockfiles, scene.json/stage-scene.json,
26
+ .cratis-render.json and bin/obj/dist output are structure-only. An unchanged-content
27
+ rename (100% similarity, no hunks) and indentation/blank-line-only hunks are also
28
+ structure-only; other refactors are not guessed from syntax. All remaining changes,
29
+ including unknown files or header-only changes, are conservatively process work.
30
+ Unmapped process paths become new-flow candidates; added public static C# methods
31
+ supply symbol hints. Empty diffs and missing watermarks/evidence mappings fail closed.
32
+
33
+ These are scope hints, not semantic proof: generated markers must be present to exclude
34
+ proxies, artifact/formatting changes can still affect behavior, and the keep list means
35
+ no process hunk matched the supplied mapping. Reconcile artifacts with their source and
36
+ inspect uncertain changes before a no-drift verdict. The helper echoes both watermarks;
37
+ it never advances the accepted one. See the [SoloCrm fixture](../scripts/fixtures/solocrm-drift/README.md).
38
+
39
+ ## Steps
40
+
41
+ 1. Compare watermarks per feature. Unchanged features are reported "unchanged since
42
+ <watermark>" and not touched.
43
+ 2. For each touched feature, classify every hunk of the diff:
44
+ - **process**: a command, field, rule or validation message, authorization, event, state
45
+ change, read-model field, job, side effect or screen field was added, changed or removed;
46
+ - **structure only**: a rename, move, refactor, layering, dependency or formatting change
47
+ that leaves observable behavior alone. Report these as one count and never model them.
48
+ 3. Re-derive only the flows a process hunk touches, from entry point to persisted or visible
49
+ effect, with the probes of `probing-and-naming.md` for the changed commands and queries.
50
+ Keep evidence ids stable; list retired ids.
51
+ 4. Output two lists. The **model delta**: slices, rules and events added, changed or removed,
52
+ with evidence ids. The **behavior changes** in business words ("a refund after 30 days is now
53
+ rejected"), each with its locator and old versus new value.
54
+ 5. Give a verdict per feature: `no drift`, `drift: model update proposed` or
55
+ `drift: needs owner decision`. Every change is a question for the owner; an accepted decision
56
+ is not edited from the diff. Append the new watermark only to features that were reconciled.
@@ -4,7 +4,7 @@
4
4
  |---|---|---|---|
5
5
  | Evidence rows that carry explicit unknowns, source kinds and locators (`references/evidence-format.md`); static before dynamic, per-kind techniques, tracing a feature across IPC, network and storage, and treating process capture as unisolated (`references/executable-intake.md`); fidelity verification ideas: behavior ledger with case kinds, undecided never passing, authority matching the claim, negative controls, read-only probes of owned originals, withheld effects, run provenance (`references/fidelity-check.md`) | morluto/rea (https://github.com/morluto/rea) | MIT | Ideas only, restated in our own wording and fields; no upstream text or schema is reused |
6
6
  | The bounded, state-aware UI walk | Martin Dilger and Nebulit GmbH, agentic-engineer and Eventmodelers Build-Kits, used with their explicit consent; adapted in `cratis-screenplay-legacy-extraction` | see that skill's `LICENSE` and provenance | Referenced, not copied: this skill points to `ui-observation.md` and `signal-to-intent.md` there |
7
- | Inverse event modeling: following one flow from entry point to persisted effect | Martin Dilger, "Inverse Event Modeling" | idea only | Credited as an idea; no text is reused |
7
+ | Inverse event modeling: following one flow from entry point to persisted effect; a watermark naming the state a model describes; process drift rather than architecture drift; flow-sized review units; a recorded reason per mapping (`references/process-drift.md`, `references/evidence-format.md`, `references/scoping.md`) | Martin Dilger, "Inverse Event Modeling" | idea only | Credited as ideas; no text is reused |
8
8
  | Workflow, safety rules, synthesis and fidelity references | Cratis/AI corpus | MIT (Cratis) | Own work |
9
9
 
10
10
  The method spine (L0-L4, evidence ladder, hosted-model disclosure rule) is the legacy extraction
@@ -70,6 +70,12 @@ Record the scope (in, out, boundary and closure reasons) in the provenance or sy
70
70
  The fidelity check scores in-scope journeys only and lists the out-of-scope features as not
71
71
  covered; do not report them as failed.
72
72
 
73
+ ## Flow by flow
74
+
75
+ Break each in-scope feature into flows: one entry point to its persisted or visible effect.
76
+ Take them one at a time, each small enough for a person to read in one sitting and say "right"
77
+ or "wrong" before the next starts; a flow the reviewer cannot judge that way is split.
78
+
73
79
  ## Changing scope later
74
80
 
75
81
  Narrowing removes the area's slices (a keep / change / remove decision applies) and turns
@@ -9,6 +9,7 @@
9
9
  - Writing through MCP
10
10
  - Specifications
11
11
  - Slices and flows
12
+ - Finding crosswalk
12
13
  - Stop conditions
13
14
 
14
15
  How black-box signals become candidate Screenplay elements. Signals are hypotheses: each result
@@ -85,11 +86,29 @@ the deliverable; see "Runnability" in [fidelity-check.md](fidelity-check.md)).
85
86
  Give the query a `performer` body (`cratis-screenplay-read-surface`, "Performer bodies are
86
87
  rendered") that applies the probed threshold, the inclusive or exclusive edge and the excluded
87
88
  states, and name the threshold as a constant in the body. Stage renders the body, so the
88
- rendered app serves the rule. Specify the boundary with `given readmodel` rows on fixed dates
89
+ rendered app serves the rule. The semantic sandbox, `screenplay test` and Stage
90
+ spec runs leave a performer body out, so verify a performer-held
91
+ rule against the rendered app (`cratis run --engine eventmodel`, or render) or fixture-dated
92
+ specs; mark it `performer-held, sandbox-unverified`, never `expressed-and-checked`. Specify the boundary with `given readmodel` rows on fixed dates
89
93
  (threshold minus one, equal, plus one), and record "today-relative filter not declarative"
90
- as a platform gap row in `event-model.md` (check the Screenplay and Stage trackers before
91
- filing).
94
+ as a platform gap row in `event-model.md` (search the Screenplay and Stage trackers first and
95
+ comment on a matching open issue rather than filing a duplicate).
92
96
  An unprobed threshold stays `unknown`; never write a guessed number.
97
+ - **Queries**: an optional argument seen in UI traffic, a capture or a probe becomes
98
+ `filter <name> <Type> optional` on the query; "observed to filter, model does not declare"
99
+ is not an acceptable note.
100
+ - **Toggles clear what the inverse clears**: when a probe shows the inverse command reset a
101
+ field (a completed-at timestamp on reopen), the projection resets it too.
102
+ - **Ownership and state-reading authorization** ("only the owner may change X"): probe it as
103
+ a second caller, record it as an authorization finding, and never drop it. The policy form
104
+ admits caller conditions only (`authenticated`, roles); a rule that reads state is not
105
+ expressible, so write a `GAP` line citing the open Cratis/Screenplay issues on state-reading
106
+ authorization policies (search the tracker for the numbers) and keep the rule as an anchored `question` note. Do not invent syntax.
107
+ - **Cross-field rules** ("a first or a last name"): write a declarative
108
+ `require <condition>` with a `message`, for example
109
+ `require firstName != "" or lastName != ""`. A fenced code body is a last resort; its
110
+ shape (yielded messages, the fields it can read) is in `cratis-screenplay-command-surface`,
111
+ and a body Stage cannot compile makes that command unsupported.
93
112
  - **Cascades and observed defects**: a cascade (deleting a parent removes its children) is an
94
113
  automation: model it when the dialect allows, else list it in `event-model.md`. Model the
95
114
  intended behavior of an observed defect and flag the defect.
@@ -123,6 +142,12 @@ proposal. The contract and the refusal handling belong to that skill; this skill
123
142
  - A specification needs both sides seen: the state before and the state after. One side alone is
124
143
  an `unknown`, not a specification.
125
144
  - Use observed values for given and expected data; replace personal data with fixtures.
145
+ - An event field stamped from `$context.occurred` (occurredAt, completedAt, changedAt) still
146
+ needs an explicit value in every `given` and `then` of a specification; a missing one is
147
+ PLAY0524, an error that skips the whole folder, and Stage refuses the whole model for it.
148
+ Write each such specification with a `given clock` line and use that same timestamp as the
149
+ field's value in the `then`. Before validation, list every event field mapped from
150
+ `$context.occurred` and check that each specification of that event supplies it.
126
151
  - A UI success proves a state change was shown. It does not prove uniqueness, idempotency or
127
152
  atomicity: those stay `unknown` until a capture or a person confirms them.
128
153
  - Optional properties are not defaulted in specifications, so each specification must list
@@ -146,6 +171,16 @@ proposal. The contract and the refusal handling belong to that skill; this skill
146
171
  - Where the capture shows ordering (create, then list, then edit), keep it as the flow, and
147
172
  state which ordering is observed and which is assumed.
148
173
 
174
+ ## Finding crosswalk
175
+
176
+ Before validation, list every numbered finding and probe row of `re/PROBES.md` with the model
177
+ construct that encodes it (projection line, `require`, filter, performer, spec) or a `GAP` line
178
+ with its cause: `skill` (not yet encoded), `platform` (the dialect cannot express it) or
179
+ `not probed`. A query that projects a time rule also needs the fields it reads (received-on,
180
+ last-activity, stage status, completed flag): per rule, cite the `from <Event>` line that
181
+ populates each; a finding that an event sets a field with no projection line is a defect.
182
+ A finding with neither is unfinished; a `skill` cause is fixed now, not reported.
183
+
149
184
  ## Stop conditions
150
185
 
151
186
  Stop and ask rather than synthesize when:
@@ -12,6 +12,9 @@ syntax are owned by `cratis-screenplay-toolchain`, `cratis-screenplay-render-and
12
12
  Neither is `unbound` or `0 executed`: the folder still has errors, so every specification was
13
13
  skipped. The gate passes only when the command exits 0 and the executed count equals the
14
14
  discovered count, apart from specifications that read an opaque performer, each listed by name.
15
+ The usual cause of `unbound` is PLAY0524: an event field stamped from `$context.occurred`
16
+ missing from a `given` or `then`. Paste the final `screenplay test` summary line
17
+ ("N discovered, N executed") into the report; a run without it is not validation.
15
18
  Report that executed count, never a per-file compile result.
16
19
  3. Start it with `cratis run <model folder>` (Stage sandbox, needs Docker), or render with
17
20
  `cratis render` and gap-fill (`cratis-screenplay-render-and-gap-fill`).
@@ -0,0 +1,87 @@
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
+ import assert from 'node:assert/strict';
5
+ import { spawnSync } from 'node:child_process';
6
+ import { readFileSync } from 'node:fs';
7
+ import { fileURLToPath } from 'node:url';
8
+
9
+ const fixture = name => new URL(`./fixtures/solocrm-drift/${name}`, import.meta.url);
10
+ const readJson = name => JSON.parse(readFileSync(fixture(name), 'utf8'));
11
+
12
+ function change(path, body, before = path) {
13
+ return `diff --git a/${before} b/${path}\n--- a/${before}\n+++ b/${path}\n${body}\n`;
14
+ }
15
+
16
+ function miniatureMap(paths = ['Source/Crm/Tags/**']) {
17
+ return {
18
+ watermarks: { from: { revision: 'before', inputDigest: 'fixture-before' }, to: { revision: 'after', inputDigest: 'fixture-after' } },
19
+ flows: [{ id: 'Tags', evidenceIds: ['RE-E1'], paths }],
20
+ };
21
+ }
22
+
23
+ function fixtureChecks(scopeDrift) {
24
+ const map = readJson('evidence-map.json');
25
+ const diff = readFileSync(fixture('change.diff'), 'utf8');
26
+ const expected = readJson('expected.json');
27
+ const actual = scopeDrift(diff, map);
28
+ assert.deepEqual(actual, expected);
29
+ assert.deepEqual(scopeDrift(diff, map), actual, 'deterministic output');
30
+ assert.equal(map.flows.length, 31);
31
+ assert.deepEqual(actual.newFlowCandidates[0].symbols, ['IsDormant', 'IsDueToday', 'IsOverdue']);
32
+ assert.ok(actual.untouchedFlows.includes('Crm/Tags/Tags'));
33
+ const cli = spawnSync(process.execPath, [fileURLToPath(new URL('./drift-scope.mjs', import.meta.url)),
34
+ fileURLToPath(fixture('change.diff')), fileURLToPath(fixture('evidence-map.json'))], { encoding: 'utf8', timeout: 10000 });
35
+ assert.equal(cli.error, undefined);
36
+ assert.equal(cli.status, 0, cli.stderr);
37
+ assert.deepEqual(JSON.parse(cli.stdout), expected);
38
+ return 8;
39
+ }
40
+
41
+ function classificationChecks(scopeDrift) {
42
+ const map = miniatureMap();
43
+ const run = (path, body, before) => scopeDrift(change(path, body, before), map);
44
+ assert.equal(run('Source/Crm/Tags/Tags.cs', '@@ -1 +1 @@\n- old();\n+new();').hunks[0].classification, 'process');
45
+ assert.equal(run('Source/Crm/Tags/Tags.cs', '@@ -1 +1 @@\n- same();\n+same();').hunks[0].classification, 'structure-only');
46
+ assert.equal(run('Source/Crm/Tags/Tags.cs', '@@ -1 +1 @@\n-Print("a b");\n+Print("ab");').hunks[0].classification, 'process');
47
+ assert.equal(run('Source/Crm/Tags/Tags.cs', '@@ -1 +0,0 @@\n-DeleteTag();').touchedFlows[0], 'Tags');
48
+ assert.equal(run('Source/Crm/New/New.cs', '@@ -0,0 +1 @@\n+NewRule();').newFlowCandidates.length, 1);
49
+ assert.equal(run('Source/dist/app.js', '@@ -1 +1 @@').hunks[0].reason, 'build output');
50
+ assert.equal(run('Source/.cratis-render.json', '@@ -1 +1 @@').hunks[0].reason, 'scene/build artifact');
51
+ assert.equal(run('Source/Crm/Tags/Tags.ts', '@@ -0,0 +1 @@\n+export const rule = 1;').hunks[0].classification, 'process');
52
+ assert.equal(run('Source/Crm/Tags/Tags.cs', '@@ -0,0 +2 @@\n+// @generated by Cratis\n+// DO NOT EDIT').hunks[0].classification, 'process');
53
+ return 9;
54
+ }
55
+
56
+ function renameAndMappingChecks(scopeDrift) {
57
+ const map = miniatureMap();
58
+ const renamed = 'diff --git a/Source/Crm/Tags/Tags.cs b/Source/Moved.cs\nsimilarity index 100%\nrename from Source/Crm/Tags/Tags.cs\nrename to Source/Moved.cs\n';
59
+ assert.equal(scopeDrift(renamed, map).hunks[0].classification, 'structure-only');
60
+ const changed = change('Source/Moved.cs', '@@ -1 +1 @@\n-old();\n+changed();', 'Source/Crm/Tags/Tags.cs');
61
+ assert.deepEqual(scopeDrift(changed, map).touchedFlows, ['Tags']);
62
+ const mixed = change('Source/Crm/Tags/Tags.cs', '@@ -1 +1 @@\n- same();\n+same();\n@@ -9 +9 @@\n-old();\n+new();');
63
+ assert.deepEqual(scopeDrift(mixed, map).hunks.map(hunk => hunk.classification), ['structure-only', 'process']);
64
+ const oneSegment = miniatureMap(['Source/*/Tags.cs']);
65
+ assert.equal(scopeDrift(change('Source/Crm/Tags.cs', '@@ -1 +1 @@\n+x'), oneSegment).touchedFlows.length, 1);
66
+ assert.equal(scopeDrift(change('Source/Crm/Other/Tags.cs', '@@ -1 +1 @@\n+x'), oneSegment).touchedFlows.length, 0);
67
+ const literal = miniatureMap(['Source/a.b.cs']);
68
+ assert.equal(scopeDrift(change('Source/axb.cs', '@@ -1 +1 @@\n+x'), literal).touchedFlows.length, 0);
69
+ return 6;
70
+ }
71
+
72
+ function rejectionChecks(scopeDrift) {
73
+ const diff = change('Source/Crm/Tags/Tags.cs', '@@ -1 +1 @@\n+x');
74
+ assert.throws(() => scopeDrift('', miniatureMap()), /unified diff/);
75
+ for (const map of [null, {}, { watermarks: {} }, { watermarks: { from: { revision: 'x' } } }]) {
76
+ assert.throws(() => scopeDrift(diff, map), /revision or inputDigest/);
77
+ }
78
+ for (const flows of [[], null, [{ id: 'Tags', paths: [] }], [miniatureMap().flows[0], miniatureMap().flows[0]]]) {
79
+ assert.throws(() => scopeDrift(diff, { ...miniatureMap(), flows }), /flows|paths|Duplicate flow/);
80
+ }
81
+ return 9;
82
+ }
83
+
84
+ export function selfTest(scopeDrift) {
85
+ const checks = fixtureChecks(scopeDrift) + classificationChecks(scopeDrift) + renameAndMappingChecks(scopeDrift) + rejectionChecks(scopeDrift);
86
+ console.log(`drift-scope self-test: ${checks} checks passed; SoloCrm: 3 process, 4 structure-only, 2 touched, 29 kept, Today candidates IsDormant/IsDueToday/IsOverdue`);
87
+ }
@@ -0,0 +1,155 @@
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
+ import { readFileSync } from 'node:fs';
5
+ import { resolve } from 'node:path';
6
+ import { pathToFileURL } from 'node:url';
7
+
8
+ function nonempty(value) {
9
+ return typeof value === 'string' && value.trim().length > 0;
10
+ }
11
+
12
+ function strings(value) {
13
+ return Array.isArray(value) && value.length > 0 && value.every(nonempty);
14
+ }
15
+
16
+ function validateWatermark(mark, side) {
17
+ const valid = ['revision', 'inputDigest'].every(key => nonempty(mark?.[key]));
18
+ if (!valid) throw new Error(`Missing ${side} revision or inputDigest`);
19
+ }
20
+
21
+ function validateFlow(flow) {
22
+ const valid = [nonempty(flow?.id), strings(flow?.paths), strings(flow?.evidenceIds)].every(Boolean);
23
+ if (!valid) throw new Error('Each flow needs id, paths and evidenceIds');
24
+ }
25
+
26
+ function validateMap(map) {
27
+ for (const side of ['from', 'to']) validateWatermark(map?.watermarks?.[side], side);
28
+ if (!Array.isArray(map.flows)) throw new Error('Evidence map needs nonempty flows');
29
+ if (map.flows.length === 0) throw new Error('Evidence map needs nonempty flows');
30
+ map.flows.forEach(validateFlow);
31
+ const ids = map.flows.map(flow => flow.id);
32
+ if (new Set(ids).size !== ids.length) throw new Error('Duplicate flow ids');
33
+ }
34
+
35
+ /** Deliberately small glob language: * matches one path segment, ** crosses segments. */
36
+ function matches(path, glob) {
37
+ const expression = glob.split(/(\*\*|\*)/).map(part => {
38
+ if (part === '**') return '.*';
39
+ if (part === '*') return '[^/]*';
40
+ return part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
41
+ }).join('');
42
+ return new RegExp(`^${expression}$`).test(path);
43
+ }
44
+
45
+ function addLine(file, line) {
46
+ if (line.startsWith('@@ ')) file.hunks.push({ header: line, lines: [] });
47
+ else if (file.hunks.length > 0) file.hunks.at(-1).lines.push(line);
48
+ else file.metadata.push(line);
49
+ }
50
+
51
+ function parseDiff(diff) {
52
+ const files = [];
53
+ for (const line of diff.replaceAll('\r\n', '\n').split('\n')) {
54
+ const header = /^diff --git a\/(.+) b\/(.+)$/.exec(line);
55
+ if (header) files.push({ before: header[1], path: header[2], metadata: [], hunks: [] });
56
+ else if (files.length > 0) addLine(files.at(-1), line);
57
+ }
58
+ if (files.length === 0) throw new Error('Expected a Git unified diff with diff --git headers');
59
+ return files;
60
+ }
61
+
62
+ const artifactRules = [
63
+ { pattern: /(^|\/)(yarn\.lock|package-lock\.json|pnpm-lock\.yaml|packages\.lock\.json)$/, reason: 'lockfile' },
64
+ { pattern: /(^|\/)(scene\.json|stage-scene\.json|\.cratis-render\.json)$/, reason: 'scene/build artifact' },
65
+ { pattern: /(^|\/)(obj|bin|dist)\//, reason: 'build output' },
66
+ ];
67
+
68
+ function generatedProxy(file) {
69
+ if (!/\.tsx?$/.test(file.path)) return false;
70
+ const text = file.hunks.flatMap(hunk => hunk.lines).join('\n');
71
+ return [/@generated by Cratis/, /DO NOT EDIT/].every(marker => marker.test(text));
72
+ }
73
+
74
+ function artifactReason(file) {
75
+ const rule = artifactRules.find(rule => rule.pattern.test(file.path));
76
+ if (rule) return rule.reason;
77
+ return generatedProxy(file) ? 'generated TypeScript proxy' : null;
78
+ }
79
+
80
+ function indentationOnly(lines) {
81
+ const content = prefix => lines.filter(line => line.startsWith(prefix)).map(line => line.slice(1).trim()).filter(Boolean);
82
+ const removed = content('-');
83
+ const added = content('+');
84
+ return removed.length + added.length > 0 && JSON.stringify(removed) === JSON.stringify(added);
85
+ }
86
+
87
+ function unchangedRename(file, hunk) {
88
+ if (hunk) return false;
89
+ if (file.before === file.path) return false;
90
+ return file.metadata.includes('similarity index 100%');
91
+ }
92
+
93
+ function classify(file, hunk, artifact) {
94
+ if (artifact) return { classification: 'structure-only', reason: artifact };
95
+ if (hunk && indentationOnly(hunk.lines)) return { classification: 'structure-only', reason: 'indentation/blank-line change only' };
96
+ if (unchangedRename(file, hunk)) return { classification: 'structure-only', reason: 'unchanged-content rename' };
97
+ return { classification: 'process', reason: 'behavior source or unrecognized change; re-derive before deciding drift' };
98
+ }
99
+
100
+ function symbols(lines) {
101
+ const names = lines.filter(line => line.startsWith('+')).flatMap(line => {
102
+ const match = /public static \S+ (\w+)\(/.exec(line);
103
+ return match ? [match[1]] : [];
104
+ });
105
+ return [...new Set(names)].sort();
106
+ }
107
+
108
+ function fileScope(file, flows) {
109
+ const artifact = artifactReason(file);
110
+ const mapped = flows.filter(flow => flow.paths.some(glob => matches(file.path, glob) || matches(file.before, glob)));
111
+ return (file.hunks.length ? file.hunks : [null]).map(hunk => {
112
+ const verdict = classify(file, hunk, artifact);
113
+ return {
114
+ path: file.path, before: file.before, hunk: hunk?.header ?? null, ...verdict,
115
+ flows: verdict.classification === 'process' ? mapped.map(flow => flow.id).sort() : [],
116
+ };
117
+ });
118
+ }
119
+
120
+ /** Work-list hints, not semantic proof of drift or permission to advance a watermark. */
121
+ export function scopeDrift(diff, map) {
122
+ validateMap(map);
123
+ const files = parseDiff(diff);
124
+ const hunks = files.flatMap(file => fileScope(file, map.flows));
125
+ const touchedFlows = [...new Set(hunks.flatMap(hunk => hunk.flows))].sort();
126
+ const candidates = new Set(hunks.filter(hunk => hunk.classification === 'process' && hunk.flows.length === 0).map(hunk => hunk.path));
127
+ const newFlowCandidates = [...candidates].sort().map(path => ({
128
+ path, symbols: symbols(files.filter(file => file.path === path).flatMap(file => file.hunks.flatMap(hunk => hunk.lines))),
129
+ reason: 'unmapped source; intake a candidate flow (including deletions or unsupported changes)',
130
+ }));
131
+ return {
132
+ watermarks: map.watermarks, hunks, touchedFlows,
133
+ untouchedFlows: map.flows.map(flow => flow.id).filter(id => !touchedFlows.includes(id)).sort(),
134
+ newFlowCandidates,
135
+ structureOnlyCount: hunks.filter(hunk => hunk.classification === 'structure-only').length,
136
+ };
137
+ }
138
+
139
+ export async function main(args = process.argv.slice(2)) {
140
+ try {
141
+ if (args.length === 1 && args[0] === '--self-test') {
142
+ const { selfTest } = await import('./drift-scope-self-test.mjs');
143
+ selfTest(scopeDrift);
144
+ return 0;
145
+ }
146
+ if (args.length !== 2) throw new Error('Usage: node drift-scope.mjs <diff> <evidence-map.json> | --self-test');
147
+ console.log(JSON.stringify(scopeDrift(readFileSync(args[0], 'utf8'), JSON.parse(readFileSync(args[1], 'utf8'))), null, 2));
148
+ return 0;
149
+ } catch (error) {
150
+ console.error(`drift-scope: ${error.message}`);
151
+ return 1;
152
+ }
153
+ }
154
+
155
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) process.exitCode = await main();
@@ -0,0 +1,23 @@
1
+ # SoloCrm process-drift case
2
+
3
+ Read-only source: SoloCrmIn5Minutes, `0cd6557..df908a2`. The first revision's
4
+ `Screenplay/Crm.play` has 31 slices and no Today feature. The later revision adds
5
+ OverdueTasks, TasksDueToday and DormantOpportunities plus hand-written date rules.
6
+
7
+ `change.diff` excerpts `git diff --unified=2` for the two existing C# query files and
8
+ includes the complete added TodayRules.cs. The generated Tasks.ts retains its header
9
+ only; yarn.lock, scene.json and src/stage-scene.json retain file/hunk headers only.
10
+ Original hunk ranges are retained: this is a scope fixture, not an applyable patch.
11
+ Other changed files, including Crm.play, are deliberately omitted. The keep list is
12
+ relative to these excerpts, not a claim that the full revision has no other drift.
13
+
14
+ `evidence-map.json` projects every baseline slice to its rendered source folder.
15
+ RE-E1 through RE-E31 are fixture-local evidence ids: each `modelLocator` cites the
16
+ baseline declaration, not a claim that implementation behavior was verified.
17
+ Paths include generated proxies so the artifact precedence is exercised. The two
18
+ watermarks carry SHA-256 digests of the respective `Screenplay/Crm.play` inputs,
19
+ not digests of the entire repositories. No private checkout is needed to run the test.
20
+
21
+ `expected.json` is the complete expected scope result: two existing flows to
22
+ re-derive, 29 to keep, and one unmapped Today source candidate with symbols for
23
+ overdue, due-today and dormant rules. It is a work list, not an accepted model delta.
@@ -0,0 +1,131 @@
1
+ diff --git a/Source/Crm/Opportunities/Pipeline/Pipeline.cs b/Source/Crm/Opportunities/Pipeline/Pipeline.cs
2
+ index e401bf9..2b47c7c 100644
3
+ --- a/Source/Crm/Opportunities/Pipeline/Pipeline.cs
4
+ +++ b/Source/Crm/Opportunities/Pipeline/Pipeline.cs
5
+ @@ -30,4 +30,7 @@ public record Opportunity(global::SoloCrm.Common.OpportunityTitle Title, global:
6
+ [global::Cratis.Arc.Authorization.AllowAnonymousAttribute]
7
+ public static global::System.Reactive.Subjects.ISubject<global::System.Collections.Generic.IEnumerable<Opportunity>> AllOpportunities(global::Cratis.Chronicle.ReadModels.IReadModels readModels) => readModels.Observe<Opportunity>();
8
+ +
9
+ + [global::Cratis.Arc.Authorization.AllowAnonymousAttribute]
10
+ + public static global::System.Reactive.Subjects.ISubject<global::System.Collections.Generic.IEnumerable<Opportunity>> DormantOpportunities(global::Cratis.Chronicle.ReadModels.IReadModels readModels) => global::SoloCrm.Crm.Today.TodayRules.Where(readModels.Observe<Opportunity>(), global::SoloCrm.Crm.Today.TodayRules.IsDormant);
11
+ }
12
+ diff --git a/Source/Crm/Tasks/Tasks/Tasks.cs b/Source/Crm/Tasks/Tasks/Tasks.cs
13
+ index 7298e09..422a293 100644
14
+ --- a/Source/Crm/Tasks/Tasks/Tasks.cs
15
+ +++ b/Source/Crm/Tasks/Tasks/Tasks.cs
16
+ @@ -25,4 +25,10 @@ public record TaskItem(string RegardingId, global::SoloCrm.Common.TaskTitle Titl
17
+ [global::Cratis.Arc.Authorization.AllowAnonymousAttribute]
18
+ public static global::System.Reactive.Subjects.ISubject<global::System.Collections.Generic.IEnumerable<TaskItem>> AllTasks(global::Cratis.Chronicle.ReadModels.IReadModels readModels, bool? isCompleted = null) => readModels.Observe<TaskItem>(instance => (isCompleted == null || global::System.Collections.Generic.EqualityComparer<bool?>.Default.Equals(instance.IsCompleted, isCompleted)));
19
+ +
20
+ + [global::Cratis.Arc.Authorization.AllowAnonymousAttribute]
21
+ + public static global::System.Reactive.Subjects.ISubject<global::System.Collections.Generic.IEnumerable<TaskItem>> OverdueTasks(global::Cratis.Chronicle.ReadModels.IReadModels readModels) => global::SoloCrm.Crm.Today.TodayRules.Where(readModels.Observe<TaskItem>(), global::SoloCrm.Crm.Today.TodayRules.IsOverdue);
22
+ +
23
+ + [global::Cratis.Arc.Authorization.AllowAnonymousAttribute]
24
+ + public static global::System.Reactive.Subjects.ISubject<global::System.Collections.Generic.IEnumerable<TaskItem>> TasksDueToday(global::Cratis.Chronicle.ReadModels.IReadModels readModels) => global::SoloCrm.Crm.Today.TodayRules.Where(readModels.Observe<TaskItem>(), global::SoloCrm.Crm.Today.TodayRules.IsDueToday);
25
+ }
26
+ diff --git a/Source/Crm/Today/TodayRules.cs b/Source/Crm/Today/TodayRules.cs
27
+ new file mode 100644
28
+ index 0000000..c00d172
29
+ --- /dev/null
30
+ +++ b/Source/Crm/Today/TodayRules.cs
31
+ @@ -0,0 +1,74 @@
32
+ +// Copyright (c) Cratis. All rights reserved.
33
+ +// Licensed under the MIT license. See LICENSE file in the project root for full license information.
34
+ +
35
+ +// Hand-written gap-fill: the Today rules from SPEC S1 compare against "today", which the Screenplay
36
+ +// executable subset cannot express (`today` and $context date comparisons are PLAY0268). The model
37
+ +// declares the OverdueTasks, TasksDueToday and DormantOpportunities queries; these rules narrow them.
38
+ +using System.Reactive.Linq;
39
+ +using System.Reactive.Subjects;
40
+ +using SoloCrm.Common;
41
+ +using SoloCrm.Crm.Opportunities.Pipeline;
42
+ +using SoloCrm.Crm.Tasks.Tasks;
43
+ +
44
+ +namespace SoloCrm.Crm.Today;
45
+ +
46
+ +/// <summary>
47
+ +/// The date rules behind the Today view, evaluated in the configured time zone (default Europe/Berlin).
48
+ +/// </summary>
49
+ +public static class TodayRules
50
+ +{
51
+ + /// <summary>The number of calendar days without activity after which an open opportunity is dormant.</summary>
52
+ + public const int DormantAfterDays = 7;
53
+ +
54
+ + static readonly TimeZoneInfo _timeZone = ResolveTimeZone();
55
+ +
56
+ + /// <summary>Gets today's date in the configured time zone.</summary>
57
+ + public static DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, _timeZone).DateTime);
58
+ +
59
+ + /// <summary>Whether a task is open and due before today.</summary>
60
+ + /// <param name="task">The task.</param>
61
+ + /// <returns>True when overdue.</returns>
62
+ + public static bool IsOverdue(TaskItem task) => !task.IsCompleted && task.DueDate < Today;
63
+ +
64
+ + /// <summary>Whether a task is open and due today.</summary>
65
+ + /// <param name="task">The task.</param>
66
+ + /// <returns>True when due today.</returns>
67
+ + public static bool IsDueToday(TaskItem task) => !task.IsCompleted && task.DueDate == Today;
68
+ +
69
+ + /// <summary>Whether an opportunity is open, not archived and has had no activity for the threshold.</summary>
70
+ + /// <param name="opportunity">The opportunity.</param>
71
+ + /// <returns>True when dormant.</returns>
72
+ + public static bool IsDormant(Opportunity opportunity)
73
+ + {
74
+ + if (opportunity.IsArchived || (opportunity.StageStatus is not null && opportunity.StageStatus != StageStatus.Open))
75
+ + {
76
+ + return false;
77
+ + }
78
+ +
79
+ + var lastTouched = opportunity.ReceivedOn;
80
+ + if (opportunity.LastActivityAt is { } lastActivity)
81
+ + {
82
+ + var activityDay = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(lastActivity, _timeZone).DateTime);
83
+ + if (activityDay > lastTouched)
84
+ + {
85
+ + lastTouched = activityDay;
86
+ + }
87
+ + }
88
+ +
89
+ + return lastTouched.AddDays(DormantAfterDays) <= Today;
90
+ + }
91
+ +
92
+ + /// <summary>Narrows an observed collection with a rule, keeping it observable.</summary>
93
+ + /// <typeparam name="T">The read model type.</typeparam>
94
+ + /// <param name="source">The observed collection.</param>
95
+ + /// <param name="rule">The rule an item must satisfy.</param>
96
+ + /// <returns>A subject producing only the matching items.</returns>
97
+ + public static ISubject<IEnumerable<T>> Where<T>(ISubject<IEnumerable<T>> source, Func<T, bool> rule) =>
98
+ + System.Reactive.Subjects.Subject.Create<IEnumerable<T>>(source, source.Select(items => items.Where(rule).ToArray()));
99
+ +
100
+ + static TimeZoneInfo ResolveTimeZone()
101
+ + {
102
+ + var id = Environment.GetEnvironmentVariable("App__TimeZone") ?? "Europe/Berlin";
103
+ + return TimeZoneInfo.TryFindSystemTimeZoneById(id, out var zone) ? zone : TimeZoneInfo.Utc;
104
+ + }
105
+ +}
106
+ diff --git a/Source/Crm/Tasks/Tasks/Tasks.ts b/Source/Crm/Tasks/Tasks/Tasks.ts
107
+ new file mode 100644
108
+ index 0000000..dce490a
109
+ --- /dev/null
110
+ +++ b/Source/Crm/Tasks/Tasks/Tasks.ts
111
+ @@ -0,0 +1,439 @@
112
+ +// Copyright (c) Cratis. All rights reserved.
113
+ +// Licensed under the MIT license. See LICENSE file in the project root for full license information.
114
+ +
115
+ +// @generated by Cratis. Source: SoloCrm.Crm.Tasks.Tasks.TaskItem, SoloCrm.Crm.Tasks.Tasks.TaskItem, SoloCrm.Crm.Tasks.Tasks.TaskItem, SoloCrm.Crm.Tasks.Tasks.TaskItem, SoloCrm.Crm.Tasks.Tasks.TaskItem. Time: 2026-10-22T14:47:52.1631720Z. Hash: DF5CD97919A2A5E11B36B476995EF8E1DC18665058C35D98CEE524C93C1C760D
116
+ +// **DO NOT EDIT** - This file is an automatically generated file.
117
+ diff --git a/Source/yarn.lock b/Source/yarn.lock
118
+ new file mode 100644
119
+ index 0000000..0ec6bad
120
+ --- /dev/null
121
+ +++ b/Source/yarn.lock
122
+ @@ -0,0 +1,1670 @@
123
+ diff --git a/Source/scene.json b/Source/scene.json
124
+ index 27ad977..6692a21 100644
125
+ --- a/Source/scene.json
126
+ +++ b/Source/scene.json
127
+ @@ -1 +1 @@
128
+ diff --git a/Source/src/stage-scene.json b/Source/src/stage-scene.json
129
+ --- a/Source/src/stage-scene.json
130
+ +++ b/Source/src/stage-scene.json
131
+ @@ -1 +1 @@
@@ -0,0 +1,39 @@
1
+ {
2
+ "watermarks": {
3
+ "from": { "revision": "0cd6557", "input": "Screenplay/Crm.play", "inputDigest": "sha256:3b93313c21d1c51ea35dac93377cc852e0a3ee3fee38d998927ba4b90c562c44" },
4
+ "to": { "revision": "df908a2", "input": "Screenplay/Crm.play", "inputDigest": "sha256:166ff866090d299fc955f69826ff70aeef920ad4b53e58168814e1d3fe562ef7" }
5
+ },
6
+ "flows": [
7
+ { "id": "Crm/Organizations/RegisterOrganization", "evidenceIds": ["RE-E1"], "modelLocator": "Screenplay/Crm.play:6-34", "paths": ["Source/Crm/Organizations/RegisterOrganization/**"] },
8
+ { "id": "Crm/Organizations/ArchiveOrganization", "evidenceIds": ["RE-E2"], "modelLocator": "Screenplay/Crm.play:35-39", "paths": ["Source/Crm/Organizations/ArchiveOrganization/**"] },
9
+ { "id": "Crm/Organizations/RestoreOrganization", "evidenceIds": ["RE-E3"], "modelLocator": "Screenplay/Crm.play:40-44", "paths": ["Source/Crm/Organizations/RestoreOrganization/**"] },
10
+ { "id": "Crm/Organizations/Organizations", "evidenceIds": ["RE-E4"], "modelLocator": "Screenplay/Crm.play:45-89", "paths": ["Source/Crm/Organizations/Organizations/**"] },
11
+ { "id": "Crm/Contacts/RegisterContact", "evidenceIds": ["RE-E5"], "modelLocator": "Screenplay/Crm.play:91-137", "paths": ["Source/Crm/Contacts/RegisterContact/**"] },
12
+ { "id": "Crm/Contacts/TagContact", "evidenceIds": ["RE-E6"], "modelLocator": "Screenplay/Crm.play:138-144", "paths": ["Source/Crm/Contacts/TagContact/**"] },
13
+ { "id": "Crm/Contacts/ArchiveContact", "evidenceIds": ["RE-E7"], "modelLocator": "Screenplay/Crm.play:145-149", "paths": ["Source/Crm/Contacts/ArchiveContact/**"] },
14
+ { "id": "Crm/Contacts/RestoreContact", "evidenceIds": ["RE-E8"], "modelLocator": "Screenplay/Crm.play:150-154", "paths": ["Source/Crm/Contacts/RestoreContact/**"] },
15
+ { "id": "Crm/Contacts/Contacts", "evidenceIds": ["RE-E9"], "modelLocator": "Screenplay/Crm.play:155-203", "paths": ["Source/Crm/Contacts/Contacts/**"] },
16
+ { "id": "Crm/Tags/DefineTag", "evidenceIds": ["RE-E10"], "modelLocator": "Screenplay/Crm.play:205-224", "paths": ["Source/Crm/Tags/DefineTag/**"] },
17
+ { "id": "Crm/Tags/Tags", "evidenceIds": ["RE-E11"], "modelLocator": "Screenplay/Crm.play:225-245", "paths": ["Source/Crm/Tags/Tags/**"] },
18
+ { "id": "Crm/Stages/DefineStage", "evidenceIds": ["RE-E12"], "modelLocator": "Screenplay/Crm.play:247-268", "paths": ["Source/Crm/Stages/DefineStage/**"] },
19
+ { "id": "Crm/Stages/RenameStage", "evidenceIds": ["RE-E13"], "modelLocator": "Screenplay/Crm.play:269-275", "paths": ["Source/Crm/Stages/RenameStage/**"] },
20
+ { "id": "Crm/Stages/ReorderStage", "evidenceIds": ["RE-E14"], "modelLocator": "Screenplay/Crm.play:276-282", "paths": ["Source/Crm/Stages/ReorderStage/**"] },
21
+ { "id": "Crm/Stages/Stages", "evidenceIds": ["RE-E15"], "modelLocator": "Screenplay/Crm.play:283-312", "paths": ["Source/Crm/Stages/Stages/**"] },
22
+ { "id": "Crm/Opportunities/RegisterOpportunity", "evidenceIds": ["RE-E16"], "modelLocator": "Screenplay/Crm.play:314-380", "paths": ["Source/Crm/Opportunities/RegisterOpportunity/**"] },
23
+ { "id": "Crm/Opportunities/MoveOpportunityToStage", "evidenceIds": ["RE-E17"], "modelLocator": "Screenplay/Crm.play:381-388", "paths": ["Source/Crm/Opportunities/MoveOpportunityToStage/**"] },
24
+ { "id": "Crm/Opportunities/ChangeOpportunityPricing", "evidenceIds": ["RE-E18"], "modelLocator": "Screenplay/Crm.play:389-406", "paths": ["Source/Crm/Opportunities/ChangeOpportunityPricing/**"] },
25
+ { "id": "Crm/Opportunities/TagOpportunity", "evidenceIds": ["RE-E19"], "modelLocator": "Screenplay/Crm.play:407-413", "paths": ["Source/Crm/Opportunities/TagOpportunity/**"] },
26
+ { "id": "Crm/Opportunities/ArchiveOpportunity", "evidenceIds": ["RE-E20"], "modelLocator": "Screenplay/Crm.play:414-418", "paths": ["Source/Crm/Opportunities/ArchiveOpportunity/**"] },
27
+ { "id": "Crm/Opportunities/RestoreOpportunity", "evidenceIds": ["RE-E21"], "modelLocator": "Screenplay/Crm.play:419-423", "paths": ["Source/Crm/Opportunities/RestoreOpportunity/**"] },
28
+ { "id": "Crm/Opportunities/Pipeline", "evidenceIds": ["RE-E22"], "modelLocator": "Screenplay/Crm.play:424-505", "paths": ["Source/Crm/Opportunities/Pipeline/**"] },
29
+ { "id": "Crm/Timeline/LogOpportunityActivity", "evidenceIds": ["RE-E23"], "modelLocator": "Screenplay/Crm.play:507-520", "paths": ["Source/Crm/Timeline/LogOpportunityActivity/**"] },
30
+ { "id": "Crm/Timeline/LogContactActivity", "evidenceIds": ["RE-E24"], "modelLocator": "Screenplay/Crm.play:521-534", "paths": ["Source/Crm/Timeline/LogContactActivity/**"] },
31
+ { "id": "Crm/Timeline/LogOrganizationActivity", "evidenceIds": ["RE-E25"], "modelLocator": "Screenplay/Crm.play:535-548", "paths": ["Source/Crm/Timeline/LogOrganizationActivity/**"] },
32
+ { "id": "Crm/Timeline/Timeline", "evidenceIds": ["RE-E26"], "modelLocator": "Screenplay/Crm.play:549-598", "paths": ["Source/Crm/Timeline/Timeline/**"] },
33
+ { "id": "Crm/Tasks/AddTask", "evidenceIds": ["RE-E27"], "modelLocator": "Screenplay/Crm.play:600-621", "paths": ["Source/Crm/Tasks/AddTask/**"] },
34
+ { "id": "Crm/Tasks/RescheduleTask", "evidenceIds": ["RE-E28"], "modelLocator": "Screenplay/Crm.play:622-628", "paths": ["Source/Crm/Tasks/RescheduleTask/**"] },
35
+ { "id": "Crm/Tasks/CompleteTask", "evidenceIds": ["RE-E29"], "modelLocator": "Screenplay/Crm.play:629-634", "paths": ["Source/Crm/Tasks/CompleteTask/**"] },
36
+ { "id": "Crm/Tasks/ReopenTask", "evidenceIds": ["RE-E30"], "modelLocator": "Screenplay/Crm.play:635-639", "paths": ["Source/Crm/Tasks/ReopenTask/**"] },
37
+ { "id": "Crm/Tasks/Tasks", "evidenceIds": ["RE-E31"], "modelLocator": "Screenplay/Crm.play:640-678", "paths": ["Source/Crm/Tasks/Tasks/**"] }
38
+ ]
39
+ }
@@ -0,0 +1,52 @@
1
+ {
2
+ "watermarks": {
3
+ "from": { "revision": "0cd6557", "input": "Screenplay/Crm.play", "inputDigest": "sha256:3b93313c21d1c51ea35dac93377cc852e0a3ee3fee38d998927ba4b90c562c44" },
4
+ "to": { "revision": "df908a2", "input": "Screenplay/Crm.play", "inputDigest": "sha256:166ff866090d299fc955f69826ff70aeef920ad4b53e58168814e1d3fe562ef7" }
5
+ },
6
+ "hunks": [
7
+ {
8
+ "path": "Source/Crm/Opportunities/Pipeline/Pipeline.cs", "before": "Source/Crm/Opportunities/Pipeline/Pipeline.cs",
9
+ "hunk": "@@ -30,4 +30,7 @@ public record Opportunity(global::SoloCrm.Common.OpportunityTitle Title, global:",
10
+ "classification": "process", "reason": "behavior source or unrecognized change; re-derive before deciding drift", "flows": ["Crm/Opportunities/Pipeline"]
11
+ },
12
+ {
13
+ "path": "Source/Crm/Tasks/Tasks/Tasks.cs", "before": "Source/Crm/Tasks/Tasks/Tasks.cs",
14
+ "hunk": "@@ -25,4 +25,10 @@ public record TaskItem(string RegardingId, global::SoloCrm.Common.TaskTitle Titl",
15
+ "classification": "process", "reason": "behavior source or unrecognized change; re-derive before deciding drift", "flows": ["Crm/Tasks/Tasks"]
16
+ },
17
+ {
18
+ "path": "Source/Crm/Today/TodayRules.cs", "before": "Source/Crm/Today/TodayRules.cs", "hunk": "@@ -0,0 +1,74 @@",
19
+ "classification": "process", "reason": "behavior source or unrecognized change; re-derive before deciding drift", "flows": []
20
+ },
21
+ {
22
+ "path": "Source/Crm/Tasks/Tasks/Tasks.ts", "before": "Source/Crm/Tasks/Tasks/Tasks.ts", "hunk": "@@ -0,0 +1,439 @@",
23
+ "classification": "structure-only", "reason": "generated TypeScript proxy", "flows": []
24
+ },
25
+ {
26
+ "path": "Source/yarn.lock", "before": "Source/yarn.lock", "hunk": "@@ -0,0 +1,1670 @@",
27
+ "classification": "structure-only", "reason": "lockfile", "flows": []
28
+ },
29
+ {
30
+ "path": "Source/scene.json", "before": "Source/scene.json", "hunk": "@@ -1 +1 @@",
31
+ "classification": "structure-only", "reason": "scene/build artifact", "flows": []
32
+ },
33
+ {
34
+ "path": "Source/src/stage-scene.json", "before": "Source/src/stage-scene.json", "hunk": "@@ -1 +1 @@",
35
+ "classification": "structure-only", "reason": "scene/build artifact", "flows": []
36
+ }
37
+ ],
38
+ "touchedFlows": ["Crm/Opportunities/Pipeline", "Crm/Tasks/Tasks"],
39
+ "untouchedFlows": [
40
+ "Crm/Contacts/ArchiveContact", "Crm/Contacts/Contacts", "Crm/Contacts/RegisterContact", "Crm/Contacts/RestoreContact", "Crm/Contacts/TagContact",
41
+ "Crm/Opportunities/ArchiveOpportunity", "Crm/Opportunities/ChangeOpportunityPricing", "Crm/Opportunities/MoveOpportunityToStage", "Crm/Opportunities/RegisterOpportunity", "Crm/Opportunities/RestoreOpportunity", "Crm/Opportunities/TagOpportunity",
42
+ "Crm/Organizations/ArchiveOrganization", "Crm/Organizations/Organizations", "Crm/Organizations/RegisterOrganization", "Crm/Organizations/RestoreOrganization",
43
+ "Crm/Stages/DefineStage", "Crm/Stages/RenameStage", "Crm/Stages/ReorderStage", "Crm/Stages/Stages",
44
+ "Crm/Tags/DefineTag", "Crm/Tags/Tags",
45
+ "Crm/Tasks/AddTask", "Crm/Tasks/CompleteTask", "Crm/Tasks/ReopenTask", "Crm/Tasks/RescheduleTask",
46
+ "Crm/Timeline/LogContactActivity", "Crm/Timeline/LogOpportunityActivity", "Crm/Timeline/LogOrganizationActivity", "Crm/Timeline/Timeline"
47
+ ],
48
+ "newFlowCandidates": [
49
+ { "path": "Source/Crm/Today/TodayRules.cs", "symbols": ["IsDormant", "IsDueToday", "IsOverdue"], "reason": "unmapped source; intake a candidate flow (including deletions or unsupported changes)" }
50
+ ],
51
+ "structureOnlyCount": 4
52
+ }
@@ -29,6 +29,8 @@
29
29
  { "kind": "skill-contains", "value": "Managed assembly intake", "file": "references/executable-intake.md" },
30
30
  { "kind": "skill-contains", "value": "Naming (non-leaked)", "file": "references/ground-truth-benchmark.md" },
31
31
  { "kind": "skill-contains", "value": "behavior catalog" },
32
- { "kind": "skill-contains", "value": "score-fidelity.mjs" }
32
+ { "kind": "skill-contains", "value": "score-fidelity.mjs" },
33
+ { "kind": "skill-contains", "value": "drift-scope.mjs --self-test" },
34
+ { "kind": "skill-contains", "value": "structure-only", "file": "references/process-drift.md" }
33
35
  ]
34
36
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cratis/pi",
3
- "version": "7.148.0",
3
+ "version": "7.149.0",
4
4
  "description": "Configuration-aware Cratis AI integration for Pi",
5
5
  "type": "module",
6
6
  "files": [
package/src/index.ts CHANGED
@@ -23,22 +23,23 @@ function skillPath(skill: string): string {
23
23
  return join(corpusRoot, 'skills', skill);
24
24
  }
25
25
 
26
- function allSkillPaths(): string[] {
27
- return [...new Set(profiles.flatMap(profile => profile.availableTargets ?? []))]
26
+ function skillPathsOf(selected: Profile[]): string[] {
27
+ return [...new Set(selected.flatMap(profile => profile.availableTargets ?? []))]
28
28
  .sort()
29
29
  .map(skillPath);
30
30
  }
31
31
 
32
+ function allSkillPaths(): string[] {
33
+ return skillPathsOf(profiles);
34
+ }
35
+
32
36
  function supportsLanguage(profile: Profile, languages: Set<string>): boolean {
33
37
  if (!profile.languages?.length) return true;
34
38
  return profile.languages.some(language => language === 'language-agnostic' || languages.has(language));
35
39
  }
36
40
 
37
- export function selectedSkillPaths(cwd: string): string[] {
38
- const configurationPath = join(cwd, '.cratis', 'ai.json');
39
- if (!existsSync(configurationPath)) return allSkillPaths();
40
-
41
- const configuration = JSON.parse(readFileSync(configurationPath, 'utf8')) as AiConfiguration;
41
+ /** The ids of the configured profiles and, transitively, the composed profiles that support the configured languages. */
42
+ function selectedProfileIds(configuration: AiConfiguration): Set<string> {
42
43
  const languages = new Set(configuration.languages ?? []);
43
44
  const selected = new Set<string>();
44
45
  const select = (id: string, explicitSelection: boolean): void => {
@@ -50,9 +51,16 @@ export function selectedSkillPaths(cwd: string): string[] {
50
51
  profile.composes?.forEach(child => select(child, false));
51
52
  };
52
53
  configuration.profiles?.forEach(profile => select(profile, true));
53
- return [...new Set(profiles.filter(profile => selected.has(profile.id)).flatMap(profile => profile.availableTargets ?? []))]
54
- .sort()
55
- .map(skillPath);
54
+ return selected;
55
+ }
56
+
57
+ export function selectedSkillPaths(cwd: string): string[] {
58
+ const configurationPath = join(cwd, '.cratis', 'ai.json');
59
+ if (!existsSync(configurationPath)) return allSkillPaths();
60
+
61
+ const configuration = JSON.parse(readFileSync(configurationPath, 'utf8')) as AiConfiguration;
62
+ const selected = selectedProfileIds(configuration);
63
+ return skillPathsOf(profiles.filter(profile => selected.has(profile.id)));
56
64
  }
57
65
 
58
66
  function isManagedInstallation(cwd: string): boolean {
@@ -68,35 +76,39 @@ function frontmatterValue(content: string, name: string): string | undefined {
68
76
  return line?.slice(prefix.length).trim().replace(/^"|"$/g, '');
69
77
  }
70
78
 
79
+ function profileMatchesSelection(profile: string | undefined, selectedProfiles: string[]): boolean {
80
+ if (profile === 'application') return selectedProfiles.some(candidate => candidate.startsWith('cratis/application'));
81
+ if (profile === 'framework') return selectedProfiles.some(candidate => candidate.startsWith('cratis/engineering'));
82
+ if (profile?.startsWith('cratis/')) return selectedProfiles.some(candidate => candidate === profile || candidate.startsWith(`${profile}/`));
83
+ return true;
84
+ }
85
+
86
+ /** A scope kind a rule can name through `applyTo`, and the configuration that satisfies it. */
87
+ interface ScopeKind {
88
+ named: (applyTo: string, path: string) => boolean;
89
+ satisfied: (configuration: AiConfiguration) => boolean;
90
+ }
91
+
92
+ const hasLanguage = (language: string) => (configuration: AiConfiguration) => (configuration.languages ?? []).includes(language);
93
+
94
+ const scopeKinds: ScopeKind[] = [
95
+ { named: applyTo => applyTo.includes('.cs'), satisfied: hasLanguage('csharp') },
96
+ { named: (applyTo, path) => applyTo.includes('.ts') || path.endsWith('/rtk.md'), satisfied: hasLanguage('typescript') },
97
+ { named: applyTo => applyTo.includes('.go') || applyTo.includes('go.mod') || applyTo.includes('go.sum'), satisfied: hasLanguage('go') },
98
+ { named: applyTo => applyTo.includes('.kt'), satisfied: hasLanguage('kotlin') },
99
+ { named: applyTo => applyTo.includes('.java'), satisfied: hasLanguage('java') },
100
+ { named: applyTo => applyTo.includes('.ex'), satisfied: hasLanguage('elixir') },
101
+ { named: applyTo => applyTo.includes('md'), satisfied: configuration => (configuration.profiles ?? []).includes('cratis/documentation') },
102
+ ];
103
+
71
104
  function ruleMatchesConfiguration(path: string, content: string, configuration: AiConfiguration): boolean {
72
- const selectedProfiles = configuration.profiles ?? [];
73
- const profile = frontmatterValue(content, 'profile');
74
- const hasApplicationProfile = selectedProfiles.some(candidate => candidate.startsWith('cratis/application'));
75
- const hasEngineeringProfile = selectedProfiles.some(candidate => candidate.startsWith('cratis/engineering'));
76
- if (profile === 'application' && !hasApplicationProfile) return false;
77
- if (profile === 'framework' && !hasEngineeringProfile) return false;
78
- if (profile?.startsWith('cratis/') && !selectedProfiles.some(candidate => candidate === profile || candidate.startsWith(`${profile}/`))) return false;
79
-
80
- const languages = configuration.languages ?? [];
81
- if (languages.length === 0) return true;
105
+ if (!profileMatchesSelection(frontmatterValue(content, 'profile'), configuration.profiles ?? [])) return false;
106
+ if ((configuration.languages ?? []).length === 0) return true;
82
107
  const applyTo = frontmatterValue(content, 'applyTo') ?? '';
83
- const needsCSharp = applyTo.includes('.cs');
84
- const needsTypeScript = applyTo.includes('.ts') || path.endsWith('/rtk.md');
85
- const needsGo = applyTo.includes('.go') || applyTo.includes('go.mod') || applyTo.includes('go.sum');
86
- const needsKotlin = applyTo.includes('.kt');
87
- const needsJava = applyTo.includes('.java');
88
- const needsElixir = applyTo.includes('.ex');
89
- const needsDocumentation = applyTo.includes('md');
90
108
  // A scope that also names model files (`.play`) is not tied to one language, so it is always kept.
91
109
  if (applyTo.includes('.play')) return true;
92
- if (!needsCSharp && !needsTypeScript && !needsGo && !needsKotlin && !needsJava && !needsElixir && !needsDocumentation) return true;
93
- return (needsCSharp && languages.includes('csharp')) ||
94
- (needsTypeScript && languages.includes('typescript')) ||
95
- (needsGo && languages.includes('go')) ||
96
- (needsKotlin && languages.includes('kotlin')) ||
97
- (needsJava && languages.includes('java')) ||
98
- (needsElixir && languages.includes('elixir')) ||
99
- (needsDocumentation && selectedProfiles.includes('cratis/documentation'));
110
+ const named = scopeKinds.filter(kind => kind.named(applyTo, path));
111
+ return named.length === 0 || named.some(kind => kind.satisfied(configuration));
100
112
  }
101
113
 
102
114
  /**