inistate-mcp 1.1.0 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,6 +12,7 @@ MCP server for the [Inistate](https://inistate.com) platform — module discover
12
12
  | `INISTATE_API_BASE` | No | `https://api.inistate.com` | API base URL |
13
13
  | `INISTATE_MCP_MODE` | No | `configure` | Initial mode: `runtime`, `configure`, or `frontend` (see [Modes](#modes)) |
14
14
  | `INISTATE_MCP_NO_SETUP` | No | — | Set to `1` to force server mode from a terminal (skip the interactive wizard) |
15
+ | `INISTATE_DEBUG_FILE` | No | — | Set to `1` to log write-path tool calls to `./debug.log`, or to a path to log there. Off by default; logs identifiers only, never field values |
15
16
 
16
17
  ### Install from npm (recommended)
17
18
 
@@ -79,14 +80,14 @@ Then point your MCP client at `node /absolute/path/to/inistate-mcp/build/index.j
79
80
 
80
81
  ## Tools
81
82
 
82
- Tools marked **(configure)** are only exposed in configure mode — see [Modes](#modes).
83
+ Tools marked **(configure)** are only exposed in configure mode — see [Modes](#modes). Tools the active backend cannot serve (e.g. `scaffold_module` on the hosted Platform) stay registered but return a structured capability message instead of failing silently.
83
84
 
84
85
  | Tool | Description |
85
86
  |------|-------------|
86
87
  | `list_workspaces` | List workspaces the user has access to |
87
88
  | `set_workspace` | Set the active workspace |
88
89
  | `list_modules` | List all discoverable modules in the workspace |
89
- | `get_module_schema` | Get the canvas schema (basic or extended tier) **(configure)** |
90
+ | `get_module_schema` | Get the canvas schema (basic or extended tier) — available in every mode |
90
91
  | `get_module_canvas` | Get full module definition with stable IDs (round-trippable) **(configure)** |
91
92
  | `list_entries` | Query entries with filters, sorting, and pagination |
92
93
  | `get_entry` | Read a single entry by ID |
@@ -102,6 +103,7 @@ Tools marked **(configure)** are only exposed in configure mode — see [Modes](
102
103
  | `validate_design` | Validate a module schema before creating or updating **(configure)** |
103
104
  | `create_module` | Create a new module with schema **(configure)** |
104
105
  | `update_module` | Update an existing module's schema **(configure)** |
106
+ | `scaffold_module` | Draft a module schema from existing data (SQLite, Notion, or Airtable table) **(configure)** — served by the local runtime (inistate-core); on the hosted Platform backend it returns a capability message pointing to `design_workflow` |
105
107
  | `switch_mode` | Switch the active mode (runtime / configure / frontend) |
106
108
 
107
109
  ## Resources
@@ -140,13 +142,12 @@ Tools and resources marked **(configure)** / **(frontend)** are absent from the
140
142
 
141
143
  ## Typical Workflow
142
144
 
143
- 1. `list_workspaces` → `set_workspace` — select a workspace
144
- 2. `list_modules` — find the module you need
145
- 3. `get_module_schema` — understand its fields, states, and activities
146
- 4. `get_form` — discover required fields before submitting
147
- 5. `submit_activity` — create or update entries
148
- 6. `list_entries` — query and browse data
149
- 7. `get_entry_history` — review entry history
145
+ 1. `list_workspaces` → `set_workspace` — select a workspace (auto-selected when exactly one matches; both return the workspace's module list, so `list_modules` is only needed to refresh)
146
+ 2. `get_module_schema` — understand a module's fields, states, and activities
147
+ 3. `get_form` — discover required fields before the first submission per (module, activity); reuse its schema for further entries
148
+ 4. `submit_activity` — create or update entries (`submit_activities` for bulk)
149
+ 5. `list_entries` — query and browse data (use the `fields` parameter to keep payloads small)
150
+ 6. `get_entry_history` — review entry history
150
151
 
151
152
  ## Development
152
153
 
@@ -155,6 +156,58 @@ npm run watch # Watch mode for TypeScript compilation
155
156
  npm run inspector # Test with MCP Inspector
156
157
  ```
157
158
 
159
+ ### MCP Setup
160
+ 1. Setup
161
+ ```bash
162
+ curl -L "https://github.com/modelcontextprotocol/registry/releases/latest/download/mcp-publisher_$(uname -s | tr '[:upper:]' '[:lower:]')_$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/').tar.gz" | tar xz mcp-publisher && sudo mv mcp-publisher /usr/local/bin/
163
+ ```
164
+
165
+ or
166
+
167
+ ```powershell
168
+ $arch = if ([System.Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture -eq "Arm64") { "arm64" } else { "amd64" }; Invoke-WebRequest -Uri "https://github.com/modelcontextprotocol/registry/releases/latest/download/mcp-publisher_windows_$arch.tar.gz" -OutFile "mcp-publisher.tar.gz"; tar xf mcp-publisher.tar.gz mcp-publisher.exe; rm mcp-publisher.tar.gz
169
+
170
+ ```
171
+
172
+ 2. Verify
173
+ ```
174
+ mcp-publisher --help
175
+ ```
176
+
177
+ 3. Authenticate
178
+ ```
179
+ mcp-publisher login github
180
+ ```
181
+
182
+ 4. Publish: see below
183
+
184
+ ### Packaging & Versioning
185
+ ```bash
186
+ # Example adding new feature
187
+ git checkout -b feat/add-user-tool
188
+
189
+
190
+ # After coding
191
+ npx changeset
192
+
193
+ # Choose:
194
+ #
195
+ # minor
196
+ # Added new user search tool
197
+
198
+ # Release
199
+ npm run release
200
+
201
+ # This does:
202
+ # install dependencies
203
+ # test
204
+ # bump version + update changelog + sync server.json
205
+ # validate MCP server config
206
+ # build (via npm prepare hook)
207
+ # publish to npm
208
+ # publish to MCP registry
209
+ ```
210
+
158
211
  ## PM2 (Ubuntu/AWS)
159
212
 
160
213
  Run the HTTP transport in production using PM2:
@@ -181,7 +234,7 @@ npm run pm2:logs
181
234
  npm run pm2:stop
182
235
  ```
183
236
 
184
- Set required environment variables (`INISTATE_API_TOKEN`, and optionally `INISTATE_API_URL`, `INISTATE_WORKSPACE_ID`, `OAUTH_ISSUER_URL`, `INISTATE_APP_URL`) in your shell, PM2 ecosystem `env`, or deployment secret manager before starting.
237
+ Set required environment variables (`INISTATE_API_TOKEN`, and optionally `INISTATE_API_BASE`, `INISTATE_WORKSPACE_ID`, `OAUTH_ISSUER_URL`, `INISTATE_APP_URL`) in your shell, PM2 ecosystem `env`, or deployment secret manager before starting.
185
238
 
186
239
  ## Testing
187
240
 
@@ -203,21 +256,22 @@ Tests are in `src/` alongside the source files and use [Vitest](https://vitest.d
203
256
 
204
257
  | File | Type | What it covers |
205
258
  |------|------|----------------|
206
- | `src/schema.test.ts` | Unit tests (41) | `designWorkflow`, `validateDesign`, helper functions (`isValidFieldType`, `isValidColor`, `isValidActor`, `suggestColorForState`) |
207
- | `src/activity-guard.test.ts` | Unit tests (35) | `submit_activity` guard rules — human/hybrid actor, state-change confirmation, confidence-inflation, reference-shape validation |
259
+ | `src/schema.test.ts` | Unit tests (76) | `designWorkflow`, `validateDesign` (including platform parity and input normalization), helper functions (`isValidFieldType`, `isValidColor`, `isValidActor`, `suggestColorForState`) |
260
+ | `src/activity-guard.test.ts` | Unit tests (42) | `submit_activity` guard rules — human/hybrid actor, state-change confirmation, confidence-inflation, reference-shape validation |
208
261
  | `src/tools.schema.test.ts` | Unit tests (19) | Tool input-schema shapes and validation |
209
- | `src/backend-capabilities.test.ts` | Unit tests (6) | Capability gating — Platform-only tools return a capability message on reduced backends |
210
- | `src/server.test.ts` | Integration tests (15) | Spins up the MCP server as a child process and exercises it through the official MCP SDK client — mode-gated tool/resource/prompt discovery, `switch_mode`, resource reads, prompt retrieval, and local tool calls |
262
+ | `src/backend-capabilities.test.ts` | Unit tests (9) | Capability gating — tools the active backend cannot serve return a capability message |
263
+ | `src/flagged-annotation.test.ts` | Integration tests (5) | Flagged-response annotation — suppressed transitions are explained (`flag_reason` + `agent_action`) so agents stop retrying with higher confidence |
264
+ | `src/server.test.ts` | Integration tests (17) | Spins up the MCP server as a child process and exercises it through the official MCP SDK client — mode-gated tool/resource/prompt discovery, `switch_mode`, resource reads, prompt retrieval, and local tool calls |
211
265
 
212
266
  Unit tests cover:
213
267
  - Field type and color validation against the schema
214
268
  - State color suggestion logic
215
269
  - Design validation: duplicate names, invalid types/colors/actors, initial state rules, flow integrity, unreachable states, unused activities, AI confidence warnings
270
+ - Input normalization: field-type, state-color, and industry aliases; parsing states from a description
216
271
  - Workflow design: pattern detection (approval, ticket, pipeline, record list), industry defaults
217
- - Intent resolution: all 5 modes, context boosting, confidence scoring
218
272
 
219
273
  Integration tests verify (no API token needed):
220
- - All 20 tools, 8 resources, and 4 prompts are registered (in configure mode)
274
+ - Mode-gated tool/resource/prompt discovery — runtime mode hides the configure surface, `switch_mode` reveals and collapses it
221
275
  - `design_workflow`, `validate_design` work end-to-end through the MCP protocol
222
276
  - Static resources (`inistate://schema/runtime`, `inistate://design-guide`) return valid content
223
277
  - All 4 prompts return correctly templated messages
@@ -19,8 +19,17 @@ interface FieldInfo {
19
19
  type: string;
20
20
  }
21
21
  interface ExtendedSchema {
22
- activities?: ActivityDef[];
22
+ activities?: Array<ActivityDef | string>;
23
23
  information?: FieldInfo[];
24
+ states?: Array<string | {
25
+ name?: string;
26
+ }>;
27
+ flows?: Record<string, {
28
+ activities?: Record<string, string>;
29
+ }>;
30
+ }
31
+ interface CanvasSchema {
32
+ activities?: ActivityDef[];
24
33
  }
25
34
  /**
26
35
  * Source of a module's extended schema. Defaults to the cloud API; the MCP tool
@@ -28,6 +37,24 @@ interface ExtendedSchema {
28
37
  * backend is injected (cloud or local) instead of always hitting api.ts.
29
38
  */
30
39
  export type SchemaFetcher = (moduleName: string) => Promise<ExtendedSchema | null>;
40
+ /**
41
+ * Warm the schema cache in the background (fire-and-forget). Called from
42
+ * get_form so the guard/shape lookups on the submit_activity that typically
43
+ * follows hit cache instead of paying an extra round trip ahead of the write.
44
+ */
45
+ export declare function primeSchemaCache(moduleName: string, fetchSchema?: SchemaFetcher): void;
46
+ /**
47
+ * Seed the schema cache with an extended schema the caller already fetched
48
+ * (e.g. the get_module_schema tool's own tier=extended response), so the
49
+ * guard does not re-fetch what just passed through this process.
50
+ */
51
+ export declare function seedSchemaCache(moduleName: string, schema: unknown): void;
52
+ /**
53
+ * Source of a module's canvas (actor data). Like SchemaFetcher, the tool
54
+ * handlers pass a backend-routed fetcher so the actor fallback works against
55
+ * whatever backend is injected; the default hits the cloud API.
56
+ */
57
+ export type CanvasFetcher = (moduleName: string) => Promise<CanvasSchema | null>;
31
58
  interface FlaggedRecord {
32
59
  confidence: number;
33
60
  at: number;
@@ -35,6 +62,11 @@ interface FlaggedRecord {
35
62
  export declare function recordFlagged(moduleName: string, entryId: unknown, activity: string, confidence: number): void;
36
63
  export declare function clearFlagged(moduleName: string, entryId: unknown, activity: string): void;
37
64
  export declare function getPriorFlag(moduleName: string, entryId: unknown, activity: string): FlaggedRecord | undefined;
65
+ /** The human-actor block recorded for an entry, if still fresh. */
66
+ export declare function getHumanBlockedStates(moduleName: string, entryId: unknown): {
67
+ activity: string;
68
+ states: Set<string>;
69
+ } | undefined;
38
70
  export interface GuardInput {
39
71
  module: string;
40
72
  activity: string;
@@ -50,13 +82,18 @@ export type GuardOutcome = {
50
82
  ok: false;
51
83
  structured: Record<string, unknown>;
52
84
  };
53
- export declare function evaluateActivity(input: GuardInput, fetchSchema?: SchemaFetcher): Promise<GuardOutcome>;
85
+ export declare function evaluateActivity(input: GuardInput, fetchSchema?: SchemaFetcher, fetchCanvas?: CanvasFetcher): Promise<GuardOutcome>;
54
86
  export interface RefShapeError {
55
87
  field: string;
56
88
  type: string;
57
89
  message: string;
58
90
  received: unknown;
59
91
  }
92
+ /**
93
+ * State names for a module, from the cached extended schema. Tolerates both
94
+ * string[] and [{name}] shapes; null when unavailable (let the API decide).
95
+ */
96
+ export declare function getModuleStates(moduleName: string, fetchSchema?: SchemaFetcher): Promise<string[] | null>;
60
97
  /**
61
98
  * Build a field-name → field-type map for a module. Returns null when the
62
99
  * schema cannot be loaded (callers should let the server decide). The
@@ -72,6 +109,24 @@ export declare function getModuleFieldTypes(moduleName: string, fetchSchema?: Sc
72
109
  * (schema unavailable), returns [] so the server makes the final call.
73
110
  */
74
111
  export declare function validateInputShapesWith(types: Map<string, string> | null, input: Record<string, unknown> | undefined | null): RefShapeError[];
112
+ export interface InputKeyResolution {
113
+ /** Near-miss keys (casing/spacing/underscores) rewritten in place to the exact field name. */
114
+ remapped: Array<{
115
+ from: string;
116
+ to: string;
117
+ }>;
118
+ /** Keys matching no field at all — the platform silently drops these, losing the data. */
119
+ unknown: string[];
120
+ }
121
+ /**
122
+ * Match input keys against the module's field names, in place. Exact names
123
+ * pass; a key that differs only in case/spacing/underscores is rewritten to
124
+ * the exact field name; anything else is reported so the caller can reject
125
+ * it — the platform discards unmatched keys without any signal, which turns
126
+ * a key typo into silent data loss. Fail-open on a null map (schema
127
+ * unavailable): the server makes the final call.
128
+ */
129
+ export declare function resolveInputKeys(types: Map<string, string> | null, input: Record<string, unknown> | undefined | null): InputKeyResolution;
75
130
  /**
76
131
  * Validate that User/Module/Users/Modules fields in `input` carry the
77
132
  * correct shape. Convenience wrapper around getModuleFieldTypes +
@@ -80,5 +135,14 @@ export declare function validateInputShapesWith(types: Map<string, string> | nul
80
135
  * directly.
81
136
  */
82
137
  export declare function validateInputShapes(moduleName: string, input: Record<string, unknown> | undefined | null, fetchSchema?: SchemaFetcher): Promise<RefShapeError[]>;
138
+ /**
139
+ * Annotation merged into platform responses that carry `flagged: true`. The
140
+ * platform itself returns the bare flag with no explanation — without this,
141
+ * agents loop retrying with higher confidence or `confirmed: true`.
142
+ */
143
+ export declare const FLAGGED_ANNOTATION: {
144
+ readonly flag_reason: "Flagged submissions are recorded as intentions pending human review — the state transition did NOT occur. Causes: ai.confidence below the activity's confidence_threshold, or the activity's actor does not permit AI execution.";
145
+ readonly agent_action: "Do not retry with a higher confidence. Report the flag to the user; a human can complete the activity in Inistate.";
146
+ };
83
147
  export declare function __resetGuardCaches(): void;
84
148
  export {};
@@ -3,6 +3,8 @@ import { requestContext } from "./context.js";
3
3
  const REF_FIELD_TYPES = new Set(["User", "Users", "Module", "Modules"]);
4
4
  // Standard activities are inherent platform operations and have no actor in the
5
5
  // module schema. They bypass the actor check (but state-change checks still run).
6
+ // The platform uses both names for the direct state change — availableActivities
7
+ // lists "changeState" while forms and history say "changeStatus".
6
8
  const STANDARD_ACTIVITIES = new Set([
7
9
  "create",
8
10
  "edit",
@@ -12,6 +14,7 @@ const STANDARD_ACTIVITIES = new Set([
12
14
  "manage",
13
15
  "view",
14
16
  "changeStatus",
17
+ "changeState",
15
18
  ]);
16
19
  const SCHEMA_TTL_MS = 5 * 60 * 1000;
17
20
  const schemaCache = new Map();
@@ -40,9 +43,59 @@ async function getExtendedSchema(moduleName, fetchSchema = defaultSchemaFetcher)
40
43
  schemaCache.set(key, { schema, at: now });
41
44
  return schema;
42
45
  }
43
- async function getActivityDef(moduleName, activity, fetchSchema = defaultSchemaFetcher) {
46
+ /**
47
+ * Warm the schema cache in the background (fire-and-forget). Called from
48
+ * get_form so the guard/shape lookups on the submit_activity that typically
49
+ * follows hit cache instead of paying an extra round trip ahead of the write.
50
+ */
51
+ export function primeSchemaCache(moduleName, fetchSchema = defaultSchemaFetcher) {
52
+ void getExtendedSchema(moduleName, fetchSchema).catch(() => { });
53
+ }
54
+ /**
55
+ * Seed the schema cache with an extended schema the caller already fetched
56
+ * (e.g. the get_module_schema tool's own tier=extended response), so the
57
+ * guard does not re-fetch what just passed through this process.
58
+ */
59
+ export function seedSchemaCache(moduleName, schema) {
60
+ if (!schema || typeof schema !== "object")
61
+ return;
62
+ schemaCache.set(cacheKey("schema", [moduleName]), {
63
+ schema: schema,
64
+ at: Date.now(),
65
+ });
66
+ }
67
+ const canvasCache = new Map();
68
+ const defaultCanvasFetcher = async (moduleName) => {
69
+ try {
70
+ return (await api.get(`/api/configure/${api.enc(moduleName)}`));
71
+ }
72
+ catch {
73
+ return null;
74
+ }
75
+ };
76
+ async function getCanvasSchema(moduleName, fetchCanvas = defaultCanvasFetcher) {
77
+ const key = cacheKey("canvas", [moduleName]);
78
+ const now = Date.now();
79
+ const cached = canvasCache.get(key);
80
+ if (cached && now - cached.at < SCHEMA_TTL_MS)
81
+ return cached.canvas;
82
+ // Cache the miss too — a caller without configure access would otherwise
83
+ // pay a failing round trip on every submit.
84
+ const canvas = await fetchCanvas(moduleName);
85
+ canvasCache.set(key, { canvas, at: now });
86
+ return canvas;
87
+ }
88
+ async function getActivityDef(moduleName, activity, fetchSchema = defaultSchemaFetcher, fetchCanvas = defaultCanvasFetcher) {
44
89
  const schema = await getExtendedSchema(moduleName, fetchSchema);
45
- return schema?.activities?.find((a) => a.name === activity) ?? null;
90
+ for (const a of schema?.activities ?? []) {
91
+ if (a && typeof a === "object" && a.name === activity) {
92
+ if (a.actor)
93
+ return a;
94
+ break; // listed without actor info — consult the canvas
95
+ }
96
+ }
97
+ const canvas = await getCanvasSchema(moduleName, fetchCanvas);
98
+ return canvas?.activities?.find((a) => a && typeof a === "object" && a.name === activity) ?? null;
46
99
  }
47
100
  const FLAG_TTL_MS = 60 * 60 * 1000;
48
101
  const flaggedCache = new Map();
@@ -66,7 +119,37 @@ export function getPriorFlag(moduleName, entryId, activity) {
66
119
  }
67
120
  return rec;
68
121
  }
69
- export async function evaluateActivity(input, fetchSchema = defaultSchemaFetcher) {
122
+ const HUMAN_BLOCK_TTL_MS = 30 * 60 * 1000;
123
+ const humanBlockCache = new Map();
124
+ function humanBlockKey(moduleName, entryId) {
125
+ return cacheKey("humanblock", [moduleName, String(entryId)]);
126
+ }
127
+ /** Target states an activity can transition to, per the module's flows. */
128
+ async function activityTargetStates(moduleName, activity, fetchSchema) {
129
+ const schema = await getExtendedSchema(moduleName, fetchSchema);
130
+ const out = [];
131
+ for (const from of Object.values(schema?.flows ?? {})) {
132
+ const target = from?.activities?.[activity];
133
+ if (typeof target === "string" && !out.includes(target))
134
+ out.push(target);
135
+ }
136
+ return out;
137
+ }
138
+ /** The human-actor block recorded for an entry, if still fresh. */
139
+ export function getHumanBlockedStates(moduleName, entryId) {
140
+ if (entryId === undefined || entryId === null)
141
+ return undefined;
142
+ const k = humanBlockKey(moduleName, entryId);
143
+ const rec = humanBlockCache.get(k);
144
+ if (!rec)
145
+ return undefined;
146
+ if (Date.now() - rec.at > HUMAN_BLOCK_TTL_MS) {
147
+ humanBlockCache.delete(k);
148
+ return undefined;
149
+ }
150
+ return rec;
151
+ }
152
+ export async function evaluateActivity(input, fetchSchema = defaultSchemaFetcher, fetchCanvas = defaultCanvasFetcher) {
70
153
  const { module: moduleName, activity, entryId, entryIds, state, confidence, confirmed } = input;
71
154
  // Rule 1 — confidence inflation after a prior flag.
72
155
  const targets = entryIds && entryIds.length > 0 ? entryIds : [entryId];
@@ -87,13 +170,54 @@ export async function evaluateActivity(input, fetchSchema = defaultSchemaFetcher
87
170
  };
88
171
  }
89
172
  }
90
- // Rule 2a — `changeStatus` is the explicit state-change override.
91
- if (activity === "changeStatus" && !confirmed) {
173
+ // Rule 2 pre-flight — a target state must exist before any confirmation
174
+ // dance. The platform returns an opaque error for unknown states.
175
+ if (state) {
176
+ const states = await getModuleStates(moduleName, fetchSchema);
177
+ if (states && !states.includes(state)) {
178
+ return {
179
+ ok: false,
180
+ structured: {
181
+ error: "unknown_state",
182
+ message: `State '${state}' does not exist on module '${moduleName}'. Available states: ${states.join(", ")}.`,
183
+ activity,
184
+ state,
185
+ agent_action: "Use one of the listed states, or omit 'state' to follow the activity's normal flow.",
186
+ },
187
+ };
188
+ }
189
+ }
190
+ // Rule 2c — bypass detection. Once a human-only activity was blocked for an
191
+ // entry, an explicit state change that reaches the same target state is the
192
+ // same transition wearing different clothes. Runs before the `confirmed`
193
+ // shortcuts: confirmed does not unlock human-only transitions.
194
+ if (state) {
195
+ for (const target of targets) {
196
+ const blocked = getHumanBlockedStates(moduleName, target);
197
+ if (blocked?.states.has(state)) {
198
+ return {
199
+ ok: false,
200
+ structured: {
201
+ error: "human_actor_bypass_blocked",
202
+ message: `Activity '${blocked.activity}' (actor='human') was blocked for this entry, and this state change reaches its target state '${state}'. confirmed: true does not unlock human-only transitions.`,
203
+ activity,
204
+ state,
205
+ entryId: target,
206
+ blocked_activity: blocked.activity,
207
+ agent_action: "Stop and do not work around this. A human must perform the transition in Inistate — report it to the user.",
208
+ },
209
+ };
210
+ }
211
+ }
212
+ }
213
+ // Rule 2a — `changeStatus` (alias `changeState`) is the explicit
214
+ // state-change override.
215
+ if ((activity === "changeStatus" || activity === "changeState") && !confirmed) {
92
216
  return {
93
217
  ok: false,
94
218
  structured: {
95
219
  error: "state_change_requires_confirmation",
96
- message: "The 'changeStatus' activity bypasses the workflow to change an entry's state directly. AI agents must not call it on their own initiative.",
220
+ message: `The '${activity}' activity bypasses the workflow to change an entry's state directly. AI agents must not call it on their own initiative.`,
97
221
  activity,
98
222
  agent_action: "Ask the user explicitly whether to change the entry's state. After they confirm, resubmit with confirmed: true.",
99
223
  },
@@ -115,11 +239,25 @@ export async function evaluateActivity(input, fetchSchema = defaultSchemaFetcher
115
239
  // Rules 3 & 4 apply to custom (workflow-defined) activities only.
116
240
  if (STANDARD_ACTIVITIES.has(activity))
117
241
  return { ok: true };
118
- const def = await getActivityDef(moduleName, activity, fetchSchema);
242
+ const def = await getActivityDef(moduleName, activity, fetchSchema, fetchCanvas);
119
243
  if (!def)
120
244
  return { ok: true }; // unknown activity — let the API decide.
121
245
  const actor = (def.actor || "").toLowerCase();
122
246
  if (actor === "human") {
247
+ // Remember which states this activity would have reached, so a follow-up
248
+ // changeState/state-override to the same state is caught (Rule 2c).
249
+ const targetStates = await activityTargetStates(moduleName, activity, fetchSchema);
250
+ if (targetStates.length > 0) {
251
+ for (const target of targets) {
252
+ if (target === undefined || target === null)
253
+ continue;
254
+ humanBlockCache.set(humanBlockKey(moduleName, target), {
255
+ activity,
256
+ states: new Set(targetStates),
257
+ at: Date.now(),
258
+ });
259
+ }
260
+ }
123
261
  return {
124
262
  ok: false,
125
263
  structured: {
@@ -127,7 +265,7 @@ export async function evaluateActivity(input, fetchSchema = defaultSchemaFetcher
127
265
  message: `Activity '${activity}' is marked actor='human'. AI agents are not permitted to execute human-only activities.`,
128
266
  activity,
129
267
  actor: "human",
130
- agent_action: "Do not retry — confirmed: true does NOT unlock this. Tell the user the activity must be performed by a human, then stop.",
268
+ agent_action: "Do not retry — confirmed: true does NOT unlock this, and neither does changeState. Tell the user the activity must be performed by a human, then stop.",
131
269
  },
132
270
  };
133
271
  }
@@ -165,8 +303,21 @@ function checkSingleRef(field, type, value, index) {
165
303
  const valueOk = typeof obj.value === "string";
166
304
  const usernameOk = !isUserType ||
167
305
  (typeof obj.username === "string" && obj.username.length > 0);
168
- if (idOk && valueOk && usernameOk)
306
+ if (idOk && valueOk && usernameOk) {
307
+ // A display name standing in for the id ({ id: "carol" }) passes the key
308
+ // checks but the platform stores it as-is — a silently dangling reference.
309
+ // Real ids are numeric or document ids ("CLN00001"); a string id with
310
+ // whitespace or no digit at all is a name, not an id.
311
+ if (typeof obj.id === "string" && (/\s/.test(obj.id) || !/\d/.test(obj.id))) {
312
+ return {
313
+ field,
314
+ type,
315
+ received: value,
316
+ message: `${type} field '${locator}' id '${obj.id}' looks like a display name, not an entry id. Look up the entry with list_entries on the connected module and round-trip its reference object unchanged.`,
317
+ };
318
+ }
169
319
  return null;
320
+ }
170
321
  const missing = [];
171
322
  if (!idOk)
172
323
  missing.push("id (string|number)");
@@ -206,6 +357,20 @@ function checkRefValue(field, type, value) {
206
357
  }
207
358
  return checkSingleRef(field, type, value);
208
359
  }
360
+ /**
361
+ * State names for a module, from the cached extended schema. Tolerates both
362
+ * string[] and [{name}] shapes; null when unavailable (let the API decide).
363
+ */
364
+ export async function getModuleStates(moduleName, fetchSchema = defaultSchemaFetcher) {
365
+ const schema = await getExtendedSchema(moduleName, fetchSchema);
366
+ const raw = schema?.states;
367
+ if (!Array.isArray(raw) || raw.length === 0)
368
+ return null;
369
+ const names = raw
370
+ .map((s) => (typeof s === "string" ? s : s?.name))
371
+ .filter((n) => typeof n === "string" && n.length > 0);
372
+ return names.length > 0 ? names : null;
373
+ }
209
374
  /**
210
375
  * Build a field-name → field-type map for a module. Returns null when the
211
376
  * schema cannot be loaded (callers should let the server decide). The
@@ -245,6 +410,44 @@ export function validateInputShapesWith(types, input) {
245
410
  }
246
411
  return errors;
247
412
  }
413
+ // ---------- Input key resolution ----------
414
+ /** Case/space/underscore-insensitive key for field-name matching. */
415
+ function fieldKey(name) {
416
+ return name.trim().toLowerCase().replace(/[\s_-]/g, "");
417
+ }
418
+ /**
419
+ * Match input keys against the module's field names, in place. Exact names
420
+ * pass; a key that differs only in case/spacing/underscores is rewritten to
421
+ * the exact field name; anything else is reported so the caller can reject
422
+ * it — the platform discards unmatched keys without any signal, which turns
423
+ * a key typo into silent data loss. Fail-open on a null map (schema
424
+ * unavailable): the server makes the final call.
425
+ */
426
+ export function resolveInputKeys(types, input) {
427
+ const result = { remapped: [], unknown: [] };
428
+ if (!input || !types)
429
+ return result;
430
+ // null marks a collision — two fields fold to the same key; never remap those.
431
+ const byKey = new Map();
432
+ for (const name of types.keys()) {
433
+ const k = fieldKey(name);
434
+ byKey.set(k, byKey.has(k) ? null : name);
435
+ }
436
+ for (const key of Object.keys(input)) {
437
+ if (types.has(key))
438
+ continue;
439
+ const match = byKey.get(fieldKey(key));
440
+ if (match && !Object.prototype.hasOwnProperty.call(input, match)) {
441
+ input[match] = input[key];
442
+ delete input[key];
443
+ result.remapped.push({ from: key, to: match });
444
+ }
445
+ else {
446
+ result.unknown.push(key);
447
+ }
448
+ }
449
+ return result;
450
+ }
248
451
  /**
249
452
  * Validate that User/Module/Users/Modules fields in `input` carry the
250
453
  * correct shape. Convenience wrapper around getModuleFieldTypes +
@@ -258,8 +461,19 @@ export async function validateInputShapes(moduleName, input, fetchSchema = defau
258
461
  const types = await getModuleFieldTypes(moduleName, fetchSchema);
259
462
  return validateInputShapesWith(types, input);
260
463
  }
464
+ /**
465
+ * Annotation merged into platform responses that carry `flagged: true`. The
466
+ * platform itself returns the bare flag with no explanation — without this,
467
+ * agents loop retrying with higher confidence or `confirmed: true`.
468
+ */
469
+ export const FLAGGED_ANNOTATION = {
470
+ flag_reason: "Flagged submissions are recorded as intentions pending human review — the state transition did NOT occur. Causes: ai.confidence below the activity's confidence_threshold, or the activity's actor does not permit AI execution.",
471
+ agent_action: "Do not retry with a higher confidence. Report the flag to the user; a human can complete the activity in Inistate.",
472
+ };
261
473
  // Test-only helpers.
262
474
  export function __resetGuardCaches() {
263
475
  schemaCache.clear();
476
+ canvasCache.clear();
264
477
  flaggedCache.clear();
478
+ humanBlockCache.clear();
265
479
  }
package/build/api.d.ts CHANGED
@@ -1,5 +1,12 @@
1
1
  export declare function setWorkspaceId(wsid: string): void;
2
2
  export declare function getWorkspaceId(): string | null;
3
+ /**
4
+ * A bare "Module 'X' not found" sends agents hunting across workspaces one
5
+ * set_workspace at a time (observed: 7 calls to locate a module created in
6
+ * the wrong workspace). Anchor the error to the active workspace and name
7
+ * the two possible fixes.
8
+ */
9
+ export declare function annotateModuleNotFound(message: string): string;
3
10
  export declare function get(path: string): Promise<unknown>;
4
11
  export declare function post(path: string, body?: unknown): Promise<unknown>;
5
12
  export declare function put(path: string, body?: unknown): Promise<unknown>;
package/build/api.js CHANGED
@@ -73,6 +73,20 @@ function headers() {
73
73
  function authHeader() {
74
74
  return buildHeaders();
75
75
  }
76
+ /**
77
+ * A bare "Module 'X' not found" sends agents hunting across workspaces one
78
+ * set_workspace at a time (observed: 7 calls to locate a module created in
79
+ * the wrong workspace). Anchor the error to the active workspace and name
80
+ * the two possible fixes.
81
+ */
82
+ export function annotateModuleNotFound(message) {
83
+ if (!/^module '.+' not found\.?$/i.test(message.trim()))
84
+ return message;
85
+ const wsid = effectiveWorkspaceId();
86
+ return wsid
87
+ ? `${message.trim().replace(/\.$/, "")} in the active workspace (id ${wsid}). Check list_modules for the exact name, or call set_workspace if the module lives in another workspace.`
88
+ : `${message.trim().replace(/\.$/, "")}. No active workspace is set — call set_workspace (or pass workspaceId) first.`;
89
+ }
76
90
  function agentAction(status) {
77
91
  switch (status) {
78
92
  case 400:
@@ -101,7 +115,7 @@ async function handleResponse(res) {
101
115
  }
102
116
  const error = {
103
117
  error: body.error || `HTTP ${res.status}`,
104
- message: body.message || text || res.statusText,
118
+ message: annotateModuleNotFound(String(body.message || text || res.statusText)),
105
119
  details: body.details || null,
106
120
  agent_action: agentAction(res.status),
107
121
  };
@@ -111,14 +125,32 @@ async function handleResponse(res) {
111
125
  if (!text)
112
126
  return null;
113
127
  const data = JSON.parse(text);
114
- // §14.8 — truncate large list responses to avoid blowing up agent context
115
- if (text.length > 30_000 &&
128
+ // §14.8 — truncate large list responses to avoid blowing up agent context.
129
+ // Size-aware: keep as many items as fit the byte budget (a fixed item count
130
+ // either overshoots for wide rows or wastes refetches for narrow ones).
131
+ const TRUNCATE_BUDGET = 30_000;
132
+ if (text.length > TRUNCATE_BUDGET &&
116
133
  data &&
117
134
  typeof data === "object" &&
118
- Array.isArray(data.list)) {
119
- data.list = data.list.slice(0, 10);
120
- data._truncated = true;
121
- data._truncated_message = `Response truncated to 10 of ${data.totalItems ?? "unknown"} items. Use pagination (currentPage, pageSize) to retrieve more.`;
135
+ Array.isArray(data.list) &&
136
+ data.list.length > 1) {
137
+ const items = data.list;
138
+ const overhead = text.length - JSON.stringify(items).length;
139
+ const budget = Math.max(TRUNCATE_BUDGET - overhead, 2_000);
140
+ let size = 2;
141
+ let keep = 0;
142
+ for (const item of items) {
143
+ const itemLen = JSON.stringify(item).length + 1;
144
+ if (keep > 0 && size + itemLen > budget)
145
+ break;
146
+ size += itemLen;
147
+ keep++;
148
+ }
149
+ if (keep < items.length) {
150
+ data.list = items.slice(0, keep);
151
+ data._truncated = true;
152
+ data._truncated_message = `Response truncated to ${keep} of ${items.length} items on this page (~30KB cap; ${data.totalItems ?? "unknown"} total). Narrow the payload with the fields parameter (biggest saving) or filters, and paginate with currentPage/pageSize.`;
153
+ }
122
154
  }
123
155
  return data;
124
156
  }