@haneinfo/state-machine 0.23.0 → 0.25.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 (42) hide show
  1. package/README.md +455 -421
  2. package/dist/index.d.ts +2 -1
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +4 -1
  5. package/dist/index.js.map +1 -1
  6. package/dist/instance-access.service.d.ts +2 -2
  7. package/dist/kind.d.ts.map +1 -1
  8. package/dist/kind.js +3 -0
  9. package/dist/kind.js.map +1 -1
  10. package/dist/plugin.js +1 -1
  11. package/dist/presentation.d.ts +35 -0
  12. package/dist/presentation.d.ts.map +1 -0
  13. package/dist/presentation.js +109 -0
  14. package/dist/presentation.js.map +1 -0
  15. package/dist/references.d.ts.map +1 -1
  16. package/dist/references.js +3 -1
  17. package/dist/references.js.map +1 -1
  18. package/dist/reporting.d.ts +4 -2
  19. package/dist/reporting.d.ts.map +1 -1
  20. package/dist/reporting.js +9 -5
  21. package/dist/reporting.js.map +1 -1
  22. package/dist/runtime.service.d.ts +38 -6
  23. package/dist/runtime.service.d.ts.map +1 -1
  24. package/dist/runtime.service.js +59 -8
  25. package/dist/runtime.service.js.map +1 -1
  26. package/dist/search.d.ts +5 -3
  27. package/dist/search.d.ts.map +1 -1
  28. package/dist/search.js +3 -3
  29. package/dist/search.js.map +1 -1
  30. package/dist/semantics.d.ts.map +1 -1
  31. package/dist/semantics.js +17 -0
  32. package/dist/semantics.js.map +1 -1
  33. package/dist/state-machine.controller.d.ts +42 -11
  34. package/dist/state-machine.controller.d.ts.map +1 -1
  35. package/dist/state-machine.controller.js +88 -33
  36. package/dist/state-machine.controller.js.map +1 -1
  37. package/dist/types.d.ts +7 -3
  38. package/dist/types.d.ts.map +1 -1
  39. package/dist/types.js.map +1 -1
  40. package/haneinfo.plugin.json +1 -1
  41. package/package.json +6 -6
  42. package/schemas/state-machine.spec.json +28 -6
package/README.md CHANGED
@@ -1,421 +1,455 @@
1
- # @haneinfo/state-machine
2
-
3
- See [agent-guide.md](agent-guide.md) for integration details.
4
-
5
- ## Instance readers and stored query values
6
-
7
- Reads allow the submitter, holders of `state-machine:instance:read`, or an instance reader grant.
8
- ADMIN continues to use existing RBAC. `mine=true` still means submitter ownership. Number lookups
9
- apply the same rule before pagination.
10
-
11
- `StateMachineReaderGrants.grantAssigned(instanceId, userIds, tx)` is a grant-only service exported
12
- by StateMachineModule. Assignment injects it and supplies the task transaction; grants use
13
- `createMany({ skipDuplicates: true })` (PostgreSQL `ON CONFLICT DO NOTHING`). There is no revoke
14
- operation or additional read port. Custom stores must implement `grantReaders`, `isReader`, and
15
- `readableBy` instance/number filters. Apps must migrate the Prisma fragment and backfill existing
16
- tasks before upgrading. The `(instance_id, user_id)` primary key supports indexed reader lookups;
17
- the separate `user_id` index supports user-led scans.
18
-
19
- ```sql
20
- INSERT INTO state_machine_instance_readers (instance_id, user_id, reason)
21
- SELECT DISTINCT instance_id, assignee_id, 'ASSIGNED'
22
- FROM assignment_tasks
23
- ON CONFLICT (instance_id, user_id) DO NOTHING;
24
- ```
25
-
26
- Top-level text, textarea, number, date and datetime formula fields can be declared in
27
- `spec.listView.fields`. Queries read stored results through the ordinary JSONB path. Queries never
28
- recompute formulas or backfill missing historical values. Select, switch, nested and container
29
- fields remain unsupported.
30
-
31
- ## Date comparisons
32
-
33
- GT/GTE/LT/LTE compare numbers, valid calendar dates (YYYY-MM-DD), or timezone-qualified datetimes
34
- (YYYY-MM-DDTHH:mm:ss with optional fractional seconds and Z or +/-HH:mm). Both operands must have
35
- the same category. Dates use calendar order; datetimes compare UTC instants at millisecond precision.
36
- Invalid dates, mixed categories and empty operands yield false. EQ/NEQ/IN retain strict scalar equality;
37
- matching instants with different textual offsets are still unequal for those operators.
38
-
39
- ## Instance privacy and submitter names
40
-
41
- All person-facing instance reads (detail including history, available transitions and exact number lookup) return `INSTANCE_NOT_FOUND`, HTTP 404, message `Instance not found`, with no suggestion for both missing and unreadable instances. No read permission name is exposed. USER transitions and data updates check readability before revision, state and write authorization; readable users missing the write/business permission still receive 403. Submitter ownership, effective instance:read and permanent reader grants are unchanged. Internal `get`/`history` remain trusted mechanism APIs without a person parameter; there is no delete endpoint.
42
-
43
- Authorized detail, instance list and numbering reads include `submitterName: string | null`. Optional identity-store `findActiveNamesByIds` resolves unique submitter ids once per result batch. Missing, inactive and deleted identities, absent identity capability and older providers return null without per-row fallbacks. No schema migration or people-lookup HTTP route is added. Numbering MCP wraps names in `$userContent`; exact unreadable/missing numbers return the same error, while recent-number lists still filter before paging.
44
-
45
- ## Delegated Assignment attribution
46
-
47
- ASSIGNMENT triggers may include optional actingUserId and onBehalfOfId. Existing userId and
48
- triggerUserId remain the actual actor. Attribution is persisted in the existing transition decision
49
- JSON and exposed as optional history fields, including getFor's embedded history. Notification
50
- outcomes merge with this metadata instead of replacing it. No history schema migration is needed.
51
- The decision remains draft (202610-6b1f). Assignment owns delegation validity and response policy.
52
-
53
- When the resolver is installed, StateMachine takes its optional shared transaction advisory lock
54
- before instance creation or any instance row lock/write. Delegation creation/revocation takes the
55
- exclusive lock on the same key. Normal instance transactions remain concurrent; a graph mutation
56
- briefly blocks new instance writers until its backfill/cancellation commits. This closes the race
57
- where creation and state entry could otherwise miss each other's uncommitted rows. The advisory lock always precedes instance locks; task CAS and delegation-row shared locks
58
- remain inside that transaction. No extra table or worker is added.
59
-
60
-
61
- ## Instance access lists (draft implementation)
62
-
63
- Implemented against draft decision 202610-c8e3; the decision remains draft. This section supersedes
64
- the earlier reader-only model and human transition eligibility. Upgrade the affected
65
- mechanisms together and apply the App migration before starting the new runtime. The maintainer
66
- selected source-specific uniqueness: `(instanceId, principalType, principalId, source)`. Existing
67
- model/table names are retained. `principalType` is USER or ROLE; `principalId` is a user id or role
68
- machine name; `level` is READ or WRITE; `source` is ASSIGNED, DELEGATED or GRANTED. Each row also
69
- has nullable grantedBy and createdAt. Indexes cover instanceId and (principalType, principalId).
70
- Permanent ASSIGNED/DELEGATED entries are READ and survive every task/delegation status. Manual
71
- GRANTED entries coexist with them; removing GRANTED never removes permanent readership.
72
-
73
- All instance reads use submitter, effective state-machine:instance:read, or a matching USER/ROLE
74
- entry. Roles come from RBAC authorizationOfUser once per query, passed into persistence; no direct
75
- RBAC-table joins. WRITE also requires an existing readable instance, then submitter, effective
76
- state-machine:instance:write, or matching WRITE. Human transitions still check their declared
77
- business permission. Assignment/Timer transition authorization is unchanged. Unreadable instances
78
- return INSTANCE_NOT_FOUND/404; readable callers without write/manage eligibility receive 403.
79
-
80
- Only the submitter or state-machine:instance:admin can manage access; instance administrators can
81
- manage any instance list. Grantees cannot regrant. InteractiveAuthGuard protects GET/PUT
82
- /state-machine-instances/:id/access and DELETE /state-machine-instances/:id/access/:principalType/:principalId.
83
- PUT targets GRANTED only, never changes permanent rows. DELETE removes GRANTED if present; a
84
- permanent-only target returns ACCESS_NOT_MANAGEABLE/409. Missing manual targets are idempotent.
85
- GET returns sources, levels, principalName and grantedByName; user names share one authorized
86
- findActiveNamesByIds batch, role display labels share one RBAC lookup, unavailable names are null.
87
- Names are plain text. maxGrantedAccess defaults to 100. Only active users or existing roles can be
88
- granted; the submitter cannot receive a USER grant. Errors include ACCESS_PRINCIPAL_INVALID/400,
89
- ACCESS_LIMIT_EXCEEDED/409 and ACCESS_NOT_MANAGEABLE/409. Repeated equal grants have no effects.
90
-
91
- StateMachineMcpTools.registerInto now also registers list_instance_access using <namespace>:instance:read.
92
- It returns items in $userContent and offers no grant/remove tools. Changed individual grants notify
93
- with state-machine-access:<historyId>; equal retries do not notify again. Role grants and removals
94
- never notify. Missing inbox capability skips delivery. Actual inbox failures roll back the mutation.
95
- ACCESS history uses the existing decision JSON and emits state-machine.access.recorded in the
96
- same transaction; collaboration adds ACCESS to its existing SQL timeline union. State, revision and
97
- transition events do not change for access mutations. List/export counts and pagination include
98
- personal and role access in one parameterized EXISTS; snapshot exports abort on role-name changes.
99
-
100
- Migration SQL ships at @haneinfo/state-machine/prisma/instance-access.sql. It renames user_id to
101
- principal_id and reason to source, preserves created_at, adds principal_type/level/granted_by,
102
- converts legacy rows to USER/READ and ASSIGNED (recognized delegation becomes DELEGATED), and
103
- backfills every assignment task regardless of status. It expects the Assignment delegation columns;
104
- Apps without Assignment/Delegation must omit the corresponding task queries/backfill. Do not reset
105
- an existing database. See the package repository validation/equipment-loan/instance-access/report.md
106
- for adoption evidence and the explicitly selected uniqueness adjustment; no decision text is changed.
107
-
108
- Configure runtime.stateMachine.maxGrantedAccess (positive integer, default 100). Apply prisma/instance-access.sql in your App migration before upgrading. Custom StateMachineStore implementations must implement listAccess, putGranted and deleteGranted and accept optional roles/source/level in reader methods. The new optional RBAC role-label lookup requires plugin API 1.14.0.
109
-
110
-
111
- ## Access management eligibility (draft 202610-e2a9)
112
-
113
- GET /state-machine-instances/:id/access adds canManage: boolean alongside the unchanged items.
114
- The service shares its submitter/instance-admin eligibility calculation with PUT/DELETE; readers
115
- can inspect but cannot regrant access. list_instance_access adds the same canManage next to its
116
- existing wrapped items. It remains read-only. No database or plugin-api contract changes apply.
117
-
118
- ## Optional attachments (draft decision 202610-5f3b)
119
-
120
- Attachment activity uses existing history with triggerType ATTACHMENT and optional decision.attachment (action, id, plain-text fileName). No storage keys, state/revision changes or notifications are introduced. Collaboration classifies these history rows as ATTACHMENT in its existing SQL union; MCP retains decision $userContent wrapping. See @haneinfo/attachments/agent-guide.md for authorization, storage, scanning, migration and retention. Apps adopting the optional package add its reverse instance relation; the core fragment does not depend on attachments.
121
-
122
-
123
- ## Document generation (draft 202610-d4f6)
124
-
125
- The optional @haneinfo/document-templates package adds DOCUMENT activity using existing history
126
- and decision.document (templateCode, templateVersion, format), attributed by triggerUserId.
127
- No tables, state/revision changes or notifications are added. Collaboration classifies the row
128
- as DOCUMENT in its existing authorized SQL timeline. Instance history and timeline fields remain
129
- unchanged. Read the document-templates agent guide for fonts, configuration, HTTP and read-only MCP.
130
-
131
-
132
- ## Instance lifecycle (draft 202610-f1a8)
133
-
134
- Implemented from draft decision 202610-f1a8; the decision remains draft. Upgrade state-machine,
135
- list-view, collaboration, attachments, import-export, assignment and timer together. No frontend,
136
- automatic archive or bulk lifecycle operations are included. Permanently purged data cannot be
137
- restored by this API: database and private file backups must cover the entire deletion retention
138
- period and be restored consistently.
139
-
140
- The instance fragment adds nullable archivedAt/archivedBy/deletedAt/deletedBy, preserving old
141
- instances as active. Apply prisma/instance-lifecycle.sql before running the upgraded packages.
142
- Indexes (machineCode, archivedAt), (deletedAt) and (submitterId, deletedAt) support archive queries,
143
- expiry scans and owner recycle lists. No new table is introduced. Install collaboration's Cascade
144
- migration when that package is present; the App adds comments CollaborationComment[] and follows
145
- CollaborationFollow[] reverse instance relations. Attachments already has Cascade; application
146
- numbers retain Restrict.
147
-
148
- Only FINAL instances can be archived. Archive is a view flag: all existing authorized reads and
149
- writes, including comments, access grants, following, attachments and exports, remain available.
150
- Unarchive clears both archive columns. Only INITIAL instances without any transition evidence or
151
- StateMachineNumber record can be soft-deleted; START, ACCESS, ATTACHMENT, DOCUMENT and LIFECYCLE
152
- activity are not state transitions. Returned, rejected and voided applications cannot be deleted.
153
- Lifecycle operations do not change state, data or revision and are idempotent without duplicate
154
- history/events. They reuse instanceManagementAllowed, also used by access-list management.
155
- Readability is checked before submitter/instance:admin eligibility; WRITE and assigned readership
156
- do not grant eligibility. An admin without ordinary read access gets 404 on active instances.
157
-
158
- All routes require InteractiveAuthGuard:
159
-
160
- | Method | Route | Operation |
161
- | --- | --- | --- |
162
- | POST | /state-machine-instances/:id/archive | Archive FINAL |
163
- | POST | /state-machine-instances/:id/unarchive | Clear archive |
164
- | DELETE | /state-machine-instances/:id | Soft-delete draft |
165
- | POST | /state-machine-instances/:id/undelete | Restore within retention |
166
- | GET | /state-machine-instances/deleted?offset=0&limit=50 | Recoverable deletions, newest first |
167
-
168
- The deleted collection precedes the :id route, caps limit at 200 and returns total plus id,
169
- machineCode, machineVersion, state, submitterId, startedAt, deletedAt, deletedBy, deletedByName
170
- and remainingRetentionDays. Owners see only their own drafts deleted by themselves; instance:admin
171
- sees all recoverable deletions. Admin-deleted drafts require admin restoration. Expired restoration
172
- is INSTANCE_NOT_FOUND even before the worker physically removes the row. Repeated DELETE by an
173
- eligible actor succeeds while its deleted row exists; after physical purge it returns 404.
174
-
175
- Public instance reads include archived and nullable archivedAt. Internal get returns null for
176
- deleted rows; history and every authorized HTTP/MCP instance read return exactly the missing-id
177
- INSTANCE_NOT_FOUND/404, `Instance not found`, with no suggestion. Lists always exclude deletions.
178
- List endpoints accept archived EXCLUDE (default), INCLUDE or ONLY; exact-number and single reads
179
- ignore archive flags. INSTANCE_NOT_ARCHIVABLE and INSTANCE_NOT_DELETABLE use 409; readable but
180
- ineligible lifecycle actions use FORBIDDEN/403. MCP exposes only existing read tools and archived
181
- metadata, never lifecycle mutations or a recycle-list tool.
182
-
183
- Each changed action writes LIFECYCLE history with decision.lifecycle.action (ARCHIVED, RESTORED,
184
- DELETED, UNDELETED) and synchronously emits state-machine.instance.archived/restored/deleted/undeleted
185
- in the same transaction. Payload: instanceId, historyId, userId, at (ISO). No notification is sent.
186
- state-machine.instance.purging has payload { instanceId } and runs before database deletion in that
187
- same transaction; listeners must use event.tx. Listener failures roll back all database changes.
188
-
189
- runtime.stateMachine supports deletedRetentionDays=30 (0–36500; 0 makes rows immediately eligible),
190
- purgeBatchSize=100 (1–500), purgePollIntervalMs=60000 (1–2147483647) and purgeWorkerEnabled=true.
191
- Direct module registration uses the same strict schema. Optional background-jobs registers
192
- state-machine.instances.purge; the producer enqueues on bootstrap and each interval, can be disabled,
193
- and waits for pending enqueue on shutdown. BACKGROUND_JOBS_WORKER_ENABLED is App wiring for the
194
- core worker; set purgeWorkerEnabled=false as well to stop this producer. Without background-jobs,
195
- human lifecycle actions still work and no jobs are enqueued. A purge batch is one job transaction,
196
- uses instance/delegation locks, checkpoints cancellation, and can retry safely. Numbered deleted rows
197
- are inconsistent: log an error and keep them (Restrict remains the final database defense). Repair
198
- such rows promptly: they count against the bounded candidate batch. Custom stores must implement
199
- lifecycle persistence and make their default find/list exclude deleted rows.
200
-
201
-
202
- ## Instance tags (draft 202610-2c5d)
203
-
204
- Implemented from draft 202610-2c5d; the decision remains draft. See @haneinfo/tags/agent-guide.md
205
- for data, migration and authorization. TAG history uses optional decision.tag with action, normalizedKey and label. It does not change
206
- state/revision or count as a lifecycle transition. The App adds tags InstanceTag[] only when
207
- installing the optional plugin; permanent purge removes tags through its Cascade foreign key.
208
-
209
-
210
- ## Concurrent field editing (draft 202610-8b3e)
211
-
212
- Implemented from draft decision 202610-8b3e; the decision remains draft. Upgrade state-machine,
213
- form, definition-registry and plugin-api together (API contract 1.18.0). Apply
214
- prisma/concurrent-editing.sql before enabling the new runtime. StateMachineInstance.fieldRevisions
215
- is JSONB with default {}; the SQL backfills every existing top-level data key to the instance's
216
- current revision. Empty or non-object data is safe. Reruns fill missing keys without overwriting
217
- existing revisions or deletion tombstones. Copy the fragment and SQL into an App migration; never
218
- reset a database to adopt it. Internal/custom stores must maintain revisions in create/update.
219
-
220
- PATCH /state-machine-instances/:id/data/fields is protected by InteractiveAuthGuard. Body:
221
- { baseRevision, fields: { stableFieldId: value }, remove?: [stableFieldId] }. Use 1–200 distinct
222
- field ids across both collections, each at most 200 characters, and JSON values. Id falls back to
223
- Form key when absent. Layout children retain Form's flat data scope; subforms replace the entire
224
- array. Formula fields, numbering targets, disabled fields and layout-only ids are not editable.
225
- Conditional disabled checks apply to both current and proposed data. Unknown ids return FIELD_UNKNOWN
226
- (400); read-only ids return FIELD_NOT_EDITABLE (400), including remove. There is no row merge.
227
-
228
- Under the instance row lock, check readability (missing, unreadable or deleted: identical
229
- INSTANCE_NOT_FOUND/404), then submitter/effective instance:write/USER-or-ROLE WRITE (403), then
230
- frozen/CHOICE/FINAL (STATE_FROZEN/409). A field conflicts only when its recorded revision exceeds
231
- baseRevision and its proposed value/presence differs deeply from current data. Any conflict aborts
232
- the entire patch. Equal stale values succeed. Future baseRevision is INVALID_INPUT/400.
233
- Success returns { revision, data, changedByOthers }; the last list contains keys revised after
234
- the base but absent from this request, including computed fields and tombstones. Every successful
235
- request increments revision, even when its normalized data is unchanged. Formula recalculation
236
- and every other actual top-level data change update fieldRevisions; unchanged values retain their
237
- revision. Removed keys retain their revision as tombstones; patch preparation preserves explicit
238
- absence. Full replacement keeps its existing expectedRevision contract and normalization.
239
-
240
- VERSION_CONFLICT/409 uses the existing details object: { currentRevision, conflicts: [{ fieldId,
241
- current, mine }] }. Missing values use null plus currentMissing/mineMissing. Small values remain
242
- original JSON. Each value has a 1 KiB UTF-8 serialized limit and all values share a 48 KiB budget;
243
- excess values use null plus currentTruncated/mineTruncated and currentBytes/mineBytes. At most 200
244
- conflicts and 200 characters / 256 serialized UTF-8 bytes per returned id keep the array below 256 KiB;
245
- oversized legacy ids carry fieldIdTruncated. Replacement conflicts use the same bounded format.
246
- Transition-only revision conflicts carry an empty conflicts array. Only authorized writers receive
247
- details. There is no data-write MCP tool; the existing MCP catalog and read tools are unchanged.
248
- MechanismError.toJSON preserves this same details envelope for MCP consumers.
249
-
250
- INITIAL data updates select prepareData(..., { requireRequired: false }) on the server. Type,
251
- options, numeric/row bounds, formats, formulas and visibility remain checked (INVALID_DATA/422);
252
- only required checks, including visible/enabled required fields and row columns, are skipped.
253
- Every transition still uses full validation, including USER, ASSIGNMENT, TIMER and CHOICE. Clients
254
- cannot select draft mode. Start retains its existing allowance for incomplete initial data.
255
-
256
- Both patch and full replacement emit state-machine.data.updated in the write transaction, payload
257
- { instanceId, revision, fields: [actuallyChangedFieldId] }, with no values. Observer failure rolls
258
- back the write. There was no prior data update event; no second event, history or notification is
259
- added. Transition events remain unchanged.
260
-
261
- Set runtime.stateMachine.dataPatchRatePerMinute (integer 0–1000000, default 60; 0 disables it).
262
- The injected STATE_MACHINE_CLOCK drives a process-local sliding minute window per instance/user.
263
- Valid authorized attempts consume budget, including subsequent conflict/validation failures;
264
- excess returns RATE_LIMITED/429 and details.retryAfterSeconds. This is single-process protection;
265
- multiple processes do not share a limit. Clients should debounce autosave by at least two seconds.
266
-
267
- Validation and byte-exact App restoration: validation/equipment-loan/concurrent-editing/report.md.
268
-
269
- ## Capability flags
270
-
271
- A single-instance read reports what the caller may do now: `canArchive`, `canUnarchive`, `canDelete`
272
- and `canEdit`. They come from the same shared rules the lifecycle routes and data edits enforce
273
- (`instanceCapabilities`), so a screen never has to guess permissions.
274
-
275
- ## Unified search (draft 202610-a3d8)
276
-
277
- Draft implementation; the decision remains draft. Specs may declare `search: { fields: string[] }`
278
- (stable field ids, key fallback). JSON Schema checks shape; semantic validation
279
- (`validateSearchFields`, INVALID_SEARCH_FIELD at `/spec/search/fields/<i>`) accepts only top-level
280
- text, textarea, select, number, date and datetime fields and rejects subforms, nested/container
281
- children, user pickers, formulas, read-only fields (disabledWhen or the numbering field),
282
- duplicates and unknown ids; SEARCH_SUBJECT_REQUIRED without a subject. `searchFieldsOf(bundle)`
283
- returns the valid declarations of an instance's pinned bundle. Nothing is indexed by default.
284
-
285
- `StateMachineSearchProvider` is the `instance` source: all numbers (new `numbersOf` store method),
286
- the submitter's active name, the machine name and declared values (select: label and value), each
287
- field ≤2,000 and the row ≤20,000 code points. It includes archived and soft-deleted instances.
288
- @haneinfo/search constructs it; nothing runs without that package. `start()` now emits
289
- `state-machine.start.recorded` (instanceId, machineCode) in the creating transaction after
290
- onStarted listeners; existing listeners filter by name and are unaffected. The manifest requires
291
- plugin API 1.19.0.
292
-
293
- ## Reports and metrics (draft 202610-c7b4)
294
-
295
- Draft implementation; the decision remains draft. Specs may declare
296
- `reporting: { dimensions: [{ fieldId }], measures: [{ fieldId, ops? }] }` (stable field ids, key
297
- fallback). JSON Schema checks shape (ops: unique, non-empty, among count, sum, avg, min, max);
298
- semantic validation (`validateReportingFields`, INVALID_REPORTING_FIELD at
299
- `/spec/reporting/{dimensions|measures}/<i>`) accepts dimensions that are top-level text, select,
300
- number, date, datetime or switch fields and not formulas, and measures that are top-level number
301
- fields (formula results included); duplicates, unknown ids, nested fields, other types, formula
302
- dimensions and repeated ops are rejected, and REPORTING_SUBJECT_REQUIRED without a subject.
303
- `reportingFieldsOf(spec, subject)` returns the valid declarations (invalid ones are skipped).
304
-
305
- `closedStateStaysSql(scope)` is a read-only history helper for @haneinfo/reports: one row per
306
- closed stay `(instance_id, state, entered_at, left_at)` for the instance ids a caller-named CTE
307
- returns, using only state-entering history rows (`STATE_ENTRY_TRIGGER_TYPES`: START, USER,
308
- ASSIGNMENT, TIMER, CHOICE). The entry is the latest entry into that state at or before the exit, so
309
- rows written in the same millisecond pair correctly; a missing entry (incomplete early history)
310
- yields NULL and is skipped. Nothing runs without the reports package. The manifest requires plugin
311
- API 1.20.0.
312
-
313
- ## Data change log and revision diff (draft 202610-d9a5)
314
-
315
- Draft implementation; the decision remains draft. Every write of instance data appends one
316
- `InstanceDataChange` row per changed top-level field, in the same transaction as the write; if the
317
- append fails, the data write rolls back with it. Apply `prisma/data-changes.sql` (table, CHECK
318
- constraints, cascade foreign key, indexes `(instance_id, revision)` and
319
- `(instance_id, field_id, revision)`) and the fragment's `InstanceDataChange` model before starting
320
- the runtime. There is no backfill.
321
-
322
- | Write path | `source` | Actor |
323
- | --- | --- | --- |
324
- | `start` (HTTP `POST /state-machines/:code/instances`, Assignment/Timer callers) | `CREATE` | `USER` submitter, or `SYSTEM` without one |
325
- | `start` with `source: 'IMPORT'` (import-export confirmation) | `IMPORT` | `USER` who confirmed the import |
326
- | `updateFields` (`PATCH …/data/fields`) and `updateData` (`PATCH …/data`) | `PATCH` | `USER` caller |
327
- | `transition` (numbering and Form preparation during a transition) | `TRANSITION` | `USER` for USER/ASSIGNMENT triggers, `MECHANISM` `timer:<code>` for timers |
328
- | automatic CHOICE routing | `TRANSITION` | `MECHANISM` `choice:<state>` |
329
-
330
- A numbered field is always attributed to `MECHANISM` `numbering`. Columns: `revision` (the
331
- revision the write produced), `fieldId`, `before`/`after` (JSON; SQL NULL when the field was absent,
332
- JSON null for a null value), `truncated`, `actorType`, `actorId`, `source`, `at`. Formula fields are
333
- derived and never recorded. A value larger than `dataChangeValueMaxBytes` (default 65,536 UTF-8
334
- bytes of JSON) is stored as SQL NULL with `truncated: true`, so only "this field changed here" is
335
- known. A write that changes no recorded field appends nothing. No domain event or timeline entry is
336
- added; rows are append-only and there is no API to change or delete them (they go with a permanent
337
- purge through the cascade).
338
-
339
- Reads share instance readership (submitter, `state-machine:instance:read`, readers and access
340
- lists, delegation); unreadable, unknown and soft-deleted instances are `INSTANCE_NOT_FOUND` (404);
341
- archived instances stay readable. Old values remain visible to everyone who can read the instance
342
- until it is purged.
343
-
344
- - `GET /state-machine-instances/:id/changes?fromRevision=&toRevision=&fieldId=&limit=&cursor=` —
345
- newest first (revision desc, field id asc); revision bounds are inclusive; `limit` defaults to 50
346
- and may not exceed `dataChangePageMaxLimit` (default 200); `nextCursor` is opaque. Items:
347
- `{ revision, fieldId, before?, after?, beforeTruncated?, afterTruncated?, truncated, actorType,
348
- actorId, actorName, source, at }`; `actorName` is the active display name of USER actors,
349
- resolved in one batch. Displayed values are bounded by `diffValueMaxChars` (default 2,000).
350
- - `GET /state-machine-instances/:id/diff?fromRevision=&toRevision=` — both snapshots are rebuilt
351
- from the current data by undoing recorded changes newer than each revision, formula fields are
352
- removed, and @haneinfo/diff compares them; a field changed and changed back does not appear.
353
- `toRevision` may not exceed the current revision. A field whose value at one end was too large to
354
- store is reported as changed (with the unknown side marked truncated) when it changed in the
355
- range. Response `{ fromRevision, toRevision, historyStartsAtRevision, summary, changes,
356
- truncated }`, bounded by `diffMaxChanges` (default 5,000).
357
-
358
- Both responses carry `historyStartsAtRevision`: the lowest recorded revision, or `null`. A
359
- `fromRevision` lower than it (or any `fromRevision` when it is `null`) returns
360
- `HISTORY_NOT_AVAILABLE` (409, `details.historyStartsAtRevision`); instances created before the
361
- upgrade start their history at their first recorded write. Invalid input is `INVALID_INPUT` (400).
362
-
363
- MCP (read only, user-bound, existing `<ns>:instance:read` scope): `get_instance_changes` and
364
- `diff_instance_revisions`. Field ids, path segments, values and actor names are wrapped as
365
- `$userContent`. Configuration (`runtime.stateMachine`, no secrets): `dataChangeValueMaxBytes`
366
- 1–1,048,576, `diffMaxChanges` 1–50,000, `diffValueMaxChars` 1–100,000, `dataChangePageMaxLimit`
367
- 1–1,000. The manifest requires plugin API 1.21.0 (`start` accepts `source`).
368
-
369
- ## Object references (draft 202610-f7a2)
370
-
371
- `StateMachineObjectTypeProvider` is the `state-machine-instance` object type of the optional
372
- @haneinfo/references package, which constructs and registers it (nothing here runs without that
373
- package). Readability and write access reuse the instance rules through `accessibleInstances`, the
374
- batch form of `instanceAccessAllowed` (one access-list query for the batch); soft-deleted instances
375
- are never readable. The store adds `findMany`, `readerIdsAmong` and `numbersOfMany`. Preview cards
376
- use the first application number (or the machine name and UTC creation date) as title, the
377
- submitter's active name as subtitle, the state and its label, the archived flag and
378
- `/instances/<id>`. A created or removed link appends a `REFERENCE` history entry with
379
- `decision.reference` (action, linkId, kind, direction, other `{ type, id, number }`) on each end
380
- whose readers (submitter and access-list users, role members through RBAC) can all read the other
381
- end, then emits `references.linked` / `references.unlinked` in the same transaction. REFERENCE does
382
- not count as a transition for the draft deletion rule. The lifecycle purge event deletes the purged
383
- instance's edges in the purge transaction. Requires plugin API 1.23.0.
384
-
385
- ## Inherited access rows (draft 202610-b1d6)
386
-
387
- The access list gains the source `INHERITED` and the nullable `viaNodeId` (column `via_node_id`,
388
- indexed). INHERITED rows are written only by the optional @haneinfo/spaces package from the
389
- container an instance is placed in: USER or ROLE, READ or WRITE, with the granting space node in
390
- `viaNodeId`. Every read rule already counts them (submitter, instance permission or a matching row
391
- of any source), so detail reads, lists, exports, search, reports and references follow container
392
- access with no change. The store adds `replaceInherited(instanceIds, rows)`, which makes the
393
- INHERITED rows of exactly those instances equal to `rows` in the caller's transaction (stale rows
394
- deleted, changed rows updated, new rows inserted, unchanged rows untouched) and never reads, changes
395
- or removes rows of another source; `assertInheritedRows` validates the rows first.
396
-
397
- Existing sources behave exactly as before: GRANTED stays the only source the access list API
398
- creates, adjusts, counts against `maxGrantedAccess` and removes; a principal with only an INHERITED
399
- row gets `ACCESS_NOT_MANAGEABLE` from DELETE, and a principal with both keeps the INHERITED row when
400
- the GRANTED one is removed. `GET /state-machine-instances/:id/access` lists INHERITED rows with their
401
- `viaNodeId`. The history trigger type `SPACE` records placements (not a transition for the draft
402
- deletion rule). Apply `prisma/inherited-access.sql` in an App migration and add `viaNodeId` with
403
- `@@index([viaNodeId])` to the App's fragment: it widens the source and permanent-row CHECK
404
- constraints and requires `via_node_id` exactly on INHERITED rows. Requires plugin API 1.24.0
405
- (`INSTANCE_ACCESS_SOURCES`).
406
-
407
- ## Generated MCP read tools declaration (draft 202610-c5e8)
408
-
409
- Draft implementation; the decision remains draft. Specs may declare
410
- `mcp: { tools: ('list' | 'get' | 'search' | 'report')[], toolName? }` to opt into the per-machine
411
- read tools of the optional @haneinfo/mcp-generated-tools package; nothing is generated without it.
412
- JSON Schema checks shape (1–4 known kinds, `toolName` matching `^[a-z][a-z0-9_]*$`, 1–32
413
- characters). Semantic validation (`validateMcpToolsDeclaration`) reports DUPLICATE_MCP_TOOL,
414
- INVALID_MCP_TOOL, MCP_TOOL_DECLARATION_REQUIRED (`search` without `search.fields`, `report` without
415
- `reporting`) at `/spec/mcp/tools/<i>`, and INVALID_MCP_TOOL_NAME for an invalid `toolName` or, without
416
- one, a code whose derived name (lower case, other characters `_`) is longer than 32; the kind
417
- registration passes `metadata.code` for that check (`validateStateMachineSpec(spec, context, code)`).
418
- `mcpToolsOf(spec, code, maxNameLength?)` returns `{ tools, fragment }` for a published machine (known
419
- kinds once each, in list/get/search/report order; `fragment` null when invalid) or null without a
420
- declaration. `StateMachineRuntime.getFor` now also satisfies the optional
421
- `StateMachineRuntimePort.getFor` of plugin API 1.25.0, which the manifest requires.
1
+ # @haneinfo/state-machine
2
+
3
+ See [agent-guide.md](agent-guide.md) for integration details.
4
+
5
+ ## Instance readers and stored query values
6
+
7
+ Reads allow the submitter, holders of `state-machine:instance:read`, or an instance reader grant.
8
+ ADMIN continues to use existing RBAC. `mine=true` still means submitter ownership. Number lookups
9
+ apply the same rule before pagination.
10
+
11
+ `StateMachineReaderGrants.grantAssigned(instanceId, userIds, tx)` is a grant-only service exported
12
+ by StateMachineModule. Assignment injects it and supplies the task transaction; grants use
13
+ `createMany({ skipDuplicates: true })` (PostgreSQL `ON CONFLICT DO NOTHING`). There is no revoke
14
+ operation or additional read port. Custom stores must implement `grantReaders`, `isReader`, and
15
+ `readableBy` instance/number filters. Apps must migrate the Prisma fragment and backfill existing
16
+ tasks before upgrading. The `(instance_id, user_id)` primary key supports indexed reader lookups;
17
+ the separate `user_id` index supports user-led scans.
18
+
19
+ ```sql
20
+ INSERT INTO state_machine_instance_readers (instance_id, user_id, reason)
21
+ SELECT DISTINCT instance_id, assignee_id, 'ASSIGNED'
22
+ FROM assignment_tasks
23
+ ON CONFLICT (instance_id, user_id) DO NOTHING;
24
+ ```
25
+
26
+ Top-level text, textarea, number, date and datetime formula fields can be declared in
27
+ `spec.listView.fields`. Queries read stored results through the ordinary JSONB path. Queries never
28
+ recompute formulas or backfill missing historical values. Select, switch, nested and container
29
+ fields remain unsupported.
30
+
31
+ ## Date comparisons
32
+
33
+ GT/GTE/LT/LTE compare numbers, valid calendar dates (YYYY-MM-DD), or timezone-qualified datetimes
34
+ (YYYY-MM-DDTHH:mm:ss with optional fractional seconds and Z or +/-HH:mm). Both operands must have
35
+ the same category. Dates use calendar order; datetimes compare UTC instants at millisecond precision.
36
+ Invalid dates, mixed categories and empty operands yield false. EQ/NEQ/IN retain strict scalar equality;
37
+ matching instants with different textual offsets are still unequal for those operators.
38
+
39
+ ## Instance privacy and submitter names
40
+
41
+ All person-facing instance reads (detail including history, available transitions and exact number lookup) return `INSTANCE_NOT_FOUND`, HTTP 404, message `Instance not found`, with no suggestion for both missing and unreadable instances. No read permission name is exposed. USER transitions and data updates check readability before revision, state and write authorization; readable users missing the write/business permission still receive 403. Submitter ownership, effective instance:read and permanent reader grants are unchanged. Internal `get`/`history` remain trusted mechanism APIs without a person parameter; there is no delete endpoint.
42
+
43
+ Authorized detail, instance list and numbering reads include `submitterName: string | null`. Optional identity-store `findActiveNamesByIds` resolves unique submitter ids once per result batch. Missing, inactive and deleted identities, absent identity capability and older providers return null without per-row fallbacks. No schema migration or people-lookup HTTP route is added. Numbering MCP wraps names in `$userContent`; exact unreadable/missing numbers return the same error, while recent-number lists still filter before paging.
44
+
45
+ ## Delegated Assignment attribution
46
+
47
+ ASSIGNMENT triggers may include optional actingUserId and onBehalfOfId. Existing userId and
48
+ triggerUserId remain the actual actor. Attribution is persisted in the existing transition decision
49
+ JSON and exposed as optional history fields, including getFor's embedded history. Notification
50
+ outcomes merge with this metadata instead of replacing it. No history schema migration is needed.
51
+ The decision remains draft (202610-6b1f). Assignment owns delegation validity and response policy.
52
+
53
+ When the resolver is installed, StateMachine takes its optional shared transaction advisory lock
54
+ before instance creation or any instance row lock/write. Delegation creation/revocation takes the
55
+ exclusive lock on the same key. Normal instance transactions remain concurrent; a graph mutation
56
+ briefly blocks new instance writers until its backfill/cancellation commits. This closes the race
57
+ where creation and state entry could otherwise miss each other's uncommitted rows. The advisory lock always precedes instance locks; task CAS and delegation-row shared locks
58
+ remain inside that transaction. No extra table or worker is added.
59
+
60
+
61
+ ## Instance access lists (draft implementation)
62
+
63
+ Implemented against draft decision 202610-c8e3; the decision remains draft. This section supersedes
64
+ the earlier reader-only model and human transition eligibility. Upgrade the affected
65
+ mechanisms together and apply the App migration before starting the new runtime. The maintainer
66
+ selected source-specific uniqueness: `(instanceId, principalType, principalId, source)`. Existing
67
+ model/table names are retained. `principalType` is USER or ROLE; `principalId` is a user id or role
68
+ machine name; `level` is READ or WRITE; `source` is ASSIGNED, DELEGATED or GRANTED. Each row also
69
+ has nullable grantedBy and createdAt. Indexes cover instanceId and (principalType, principalId).
70
+ Permanent ASSIGNED/DELEGATED entries are READ and survive every task/delegation status. Manual
71
+ GRANTED entries coexist with them; removing GRANTED never removes permanent readership.
72
+
73
+ All instance reads use submitter, effective state-machine:instance:read, or a matching USER/ROLE
74
+ entry. Roles come from RBAC authorizationOfUser once per query, passed into persistence; no direct
75
+ RBAC-table joins. WRITE also requires an existing readable instance, then submitter, effective
76
+ state-machine:instance:write, or matching WRITE. Human transitions still check their declared
77
+ business permission. Assignment/Timer transition authorization is unchanged. Unreadable instances
78
+ return INSTANCE_NOT_FOUND/404; readable callers without write/manage eligibility receive 403.
79
+
80
+ Only the submitter or state-machine:instance:admin can manage access; instance administrators can
81
+ manage any instance list. Grantees cannot regrant. InteractiveAuthGuard protects GET/PUT
82
+ /state-machine-instances/:id/access and DELETE /state-machine-instances/:id/access/:principalType/:principalId.
83
+ PUT targets GRANTED only, never changes permanent rows. DELETE removes GRANTED if present; a
84
+ permanent-only target returns ACCESS_NOT_MANAGEABLE/409. Missing manual targets are idempotent.
85
+ GET returns sources, levels, principalName and grantedByName; user names share one authorized
86
+ findActiveNamesByIds batch, role display labels share one RBAC lookup, unavailable names are null.
87
+ Names are plain text. maxGrantedAccess defaults to 100. Only active users or existing roles can be
88
+ granted; the submitter cannot receive a USER grant. Errors include ACCESS_PRINCIPAL_INVALID/400,
89
+ ACCESS_LIMIT_EXCEEDED/409 and ACCESS_NOT_MANAGEABLE/409. Repeated equal grants have no effects.
90
+
91
+ StateMachineMcpTools.registerInto now also registers list_instance_access using <namespace>:instance:read.
92
+ It returns items in $userContent and offers no grant/remove tools. Changed individual grants notify
93
+ with state-machine-access:<historyId>; equal retries do not notify again. Role grants and removals
94
+ never notify. Missing inbox capability skips delivery. Actual inbox failures roll back the mutation.
95
+ ACCESS history uses the existing decision JSON and emits state-machine.access.recorded in the
96
+ same transaction; collaboration adds ACCESS to its existing SQL timeline union. State, revision and
97
+ transition events do not change for access mutations. List/export counts and pagination include
98
+ personal and role access in one parameterized EXISTS; snapshot exports abort on role-name changes.
99
+
100
+ Migration SQL ships at @haneinfo/state-machine/prisma/instance-access.sql. It renames user_id to
101
+ principal_id and reason to source, preserves created_at, adds principal_type/level/granted_by,
102
+ converts legacy rows to USER/READ and ASSIGNED (recognized delegation becomes DELEGATED), and
103
+ backfills every assignment task regardless of status. It expects the Assignment delegation columns;
104
+ Apps without Assignment/Delegation must omit the corresponding task queries/backfill. Do not reset
105
+ an existing database. See the package repository validation/equipment-loan/instance-access/report.md
106
+ for adoption evidence and the explicitly selected uniqueness adjustment; no decision text is changed.
107
+
108
+ Configure runtime.stateMachine.maxGrantedAccess (positive integer, default 100). Apply prisma/instance-access.sql in your App migration before upgrading. Custom StateMachineStore implementations must implement listAccess, putGranted and deleteGranted and accept optional roles/source/level in reader methods. The new optional RBAC role-label lookup requires plugin API 1.14.0.
109
+
110
+
111
+ ## Access management eligibility (draft 202610-e2a9)
112
+
113
+ GET /state-machine-instances/:id/access adds canManage: boolean alongside the unchanged items.
114
+ The service shares its submitter/instance-admin eligibility calculation with PUT/DELETE; readers
115
+ can inspect but cannot regrant access. list_instance_access adds the same canManage next to its
116
+ existing wrapped items. It remains read-only. No database or plugin-api contract changes apply.
117
+
118
+ ## Optional attachments (draft decision 202610-5f3b)
119
+
120
+ Attachment activity uses existing history with triggerType ATTACHMENT and optional decision.attachment (action, id, plain-text fileName). No storage keys, state/revision changes or notifications are introduced. Collaboration classifies these history rows as ATTACHMENT in its existing SQL union; MCP retains decision $userContent wrapping. See @haneinfo/attachments/agent-guide.md for authorization, storage, scanning, migration and retention. Apps adopting the optional package add its reverse instance relation; the core fragment does not depend on attachments.
121
+
122
+
123
+ ## Document generation (draft 202610-d4f6)
124
+
125
+ The optional @haneinfo/document-templates package adds DOCUMENT activity using existing history
126
+ and decision.document (templateCode, templateVersion, format), attributed by triggerUserId.
127
+ No tables, state/revision changes or notifications are added. Collaboration classifies the row
128
+ as DOCUMENT in its existing authorized SQL timeline. Instance history and timeline fields remain
129
+ unchanged. Read the document-templates agent guide for fonts, configuration, HTTP and read-only MCP.
130
+
131
+
132
+ ## Instance lifecycle (draft 202610-f1a8)
133
+
134
+ Implemented from draft decision 202610-f1a8; the decision remains draft. Upgrade state-machine,
135
+ list-view, collaboration, attachments, import-export, assignment and timer together. No frontend,
136
+ automatic archive or bulk lifecycle operations are included. Permanently purged data cannot be
137
+ restored by this API: database and private file backups must cover the entire deletion retention
138
+ period and be restored consistently.
139
+
140
+ The instance fragment adds nullable archivedAt/archivedBy/deletedAt/deletedBy, preserving old
141
+ instances as active. Apply prisma/instance-lifecycle.sql before running the upgraded packages.
142
+ Indexes (machineCode, archivedAt), (deletedAt) and (submitterId, deletedAt) support archive queries,
143
+ expiry scans and owner recycle lists. No new table is introduced. Install collaboration's Cascade
144
+ migration when that package is present; the App adds comments CollaborationComment[] and follows
145
+ CollaborationFollow[] reverse instance relations. Attachments already has Cascade; application
146
+ numbers retain Restrict.
147
+
148
+ Only FINAL instances can be archived. Archive is a view flag: all existing authorized reads and
149
+ writes, including comments, access grants, following, attachments and exports, remain available.
150
+ Unarchive clears both archive columns. Only INITIAL instances without any transition evidence or
151
+ StateMachineNumber record can be soft-deleted; START, ACCESS, ATTACHMENT, DOCUMENT and LIFECYCLE
152
+ activity are not state transitions. Returned, rejected and voided applications cannot be deleted.
153
+ Lifecycle operations do not change state, data or revision and are idempotent without duplicate
154
+ history/events. They reuse instanceManagementAllowed, also used by access-list management.
155
+ Readability is checked before submitter/instance:admin eligibility; WRITE and assigned readership
156
+ do not grant eligibility. An admin without ordinary read access gets 404 on active instances.
157
+
158
+ All routes require InteractiveAuthGuard:
159
+
160
+ | Method | Route | Operation |
161
+ | --- | --- | --- |
162
+ | POST | /state-machine-instances/:id/archive | Archive FINAL |
163
+ | POST | /state-machine-instances/:id/unarchive | Clear archive |
164
+ | DELETE | /state-machine-instances/:id | Soft-delete draft |
165
+ | POST | /state-machine-instances/:id/undelete | Restore within retention |
166
+ | GET | /state-machine-instances/deleted?offset=0&limit=50 | Recoverable deletions, newest first |
167
+
168
+ The deleted collection precedes the :id route, caps limit at 200 and returns total plus id,
169
+ machineCode, machineVersion, state, submitterId, startedAt, deletedAt, deletedBy, deletedByName
170
+ and remainingRetentionDays. Owners see only their own drafts deleted by themselves; instance:admin
171
+ sees all recoverable deletions. Admin-deleted drafts require admin restoration. Expired restoration
172
+ is INSTANCE_NOT_FOUND even before the worker physically removes the row. Repeated DELETE by an
173
+ eligible actor succeeds while its deleted row exists; after physical purge it returns 404.
174
+
175
+ Public instance reads include archived and nullable archivedAt. Internal get returns null for
176
+ deleted rows; history and every authorized HTTP/MCP instance read return exactly the missing-id
177
+ INSTANCE_NOT_FOUND/404, `Instance not found`, with no suggestion. Lists always exclude deletions.
178
+ List endpoints accept archived EXCLUDE (default), INCLUDE or ONLY; exact-number and single reads
179
+ ignore archive flags. INSTANCE_NOT_ARCHIVABLE and INSTANCE_NOT_DELETABLE use 409; readable but
180
+ ineligible lifecycle actions use FORBIDDEN/403. MCP exposes only existing read tools and archived
181
+ metadata, never lifecycle mutations or a recycle-list tool.
182
+
183
+ Each changed action writes LIFECYCLE history with decision.lifecycle.action (ARCHIVED, RESTORED,
184
+ DELETED, UNDELETED) and synchronously emits state-machine.instance.archived/restored/deleted/undeleted
185
+ in the same transaction. Payload: instanceId, historyId, userId, at (ISO). No notification is sent.
186
+ state-machine.instance.purging has payload { instanceId } and runs before database deletion in that
187
+ same transaction; listeners must use event.tx. Listener failures roll back all database changes.
188
+
189
+ runtime.stateMachine supports deletedRetentionDays=30 (0–36500; 0 makes rows immediately eligible),
190
+ purgeBatchSize=100 (1–500), purgePollIntervalMs=60000 (1–2147483647) and purgeWorkerEnabled=true.
191
+ Direct module registration uses the same strict schema. Optional background-jobs registers
192
+ state-machine.instances.purge; the producer enqueues on bootstrap and each interval, can be disabled,
193
+ and waits for pending enqueue on shutdown. BACKGROUND_JOBS_WORKER_ENABLED is App wiring for the
194
+ core worker; set purgeWorkerEnabled=false as well to stop this producer. Without background-jobs,
195
+ human lifecycle actions still work and no jobs are enqueued. A purge batch is one job transaction,
196
+ uses instance/delegation locks, checkpoints cancellation, and can retry safely. Numbered deleted rows
197
+ are inconsistent: log an error and keep them (Restrict remains the final database defense). Repair
198
+ such rows promptly: they count against the bounded candidate batch. Custom stores must implement
199
+ lifecycle persistence and make their default find/list exclude deleted rows.
200
+
201
+
202
+ ## Instance tags (draft 202610-2c5d)
203
+
204
+ Implemented from draft 202610-2c5d; the decision remains draft. See @haneinfo/tags/agent-guide.md
205
+ for data, migration and authorization. TAG history uses optional decision.tag with action, normalizedKey and label. It does not change
206
+ state/revision or count as a lifecycle transition. The App adds tags InstanceTag[] only when
207
+ installing the optional plugin; permanent purge removes tags through its Cascade foreign key.
208
+
209
+
210
+ ## Concurrent field editing (draft 202610-8b3e)
211
+
212
+ Implemented from draft decision 202610-8b3e; the decision remains draft. Upgrade state-machine,
213
+ form, definition-registry and plugin-api together (API contract 1.18.0). Apply
214
+ prisma/concurrent-editing.sql before enabling the new runtime. StateMachineInstance.fieldRevisions
215
+ is JSONB with default {}; the SQL backfills every existing top-level data key to the instance's
216
+ current revision. Empty or non-object data is safe. Reruns fill missing keys without overwriting
217
+ existing revisions or deletion tombstones. Copy the fragment and SQL into an App migration; never
218
+ reset a database to adopt it. Internal/custom stores must maintain revisions in create/update.
219
+
220
+ PATCH /state-machine-instances/:id/data/fields is protected by InteractiveAuthGuard. Body:
221
+ { baseRevision, fields: { stableFieldId: value }, remove?: [stableFieldId] }. Use 1–200 distinct
222
+ field ids across both collections, each at most 200 characters, and JSON values. Id falls back to
223
+ Form key when absent. Layout children retain Form's flat data scope; subforms replace the entire
224
+ array. Formula fields, numbering targets, disabled fields and layout-only ids are not editable.
225
+ Conditional disabled checks apply to both current and proposed data. Unknown ids return FIELD_UNKNOWN
226
+ (400); read-only ids return FIELD_NOT_EDITABLE (400), including remove. There is no row merge.
227
+
228
+ Under the instance row lock, check readability (missing, unreadable or deleted: identical
229
+ INSTANCE_NOT_FOUND/404), then submitter/effective instance:write/USER-or-ROLE WRITE (403), then
230
+ frozen/CHOICE/FINAL (STATE_FROZEN/409). A field conflicts only when its recorded revision exceeds
231
+ baseRevision and its proposed value/presence differs deeply from current data. Any conflict aborts
232
+ the entire patch. Equal stale values succeed. Future baseRevision is INVALID_INPUT/400.
233
+ Success returns { revision, data, changedByOthers }; the last list contains keys revised after
234
+ the base but absent from this request, including computed fields and tombstones. Every successful
235
+ request increments revision, even when its normalized data is unchanged. Formula recalculation
236
+ and every other actual top-level data change update fieldRevisions; unchanged values retain their
237
+ revision. Removed keys retain their revision as tombstones; patch preparation preserves explicit
238
+ absence. Full replacement keeps its existing expectedRevision contract and normalization.
239
+
240
+ VERSION_CONFLICT/409 uses the existing details object: { currentRevision, conflicts: [{ fieldId,
241
+ current, mine }] }. Missing values use null plus currentMissing/mineMissing. Small values remain
242
+ original JSON. Each value has a 1 KiB UTF-8 serialized limit and all values share a 48 KiB budget;
243
+ excess values use null plus currentTruncated/mineTruncated and currentBytes/mineBytes. At most 200
244
+ conflicts and 200 characters / 256 serialized UTF-8 bytes per returned id keep the array below 256 KiB;
245
+ oversized legacy ids carry fieldIdTruncated. Replacement conflicts use the same bounded format.
246
+ Transition-only revision conflicts carry an empty conflicts array. Only authorized writers receive
247
+ details. There is no data-write MCP tool; the existing MCP catalog and read tools are unchanged.
248
+ MechanismError.toJSON preserves this same details envelope for MCP consumers.
249
+
250
+ INITIAL data updates select prepareData(..., { requireRequired: false }) on the server. Type,
251
+ options, numeric/row bounds, formats, formulas and visibility remain checked (INVALID_DATA/422);
252
+ only required checks, including visible/enabled required fields and row columns, are skipped.
253
+ Every transition still uses full validation, including USER, ASSIGNMENT, TIMER and CHOICE. Clients
254
+ cannot select draft mode. Start retains its existing allowance for incomplete initial data.
255
+
256
+ Both patch and full replacement emit state-machine.data.updated in the write transaction, payload
257
+ { instanceId, revision, fields: [actuallyChangedFieldId] }, with no values. Observer failure rolls
258
+ back the write. There was no prior data update event; no second event, history or notification is
259
+ added. Transition events remain unchanged.
260
+
261
+ Set runtime.stateMachine.dataPatchRatePerMinute (integer 0–1000000, default 60; 0 disables it).
262
+ The injected STATE_MACHINE_CLOCK drives a process-local sliding minute window per instance/user.
263
+ Valid authorized attempts consume budget, including subsequent conflict/validation failures;
264
+ excess returns RATE_LIMITED/429 and details.retryAfterSeconds. This is single-process protection;
265
+ multiple processes do not share a limit. Clients should debounce autosave by at least two seconds.
266
+
267
+ Validation and byte-exact App restoration: validation/equipment-loan/concurrent-editing/report.md.
268
+
269
+ ## Capability flags
270
+
271
+ A single-instance read reports what the caller may do now: `canArchive`, `canUnarchive`, `canDelete`
272
+ and `canEdit`. They come from the same shared rules the lifecycle routes and data edits enforce
273
+ (`instanceCapabilities`), so a screen never has to guess permissions.
274
+
275
+ ## Unified search (draft 202610-a3d8)
276
+
277
+ Draft implementation; the decision remains draft. Specs may declare `search: { fields: string[] }`
278
+ (stable field ids, key fallback). JSON Schema checks shape; semantic validation
279
+ (`validateSearchFields`, INVALID_SEARCH_FIELD at `/spec/search/fields/<i>`) accepts only top-level
280
+ text, textarea, select, number, date and datetime fields and rejects subforms, nested/container
281
+ children, user pickers, formulas, read-only fields (disabledWhen or the numbering field),
282
+ duplicates and unknown ids; SEARCH_SUBJECT_REQUIRED without a subject. `searchFieldsOf(bundle)`
283
+ returns the valid declarations of an instance's pinned bundle. Nothing is indexed by default.
284
+
285
+ `StateMachineSearchProvider` is the `instance` source: all numbers (new `numbersOf` store method),
286
+ the submitter's active name, the machine name and declared values (select: label and value), each
287
+ field ≤2,000 and the row ≤20,000 code points. It includes archived and soft-deleted instances.
288
+ @haneinfo/search constructs it; nothing runs without that package. `start()` now emits
289
+ `state-machine.start.recorded` (instanceId, machineCode) in the creating transaction after
290
+ onStarted listeners; existing listeners filter by name and are unaffected. The manifest requires
291
+ plugin API 1.19.0.
292
+
293
+ ## Reports and metrics (draft 202610-c7b4)
294
+
295
+ Draft implementation; the decision remains draft. Specs may declare
296
+ `reporting: { dimensions: [{ fieldId }], measures: [{ fieldId, ops? }] }` (stable field ids, key
297
+ fallback). JSON Schema checks shape (ops: unique, non-empty, among count, sum, avg, min, max);
298
+ semantic validation (`validateReportingFields`, INVALID_REPORTING_FIELD at
299
+ `/spec/reporting/{dimensions|measures}/<i>`) accepts dimensions that are top-level text, select,
300
+ number, date, datetime or switch fields and not formulas, and measures that are top-level number
301
+ fields (formula results included); duplicates, unknown ids, nested fields, other types, formula
302
+ dimensions and repeated ops are rejected, and REPORTING_SUBJECT_REQUIRED without a subject.
303
+ `reportingFieldsOf(spec, subject)` returns the valid declarations (invalid ones are skipped).
304
+
305
+ `closedStateStaysSql(scope)` is a read-only history helper for @haneinfo/reports: one row per
306
+ closed stay `(instance_id, state, entered_at, left_at)` for the instance ids a caller-named CTE
307
+ returns, using only state-entering history rows (`STATE_ENTRY_TRIGGER_TYPES`: START, USER,
308
+ ASSIGNMENT, TIMER, CHOICE). The entry is the latest entry into that state at or before the exit, so
309
+ rows written in the same millisecond pair correctly; a missing entry (incomplete early history)
310
+ yields NULL and is skipped. Nothing runs without the reports package. The manifest requires plugin
311
+ API 1.20.0.
312
+
313
+ ## Data change log and revision diff (draft 202610-d9a5)
314
+
315
+ Draft implementation; the decision remains draft. Every write of instance data appends one
316
+ `InstanceDataChange` row per changed top-level field, in the same transaction as the write; if the
317
+ append fails, the data write rolls back with it. Apply `prisma/data-changes.sql` (table, CHECK
318
+ constraints, cascade foreign key, indexes `(instance_id, revision)` and
319
+ `(instance_id, field_id, revision)`) and the fragment's `InstanceDataChange` model before starting
320
+ the runtime. There is no backfill.
321
+
322
+ | Write path | `source` | Actor |
323
+ | --- | --- | --- |
324
+ | `start` (HTTP `POST /state-machines/:code/instances`, Assignment/Timer callers) | `CREATE` | `USER` submitter, or `SYSTEM` without one |
325
+ | `start` with `source: 'IMPORT'` (import-export confirmation) | `IMPORT` | `USER` who confirmed the import |
326
+ | `updateFields` (`PATCH …/data/fields`) and `updateData` (`PATCH …/data`) | `PATCH` | `USER` caller |
327
+ | `transition` (numbering and Form preparation during a transition) | `TRANSITION` | `USER` for USER/ASSIGNMENT triggers, `MECHANISM` `timer:<code>` for timers |
328
+ | automatic CHOICE routing | `TRANSITION` | `MECHANISM` `choice:<state>` |
329
+
330
+ A numbered field is always attributed to `MECHANISM` `numbering`. Columns: `revision` (the
331
+ revision the write produced), `fieldId`, `before`/`after` (JSON; SQL NULL when the field was absent,
332
+ JSON null for a null value), `truncated`, `actorType`, `actorId`, `source`, `at`. Formula fields are
333
+ derived and never recorded. A value larger than `dataChangeValueMaxBytes` (default 65,536 UTF-8
334
+ bytes of JSON) is stored as SQL NULL with `truncated: true`, so only "this field changed here" is
335
+ known. A write that changes no recorded field appends nothing. No domain event or timeline entry is
336
+ added; rows are append-only and there is no API to change or delete them (they go with a permanent
337
+ purge through the cascade).
338
+
339
+ Reads share instance readership (submitter, `state-machine:instance:read`, readers and access
340
+ lists, delegation); unreadable, unknown and soft-deleted instances are `INSTANCE_NOT_FOUND` (404);
341
+ archived instances stay readable. Old values remain visible to everyone who can read the instance
342
+ until it is purged.
343
+
344
+ - `GET /state-machine-instances/:id/changes?fromRevision=&toRevision=&fieldId=&limit=&cursor=` —
345
+ newest first (revision desc, field id asc); revision bounds are inclusive; `limit` defaults to 50
346
+ and may not exceed `dataChangePageMaxLimit` (default 200); `nextCursor` is opaque. Items:
347
+ `{ revision, fieldId, before?, after?, beforeTruncated?, afterTruncated?, truncated, actorType,
348
+ actorId, actorName, source, at }`; `actorName` is the active display name of USER actors,
349
+ resolved in one batch. Displayed values are bounded by `diffValueMaxChars` (default 2,000).
350
+ - `GET /state-machine-instances/:id/diff?fromRevision=&toRevision=` — both snapshots are rebuilt
351
+ from the current data by undoing recorded changes newer than each revision, formula fields are
352
+ removed, and @haneinfo/diff compares them; a field changed and changed back does not appear.
353
+ `toRevision` may not exceed the current revision. A field whose value at one end was too large to
354
+ store is reported as changed (with the unknown side marked truncated) when it changed in the
355
+ range. Response `{ fromRevision, toRevision, historyStartsAtRevision, summary, changes,
356
+ truncated }`, bounded by `diffMaxChanges` (default 5,000).
357
+
358
+ Both responses carry `historyStartsAtRevision`: the lowest recorded revision, or `null`. A
359
+ `fromRevision` lower than it (or any `fromRevision` when it is `null`) returns
360
+ `HISTORY_NOT_AVAILABLE` (409, `details.historyStartsAtRevision`); instances created before the
361
+ upgrade start their history at their first recorded write. Invalid input is `INVALID_INPUT` (400).
362
+
363
+ MCP (read only, user-bound, existing `<ns>:instance:read` scope): `get_instance_changes` and
364
+ `diff_instance_revisions`. Field ids, path segments, values and actor names are wrapped as
365
+ `$userContent`. Configuration (`runtime.stateMachine`, no secrets): `dataChangeValueMaxBytes`
366
+ 1–1,048,576, `diffMaxChanges` 1–50,000, `diffValueMaxChars` 1–100,000, `dataChangePageMaxLimit`
367
+ 1–1,000. The manifest requires plugin API 1.21.0 (`start` accepts `source`).
368
+
369
+ ## Object references (draft 202610-f7a2)
370
+
371
+ `StateMachineObjectTypeProvider` is the `state-machine-instance` object type of the optional
372
+ @haneinfo/references package, which constructs and registers it (nothing here runs without that
373
+ package). Readability and write access reuse the instance rules through `accessibleInstances`, the
374
+ batch form of `instanceAccessAllowed` (one access-list query for the batch); soft-deleted instances
375
+ are never readable. The store adds `findMany`, `readerIdsAmong` and `numbersOfMany`. Preview cards
376
+ use the first application number (or the machine name and UTC creation date) as title, the
377
+ submitter's active name as subtitle, the state and its label, the archived flag and
378
+ `/instances/<id>`. A created or removed link appends a `REFERENCE` history entry with
379
+ `decision.reference` (action, linkId, kind, direction, other `{ type, id, number }`) on each end
380
+ whose readers (submitter and access-list users, role members through RBAC) can all read the other
381
+ end, then emits `references.linked` / `references.unlinked` in the same transaction. REFERENCE does
382
+ not count as a transition for the draft deletion rule. The lifecycle purge event deletes the purged
383
+ instance's edges in the purge transaction. Requires plugin API 1.23.0.
384
+
385
+ ## Inherited access rows (draft 202610-b1d6)
386
+
387
+ The access list gains the source `INHERITED` and the nullable `viaNodeId` (column `via_node_id`,
388
+ indexed). INHERITED rows are written only by the optional @haneinfo/spaces package from the
389
+ container an instance is placed in: USER or ROLE, READ or WRITE, with the granting space node in
390
+ `viaNodeId`. Every read rule already counts them (submitter, instance permission or a matching row
391
+ of any source), so detail reads, lists, exports, search, reports and references follow container
392
+ access with no change. The store adds `replaceInherited(instanceIds, rows)`, which makes the
393
+ INHERITED rows of exactly those instances equal to `rows` in the caller's transaction (stale rows
394
+ deleted, changed rows updated, new rows inserted, unchanged rows untouched) and never reads, changes
395
+ or removes rows of another source; `assertInheritedRows` validates the rows first.
396
+
397
+ Existing sources behave exactly as before: GRANTED stays the only source the access list API
398
+ creates, adjusts, counts against `maxGrantedAccess` and removes; a principal with only an INHERITED
399
+ row gets `ACCESS_NOT_MANAGEABLE` from DELETE, and a principal with both keeps the INHERITED row when
400
+ the GRANTED one is removed. `GET /state-machine-instances/:id/access` lists INHERITED rows with their
401
+ `viaNodeId`. The history trigger type `SPACE` records placements (not a transition for the draft
402
+ deletion rule). Apply `prisma/inherited-access.sql` in an App migration and add `viaNodeId` with
403
+ `@@index([viaNodeId])` to the App's fragment: it widens the source and permanent-row CHECK
404
+ constraints and requires `via_node_id` exactly on INHERITED rows. Requires plugin API 1.24.0
405
+ (`INSTANCE_ACCESS_SOURCES`).
406
+
407
+ ## Generated MCP read tools declaration (draft 202610-c5e8)
408
+
409
+ Draft implementation; the decision remains draft. Specs may declare
410
+ `mcp: { tools: ('list' | 'get' | 'search' | 'report')[], toolName? }` to opt into the per-machine
411
+ read tools of the optional @haneinfo/mcp-generated-tools package; nothing is generated without it.
412
+ JSON Schema checks shape (1–4 known kinds, `toolName` matching `^[a-z][a-z0-9_]*$`, 1–32
413
+ characters). Semantic validation (`validateMcpToolsDeclaration`) reports DUPLICATE_MCP_TOOL,
414
+ INVALID_MCP_TOOL, MCP_TOOL_DECLARATION_REQUIRED (`search` without `search.fields`, `report` without
415
+ `reporting`) at `/spec/mcp/tools/<i>`, and INVALID_MCP_TOOL_NAME for an invalid `toolName` or, without
416
+ one, a code whose derived name (lower case, other characters `_`) is longer than 32; the kind
417
+ registration passes `metadata.code` for that check (`validateStateMachineSpec(spec, context, code)`).
418
+ `mcpToolsOf(spec, code, maxNameLength?)` returns `{ tools, fragment }` for a published machine (known
419
+ kinds once each, in list/get/search/report order; `fragment` null when invalid) or null without a
420
+ declaration. `StateMachineRuntime.getFor` now also satisfies the optional
421
+ `StateMachineRuntimePort.getFor` of plugin API 1.25.0, which the manifest requires.
422
+
423
+ ## Localized labels, state tones and display reads (draft 202610-a8d3)
424
+
425
+ Draft implementation; the decision remains draft. State and transition `label` accept a string or a
426
+ zh-TW/en locale map (`$defs/label`, the plugin-api schema; INVALID_LOCALIZED_TEXT for
427
+ whitespace-only translations; `/label/*` free-text paths). States may declare
428
+ `tone` (`neutral`, `info`, `success`, `warning`, `danger`); without it the type decides (INITIAL and
429
+ FINAL neutral, NORMAL and CHOICE info).
430
+
431
+ Public reads resolve labels in the request locale (`?locale=` zh-TW or en, else INVALID_LOCALE/400,
432
+ then Accept-Language, then zh-TW; `requestLocale(query, acceptLanguage)` is exported for other
433
+ controllers): `GET /state-machine-instances/:id`, `GET /state-machine-instances`, start, transition and
434
+ `PATCH …/data` return the instance with its bundle localized (every Form and StateMachine of it) plus
435
+ `stateLabel` and `stateTone`. `GET …/available` keeps `available` (keys, same rules) and adds
436
+ `transitions: [{ key, label, from, to, toLabel }]` (`from` is the current state).
437
+ `getFor(userId, id, { locale })`, `listFor(userId, filter, { locale })` and
438
+ `availableTransitionsFor(userId, id, { locale })` are the service forms; internal `get` keeps the
439
+ pinned definitions as published. Pure helpers: `localizeStateMachineSpec`, `localizeBundle`,
440
+ `stateLabelOf`, `transitionLabelOf`, `stateToneFor`, `presentInstance`, `availableTransitionsOf`.
441
+ `reportingFieldsOf` and `searchFieldsOf` take an optional locale; search indexes every translation of
442
+ a select option label. Reference previews, notifications and MCP use zh-TW. Requires plugin API 1.26.0.
443
+
444
+ ## Human routing recovery (draft decision 202610-d1f4)
445
+
446
+ GET /state-machine-instances/:id/available keeps available and localized transitions, and
447
+ adds routingFailed and canRetryRouting. The flags are computed from the pinned CHOICE state
448
+ and latest failed routing evidence; reads never retry automatically.
449
+
450
+ POST /state-machine-instances/:id/retry-routing accepts optional expectedRevision and
451
+ reevaluates automatic routing only for a failed CHOICE instance. Readability is checked first
452
+ (404), then submitter or state-machine:instance:write authority (403). A manual WRITE access
453
+ grant alone does not authorize recovery. Success returns the localized new instance; continued
454
+ failure commits fresh routing evidence and returns ASSIGNEE_UNRESOLVED. Non-failed routing
455
+ returns ROUTING_NOT_FAILED. Concurrent retries serialize on the instance lock. No migration.