suppa-mcp-2 1.44.1 → 1.44.3
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.
- package/README.md +6 -0
- package/package.json +1 -1
- package/skills/building-suppa-automations/SKILL.md +53 -3
- package/skills/building-suppa-automations/references/node-reference.md +4 -2
- package/skills/building-suppa-automations/scripts/lint-graph.mjs +28 -0
- package/skills/suppa-entity-code/SKILL.md +3 -0
- package/skills/suppa-entity-code/references/enforcement.md +31 -4
- package/skills/suppa-entity-code/scripts/entity-code-guard.mjs +330 -29
- package/skills/suppa-entity-code/scripts/validate-suppa-schema.mjs +28 -7
package/README.md
CHANGED
|
@@ -658,6 +658,9 @@ commit, a `.gitlab/suppa-schema-gate.yml` job refuses the merge request, and a
|
|
|
658
658
|
managed section in `AGENTS.md` / `CLAUDE.md` carries the same rules to editors
|
|
659
659
|
with no hook support. Re-running the installer is safe, `--dry-run` prints the
|
|
660
660
|
plan, and details are in `skills/suppa-entity-code/references/enforcement.md`.
|
|
661
|
+
The hook layers count what a change brings — findings in the files it touches,
|
|
662
|
+
and anything HEAD did not have. Older findings are listed, not counted, and CI
|
|
663
|
+
counts everything.
|
|
661
664
|
|
|
662
665
|
It also enforces the **authoring rules** the platform doc does not: a
|
|
663
666
|
relation property must carry a TypeScript type that agrees with its decorator
|
|
@@ -722,6 +725,9 @@ process when someone opens it:
|
|
|
722
725
|
- request and form flows take what the submission already carries (`formData`,
|
|
723
726
|
`number`, `createdBy`) instead of selecting it again;
|
|
724
727
|
- business rules are visible on the canvas, technical logic goes into one `code` node.
|
|
728
|
+
- **Settings and the Set node.** `$workflow.settings` is read in any expression, trigger
|
|
729
|
+
conditions included, with no read node; a Set «Config» holds per-flow constants;
|
|
730
|
+
settings are never state and never hold secrets (those are credentials).
|
|
725
731
|
- **Publishing that survives the builder.** It writes through the API with the builder
|
|
726
732
|
tab closed, verifies the draft by hash, then publishes and tests a live run.
|
|
727
733
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "suppa-mcp-2",
|
|
3
|
-
"version": "1.44.
|
|
3
|
+
"version": "1.44.3",
|
|
4
4
|
"description": "MCP server for the Suppa platform (modern.suppa.me) — Tasks, Docs/Pages, Entities & Schema, Forms, Automations, and file attachments, with multi-tenant Google auth. Node port of PyPI suppa-mcp.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -33,7 +33,7 @@ Parameter shapes (triggers, conditions, switch outputs, approvals, links) are in
|
|
|
33
33
|
- **Loop protection is keyed by workflow id.** A write from flow A never starts flow B of the same automation. A write from another automation does start it. So:
|
|
34
34
|
- inside one automation, the flow that writes does its own follow-up (mark the request rejected, notify);
|
|
35
35
|
- across automations, the same write runs twice. That is the classic duplicate notification.
|
|
36
|
-
- **Settings live in the automation.** Put everything tenant-specific in `settings.<key>`: people, project and stage ids, BP switches, testMode.
|
|
36
|
+
- **Settings live in the automation.** Put everything tenant-specific in `settings.<key>`: people, project and stage ids, BP switches, testMode. Every expression reads it directly, trigger conditions included: `={{ $workflow.settings.<key>.<name> }}`. No settings read node is needed, and no separate settings record or select. Details and limits are in «Settings and the Set node».
|
|
37
37
|
|
|
38
38
|
## Requests and form submissions: the trigger already holds the data
|
|
39
39
|
|
|
@@ -111,7 +111,53 @@ Someone who opens the automation should read the flow from the canvas alone. Eve
|
|
|
111
111
|
|
|
112
112
|
- **Do not leave dangling ends by accident.** A free `false` / `rejected` / switch output must be intended. Say so in the description, or connect it.
|
|
113
113
|
- **Size budget.** More than ~25 nodes or ~20 columns in one flow means it no longer reads at a glance. Move logic into a `code` node or drop decoration before splitting.
|
|
114
|
-
- **Settings over literals.** Ids, people, stages and switches live in settings. The trigger filter
|
|
114
|
+
- **Settings over literals.** Ids, people, stages and switches live in settings. The trigger filter reads them too (`"value": "={{ $workflow.settings.<key>.stages }}"`), so a change needs a republish, not a rebuild.
|
|
115
|
+
|
|
116
|
+
## Settings and the Set node
|
|
117
|
+
|
|
118
|
+
Verified on modern-expo.test (2026-10-27, a throwaway probe automation):
|
|
119
|
+
- `$workflow.settings.*` resolves in any node's expressions and in trigger conditions;
|
|
120
|
+
- a production run sees the **published** settings: a draft change it ignored until the republish.
|
|
121
|
+
|
|
122
|
+
| Where a value lives | Use it for | How it is read |
|
|
123
|
+
|---|---|---|
|
|
124
|
+
| `settings.<key>` | Everything tenant-specific the whole automation shares: people, project / stage ids, switches, testMode. **The only place a trigger condition can read from** | `={{ $workflow.settings.<key>.<name> }}` in any expression. A `code` node has no `$workflow`, so pass it through the `set` before it |
|
|
125
|
+
| A `set` node «Config» right after the trigger | Constants and derived values local to one flow, including ones computed from settings (`={{ $workflow.settings.<key>.limit * 2 }}`) | `={{ $('A1.1 Config').first().json.<name> }}` |
|
|
126
|
+
| A dedicated directory entity (real relation fields) | Many record references, or references that must survive moving the automation between dev / stage / prod | A `suppa` read |
|
|
127
|
+
| Credentials | **Secrets.** Never in settings or a `set`: every value an expression produces lands in the run data, which anyone who can read the automation's runs can see | — |
|
|
128
|
+
|
|
129
|
+
**Settings: shape and limits**
|
|
130
|
+
- **A relation from settings is written like any relation, `{ id }`, and the expression must be the whole field.** A Suppa node passes `fields` to entity-builder as they are.
|
|
131
|
+
|
|
132
|
+
| Field type | Value |
|
|
133
|
+
|---|---|
|
|
134
|
+
| many-to-one | `"responsible": "={{ { id: $workflow.settings.<key>.responsibleId } }}"` |
|
|
135
|
+
| many-to-many, replaced | `"watchers": "={{ $workflow.settings.<key>.watchers }}"`, with settings holding `[{ "id": 5 }, { "id": 7 }]` |
|
|
136
|
+
| many-to-many, added or removed | the same, plus `merge` / `unmerge: ["watchers"]` on an update |
|
|
137
|
+
| enum (a relation in 2.0) | `{ id: <enumValueId> }`, never the value text |
|
|
138
|
+
|
|
139
|
+
- `={{ … }}` in the middle of text turns an object into the string `[object Object]`. This was verified: `"owner ={{ { id: 1 } }}"` gave `"owner [object Object]"`.
|
|
140
|
+
- A bare number instead of `{ id }` returns success and stores `null`.
|
|
141
|
+
- **An id in settings is a number in JSON, not a relation.**
|
|
142
|
+
- Nothing checks that the record exists. A deleted record leaves a dangling id.
|
|
143
|
+
- Ids differ between tenants and environments. Moving an automation between dev, stage and prod does not remap the ids inside settings.
|
|
144
|
+
- Fields of that record are **not** reachable through settings. `$workflow.settings.<key>.responsible.name` does not exist, and lazy loading works only for `$json` items. For a name, read the record (`getById`).
|
|
145
|
+
- Settings suit one or two stable records, such as a default assignee. For many references, or ones that must survive environment moves, use a directory entity with real relation fields.
|
|
146
|
+
- **One top-level key per process (`settings.itRequest`).** The platform keeps keys of its own next to yours (seen on test: `alertUserIds`, `fullRefresh`, `definitionKey` / `definitionVersion`; the engine also reads `rateLimit*`, `errorBreaker*` and `alertChannels` there). An update merges top-level keys, so resend your whole `settings.<key>` and never replace the object as a whole.
|
|
147
|
+
- `settings.variables` / `$vars` is not available yet: `typeof $vars` is `undefined` in a run. Keep user-facing configuration under your own key.
|
|
148
|
+
|
|
149
|
+
**The Set node «Config»: what it does and does not do**
|
|
150
|
+
- **It is not visible to trigger conditions.** They are checked before any node has run, so filters read settings only.
|
|
151
|
+
- **It must be on the path the run took.** `$('Config')` sees only nodes that ran in this run. On a branch that did not run, it is `undefined`, and no error is raised.
|
|
152
|
+
- **It reshapes the item.**
|
|
153
|
+
- Without `keepOnlySet`, the config fields join `$json` and travel on with the record.
|
|
154
|
+
- With `keepOnlySet: true`, the item becomes the config, and the trigger data is reachable only through `$('A1. Start…')`.
|
|
155
|
+
- **Changing a value needs a republish, as with settings.** The value is part of the published nodes. A test run sees the draft at once.
|
|
156
|
+
|
|
157
|
+
**Settings are not state.** Nothing a run does reaches the automation's published settings:
|
|
158
|
+
- A `set` changes only the items moving through the flow.
|
|
159
|
+
- A Suppa write to `AutomationWorkflow.settings` changes only the **draft**. entity-builder's `AutomationDraftGuardExtension` strips every write to `activeSettings` except the publish, and raises `hasUnpublishedChanges`. Production runs do not see the value, and a run already going keeps its snapshot. An automation that edits itself is a bad idea in any case.
|
|
160
|
+
- A counter or a «last processed» marker belongs in a record of its own entity, read and written by `suppa` nodes.
|
|
115
161
|
|
|
116
162
|
## Safe runs
|
|
117
163
|
|
|
@@ -144,7 +190,7 @@ Someone who opens the automation should read the flow from the canvas alone. Eve
|
|
|
144
190
|
## Optimize with measurements
|
|
145
191
|
|
|
146
192
|
- `suppa_get_automation_run` gives per-node timings. Writes cost 150–500 ms each (create task, link, update); reads cost about 30 ms each, plus a node on the canvas. Reads of **the same entity** merge into one query (see «One read per entity per flow»). Reads of different entities stay separate nodes, because merging them through `code` hides what the flow reads.
|
|
147
|
-
- **Idle runs** are the real waste. Filter in the trigger: `watchFields` plus `conditions` (for example `stage.id in [...]`), so moves that mean nothing start no run.
|
|
193
|
+
- **Idle runs** are the real waste. Filter in the trigger: `watchFields` plus `conditions` (for example `stage.id in [...]`), so moves that mean nothing start no run. Take the id lists from `$workflow.settings` in the condition value.
|
|
148
194
|
- **A select that returns nothing ends the branch.** Guard optional lookups with an `if`, or fan out to the select and to a `merge` (append) so the flow continues.
|
|
149
195
|
- A `code` node sees only `$json` / `$input`. Feed it from a `set` node that gathers `$('…')` values.
|
|
150
196
|
- testMode: route every role to the test user, and send approvals to a **second** account. An approval whose approver started the run is auto-approved.
|
|
@@ -169,6 +215,10 @@ Follow `references/publishing.md`:
|
|
|
169
215
|
| Guard selects against duplicates from your own other automation | Merge the automations, or let only one side write |
|
|
170
216
|
| `if` true/false or approved/rejected drawn into one row "because same size" | Place by handle offset, detour above |
|
|
171
217
|
| Publishing a draft saved in the builder UI | The UI drops expression `approvers` to `[]`. Rebuild from source |
|
|
218
|
+
| A `getById AutomationWorkflow` node to read settings | `={{ $workflow.settings.<key> }}` in the expression: one node and one query fewer. `lint-graph` notes it |
|
|
219
|
+
| A secret (token, password) in settings or a `set` | Credentials. Expression values are stored in run data that everyone who reads runs can see |
|
|
220
|
+
| A counter or «last processed» written into settings | Its own entity. A settings write changes only the draft |
|
|
221
|
+
| `"text ={{ { id: x } }}"` for a relation | Make the expression the whole field. In text, an object becomes `[object Object]` |
|
|
172
222
|
| Editing settings partially | Updates merge top-level keys. Resend the whole `settings.<key>`, then republish |
|
|
173
223
|
| Option key `constructor` in settings | The platform strips it. Look options up with `hasOwnProperty` |
|
|
174
224
|
| A node reads `$('X')` where X runs on another branch or later | `undefined` at runtime, with no error. `lint-graph` catches it |
|
|
@@ -33,7 +33,7 @@ Several triggers in one automation are allowed. The run starts at the trigger th
|
|
|
33
33
|
|
|
34
34
|
| Node | Parameters |
|
|
35
35
|
|---|---|
|
|
36
|
-
| `suppa` getById | `{ "action": "getById", "entityName": "
|
|
36
|
+
| `suppa` getById | `{ "action": "getById", "entityName": "Users", "id": "={{ $('A1. Start…').first().json.createdBy.id }}", "fields": {"id": true, "fullName": true, "employees": {"department": {"title": true}}} }` — one record, related records nested in `fields`. Settings need no read node: `={{ $workflow.settings.<key> }}`. |
|
|
37
37
|
| `suppa` select | `{ "action": "select", "entityName": "OrgEmployees", "limit": 50, "fields": {"id": true, "user": {"id": true}}, "conditions": {"operator": "and", "filters": [{"field": "id", "comparator": "in", "value": "={{ … }}"}]} }` — **0 rows ends the branch.** |
|
|
38
38
|
| `suppa` insert / updateById | `{ "action": "updateById", "entityName": "Tasks", "id": "={{ … }}", "fields": {"stage": "={{ x != null ? { id: x } : null }}"}, "merge": ["watchers"] }` — relations are `{id}`. List fields are replaced unless named in `merge`. |
|
|
39
39
|
| `set` | `{ "keepOnlySet": true, "assignments": [{"name": "request", "value": "={{ $('A1. Start: …').first().json }}"}] }` |
|
|
@@ -69,8 +69,10 @@ then read `instanceA.value.id ?? instanceA.id`.
|
|
|
69
69
|
- `={{ js }}` evaluates. Text and several `={{ }}` mix inside one string.
|
|
70
70
|
- Reference a node as `$('Node name').first().json`. `$json` is the incoming item.
|
|
71
71
|
- A trigger or `suppa` item lazily loads `$json.<field>` that was not selected (the item carries `meta.entity`).
|
|
72
|
+
- `$workflow.settings.<key>` is the published settings in any expression, trigger conditions included; a test run sees the draft. A `code` node has no `$workflow` — pass values through a `set`.
|
|
72
73
|
- Settings are stored as jsonb:
|
|
73
74
|
- object keys get re-sorted, so keep an explicit order array;
|
|
74
75
|
- a key named `constructor` is stripped;
|
|
75
76
|
- an update merges top-level keys only, so resend the whole `settings.<key>`;
|
|
76
|
-
-
|
|
77
|
+
- production runs read the published settings, so republish after any change.
|
|
78
|
+
- Never put a secret in settings or a `set`: expression values are kept in run data. Use credentials.
|
|
@@ -125,6 +125,16 @@ export const lint = (graph, { previous } = {}) => {
|
|
|
125
125
|
else if (/formData/.test(text) && fieldKeys.length && fieldKeys.every((k) => k === 'id')) add('WARN', `${n.id}: reads only id of a record picked in the form — formData already has { id }`);
|
|
126
126
|
}
|
|
127
127
|
if (n.type === 'suppa' && p.entityName === 'AutomationWorkflow' && p.action === 'getById' && !/\$workflow\.id/.test(String(p.id))) add('WARN', `${n.id}: reads another automation's settings by literal id — keep settings in this automation ($workflow.id)`);
|
|
128
|
+
else if (n.type === 'suppa' && p.entityName === 'AutomationWorkflow' && p.action === 'getById') add('NOTE', `${n.id}: reads this automation's settings — every expression has them as $workflow.settings.<key>, trigger conditions included; drop the node`);
|
|
129
|
+
// An object literal inside a string that is not ONE whole expression arrives as "[object Object]".
|
|
130
|
+
// Only an object: an array of plain values in text joins as "a,b" (`[a, b].join('-')` is fine), and a
|
|
131
|
+
// string holding two expressions is text even when it starts with ={{ and ends with }}.
|
|
132
|
+
const objectInText = (v) => {
|
|
133
|
+
if (typeof v !== 'string' || !/=\{\{\s*\(?\s*\{/.test(v)) return false;
|
|
134
|
+
return !(v.split('={{').length === 2 && /^=\{\{[\s\S]*\}\}$/.test(v.trim()));
|
|
135
|
+
};
|
|
136
|
+
const values = n.type === 'set' ? (p.assignments || []).map((a) => [a.name, a.value]) : n.type === 'suppa' ? Object.entries(p.fields ?? {}) : [];
|
|
137
|
+
for (const [k, v] of values) if (objectInText(v)) add('WARN', `${n.id}: ${k} builds an object inside text — it arrives as "[object Object]"; make ={{ … }} the whole value`);
|
|
128
138
|
if (n.type === 'triggerEntity') {
|
|
129
139
|
const upd = (p.events || []).some((e) => /update/.test(e));
|
|
130
140
|
if (upd && !(p.watchFields || []).length) add('WARN', `${n.id}: update trigger without watchFields starts a run on every edit`);
|
|
@@ -178,6 +188,24 @@ export const lint = (graph, { previous } = {}) => {
|
|
|
178
188
|
if (t && typeof t === 'object' && !('uk' in t)) add('WARN', `${n.id}: ${key} has no uk — notifications carry the users' language next to en`);
|
|
179
189
|
}
|
|
180
190
|
}
|
|
191
|
+
// Settings values land in run data that anyone reading runs can see: secrets go to credentials.
|
|
192
|
+
// Matched on whole words of the key, so apiToken / webhookSecret / API_KEY are caught and
|
|
193
|
+
// secretaryId / tokenizerMode are not; only a filled string can be a secret.
|
|
194
|
+
const secretLike = (key) => {
|
|
195
|
+
const words = key.replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
|
|
196
|
+
return words.some((w, i) => /^(password|passwd|secret|token|apikey|privatekey)s?$/.test(w) || (/^(api|private)$/.test(w) && words[i + 1] === 'key'));
|
|
197
|
+
};
|
|
198
|
+
const secretKeys = [];
|
|
199
|
+
const walk = (v, path) => {
|
|
200
|
+
if (!v || typeof v !== 'object') return;
|
|
201
|
+
for (const [k, x] of Object.entries(v)) {
|
|
202
|
+
const at = path ? `${path}.${k}` : k;
|
|
203
|
+
if (secretLike(k) && typeof x === 'string' && x !== '') secretKeys.push(at);
|
|
204
|
+
walk(x, at);
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
walk(graph.settings, '');
|
|
208
|
+
if (secretKeys.length) add('WARN', `settings hold what looks like a secret (${secretKeys.join(', ')}) — expression values are kept in run data; use credentials`);
|
|
181
209
|
if (previous) {
|
|
182
210
|
const now = new Set(nodes.map((n) => n.id));
|
|
183
211
|
for (const n of previous.nodes ?? []) if (n.type === 'approval' && !now.has(n.id)) add('WARN', `approval ${n.id} («${n.name}») is published now and missing from the new graph — runs waiting there cannot continue; keep its id, or check status:"waiting" runs before publishing`);
|
|
@@ -488,10 +488,13 @@ The validator parses with the TypeScript compiler API, read from the app repo yo
|
|
|
488
488
|
| A stub took an entity over: another application's deploy now gets extension mode on it | The entity had no owning application, so the stub ran in OWN mode and claimed it | rule 19 — read the owner before writing a stub |
|
|
489
489
|
| The build stops with `refusing to build system metadata: this is an application build but applicationId is missing` | The platform is older than extension mode, or the runner does not pass the application id. Update the platform — there is nothing to change in the code | not statically checkable |
|
|
490
490
|
| A relation names its target with a string (`@ManyToOne('Invoices', …)`), anywhere | The SDK types the target `() => Target` and calls it at registration — a string fails tsc and would throw. Use a thunk, or `@Column({ relationEntityName: 'Invoices', … })` for an entity you cannot import | W620 (blocks the gate) |
|
|
491
|
+
| A stub on a nobody's entity declares its representative column (an empty one wrote `id` there on import), and the gate refuses it as E117 | The stub ran in OWN mode and the entity is yours now (`application` = your application). It is not a stub any more: rename it to `<name>.entity.ts` and keep the class as it is. A class may declare part of an entity it owns; the tenant's own columns (initiator `client`) that it leaves out stay where they are | E117 — rule 19 |
|
|
491
492
|
| A stub kept its fields, and the migration altered a table another application owns | The empty body is the whole point of a stub — a fielded one converges columns onto the real table | E117 |
|
|
492
493
|
| A field-less entity that is really a stub, in an ordinary `*.entity.ts` | Nothing marks it as a stub, so E117 cannot apply — rename to `<name>.stub.entity.ts` | W617 (blocks the gate) |
|
|
493
494
|
| Several stubs piled into one `relation-targets.ts` | Each existing-entity stub lives in its OWN file | W616 (blocks the gate) |
|
|
494
495
|
| A stub was left out of `forFeature()` "so the migration can't touch the real table" | A stub is registered like any other entity — its EMPTY body is what protects the real table, not the missing registration | E301 |
|
|
495
496
|
| The gate passes, but nobody ran it | Install the guards: `node scripts/install-entity-code-guards.mjs <app-root>` — hooks put the rules in front of an agent before it writes and the gate in front of it after, a pre-commit refusal catches whoever had no hooks, and a CI job catches whatever reached the branch. See `references/enforcement.md` | — |
|
|
497
|
+
| Every commit that touches an entity is refused over findings it did not add, so commits go in with `--no-verify` | Before 1.44.2 the hooks counted every finding in the application root. Now a finding counts when the change touches its file, or when HEAD does not have it; the rest are listed under *Not counted against this change*, and `--ci` still fails on them. Fix them in a change of their own, and drop `--no-verify`: it switches the gate off for the new findings too | `references/enforcement.md` |
|
|
498
|
+
| `node node_modules/suppa-mcp-2/…/validate-suppa-schema.mjs .` prints nothing and exits 0 | pnpm links `node_modules/suppa-mcp-2`, and before 1.44.2 the CLI compared its real path with the linked one and never ran. Fixed; on an older install, `entity-code-guard.mjs --ci .` (`npm run schema:gate`) was never affected | — |
|
|
496
499
|
| Validator warns W606 | Content delivered via spread or reference — options, `default`, `subType`, `importKeyFields`, seed records, enum refs, `$key`, autoload paths, registration arrays, tabular-part `type`/`relationEntityName` — is not statically verifiable; the matching check is skipped. Inline it so the validator can check | W606 |
|
|
497
500
|
| Validator warns W608 | No `tsconfig.json` at the given root, so `experimentalDecorators`/`emitDecoratorMetadata` could not be verified — point the validator at the app root | W608 |
|
|
@@ -45,7 +45,8 @@ The gate runs over the file's application root (nearest `package.json`). A
|
|
|
45
45
|
failure exits `2`, which puts the findings — with the rules attached — in front
|
|
46
46
|
of the agent as the next thing it reads. `PostToolUse` cannot undo the write;
|
|
47
47
|
this makes the violation the agent's immediate problem instead of a surprise at
|
|
48
|
-
review time.
|
|
48
|
+
review time. Only what the change brought counts — see
|
|
49
|
+
[What a change answers for](#what-a-change-answers-for).
|
|
49
50
|
|
|
50
51
|
If the gate cannot run (no `typescript` in the target repo), the guard says so
|
|
51
52
|
as context and exits `0`. A guard that walls off unrelated edits gets
|
|
@@ -53,14 +54,14 @@ uninstalled, and then it protects nothing.
|
|
|
53
54
|
|
|
54
55
|
### 3. Before the turn ends — `Stop`
|
|
55
56
|
|
|
56
|
-
If any schema file in the working tree is changed and
|
|
57
|
-
the turn is refused. This is the layer that stops "I will fix the gate findings
|
|
57
|
+
If any schema file in the working tree is changed and the gate finds something
|
|
58
|
+
the change brought in its root, the turn is refused. This is the layer that stops "I will fix the gate findings
|
|
58
59
|
later" — there is no later. `stop_hook_active` is honoured, so a turn that is
|
|
59
60
|
already inside a Stop continuation is never blocked twice.
|
|
60
61
|
|
|
61
62
|
### 4. Before the commit — `.githooks/pre-commit`
|
|
62
63
|
|
|
63
|
-
The same gate over **staged** schema files, exit `1`. This catches the case the
|
|
64
|
+
The same gate over **staged** schema files, counted the same way, exit `1`. This catches the case the
|
|
64
65
|
hooks cannot: a human editing by hand, an agent in an editor with no hook
|
|
65
66
|
support, a `--dangerously-skip-permissions` run with hooks disabled.
|
|
66
67
|
|
|
@@ -72,6 +73,32 @@ the call from the existing hook:
|
|
|
72
73
|
node node_modules/suppa-mcp-2/skills/suppa-entity-code/scripts/entity-code-guard.mjs --pre-commit
|
|
73
74
|
```
|
|
74
75
|
|
|
76
|
+
### What a change answers for
|
|
77
|
+
|
|
78
|
+
Layers 2–4 run the gate over the whole application root, because a change in one
|
|
79
|
+
file breaks another: E308 lands in the module that still registers the class a
|
|
80
|
+
commit deleted, W635 in a runtime file a new import pulls into the bundle. What
|
|
81
|
+
they COUNT is narrower:
|
|
82
|
+
|
|
83
|
+
- every finding in a file the change touches — the staged files for the commit,
|
|
84
|
+
the changed files for the hooks. Touch a file and it has to pass;
|
|
85
|
+
- every finding anywhere else that HEAD does not have — same file, same code,
|
|
86
|
+
same message, matched as a multiset, positions ignored.
|
|
87
|
+
|
|
88
|
+
The rest were there before the change. They are listed under *Not counted against
|
|
89
|
+
this change* every time, and they do not block. `--ci` still counts them, so the
|
|
90
|
+
merge request shows the whole picture. Before 1.44.2 every finding in the root
|
|
91
|
+
counted: one old finding refused every commit that touched an entity, the only
|
|
92
|
+
way through was `--no-verify`, and `--no-verify` switched the gate off for the new
|
|
93
|
+
findings as well.
|
|
94
|
+
|
|
95
|
+
HEAD's findings come from a snapshot of the application root read with
|
|
96
|
+
`git cat-file` (the work tree, the index and the refs are never touched), judged
|
|
97
|
+
with the working tree's own compiler and SDK. It is computed only when a finding
|
|
98
|
+
sits outside the touched files, and once per HEAD tree: the answer is cached in
|
|
99
|
+
`<git-dir>/suppa-gate/`. With no commit to compare with, or a HEAD the gate
|
|
100
|
+
cannot run on, every finding counts, and the report says why.
|
|
101
|
+
|
|
75
102
|
### 5. Before the merge — CI
|
|
76
103
|
|
|
77
104
|
`.gitlab/suppa-schema-gate.yml` runs `--ci` over the repo on merge-request
|
|
@@ -20,6 +20,10 @@
|
|
|
20
20
|
* --ci one run over the repo, for a pipeline
|
|
21
21
|
* --print-rules the digest, for a human or a doc
|
|
22
22
|
*
|
|
23
|
+
* The three layers that judge a CHANGE (--post-tool-use, --stop, --pre-commit)
|
|
24
|
+
* count what the change brought, not every finding the repo already had — see
|
|
25
|
+
* splitByChange. --ci counts everything.
|
|
26
|
+
*
|
|
23
27
|
* The hooks are safe to run anywhere: a repo with no schema files, no git and
|
|
24
28
|
* no typescript exits 0 and says why, because a guard that breaks unrelated
|
|
25
29
|
* work gets uninstalled. The two layers that decide what LANDS (--pre-commit,
|
|
@@ -28,7 +32,12 @@
|
|
|
28
32
|
*/
|
|
29
33
|
|
|
30
34
|
import { execFileSync } from "node:child_process";
|
|
31
|
-
import {
|
|
35
|
+
import { createHash } from "node:crypto";
|
|
36
|
+
import {
|
|
37
|
+
existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync,
|
|
38
|
+
unlinkSync, writeFileSync,
|
|
39
|
+
} from "node:fs";
|
|
40
|
+
import { tmpdir } from "node:os";
|
|
32
41
|
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
33
42
|
|
|
34
43
|
// The checker is loaded, not statically imported, so that a truncated or half-installed file is
|
|
@@ -85,7 +94,11 @@ function readStdinJson() {
|
|
|
85
94
|
|
|
86
95
|
function git(args, cwd) {
|
|
87
96
|
try {
|
|
88
|
-
|
|
97
|
+
// The default 1 MB buffer is a listing of a few thousand paths: past it the
|
|
98
|
+
// call threw, and every answer built on it read as "no git".
|
|
99
|
+
return execFileSync("git", args, {
|
|
100
|
+
cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 256 * 1024 * 1024,
|
|
101
|
+
});
|
|
89
102
|
} catch {
|
|
90
103
|
return null;
|
|
91
104
|
}
|
|
@@ -161,17 +174,29 @@ function canonicalRoot(p) {
|
|
|
161
174
|
return process.platform === "win32" ? abs.toLowerCase() : abs;
|
|
162
175
|
}
|
|
163
176
|
|
|
177
|
+
/** The same, for a file: a changed path and a finding's file must meet however each was spelled. */
|
|
178
|
+
const fileKey = canonicalRoot;
|
|
179
|
+
|
|
180
|
+
function findingLine(root, f) {
|
|
181
|
+
const rel = relative(root, f.file);
|
|
182
|
+
const shown = !rel || rel.startsWith("..") || isAbsolute(rel) ? f.file : rel.replace(/\\/g, "/");
|
|
183
|
+
return `${shown}:${f.line}:${f.col} ${f.code} ${f.message}`;
|
|
184
|
+
}
|
|
185
|
+
|
|
164
186
|
/**
|
|
165
187
|
* Run the gate over one application root.
|
|
166
|
-
* -> { ok
|
|
188
|
+
* -> { ok, blocking, lines } | { skipped } | { toolchain } | { unreadable }
|
|
167
189
|
*
|
|
168
190
|
* `skipped` is "nothing to run on"; `toolchain` and `unreadable` are "could not
|
|
169
191
|
* run". They used to be one answer: any failure to read the root became a skip,
|
|
170
192
|
* and a skip is reported as clean — so a typo'd `--ci ./srcc`, a root that is a
|
|
171
193
|
* file, or a dead junction anywhere under the app (statSync threw, the walk
|
|
172
194
|
* aborted) printed "gate: clean" over a staged rule-breaking entity.
|
|
195
|
+
*
|
|
196
|
+
* `lookupRoot` is where the compiler and the SDK typings are found, when that is
|
|
197
|
+
* not the root itself — the HEAD snapshot has no node_modules of its own.
|
|
173
198
|
*/
|
|
174
|
-
function runGate(root) {
|
|
199
|
+
function runGate(root, { lookupRoot = null } = {}) {
|
|
175
200
|
let st;
|
|
176
201
|
try {
|
|
177
202
|
st = statSync(root);
|
|
@@ -191,7 +216,7 @@ function runGate(root) {
|
|
|
191
216
|
|
|
192
217
|
let res;
|
|
193
218
|
try {
|
|
194
|
-
res = validateSchema({ files, rootDir: root });
|
|
219
|
+
res = validateSchema({ files, rootDir: root, ...(lookupRoot ? { lookupRoot } : {}) });
|
|
195
220
|
} catch (e) {
|
|
196
221
|
// A missing or unusable typescript in the target repo is the repo's to fix;
|
|
197
222
|
// it must never turn into a wall in front of every edit.
|
|
@@ -202,21 +227,246 @@ function runGate(root) {
|
|
|
202
227
|
const blocking = res.findings.filter(
|
|
203
228
|
(f) => f.level === "error" || RULE_WARNINGS.includes(f.code),
|
|
204
229
|
);
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
230
|
+
return { ok: blocking.length === 0, blocking, lines: blocking.map((f) => findingLine(root, f)) };
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// ── what a change answers for ──
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Split a root's blocking findings into the ones this change brought and the
|
|
237
|
+
* ones it found already there.
|
|
238
|
+
*
|
|
239
|
+
* The write, Stop and pre-commit layers gate the WHOLE application root, and
|
|
240
|
+
* they must: a change in one file breaks another — E308 lands in the module
|
|
241
|
+
* that still registers the class a commit deleted, W635 in a runtime file a new
|
|
242
|
+
* import pulls into the bundle. They then refused on every finding in that
|
|
243
|
+
* root, which is more than they promise ("refused while a staged schema file
|
|
244
|
+
* fails"). One old finding anywhere refused every commit that touched an
|
|
245
|
+
* entity, the only way through was --no-verify, and --no-verify switched the
|
|
246
|
+
* gate off for the new findings too: modern-expo put every commit from
|
|
247
|
+
* 2026-10-21 to 2026-10-27 behind it, over twelve findings none of them added.
|
|
248
|
+
*
|
|
249
|
+
* A finding COUNTS when it sits in a file the change touches, or when the
|
|
250
|
+
* gate's answer for HEAD does not have it — same file, same code, same message,
|
|
251
|
+
* matched as a multiset, so a second copy of an old finding is new. Positions
|
|
252
|
+
* are left out of the match: an edit above an old finding moves it without
|
|
253
|
+
* making it new. The rest are OLDER: listed every time, never counted here.
|
|
254
|
+
*
|
|
255
|
+
* Without a HEAD to compare with — no git, no commit yet, a HEAD the gate
|
|
256
|
+
* cannot run on — every finding counts, as before, and the report says why.
|
|
257
|
+
* HEAD's findings are computed only when a finding sits outside the touched
|
|
258
|
+
* files, and once per HEAD tree (cachePath).
|
|
259
|
+
*/
|
|
260
|
+
function splitByChange(root, blocking, touched) {
|
|
261
|
+
const outside = blocking.filter((f) => !touched.has(fileKey(f.file)));
|
|
262
|
+
if (!outside.length) return { counted: blocking, older: [] };
|
|
263
|
+
const head = headFindings(root);
|
|
264
|
+
if (head.reason) return { counted: blocking, older: [], uncompared: head.reason };
|
|
265
|
+
const left = new Map(head.keys);
|
|
266
|
+
const older = new Set();
|
|
267
|
+
for (const f of outside) {
|
|
268
|
+
const key = findingKey(root, f);
|
|
269
|
+
const n = left.get(key) ?? 0;
|
|
270
|
+
if (n > 0) {
|
|
271
|
+
left.set(key, n - 1);
|
|
272
|
+
older.add(f);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
return { counted: blocking.filter((f) => !older.has(f)), older: blocking.filter((f) => older.has(f)) };
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
279
|
+
|
|
280
|
+
/** A finding as HEAD and the working tree can both spell it: root-relative, position-free. */
|
|
281
|
+
function findingKey(root, f) {
|
|
282
|
+
const win = process.platform === "win32";
|
|
283
|
+
const rel = relative(root, f.file).replace(/\\/g, "/");
|
|
284
|
+
let message = String(f.message ?? "");
|
|
285
|
+
for (const spelling of new Set([root, root.replace(/\\/g, "/")])) {
|
|
286
|
+
message = message.replace(new RegExp(escapeRe(spelling), win ? "gi" : "g"), "<root>");
|
|
287
|
+
}
|
|
288
|
+
message = message.replace(/(\.[cm]?tsx?):\d+(?::\d+)?/g, "$1");
|
|
289
|
+
return `${win ? rel.toLowerCase() : rel}\0${f.code}\0${message}`;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
let checkerStamp = null;
|
|
293
|
+
/** What HEAD's findings depend on besides HEAD: this checker, and the SDK it reads option catalogs from. */
|
|
294
|
+
function stampFor(realRoot) {
|
|
295
|
+
if (checkerStamp === null) {
|
|
296
|
+
const h = createHash("sha1");
|
|
297
|
+
for (const f of ["entity-code-guard.mjs", "validate-suppa-schema.mjs", "house-rules.mjs"]) {
|
|
298
|
+
try {
|
|
299
|
+
h.update(readFileSync(new URL(`./${f}`, import.meta.url)));
|
|
300
|
+
} catch {
|
|
301
|
+
h.update(`missing:${f}`);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
checkerStamp = h.digest("hex");
|
|
305
|
+
}
|
|
306
|
+
let sdk = "none";
|
|
307
|
+
for (let dir = realRoot; ; dir = dirname(dir)) {
|
|
308
|
+
const p = join(dir, "node_modules", "@suppa", "sdk", "package.json");
|
|
309
|
+
if (existsSync(p)) {
|
|
310
|
+
try {
|
|
311
|
+
sdk = `${dir}:${JSON.parse(readFileSync(p, "utf-8")).version}`;
|
|
312
|
+
} catch {
|
|
313
|
+
sdk = `${dir}:unreadable`;
|
|
314
|
+
}
|
|
315
|
+
break;
|
|
316
|
+
}
|
|
317
|
+
if (dirname(dir) === dir) break;
|
|
318
|
+
}
|
|
319
|
+
return `${checkerStamp}\0${sdk}`;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** <git-dir>/suppa-gate/head-<tree>-<scope>.json, or null when git will not say where its dir is. */
|
|
323
|
+
function cachePath(top, tree, relPosix, realRoot) {
|
|
324
|
+
const gitDir = git(["rev-parse", "--absolute-git-dir"], top)?.trim();
|
|
325
|
+
if (!gitDir) return null;
|
|
326
|
+
const scope = createHash("sha1").update(`${stampFor(realRoot)}\0${relPosix}`).digest("hex").slice(0, 16);
|
|
327
|
+
return join(gitDir, "suppa-gate", `head-${tree}-${scope}.json`);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
const CACHE_KEPT = 8;
|
|
331
|
+
|
|
332
|
+
/** A cache is an optimisation: failing to write or prune it never changes an answer. */
|
|
333
|
+
function saveCache(file, keys) {
|
|
334
|
+
try {
|
|
335
|
+
const dir = dirname(file);
|
|
336
|
+
mkdirSync(dir, { recursive: true });
|
|
337
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
338
|
+
writeFileSync(tmp, JSON.stringify([...keys]));
|
|
339
|
+
renameSync(tmp, file);
|
|
340
|
+
const entries = readdirSync(dir)
|
|
341
|
+
.filter((n) => /^head-.*\.json$/.test(n))
|
|
342
|
+
.map((n) => ({ p: join(dir, n), t: statSync(join(dir, n)).mtimeMs }))
|
|
343
|
+
.sort((a, b) => b.t - a.t);
|
|
344
|
+
for (const old of entries.slice(CACHE_KEPT)) unlinkSync(old.p);
|
|
345
|
+
} catch {
|
|
346
|
+
/* read-only git dir, a concurrent prune — the next run computes it again */
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* The gate's blocking findings for this root as HEAD has it.
|
|
352
|
+
* -> { keys: Map<findingKey, count> } | { reason }
|
|
353
|
+
*/
|
|
354
|
+
function headFindings(root) {
|
|
355
|
+
const top = git(["rev-parse", "--show-toplevel"], root)?.trim();
|
|
356
|
+
if (!top) return { reason: "this is not a git work tree" };
|
|
357
|
+
const tree = git(["rev-parse", "--verify", "--quiet", "HEAD^{tree}"], top)?.trim();
|
|
358
|
+
if (!tree) return { reason: "there is no commit yet" };
|
|
359
|
+
let realTop;
|
|
360
|
+
let realRoot;
|
|
361
|
+
try {
|
|
362
|
+
realTop = realpathSync.native(top);
|
|
363
|
+
realRoot = realpathSync.native(root);
|
|
364
|
+
} catch {
|
|
365
|
+
return { reason: `${root} cannot be resolved` };
|
|
366
|
+
}
|
|
367
|
+
const rel = relative(realTop, realRoot);
|
|
368
|
+
if (rel.startsWith("..") || isAbsolute(rel)) return { reason: `${root} is not inside ${top}` };
|
|
369
|
+
const relPosix = rel.replace(/\\/g, "/");
|
|
370
|
+
|
|
371
|
+
const cache = cachePath(top, tree, relPosix, realRoot);
|
|
372
|
+
if (cache && existsSync(cache)) {
|
|
373
|
+
try {
|
|
374
|
+
return { keys: new Map(JSON.parse(readFileSync(cache, "utf-8"))) };
|
|
375
|
+
} catch {
|
|
376
|
+
/* torn or foreign: compute it again */
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
let box = null;
|
|
380
|
+
try {
|
|
381
|
+
box = mkdtempSync(join(tmpdir(), "suppa-gate-head-"));
|
|
382
|
+
writeHeadSnapshot(realTop, relPosix, box);
|
|
383
|
+
const headRoot = relPosix ? join(box, ...relPosix.split("/")) : box;
|
|
384
|
+
const r = runGate(headRoot, { lookupRoot: realRoot });
|
|
385
|
+
if (r.toolchain || r.unreadable) return { reason: `the gate could not run on HEAD (${r.toolchain ?? r.unreadable})` };
|
|
386
|
+
const keys = new Map();
|
|
387
|
+
for (const f of r.blocking ?? []) {
|
|
388
|
+
const key = findingKey(headRoot, f);
|
|
389
|
+
keys.set(key, (keys.get(key) ?? 0) + 1);
|
|
390
|
+
}
|
|
391
|
+
if (cache) saveCache(cache, keys);
|
|
392
|
+
return { keys };
|
|
393
|
+
} catch (e) {
|
|
394
|
+
return { reason: `HEAD could not be read (${e?.message ?? e})` };
|
|
395
|
+
} finally {
|
|
396
|
+
if (box) {
|
|
397
|
+
try {
|
|
398
|
+
rmSync(box, { recursive: true, force: true });
|
|
399
|
+
} catch {
|
|
400
|
+
/* the OS's temp dir keeps it */
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** What the checker reads: TypeScript, package.json / tsconfig*.json / pnpm-workspace.yaml, the ignore list. */
|
|
407
|
+
const SNAPSHOT_NAME_RE = /\.(?:[cm]?tsx?|json|ya?ml)$/;
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* Write HEAD's copy of the application root into `box`, at the same path
|
|
411
|
+
* relative to the repository top — plus the config files of the directories
|
|
412
|
+
* above it, which a tsconfig `extends` or a workspace file may name. Read with
|
|
413
|
+
* `git cat-file --batch`, so nothing in the work tree, the index or the refs is
|
|
414
|
+
* touched while a commit is being made.
|
|
415
|
+
*/
|
|
416
|
+
function writeHeadSnapshot(top, relPosix, box) {
|
|
417
|
+
const listing = git(["ls-tree", "-r", "-z", "--full-tree", "HEAD"], top);
|
|
418
|
+
if (listing === null) throw new Error("git ls-tree failed");
|
|
419
|
+
const prefix = relPosix ? `${relPosix}/` : "";
|
|
420
|
+
const above = new Set([""]);
|
|
421
|
+
for (let i = relPosix.indexOf("/"); i > 0; i = relPosix.indexOf("/", i + 1)) above.add(relPosix.slice(0, i));
|
|
422
|
+
const wanted = [];
|
|
423
|
+
for (const entry of listing.split("\0")) {
|
|
424
|
+
if (!entry) continue;
|
|
425
|
+
const tab = entry.indexOf("\t");
|
|
426
|
+
const [mode, type, sha] = entry.slice(0, tab).split(" ");
|
|
427
|
+
const path = entry.slice(tab + 1);
|
|
428
|
+
if (type !== "blob" || mode === "120000") continue; // submodules and symlinks hold no schema code
|
|
429
|
+
const segments = path.split("/");
|
|
430
|
+
if (segments.some((s) => !s || s === "." || s === ".." || s === "node_modules")) continue;
|
|
431
|
+
const name = segments[segments.length - 1];
|
|
432
|
+
if (!SNAPSHOT_NAME_RE.test(name) && name !== ".suppa-gate-ignore") continue;
|
|
433
|
+
const dir = segments.slice(0, -1).join("/");
|
|
434
|
+
if (prefix && !path.startsWith(prefix) && !above.has(dir)) continue;
|
|
435
|
+
wanted.push({ sha, segments });
|
|
436
|
+
}
|
|
437
|
+
if (!wanted.length) return;
|
|
438
|
+
const out = execFileSync("git", ["cat-file", "--batch"], {
|
|
439
|
+
cwd: top,
|
|
440
|
+
input: `${wanted.map((w) => w.sha).join("\n")}\n`,
|
|
441
|
+
stdio: ["pipe", "pipe", "ignore"],
|
|
442
|
+
maxBuffer: 1024 * 1024 * 1024,
|
|
209
443
|
});
|
|
210
|
-
|
|
444
|
+
let at = 0;
|
|
445
|
+
for (const w of wanted) {
|
|
446
|
+
const nl = out.indexOf(0x0a, at);
|
|
447
|
+
if (nl < 0) throw new Error("git cat-file: truncated answer");
|
|
448
|
+
const header = out.toString("utf-8", at, nl).split(" ");
|
|
449
|
+
if (header[1] !== "blob") throw new Error(`git cat-file: ${header.join(" ")}`);
|
|
450
|
+
const size = Number(header[2]);
|
|
451
|
+
const dest = join(box, ...w.segments);
|
|
452
|
+
mkdirSync(dirname(dest), { recursive: true });
|
|
453
|
+
writeFileSync(dest, out.subarray(nl + 1, nl + 1 + size));
|
|
454
|
+
at = nl + 1 + size + 1;
|
|
455
|
+
}
|
|
211
456
|
}
|
|
212
457
|
|
|
213
458
|
/**
|
|
214
459
|
* Gate several roots at once, each physical root once.
|
|
215
|
-
* -> { failures, notes, checked } — `checked` counts roots the gate actually ran on.
|
|
460
|
+
* -> { failures, notes, checked, older } — `checked` counts roots the gate actually ran on.
|
|
461
|
+
*
|
|
462
|
+
* With `touched` (fileKeys of the paths a change touches) each root's findings
|
|
463
|
+
* are split by splitByChange: `failures` carries only what counts, `older` what
|
|
464
|
+
* does not. Without it — --ci — every finding counts.
|
|
216
465
|
*/
|
|
217
|
-
function gateRoots(roots) {
|
|
466
|
+
function gateRoots(roots, touched = null) {
|
|
218
467
|
const failures = [];
|
|
219
468
|
const notes = [];
|
|
469
|
+
const older = [];
|
|
220
470
|
const seen = new Set();
|
|
221
471
|
let checked = 0;
|
|
222
472
|
for (const root of roots) {
|
|
@@ -231,13 +481,48 @@ function gateRoots(roots) {
|
|
|
231
481
|
else if (r.skipped) notes.push({ kind: "skipped", root, text: `${root}: ${r.skipped}` });
|
|
232
482
|
else {
|
|
233
483
|
checked++;
|
|
234
|
-
if (
|
|
484
|
+
if (r.ok) continue;
|
|
485
|
+
if (!touched) {
|
|
486
|
+
failures.push({ root, lines: r.lines });
|
|
487
|
+
continue;
|
|
488
|
+
}
|
|
489
|
+
const split = splitByChange(root, r.blocking, touched);
|
|
490
|
+
if (split.older.length) older.push({ root, lines: split.older.map((f) => findingLine(root, f)) });
|
|
491
|
+
if (split.counted.length) {
|
|
492
|
+
failures.push({ root, lines: split.counted.map((f) => findingLine(root, f)), uncompared: split.uncompared });
|
|
493
|
+
}
|
|
235
494
|
}
|
|
236
495
|
}
|
|
237
|
-
return { failures, notes, checked };
|
|
496
|
+
return { failures, notes, checked, older };
|
|
238
497
|
}
|
|
239
498
|
|
|
240
|
-
|
|
499
|
+
const OLDER_SHOWN = 10;
|
|
500
|
+
const OLDER_WIDTH = 160;
|
|
501
|
+
|
|
502
|
+
/** The findings a change found already there: named every time, so they stay somebody's to fix. */
|
|
503
|
+
function olderReport(older) {
|
|
504
|
+
const total = older.reduce((n, o) => n + o.lines.length, 0);
|
|
505
|
+
if (!total) return [];
|
|
506
|
+
const out = [
|
|
507
|
+
`Not counted against this change: ${total} finding(s) HEAD already has, in files the change does ` +
|
|
508
|
+
"not touch. --ci still fails on them; fix them in a change of their own.",
|
|
509
|
+
];
|
|
510
|
+
let shown = 0;
|
|
511
|
+
for (const o of older) {
|
|
512
|
+
if (shown >= OLDER_SHOWN) break;
|
|
513
|
+
out.push(`${o.root}`);
|
|
514
|
+
for (const line of o.lines) {
|
|
515
|
+
if (shown >= OLDER_SHOWN) break;
|
|
516
|
+
out.push(` ${line.length > OLDER_WIDTH ? `${line.slice(0, OLDER_WIDTH - 1)}…` : line}`);
|
|
517
|
+
shown++;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
if (total > shown) out.push(` … and ${total - shown} more (entity-code-guard.mjs --ci lists every one)`);
|
|
521
|
+
out.push("");
|
|
522
|
+
return out;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
function failureReport(failures, older = []) {
|
|
241
526
|
const out = [
|
|
242
527
|
"SUPPA ENTITY-CODE GATE FAILED — the schema code below breaks the platform's house rules.",
|
|
243
528
|
"",
|
|
@@ -245,8 +530,12 @@ function failureReport(failures) {
|
|
|
245
530
|
for (const f of failures) {
|
|
246
531
|
out.push(`${f.root}`);
|
|
247
532
|
for (const line of f.lines) out.push(` ${line}`);
|
|
533
|
+
if (f.uncompared) {
|
|
534
|
+
out.push(` (Not compared with HEAD: ${f.uncompared}. So findings in files this change does not touch count too.)`);
|
|
535
|
+
}
|
|
248
536
|
out.push("");
|
|
249
537
|
}
|
|
538
|
+
out.push(...olderReport(older));
|
|
250
539
|
out.push(`These block by design: ${BLOCKING_SUMMARY}.`);
|
|
251
540
|
out.push("Fix every line above and re-run the gate; a failure is not advisory.");
|
|
252
541
|
out.push("");
|
|
@@ -284,7 +573,8 @@ function gitPathsZ(raw, { porcelain }) {
|
|
|
284
573
|
}
|
|
285
574
|
|
|
286
575
|
/**
|
|
287
|
-
*
|
|
576
|
+
* Files git reports as changed in the working tree (staged or not), schema or
|
|
577
|
+
* not — a runtime file the change touched answers for its own W635.
|
|
288
578
|
* -> [{ path, deleted }]
|
|
289
579
|
*
|
|
290
580
|
* A deletion is kept, not filtered out: the module that registered the class
|
|
@@ -292,28 +582,32 @@ function gitPathsZ(raw, { porcelain }) {
|
|
|
292
582
|
* every path that no longer existed let a `git rm` of an entity file skip the
|
|
293
583
|
* gate while the registration went stale.
|
|
294
584
|
*/
|
|
295
|
-
function
|
|
585
|
+
function changedFiles(cwd) {
|
|
296
586
|
const top = git(["rev-parse", "--show-toplevel"], cwd)?.trim();
|
|
297
587
|
if (!top) return [];
|
|
298
588
|
const status = git(["status", "--porcelain", "-z", "--untracked-files=all"], cwd);
|
|
299
589
|
if (status === null) return [];
|
|
300
590
|
return gitPathsZ(status, { porcelain: true })
|
|
301
|
-
.filter((p) => SCHEMA_NAME_RE.test(p))
|
|
302
591
|
.map((p) => resolve(top, p))
|
|
303
592
|
.map((p) => ({ path: p, deleted: !existsSync(p) }));
|
|
304
593
|
}
|
|
305
594
|
|
|
306
|
-
function
|
|
595
|
+
function stagedFiles(cwd) {
|
|
307
596
|
const top = git(["rev-parse", "--show-toplevel"], cwd)?.trim();
|
|
308
597
|
if (!top) return [];
|
|
309
598
|
const names = git(["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMRD"], cwd);
|
|
310
599
|
if (!names) return [];
|
|
311
600
|
return gitPathsZ(names, { porcelain: false })
|
|
312
|
-
.filter((p) => SCHEMA_NAME_RE.test(p))
|
|
313
601
|
.map((p) => resolve(top, p))
|
|
314
602
|
.map((p) => ({ path: p, deleted: !existsSync(p) }));
|
|
315
603
|
}
|
|
316
604
|
|
|
605
|
+
/** The schema files among them that the gate must hear about, minus the declared exclusions. */
|
|
606
|
+
const schemaChanges = (files) =>
|
|
607
|
+
files.filter((c) => SCHEMA_NAME_RE.test(c.path) && !isIgnored(appRootFor(c.path), c.path));
|
|
608
|
+
|
|
609
|
+
const touchedSet = (paths) => new Set(paths.map(fileKey));
|
|
610
|
+
|
|
317
611
|
function emitHookJson(event, context) {
|
|
318
612
|
process.stdout.write(
|
|
319
613
|
`${JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: context } })}\n`,
|
|
@@ -343,11 +637,14 @@ function postToolUse() {
|
|
|
343
637
|
const root = appRootFor(p);
|
|
344
638
|
if (isIgnored(root, p)) return 0;
|
|
345
639
|
|
|
346
|
-
|
|
640
|
+
// The file just written, and whatever else this session has changed: an
|
|
641
|
+
// earlier write's findings are this change's too.
|
|
642
|
+
const touched = touchedSet([p, ...changedFiles(dirname(resolve(p))).map((c) => c.path)]);
|
|
643
|
+
const { failures, notes, older } = gateRoots([root], touched);
|
|
347
644
|
if (failures.length) {
|
|
348
645
|
// PostToolUse cannot undo the write, but exit 2 puts this in front of the
|
|
349
646
|
// agent as the next thing it reads — which is the point.
|
|
350
|
-
process.stderr.write(`${failureReport(failures)}\n`);
|
|
647
|
+
process.stderr.write(`${failureReport(failures, older)}\n`);
|
|
351
648
|
return 2;
|
|
352
649
|
}
|
|
353
650
|
if (notes.length) {
|
|
@@ -366,15 +663,16 @@ function stop() {
|
|
|
366
663
|
// Blocking again from inside it is how a hook loops forever.
|
|
367
664
|
if (input?.stop_hook_active) return 0;
|
|
368
665
|
const cwd = input?.cwd || process.cwd();
|
|
369
|
-
const
|
|
666
|
+
const changed = changedFiles(cwd);
|
|
667
|
+
const changes = schemaChanges(changed);
|
|
370
668
|
if (!changes.length) return 0;
|
|
371
669
|
|
|
372
670
|
// A deleted file has no content to judge; its ROOT does — the gate over the
|
|
373
671
|
// whole root is what notices a module still registering the missing class.
|
|
374
|
-
const { failures } = gateRoots(changes.map((c) => appRootFor(c.path)));
|
|
672
|
+
const { failures, older } = gateRoots(changes.map((c) => appRootFor(c.path)), touchedSet(changed.map((c) => c.path)));
|
|
375
673
|
if (!failures.length) return 0;
|
|
376
674
|
process.stderr.write(
|
|
377
|
-
`${failureReport(failures)}\n\nYou changed schema files in this session, so this turn is not ` +
|
|
675
|
+
`${failureReport(failures, older)}\n\nYou changed schema files in this session, so this turn is not ` +
|
|
378
676
|
`finished: fix the findings above, then re-run the gate.\n`,
|
|
379
677
|
);
|
|
380
678
|
return 2;
|
|
@@ -412,9 +710,10 @@ function couldNotRun(notes) {
|
|
|
412
710
|
}
|
|
413
711
|
|
|
414
712
|
function preCommit() {
|
|
415
|
-
const
|
|
713
|
+
const staged = stagedFiles(process.cwd());
|
|
714
|
+
const changes = schemaChanges(staged);
|
|
416
715
|
if (!changes.length) return 0;
|
|
417
|
-
const { failures, notes } = gateRoots(changes.map((c) => appRootFor(c.path)));
|
|
716
|
+
const { failures, notes, older } = gateRoots(changes.map((c) => appRootFor(c.path)), touchedSet(staged.map((c) => c.path)));
|
|
418
717
|
const broken = couldNotRun(notes);
|
|
419
718
|
if (broken) {
|
|
420
719
|
process.stderr.write(
|
|
@@ -424,11 +723,13 @@ function preCommit() {
|
|
|
424
723
|
return 1;
|
|
425
724
|
}
|
|
426
725
|
if (!failures.length) {
|
|
427
|
-
process.stdout.write(
|
|
726
|
+
process.stdout.write(
|
|
727
|
+
older.length ? `suppa entity-code gate: clean for this commit\n${olderReport(older).join("\n")}` : "suppa entity-code gate: clean\n",
|
|
728
|
+
);
|
|
428
729
|
return 0;
|
|
429
730
|
}
|
|
430
731
|
process.stderr.write(
|
|
431
|
-
`${failureReport(failures)}\n\nCommit refused. Fix the findings, or pass --no-verify if you ` +
|
|
732
|
+
`${failureReport(failures, older)}\n\nCommit refused. Fix the findings, or pass --no-verify if you ` +
|
|
432
733
|
`genuinely mean to commit code that will not converge.\n`,
|
|
433
734
|
);
|
|
434
735
|
return 1;
|
|
@@ -24,9 +24,9 @@
|
|
|
24
24
|
* advisory, for a legacy repo you are not cleaning up in this pass.
|
|
25
25
|
*/
|
|
26
26
|
import { builtinModules, createRequire } from "node:module";
|
|
27
|
-
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
27
|
+
import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
|
|
28
28
|
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
29
|
-
import { pathToFileURL } from "node:url";
|
|
29
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
30
30
|
|
|
31
31
|
// ── Doc-derived catalogs (fallback when @suppa/sdk typings are absent) ──
|
|
32
32
|
export const SYSTEM_COLUMNS = ["id", "createdAt", "updatedAt", "deletedAt", "createdBy", "removedBy"];
|
|
@@ -5301,12 +5301,15 @@ function parseSchemaFile(ts, file) {
|
|
|
5301
5301
|
}
|
|
5302
5302
|
|
|
5303
5303
|
// ── public API ──
|
|
5304
|
-
export function validateSchema({ files = [], rootDir = null } = {}) {
|
|
5304
|
+
export function validateSchema({ files = [], rootDir = null, lookupRoot: lookupAt = null } = {}) {
|
|
5305
5305
|
// Where the compiler and the SDK typings are looked up: the repo being validated. For named
|
|
5306
5306
|
// files that is the first file's own directory — without it an INSTALLED gate (no typescript
|
|
5307
5307
|
// of its own) refused a file whose app had one, and the SDK catalog came back empty. rootDir
|
|
5308
5308
|
// stays null: it switches on the whole-repo rules, which one file cannot satisfy.
|
|
5309
|
-
|
|
5309
|
+
// `lookupRoot` names it for a copy of an app that has no node_modules of its own — the
|
|
5310
|
+
// guard's HEAD snapshot, which must be judged with the compiler and the SDK catalog of the
|
|
5311
|
+
// working tree it is compared with, or the two answers differ by more than the change.
|
|
5312
|
+
const lookupRoot = lookupAt ?? rootDir ?? (files.length ? dirname(resolve(files[0])) : null);
|
|
5310
5313
|
const ts = loadTypescript(lookupRoot);
|
|
5311
5314
|
const sdk = loadSdkCatalog(ts, lookupRoot);
|
|
5312
5315
|
const model = {
|
|
@@ -5601,9 +5604,27 @@ function importedEnumModules(files) {
|
|
|
5601
5604
|
}
|
|
5602
5605
|
|
|
5603
5606
|
// ── CLI ──
|
|
5604
|
-
|
|
5605
|
-
|
|
5606
|
-
|
|
5607
|
+
/**
|
|
5608
|
+
* Was this file STARTED, or imported?
|
|
5609
|
+
*
|
|
5610
|
+
* Node resolves the main module through symlinks, so import.meta.url names the REAL file while
|
|
5611
|
+
* argv[1] keeps the path as typed. Under pnpm, node_modules/suppa-mcp-2 is a symlink (a junction
|
|
5612
|
+
* on Windows), and `node node_modules/suppa-mcp-2/…/validate-suppa-schema.mjs .` — the command the
|
|
5613
|
+
* house rules print — compared the two, found them different, never ran, and exited 0 having
|
|
5614
|
+
* printed nothing: a pass nobody computed. Compare realpaths, as validate-form-schema.mjs already
|
|
5615
|
+
* does, falling back to the encoded URL when a path cannot be resolved.
|
|
5616
|
+
*/
|
|
5617
|
+
function startedDirectly() {
|
|
5618
|
+
const arg = process.argv[1];
|
|
5619
|
+
if (!arg) return false;
|
|
5620
|
+
try {
|
|
5621
|
+
return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(arg);
|
|
5622
|
+
} catch {
|
|
5623
|
+
return pathToFileURL(resolve(arg)).href === import.meta.url;
|
|
5624
|
+
}
|
|
5625
|
+
}
|
|
5626
|
+
|
|
5627
|
+
if (startedDirectly()) {
|
|
5607
5628
|
const argv = process.argv.slice(2);
|
|
5608
5629
|
// Default is strict: the authoring rules block. --no-strict is the escape for
|
|
5609
5630
|
// a legacy repo whose existing entities restate defaults everywhere. Flags are
|