@jupiterone/jupiterone-mcp 2.6.2 → 2.7.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 (113) hide show
  1. package/README.md +122 -72
  2. package/dist/client/graphql/mutations.d.ts +16 -0
  3. package/dist/client/graphql/mutations.d.ts.map +1 -1
  4. package/dist/client/graphql/mutations.js +126 -1
  5. package/dist/client/graphql/mutations.js.map +1 -1
  6. package/dist/client/graphql/queries.d.ts +27 -2
  7. package/dist/client/graphql/queries.d.ts.map +1 -1
  8. package/dist/client/graphql/queries.js +96 -4
  9. package/dist/client/graphql/queries.js.map +1 -1
  10. package/dist/client/jupiterone-client.d.ts +30 -0
  11. package/dist/client/jupiterone-client.d.ts.map +1 -1
  12. package/dist/client/jupiterone-client.js +60 -0
  13. package/dist/client/jupiterone-client.js.map +1 -1
  14. package/dist/client/services/compliance-service.d.ts +48 -1
  15. package/dist/client/services/compliance-service.d.ts.map +1 -1
  16. package/dist/client/services/compliance-service.js +292 -0
  17. package/dist/client/services/compliance-service.js.map +1 -1
  18. package/dist/client/services/j1ql-service.d.ts +10 -2
  19. package/dist/client/services/j1ql-service.d.ts.map +1 -1
  20. package/dist/client/services/j1ql-service.js +11 -3
  21. package/dist/client/services/j1ql-service.js.map +1 -1
  22. package/dist/client/services/rule-service.d.ts +3 -1
  23. package/dist/client/services/rule-service.d.ts.map +1 -1
  24. package/dist/client/services/rule-service.js +7 -5
  25. package/dist/client/services/rule-service.js.map +1 -1
  26. package/dist/generated/description-map.d.ts.map +1 -1
  27. package/dist/generated/description-map.js +692 -38
  28. package/dist/generated/description-map.js.map +1 -1
  29. package/dist/server/mcp-server.d.ts.map +1 -1
  30. package/dist/server/mcp-server.js +38 -1
  31. package/dist/server/mcp-server.js.map +1 -1
  32. package/dist/server/skills.d.ts +25 -0
  33. package/dist/server/skills.d.ts.map +1 -0
  34. package/dist/server/skills.js +115 -0
  35. package/dist/server/skills.js.map +1 -0
  36. package/dist/server/tools/compliance/attestations.d.ts.map +1 -1
  37. package/dist/server/tools/compliance/attestations.js +20 -37
  38. package/dist/server/tools/compliance/attestations.js.map +1 -1
  39. package/dist/server/tools/compliance/authoring.d.ts +3 -0
  40. package/dist/server/tools/compliance/authoring.d.ts.map +1 -0
  41. package/dist/server/tools/compliance/authoring.js +773 -0
  42. package/dist/server/tools/compliance/authoring.js.map +1 -0
  43. package/dist/server/tools/compliance/controls.d.ts.map +1 -1
  44. package/dist/server/tools/compliance/controls.js +193 -19
  45. package/dist/server/tools/compliance/controls.js.map +1 -1
  46. package/dist/server/tools/compliance/exemptions.d.ts +3 -0
  47. package/dist/server/tools/compliance/exemptions.d.ts.map +1 -0
  48. package/dist/server/tools/compliance/exemptions.js +287 -0
  49. package/dist/server/tools/compliance/exemptions.js.map +1 -0
  50. package/dist/server/tools/compliance/framework.d.ts +3 -0
  51. package/dist/server/tools/compliance/framework.d.ts.map +1 -0
  52. package/dist/server/tools/compliance/framework.js +445 -0
  53. package/dist/server/tools/compliance/framework.js.map +1 -0
  54. package/dist/server/tools/compliance/graph.d.ts +56 -0
  55. package/dist/server/tools/compliance/graph.d.ts.map +1 -0
  56. package/dist/server/tools/compliance/graph.js +115 -0
  57. package/dist/server/tools/compliance/graph.js.map +1 -0
  58. package/dist/server/tools/compliance/index.d.ts +2 -16
  59. package/dist/server/tools/compliance/index.d.ts.map +1 -1
  60. package/dist/server/tools/compliance/index.js +45 -15
  61. package/dist/server/tools/compliance/index.js.map +1 -1
  62. package/dist/server/tools/compliance/requirements.d.ts +3 -0
  63. package/dist/server/tools/compliance/requirements.d.ts.map +1 -0
  64. package/dist/server/tools/compliance/requirements.js +243 -0
  65. package/dist/server/tools/compliance/requirements.js.map +1 -0
  66. package/dist/server/tools/compliance/schemas.d.ts +409 -8
  67. package/dist/server/tools/compliance/schemas.d.ts.map +1 -1
  68. package/dist/server/tools/compliance/schemas.js +337 -7
  69. package/dist/server/tools/compliance/schemas.js.map +1 -1
  70. package/dist/server/tools/compliance/shared.d.ts +103 -1
  71. package/dist/server/tools/compliance/shared.d.ts.map +1 -1
  72. package/dist/server/tools/compliance/shared.js +235 -1
  73. package/dist/server/tools/compliance/shared.js.map +1 -1
  74. package/dist/server/tools/compliance/summary.d.ts +2 -8
  75. package/dist/server/tools/compliance/summary.d.ts.map +1 -1
  76. package/dist/server/tools/compliance/summary.js +149 -87
  77. package/dist/server/tools/compliance/summary.js.map +1 -1
  78. package/dist/server/tools/compliance/tests.d.ts +3 -0
  79. package/dist/server/tools/compliance/tests.d.ts.map +1 -0
  80. package/dist/server/tools/compliance/tests.js +463 -0
  81. package/dist/server/tools/compliance/tests.js.map +1 -0
  82. package/dist/server/tools/compliance/transitions.d.ts +6 -0
  83. package/dist/server/tools/compliance/transitions.d.ts.map +1 -0
  84. package/dist/server/tools/compliance/transitions.js +659 -0
  85. package/dist/server/tools/compliance/transitions.js.map +1 -0
  86. package/dist/server/tools/integrations.d.ts.map +1 -1
  87. package/dist/server/tools/integrations.js +43 -49
  88. package/dist/server/tools/integrations.js.map +1 -1
  89. package/dist/server/tools/reference.d.ts +1 -1
  90. package/dist/server/tools/reference.d.ts.map +1 -1
  91. package/dist/server/tools/reference.js +1 -0
  92. package/dist/server/tools/reference.js.map +1 -1
  93. package/dist/server/tools/result.d.ts +3 -2
  94. package/dist/server/tools/result.d.ts.map +1 -1
  95. package/dist/server/tools/result.js +3 -2
  96. package/dist/server/tools/result.js.map +1 -1
  97. package/dist/server/tools/rules.d.ts.map +1 -1
  98. package/dist/server/tools/rules.js +19 -21
  99. package/dist/server/tools/rules.js.map +1 -1
  100. package/dist/server/tools/types.d.ts +2 -0
  101. package/dist/server/tools/types.d.ts.map +1 -1
  102. package/dist/server/tools/types.js.map +1 -1
  103. package/dist/server/tools/usage.d.ts +6 -7
  104. package/dist/server/tools/usage.d.ts.map +1 -1
  105. package/dist/server/tools/usage.js +193 -4
  106. package/dist/server/tools/usage.js.map +1 -1
  107. package/dist/types/jupiterone.d.ts +179 -0
  108. package/dist/types/jupiterone.d.ts.map +1 -1
  109. package/dist/utils/j1ql-validator.d.ts.map +1 -1
  110. package/dist/utils/j1ql-validator.js +129 -1
  111. package/dist/utils/j1ql-validator.js.map +1 -1
  112. package/node_modules/dtrace-provider/build/Makefile +1 -1
  113. package/package.json +3 -3
@@ -0,0 +1,659 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.transitionTools = void 0;
4
+ exports.pathBetween = pathBetween;
5
+ const zod_1 = require("zod");
6
+ const load_description_js_1 = require("../../../utils/load-description.js");
7
+ const errors_js_1 = require("../errors.js");
8
+ const result_js_1 = require("../result.js");
9
+ const types_js_1 = require("../types.js");
10
+ const graph_js_1 = require("./graph.js");
11
+ const schemas_js_1 = require("./schemas.js");
12
+ const shared_js_1 = require("./shared.js");
13
+ /**
14
+ * transition-controls and evaluate-controls: the lifecycle. The API enforces the moves
15
+ * (DRAFT->LIVE is refused with "Valid transitions from DRAFT: REVIEW", j1dev 2026-10-28), so a
16
+ * two-hop move is two calls, landed across the whole batch one hop at a time; a non-LIVE control's
17
+ * tests run only on request and the control stays unscored until LIVE.
18
+ */
19
+ const STATES = ['DRAFT', 'REVIEW', 'LIVE', 'RETIRED'];
20
+ /** The moves the backend accepts (apps `services/control/types.ts`, mirrored by the app). */
21
+ const VALID_MOVES = {
22
+ DRAFT: ['REVIEW'],
23
+ REVIEW: ['DRAFT', 'LIVE'],
24
+ LIVE: ['REVIEW', 'RETIRED'],
25
+ RETIRED: ['LIVE'],
26
+ };
27
+ /** The shortest chain of moves from one state to another, or null when there is none. */
28
+ function pathBetween(from, to) {
29
+ if (from === to)
30
+ return [];
31
+ const seen = new Set([from]);
32
+ const queue = [{ state: from, path: [] }];
33
+ while (queue.length > 0) {
34
+ const { state, path } = queue.shift();
35
+ for (const next of VALID_MOVES[state]) {
36
+ if (seen.has(next))
37
+ continue;
38
+ const nextPath = [...path, next];
39
+ if (next === to)
40
+ return nextPath;
41
+ seen.add(next);
42
+ queue.push({ state: next, path: nextPath });
43
+ }
44
+ }
45
+ return null;
46
+ }
47
+ function isState(value) {
48
+ return STATES.includes(value ?? '');
49
+ }
50
+ /**
51
+ * A framework's controls in the given states, through its requirements. The stored
52
+ * `frameworkId` is not used: CCM recomputes it from a graph read made right after writing a
53
+ * link (apps `updateControl.ts`), so it can miss a control just linked into the framework or keep
54
+ * one just detached. UNIQUE keeps a control under several requirements to one row, as CCM's own
55
+ * listing does: without it the duplicates filled the four-page cap and a framework pass could hand
56
+ * itself back forever (review, 2026-10-30). On j1dev it paged 433 controls in two pages with no
57
+ * duplicate, against 445 rows without it.
58
+ */
59
+ function selectionQuery(frameworkId, states) {
60
+ return (`FIND UNIQUE ccm_framework WITH id = '${frameworkId}' THAT HAS ccm_requirement ` +
61
+ `THAT HAS ccm_control WITH state = (${states.map((state) => `'${state}'`).join(' OR ')}) ` +
62
+ `AS c RETURN c.id AS id, c.name AS name, c.state AS state LIMIT ${graph_js_1.GRAPH_PAGE_SIZE}`);
63
+ }
64
+ /** Selected controls with their test count, for an evaluation. */
65
+ function evaluationSelectionQuery(ids) {
66
+ return (`FIND ccm_control WITH id = (${ids.map(shared_js_1.j1qlLiteral).join(' OR ')}) AS c ` +
67
+ '(THAT DEFINES ccm_control_test AS t)? ' +
68
+ `RETURN c.id AS id, c.name AS name, c.state AS state, t.id AS testId LIMIT ${graph_js_1.GRAPH_PAGE_SIZE}`);
69
+ }
70
+ /** Pages of a framework's controls one call selects: 1,000 controls. */
71
+ const SELECTION_PAGES = 4;
72
+ async function readSelection(client, query, deadlineAt) {
73
+ const read = await (0, graph_js_1.runGraphQuery)(client, query, deadlineAt, SELECTION_PAGES, { fresh: true });
74
+ if (read.kind !== 'rows') {
75
+ if (read.kind === 'failed')
76
+ console.error('Error selecting controls:', read.error);
77
+ return null;
78
+ }
79
+ const selected = new Map();
80
+ for (const row of read.rows) {
81
+ const id = (0, graph_js_1.rowText)(row.id);
82
+ if (!id)
83
+ continue;
84
+ const state = (0, graph_js_1.rowText)(row.state);
85
+ selected.set(id, { id, name: (0, graph_js_1.rowText)(row.name), state: isState(state) ? state : null });
86
+ }
87
+ return { selected, more: read.more };
88
+ }
89
+ /**
90
+ * The control as the API holds it now: name, state and live test count. The graph lags a write
91
+ * by seconds to minutes, so a control created, moved or given a test moments ago reads stale
92
+ * there; on j1dev a control moved to REVIEW still read DRAFT and a test created 70 s earlier
93
+ * read as no test (2026-10-28). The API is the authority wherever the graph's answer would skip
94
+ * or misreport a control. `null` when the API has no such control; `undefined` when the read did
95
+ * not finish in time or failed.
96
+ */
97
+ async function confirmControl(client, id, deadlineAt) {
98
+ try {
99
+ const read = await (0, shared_js_1.withDeadline)((0, shared_js_1.findControl)(client, id), deadlineAt);
100
+ if (read === shared_js_1.DEADLINE_PASSED)
101
+ return undefined;
102
+ if (read === null)
103
+ return null;
104
+ const state = isState(read.state) ? read.state : null;
105
+ return {
106
+ id,
107
+ name: read.name,
108
+ state,
109
+ tests: (read.controlTests ?? []).filter((test) => !test.deleted).length,
110
+ };
111
+ }
112
+ catch (error) {
113
+ if ((0, shared_js_1.isAborted)(error))
114
+ throw error;
115
+ console.error('Error confirming a control with the API:', error);
116
+ return undefined;
117
+ }
118
+ }
119
+ /**
120
+ * CCM writes a control back whole from a read that can lag: `updateControl` (behind
121
+ * `update-control` and `link-controls`) and the re-score after an evaluation both replace the
122
+ * entity they read (apps `updateControl.ts`, `updateControlStatus.ts`), so a write landing in the
123
+ * lag after a move restores the old state (PR #59 review, 2026-10-29).
124
+ */
125
+ /**
126
+ * Said when a move was cut off. The cut mutation can land after the follow-up has finished and,
127
+ * carrying only a target, undo it: a cut DRAFT->REVIEW landing after the follow-up reached LIVE is
128
+ * a valid LIVE->REVIEW (review, 2026-10-30; dev's TR-5 landed after its call gave up). Waiting for
129
+ * the state to settle closes that window; CCM's missing expected-state check is the real fix.
130
+ */
131
+ const CUT_WAIT = ' Some moves were cut off (`interrupted[]`) and may still land: wait about a minute and read ' +
132
+ 'those controls with `get-control` until their state stops changing before making their call.';
133
+ const WRITE_BACK_NOTE = 'Before an `update-control` or `link-controls` on a control moved here, read it with ' +
134
+ '`get-control` until it shows the new state: CCM writes a control back whole from a read that ' +
135
+ 'can lag, so an earlier write can restore the old state. For the same reason, do not demote or ' +
136
+ 'retire a control while an evaluation queued for it is still running.';
137
+ const STATE_NOTE = {
138
+ DRAFT: 'DRAFT controls are excluded from every scorecard and their tests run only on `evaluate-controls`.',
139
+ REVIEW: 'REVIEW controls are still excluded from scorecards; `transition-controls` to LIVE makes them count.',
140
+ LIVE: 'Newly LIVE controls read "0 passing, 0 failing" until their first daily evaluation; `evaluate-controls` runs it now.',
141
+ RETIRED: 'Retired controls are excluded; their stored status was cleared on leaving LIVE and is re-scored on return.',
142
+ };
143
+ async function hop(client, id, to, note) {
144
+ try {
145
+ const result = await client.transitionControlState({ controlId: id, targetState: to, note });
146
+ return { kind: 'moved', state: isState(result.state) ? result.state : to };
147
+ }
148
+ catch (error) {
149
+ if ((0, shared_js_1.isAborted)(error))
150
+ throw error;
151
+ if ((0, shared_js_1.isNotFound)(error))
152
+ return { kind: 'not_found' };
153
+ const limit = (0, shared_js_1.liveLimitReason)(error);
154
+ return limit
155
+ ? { kind: 'refused', reason: limit, liveLimit: true }
156
+ : { kind: 'refused', reason: (0, shared_js_1.backendReason)(error), liveLimit: false };
157
+ }
158
+ }
159
+ const DEFAULT_FROM_STATES = ['DRAFT', 'REVIEW'];
160
+ /**
161
+ * The state the backend will move a control from. `control(id)` resolves through the same read the
162
+ * transition mutation decides on (apps `controlService.getControl` -> `graphService.getControl`);
163
+ * J1QL lagged a move by minutes on j1dev, and planning from it moved LIVE controls back to REVIEW
164
+ * (2026-10-28). Only a read that ran out of time or failed transiently is handed back: a refused
165
+ * or missing control handed back every call looped an agent with no reason given (review,
166
+ * 2026-10-29).
167
+ */
168
+ async function readState(client, id, deadlineAt) {
169
+ try {
170
+ const read = await (0, shared_js_1.withDeadline)(client.getControlState(id), deadlineAt);
171
+ if (read === shared_js_1.DEADLINE_PASSED)
172
+ return { kind: 'unread' };
173
+ if (read === null)
174
+ return { kind: 'not_found' };
175
+ return {
176
+ kind: 'read',
177
+ control: { id, name: read.name, state: isState(read.state) ? read.state : null },
178
+ };
179
+ }
180
+ catch (error) {
181
+ if ((0, shared_js_1.isAborted)(error))
182
+ throw error;
183
+ if ((0, shared_js_1.isNotFound)(error))
184
+ return { kind: 'not_found' };
185
+ if ((0, errors_js_1.accessDeniedStatus)(error) !== null)
186
+ return { kind: 'denied', reason: (0, shared_js_1.backendReason)(error) };
187
+ console.error('Error reading a control state:', error);
188
+ return { kind: 'unread' };
189
+ }
190
+ }
191
+ /**
192
+ * The hops from a control's real state to the target, or why it stays where it is. A path through
193
+ * LIVE toward another state (DRAFT or REVIEW to RETIRED, RETIRED to REVIEW or DRAFT) is not taken:
194
+ * the LIVE stop counts against the live-controls limit, and a call cut off there leaves a control
195
+ * meant to leave the program scored instead (review, 2026-10-29).
196
+ */
197
+ function verdictFor(state, targetState, allowed) {
198
+ if (!state)
199
+ return { skip: 'invalid_transition' };
200
+ const path = pathBetween(state, targetState);
201
+ if (path?.length === 0)
202
+ return { skip: 'already_in_state' };
203
+ if (allowed && !allowed.includes(state))
204
+ return { skip: 'not_in_from_states' };
205
+ if (!path)
206
+ return { skip: 'invalid_transition' };
207
+ if (targetState !== 'LIVE' && path.includes('LIVE'))
208
+ return { skip: 'passes_through_live' };
209
+ return { path };
210
+ }
211
+ /**
212
+ * Reads each candidate's state from the API, in waves, until MAX_CONTROLS_PER_CALL of them need
213
+ * moving, the candidates run out or the read budget ends. A control already at the target takes no
214
+ * slot: the graph kept selecting the same 25 controls, already moved, on every call (dev,
215
+ * 2026-10-28), so the controls behind them were never reached.
216
+ */
217
+ async function confirmCandidates(client, order, context) {
218
+ const result = { plans: new Map(), skipped: [], refused: [], unreached: [] };
219
+ let next = 0;
220
+ while (next < order.length &&
221
+ result.plans.size < shared_js_1.MAX_CONTROLS_PER_CALL &&
222
+ Date.now() < context.deadlineAt) {
223
+ const wave = order.slice(next, next + shared_js_1.MAX_CONTROLS_PER_CALL - result.plans.size);
224
+ next += wave.length;
225
+ const slots = await (0, shared_js_1.runBatch)(wave, { deadlineAt: context.deadlineAt, concurrency: shared_js_1.BATCH_CONCURRENCY }, (id) => readState(client, id, context.deadlineAt));
226
+ slots.forEach((slot, index) => {
227
+ const id = wave[index];
228
+ const read = slot.kind === 'done' ? slot.value : { kind: 'unread' };
229
+ if (read.kind === 'unread') {
230
+ result.unreached.push(id);
231
+ }
232
+ else if (read.kind === 'not_found') {
233
+ result.skipped.push({ id, name: null, reason: 'not_found', state: null });
234
+ }
235
+ else if (read.kind === 'denied') {
236
+ result.refused.push({ id, name: null, reason: read.reason });
237
+ }
238
+ else {
239
+ const { control } = read;
240
+ const verdict = verdictFor(control.state, context.targetState, context.allowed);
241
+ if ('skip' in verdict) {
242
+ result.skipped.push({
243
+ id,
244
+ name: control.name,
245
+ reason: verdict.skip,
246
+ state: control.state,
247
+ });
248
+ }
249
+ else {
250
+ result.plans.set(id, { control, path: verdict.path });
251
+ }
252
+ }
253
+ });
254
+ }
255
+ result.unreached.push(...order.slice(next));
256
+ return result;
257
+ }
258
+ const MAX_ROUNDS = 6;
259
+ /** The state the backend says it moved from, in its refusal of an invalid move. */
260
+ const BACKEND_FROM_STATE = /cannot transition from (DRAFT|REVIEW|LIVE|RETIRED) to/;
261
+ /**
262
+ * Hop by hop across the batch: every control lands its first move before any makes the second,
263
+ * so a cut-off call leaves a consistent, resumable state. A refused hop is checked against the API
264
+ * once. A state this call already moved the control past is a stale read, not a change: a 502 on a
265
+ * move that landed, read back as the old state, re-planned the control back down through REVIEW
266
+ * (review, 2026-10-29), so such a control is handed back unfinished. So is one the backend refused
267
+ * from a state other than the one the API reads now: the backend's own read lagged. Any other
268
+ * changed state is re-planned, counted in `replannedCount`, from a state the caller allowed only; a
269
+ * real refusal stands.
270
+ */
271
+ async function runHops(client, plans, context) {
272
+ const run = {
273
+ transitioned: [],
274
+ skipped: [],
275
+ refused: [],
276
+ interrupted: [],
277
+ unfinished: [],
278
+ replannedCount: 0,
279
+ liveLimitHit: false,
280
+ };
281
+ const paths = new Map([...plans].map(([id, plan]) => [id, plan.path]));
282
+ const current = new Map([...plans].map(([id, plan]) => [id, plan.control.state]));
283
+ const cut = new Map();
284
+ const visited = new Map([...plans].map(([id, plan]) => [id, new Set([plan.control.state])]));
285
+ const nameOf = (id) => plans.get(id).control.name;
286
+ let pending = [...plans.keys()];
287
+ for (let round = 0; round < MAX_ROUNDS && pending.length > 0 && !run.liveLimitHit; round++) {
288
+ const slots = await (0, shared_js_1.runBatch)(pending, {
289
+ deadlineAt: context.deadlineAt,
290
+ concurrency: shared_js_1.BATCH_CONCURRENCY,
291
+ stopAfter: (value) => value.outcome.kind === 'refused' && value.outcome.liveLimit,
292
+ }, async (id) => {
293
+ const outcome = await hop(client, id, paths.get(id)[0], context.note);
294
+ if (outcome.kind !== 'refused' || outcome.liveLimit)
295
+ return { id, outcome };
296
+ // The hop was refused, so nothing landed: an abort on the re-read leaves it a refusal,
297
+ // not a cut-off move that "may have landed".
298
+ const fresh = await readState(client, id, context.deadlineAt).catch((error) => {
299
+ if ((0, shared_js_1.isAborted)(error))
300
+ return { kind: 'unread' };
301
+ throw error;
302
+ });
303
+ return { id, outcome, fresh };
304
+ });
305
+ const next = [];
306
+ slots.forEach((slot, index) => {
307
+ if (slot.kind === 'interrupted') {
308
+ const id = pending[index];
309
+ const to = paths.get(id)[0];
310
+ run.interrupted.push({ id, name: nameOf(id), from: current.get(id) ?? null, to });
311
+ cut.set(id, to);
312
+ return;
313
+ }
314
+ if (slot.kind !== 'done')
315
+ return;
316
+ const id = pending[index];
317
+ const { outcome, fresh } = slot.value;
318
+ if (outcome.kind === 'moved') {
319
+ run.transitioned.push({
320
+ id,
321
+ name: nameOf(id),
322
+ from: current.get(id) ?? null,
323
+ to: outcome.state,
324
+ url: (0, shared_js_1.controlUrl)(id, context.subdomain),
325
+ });
326
+ current.set(id, outcome.state);
327
+ visited.get(id).add(outcome.state);
328
+ const rest = paths.get(id).slice(1);
329
+ paths.set(id, rest);
330
+ if (rest.length > 0)
331
+ next.push(id);
332
+ return;
333
+ }
334
+ if (outcome.kind === 'not_found') {
335
+ run.skipped.push({
336
+ id,
337
+ name: nameOf(id),
338
+ reason: 'not_found',
339
+ state: current.get(id) ?? null,
340
+ });
341
+ return;
342
+ }
343
+ const real = fresh?.kind === 'read' ? fresh.control.state : null;
344
+ if (real === null || real === current.get(id)) {
345
+ const backendFrom = BACKEND_FROM_STATE.exec(outcome.reason)?.[1];
346
+ if (real !== null && backendFrom && backendFrom !== real)
347
+ return;
348
+ if (outcome.liveLimit)
349
+ run.liveLimitHit = true;
350
+ run.refused.push({ id, name: nameOf(id), reason: outcome.reason });
351
+ return;
352
+ }
353
+ if (visited.get(id).has(real))
354
+ return;
355
+ run.replannedCount += 1;
356
+ current.set(id, real);
357
+ visited.get(id).add(real);
358
+ const verdict = verdictFor(real, context.targetState, context.allowed);
359
+ if ('skip' in verdict) {
360
+ run.skipped.push({ id, name: nameOf(id), reason: verdict.skip, state: real });
361
+ }
362
+ else {
363
+ paths.set(id, verdict.path);
364
+ next.push(id);
365
+ }
366
+ });
367
+ pending = next;
368
+ }
369
+ const settled = new Set([...run.refused, ...run.skipped].map((entry) => entry.id));
370
+ run.unfinished = [...plans.keys()]
371
+ .filter((id) => current.get(id) !== context.targetState && !settled.has(id))
372
+ .map((id) => ({
373
+ id,
374
+ state: current.get(id),
375
+ moved: run.transitioned.some((move) => move.id === id),
376
+ ...(cut.has(id) ? { cutTo: cut.get(id) } : {}),
377
+ }));
378
+ return run;
379
+ }
380
+ /**
381
+ * The calls that finish what this one left, never wider than the caller asked. A control this call
382
+ * moved is handed back by id with only the state it was left in: a follow-up that re-read it
383
+ * stale, through the framework or with the caller's `fromStates`, demoted it again (review,
384
+ * 2026-10-29). Everything else goes back the way it came: a framework pass as the framework,
385
+ * re-selected and re-confirmed (handing back only the first 25 ids dropped the rest, same review),
386
+ * named controls by id with the caller's `fromStates`.
387
+ */
388
+ function nextInputs(context, hops, unreached) {
389
+ const { targetState, fromStates } = context;
390
+ const calls = [];
391
+ // A cut-off hop may or may not have landed, so it goes back by id from either state; both lie
392
+ // on its path to the target, so neither is a step backwards.
393
+ const cutBack = new Map();
394
+ for (const entry of hops.unfinished.filter((candidate) => candidate.cutTo)) {
395
+ const from = [entry.state, entry.cutTo].filter((state) => state !== targetState);
396
+ const call = cutBack.get(from.join()) ?? { controlIds: [], targetState, fromStates: from };
397
+ call.controlIds.push(entry.id);
398
+ cutBack.set(from.join(), call);
399
+ }
400
+ calls.push(...cutBack.values());
401
+ const moved = hops.unfinished.filter((entry) => entry.moved && !entry.cutTo);
402
+ for (const state of new Set(moved.map((entry) => entry.state))) {
403
+ calls.push({
404
+ controlIds: moved.filter((entry) => entry.state === state).map((entry) => entry.id),
405
+ targetState,
406
+ fromStates: [state],
407
+ });
408
+ }
409
+ const rest = [
410
+ ...hops.unfinished.filter((entry) => !entry.moved && !entry.cutTo).map((entry) => entry.id),
411
+ ...unreached,
412
+ ];
413
+ const restFromStates = fromStates ? { fromStates: [...fromStates] } : {};
414
+ if (context.frameworkId && fromStates?.length && (rest.length > 0 || context.selectionMore)) {
415
+ calls.push({ frameworkId: context.frameworkId, targetState, ...restFromStates });
416
+ }
417
+ else if (!context.frameworkId && rest.length > 0) {
418
+ calls.push({ controlIds: rest, targetState, ...restFromStates });
419
+ }
420
+ return calls;
421
+ }
422
+ /**
423
+ * What to do with evaluations this call did not finish. Unreached ones are simply queued again; a
424
+ * cut-off one may be queued already, and each call queues a fresh run, so it is read back first.
425
+ */
426
+ function evaluateRemainingStep(notAttempted, interrupted) {
427
+ const parts = [];
428
+ if (notAttempted > 0) {
429
+ parts.push(`${notAttempted} control${notAttempted === 1 ? ' was' : 's were'} not reached in this ` +
430
+ "call's budget: call again with those ids (`not_attempted` items).");
431
+ }
432
+ if (interrupted > 0) {
433
+ parts.push(`${interrupted} ${interrupted === 1 ? 'was' : 'were'} cut off and may already be queued: ` +
434
+ 'read them with `get-control` in a few minutes before queueing them again.');
435
+ }
436
+ return parts.join(' ');
437
+ }
438
+ exports.transitionTools = [
439
+ (0, types_js_1.defineTool)({
440
+ name: 'transition-controls',
441
+ title: 'Change Control States',
442
+ description: (0, load_description_js_1.loadDescription)('transition-controls.md'),
443
+ inputSchema: {
444
+ controlIds: zod_1.z
445
+ .array(zod_1.z
446
+ .string()
447
+ .trim()
448
+ .min(1)
449
+ .refine((value) => !shared_js_1.CONTROL_ID_FORBIDDEN.test(value), {
450
+ message: 'A control id never contains a quote or a backslash.',
451
+ }))
452
+ .min(1)
453
+ .max(shared_js_1.MAX_CONTROLS_PER_CALL)
454
+ .optional()
455
+ .describe(`Exact control ids, 1 to ${shared_js_1.MAX_CONTROLS_PER_CALL}; required for RETIRED.`),
456
+ frameworkId: zod_1.z
457
+ .string()
458
+ .trim()
459
+ .min(1)
460
+ .optional()
461
+ .describe('Instead of ids: every control of this framework in one of `fromStates`.'),
462
+ fromStates: zod_1.z
463
+ .array(zod_1.z.enum(STATES))
464
+ .min(1)
465
+ .optional()
466
+ .describe('The states to move from. With `frameworkId` the default is DRAFT and REVIEW; with ' +
467
+ '`controlIds`, any state unless given.'),
468
+ targetState: zod_1.z.enum(STATES).describe('Where to move them: DRAFT, REVIEW, LIVE or RETIRED.'),
469
+ note: zod_1.z.string().trim().min(1).optional().describe('Recorded on each transition.'),
470
+ },
471
+ outputSchema: schemas_js_1.transitionControlsOutput,
472
+ // Repeating the same input finds the controls already in the target state and skips them.
473
+ annotations: { ...types_js_1.MUTATE, idempotentHint: true },
474
+ accessDeniedHint: shared_js_1.ACCESS_DENIED_HINT,
475
+ errorContext: 'Error transitioning controls',
476
+ handler: async ({ controlIds, frameworkId, fromStates, targetState, note }, client) => {
477
+ if ((controlIds && frameworkId) || (!controlIds && !frameworkId)) {
478
+ return (0, shared_js_1.validationError)('Pass exactly one of `controlIds` and `frameworkId`.');
479
+ }
480
+ if (targetState === 'RETIRED' && !controlIds) {
481
+ return (0, shared_js_1.validationError)('RETIRED needs explicit `controlIds`; a framework is never retired at once.');
482
+ }
483
+ if (frameworkId && !graph_js_1.GRAPH_FRAMEWORK_ID.test(frameworkId)) {
484
+ return (0, shared_js_1.refusal)('framework_not_found', 'No framework has this id; take the `id` from `get-compliance-summary`.', { frameworkId });
485
+ }
486
+ const startedAt = Date.now();
487
+ const readDeadline = startedAt + shared_js_1.AUTHORING_READ_DEADLINE_MS;
488
+ const timings = {};
489
+ const subdomainRead = (0, shared_js_1.readSubdomain)(client, timings);
490
+ // Framework mode moves only controls in `fromStates` (DRAFT and REVIEW by default); id mode
491
+ // moves the named controls from any state unless `fromStates` narrows it.
492
+ // A control already at the target needs no read, so the framework selection leaves that
493
+ // state out: with REVIEW both the target and a default from-state, a 1,100-control move to
494
+ // REVIEW re-selected its first 1,000 every call and never reached the rest (review,
495
+ // 2026-10-29).
496
+ const allowed = (fromStates ?? (frameworkId ? DEFAULT_FROM_STATES : undefined))?.filter((state) => !frameworkId || state !== targetState);
497
+ let order;
498
+ let selectionMore = false;
499
+ if (frameworkId && allowed?.length === 0) {
500
+ order = [];
501
+ }
502
+ else if (frameworkId) {
503
+ const selection = await (0, shared_js_1.timed)(timings, 'selection', () => readSelection(client, selectionQuery(frameworkId, allowed ?? []), readDeadline));
504
+ if (!selection) {
505
+ return (0, shared_js_1.refusal)('read_failed', "The framework's controls could not be read in time, so nothing was moved. Call again.", {});
506
+ }
507
+ order = [...selection.selected.keys()];
508
+ selectionMore = selection.more;
509
+ }
510
+ else {
511
+ order = [...new Set(controlIds)];
512
+ }
513
+ const confirmation = await (0, shared_js_1.timed)(timings, 'confirm', () => confirmCandidates(client, order, { targetState, allowed, deadlineAt: readDeadline }));
514
+ const subdomain = await (0, shared_js_1.subdomainBy)(subdomainRead, readDeadline);
515
+ const hops = await (0, shared_js_1.timed)(timings, 'transitions', () => runHops(client, confirmation.plans, {
516
+ targetState,
517
+ allowed,
518
+ note,
519
+ subdomain,
520
+ deadlineAt: startedAt + shared_js_1.AUTHORING_DEADLINE_MS,
521
+ }));
522
+ const remainingControlIds = [
523
+ ...hops.unfinished.map((entry) => entry.id),
524
+ ...confirmation.unreached,
525
+ ];
526
+ const remaining = remainingControlIds.length;
527
+ const calls = hops.liveLimitHit
528
+ ? []
529
+ : nextInputs({ frameworkId, targetState, fromStates: allowed, selectionMore }, hops, confirmation.unreached);
530
+ return (0, result_js_1.structuredResult)({
531
+ outcome: 'ok',
532
+ targetState,
533
+ transitioned: hops.transitioned,
534
+ ...(hops.interrupted.length > 0 ? { interrupted: hops.interrupted } : {}),
535
+ skipped: [...confirmation.skipped, ...hops.skipped],
536
+ refused: [...confirmation.refused, ...hops.refused],
537
+ remaining,
538
+ ...(remaining > 0 ? { remainingControlIds } : {}),
539
+ ...(selectionMore ? { selectionComplete: false } : {}),
540
+ ...(calls.length > 0 ? { nextInputs: calls } : {}),
541
+ replannedCount: hops.replannedCount,
542
+ liveLimitHit: hops.liveLimitHit,
543
+ // A cut-off move can land after the call gives up, so it carries the warning too.
544
+ note: hops.transitioned.length > 0 || hops.interrupted.length > 0
545
+ ? `${STATE_NOTE[targetState]} ${WRITE_BACK_NOTE}`
546
+ : STATE_NOTE[targetState],
547
+ nextStep: hops.liveLimitHit
548
+ ? 'The live-controls limit was reached: retire controls or keep the rest below LIVE; the refusal carries the numbers.'
549
+ : calls.length > 0
550
+ ? `${remaining > 0 ? `${remaining} control${remaining === 1 ? ' was' : 's were'} not reached or not finished` : 'The framework has more controls than one call selects'}: make each call in \`nextInputs\`, then repeat with each result's \`nextInputs\` until there are none.${hops.interrupted.length > 0 ? CUT_WAIT : ''}`
551
+ : targetState === 'LIVE'
552
+ ? 'Read `get-compliance-summary` after the first evaluation, or `evaluate-controls` to run it now.'
553
+ : 'Done. `list-controls` with `states` shows where the controls stand.',
554
+ timingsMs: timings,
555
+ });
556
+ },
557
+ }),
558
+ (0, types_js_1.defineTool)({
559
+ name: 'evaluate-controls',
560
+ title: 'Evaluate Controls',
561
+ description: (0, load_description_js_1.loadDescription)('evaluate-controls.md'),
562
+ inputSchema: {
563
+ controlIds: zod_1.z
564
+ .array(zod_1.z
565
+ .string()
566
+ .trim()
567
+ .min(1)
568
+ .refine((value) => !shared_js_1.CONTROL_ID_FORBIDDEN.test(value), {
569
+ message: 'A control id never contains a quote or a backslash.',
570
+ }))
571
+ .min(1)
572
+ .max(shared_js_1.MAX_CONTROLS_PER_CALL)
573
+ .describe(`Exact control ids to evaluate now, 1 to ${shared_js_1.MAX_CONTROLS_PER_CALL}.`),
574
+ },
575
+ outputSchema: schemas_js_1.evaluateControlsOutput,
576
+ // No idempotentHint: a repeat queues another run that rewrites test statuses and timestamps.
577
+ annotations: types_js_1.MUTATE,
578
+ accessDeniedHint: shared_js_1.ACCESS_DENIED_HINT,
579
+ errorContext: 'Error evaluating controls',
580
+ handler: async ({ controlIds }, client) => {
581
+ const startedAt = Date.now();
582
+ const readDeadline = startedAt + shared_js_1.AUTHORING_READ_DEADLINE_MS;
583
+ const writeDeadline = startedAt + shared_js_1.AUTHORING_DEADLINE_MS;
584
+ const timings = {};
585
+ const ids = [...new Set(controlIds)];
586
+ const read = await (0, shared_js_1.timed)(timings, 'selection', () => (0, graph_js_1.runGraphQuery)(client, evaluationSelectionQuery(ids), readDeadline, 1, { fresh: true }));
587
+ if (read.kind !== 'rows') {
588
+ if (read.kind === 'failed')
589
+ console.error('Error selecting controls to evaluate:', read.error);
590
+ return (0, shared_js_1.refusal)('read_failed', 'The controls could not be read in time, so nothing was queued. Call again.', {});
591
+ }
592
+ const known = new Map();
593
+ for (const row of read.rows) {
594
+ const id = (0, graph_js_1.rowText)(row.id);
595
+ if (!id)
596
+ continue;
597
+ const entry = known.get(id) ?? {
598
+ name: (0, graph_js_1.rowText)(row.name),
599
+ state: (0, graph_js_1.rowText)(row.state),
600
+ tests: 0,
601
+ };
602
+ if ((0, graph_js_1.rowText)(row.testId))
603
+ entry.tests += 1;
604
+ known.set(id, entry);
605
+ }
606
+ // A test or a control created moments ago is not in the graph yet: confirm with the API
607
+ // before answering no_tests or not_found.
608
+ const unconfirmed = ids.filter((id) => (known.get(id)?.tests ?? 0) === 0);
609
+ if (unconfirmed.length > 0) {
610
+ const confirmed = await (0, shared_js_1.timed)(timings, 'confirm', () => (0, shared_js_1.runBatch)(unconfirmed, { deadlineAt: readDeadline, concurrency: shared_js_1.BATCH_CONCURRENCY }, (id) => confirmControl(client, id, readDeadline)));
611
+ confirmed.forEach((slot, index) => {
612
+ const fresh = slot.kind === 'done' ? slot.value : undefined;
613
+ if (fresh === null)
614
+ known.delete(unconfirmed[index]);
615
+ else if (fresh)
616
+ known.set(unconfirmed[index], fresh);
617
+ });
618
+ }
619
+ const slots = await (0, shared_js_1.timed)(timings, 'evaluate', () => (0, shared_js_1.runBatch)(ids, { deadlineAt: writeDeadline, concurrency: shared_js_1.BATCH_CONCURRENCY }, async (id) => {
620
+ const control = known.get(id);
621
+ if (!control)
622
+ return { outcome: 'not_found', id };
623
+ const base = { id, name: control.name, state: control.state, testCount: control.tests };
624
+ if (control.tests === 0)
625
+ return { outcome: 'no_tests', ...base };
626
+ try {
627
+ await client.evaluateControl(id);
628
+ return { outcome: 'queued', ...base };
629
+ }
630
+ catch (error) {
631
+ if ((0, shared_js_1.isAborted)(error))
632
+ throw error;
633
+ if ((0, shared_js_1.isNotFound)(error))
634
+ return { outcome: 'not_found', id };
635
+ return { outcome: 'refused', ...base, reason: (0, shared_js_1.backendReason)(error) };
636
+ }
637
+ }));
638
+ const items = slots.map((slot, index) => slot.kind === 'done' ? slot.value : { outcome: slot.kind, id: ids[index] });
639
+ const count = (outcome) => items.filter((item) => item.outcome === outcome).length;
640
+ const remaining = count('not_attempted') + count('interrupted');
641
+ const anyDraft = items.some((item) => item.outcome === 'queued' && item.state !== 'LIVE');
642
+ return (0, result_js_1.structuredResult)({
643
+ outcome: 'ok',
644
+ items,
645
+ queuedCount: count('queued'),
646
+ remaining,
647
+ nextStep: remaining > 0
648
+ ? evaluateRemainingStep(count('not_attempted'), count('interrupted'))
649
+ : 'Wait a few minutes, then `get-control` on each: ' +
650
+ (anyDraft
651
+ ? 'on a DRAFT or REVIEW control `testsRan`, `testsPassing` and `testsFailing` carry the proof while `statusExplanation` stays `not_live`; '
652
+ : '') +
653
+ 'on a LIVE control `status` and `statusExplanation` follow the tests.',
654
+ timingsMs: timings,
655
+ });
656
+ },
657
+ }),
658
+ ];
659
+ //# sourceMappingURL=transitions.js.map