@haneinfo/state-machine 0.16.0 → 0.18.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 (43) hide show
  1. package/README.md +223 -199
  2. package/agent-guide.md +447 -439
  3. package/dist/access.d.ts +8 -0
  4. package/dist/access.d.ts.map +1 -1
  5. package/dist/access.js +28 -0
  6. package/dist/access.js.map +1 -1
  7. package/dist/index.d.ts +1 -0
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +1 -0
  10. package/dist/index.js.map +1 -1
  11. package/dist/instance-access.service.d.ts +2 -2
  12. package/dist/instance-lifecycle.service.d.ts.map +1 -1
  13. package/dist/instance-lifecycle.service.js +3 -9
  14. package/dist/instance-lifecycle.service.js.map +1 -1
  15. package/dist/plugin.d.ts.map +1 -1
  16. package/dist/plugin.js +6 -1
  17. package/dist/plugin.js.map +1 -1
  18. package/dist/prisma-store.d.ts.map +1 -1
  19. package/dist/prisma-store.js +7 -0
  20. package/dist/prisma-store.js.map +1 -1
  21. package/dist/runtime.service.d.ts +18 -1
  22. package/dist/runtime.service.d.ts.map +1 -1
  23. package/dist/runtime.service.js +12 -4
  24. package/dist/runtime.service.js.map +1 -1
  25. package/dist/search.d.ts +53 -0
  26. package/dist/search.d.ts.map +1 -0
  27. package/dist/search.js +136 -0
  28. package/dist/search.js.map +1 -0
  29. package/dist/semantics.d.ts.map +1 -1
  30. package/dist/semantics.js +6 -0
  31. package/dist/semantics.js.map +1 -1
  32. package/dist/state-machine.controller.d.ts +18 -1
  33. package/dist/state-machine.controller.d.ts.map +1 -1
  34. package/dist/store.d.ts +2 -0
  35. package/dist/store.d.ts.map +1 -1
  36. package/dist/store.js +6 -0
  37. package/dist/store.js.map +1 -1
  38. package/dist/types.d.ts +4 -0
  39. package/dist/types.d.ts.map +1 -1
  40. package/dist/types.js.map +1 -1
  41. package/haneinfo.plugin.json +6 -1
  42. package/package.json +8 -8
  43. package/schemas/state-machine.spec.json +17 -0
package/README.md CHANGED
@@ -1,202 +1,202 @@
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.
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
200
 
201
201
 
202
202
  ## Instance tags (draft 202610-2c5d)
@@ -265,3 +265,27 @@ excess returns RATE_LIMITED/429 and details.retryAfterSeconds. This is single-pr
265
265
  multiple processes do not share a limit. Clients should debounce autosave by at least two seconds.
266
266
 
267
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.