@jupiterone/jupiterone-mcp 2.4.2 → 2.5.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 (60) hide show
  1. package/README.md +22 -0
  2. package/dist/client/graphql/mutations.d.ts +3 -0
  3. package/dist/client/graphql/mutations.d.ts.map +1 -1
  4. package/dist/client/graphql/mutations.js +20 -1
  5. package/dist/client/graphql/mutations.js.map +1 -1
  6. package/dist/client/graphql/queries.d.ts +27 -0
  7. package/dist/client/graphql/queries.d.ts.map +1 -1
  8. package/dist/client/graphql/queries.js +186 -1
  9. package/dist/client/graphql/queries.js.map +1 -1
  10. package/dist/client/jupiterone-client.d.ts +26 -1
  11. package/dist/client/jupiterone-client.d.ts.map +1 -1
  12. package/dist/client/jupiterone-client.js +44 -3
  13. package/dist/client/jupiterone-client.js.map +1 -1
  14. package/dist/client/sanitize-error.d.ts +2 -0
  15. package/dist/client/sanitize-error.d.ts.map +1 -1
  16. package/dist/client/sanitize-error.js +9 -1
  17. package/dist/client/sanitize-error.js.map +1 -1
  18. package/dist/client/services/compliance-service.d.ts +63 -0
  19. package/dist/client/services/compliance-service.d.ts.map +1 -0
  20. package/dist/client/services/compliance-service.js +248 -0
  21. package/dist/client/services/compliance-service.js.map +1 -0
  22. package/dist/client/services/rule-service.d.ts +4 -6
  23. package/dist/client/services/rule-service.d.ts.map +1 -1
  24. package/dist/client/services/rule-service.js +6 -21
  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 +736 -4
  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 +1 -0
  31. package/dist/server/mcp-server.js.map +1 -1
  32. package/dist/server/tools/account.d.ts.map +1 -1
  33. package/dist/server/tools/account.js +4 -4
  34. package/dist/server/tools/account.js.map +1 -1
  35. package/dist/server/tools/compliance.d.ts +107 -0
  36. package/dist/server/tools/compliance.d.ts.map +1 -0
  37. package/dist/server/tools/compliance.js +2886 -0
  38. package/dist/server/tools/compliance.js.map +1 -0
  39. package/dist/server/tools/errors.d.ts +17 -1
  40. package/dist/server/tools/errors.d.ts.map +1 -1
  41. package/dist/server/tools/errors.js +59 -4
  42. package/dist/server/tools/errors.js.map +1 -1
  43. package/dist/server/tools/index.d.ts.map +1 -1
  44. package/dist/server/tools/index.js +2 -0
  45. package/dist/server/tools/index.js.map +1 -1
  46. package/dist/server/tools/rules.d.ts +35 -1
  47. package/dist/server/tools/rules.d.ts.map +1 -1
  48. package/dist/server/tools/rules.js +245 -9
  49. package/dist/server/tools/rules.js.map +1 -1
  50. package/dist/server/tools/threat.js +1 -1
  51. package/dist/server/tools/threat.js.map +1 -1
  52. package/dist/server/tools/usage.d.ts.map +1 -1
  53. package/dist/server/tools/usage.js +251 -0
  54. package/dist/server/tools/usage.js.map +1 -1
  55. package/dist/types/jupiterone.d.ts +247 -0
  56. package/dist/types/jupiterone.d.ts.map +1 -1
  57. package/node_modules/@jupiterone/query-language-interface-types/package.json +2 -2
  58. package/node_modules/@jupiterone/query-language-parser/package.json +3 -3
  59. package/node_modules/dtrace-provider/build/Makefile +1 -1
  60. package/package.json +3 -3
@@ -0,0 +1,2886 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.complianceTools = exports.STATUS_EXPLANATIONS = exports.ORG_UNIT_SUGGESTIONS = exports.GRAPH_MAX_PAGES = exports.GRAPH_PAGE_SIZE = exports.SUMMARY_READ_DEADLINE_MS = exports.WRITE_READ_DEADLINE_MS = exports.GET_CONTROL_DEADLINE_MS = exports.READ_FANOUT_DEADLINE_MS = exports.MAX_EXPIRED_ATTESTATIONS = exports.STATS_CHUNK_SIZE = exports.MAX_REQUIREMENT_LOOKUPS = exports.MAX_EVALUATION_LOOKUPS = exports.MAX_NAMED_CONTROLS = exports.CONTROL_ID_FORBIDDEN = void 0;
4
+ exports.parseExpiresOn = parseExpiresOn;
5
+ exports.explainControlStatus = explainControlStatus;
6
+ exports.lookupLatestEvaluation = lookupLatestEvaluation;
7
+ const zod_1 = require("zod");
8
+ const sanitize_error_js_1 = require("../../client/sanitize-error.js");
9
+ const j1ql_service_js_1 = require("../../client/services/j1ql-service.js");
10
+ const appUrl_js_1 = require("../../utils/appUrl.js");
11
+ const load_description_js_1 = require("../../utils/load-description.js");
12
+ const errors_js_1 = require("./errors.js");
13
+ const result_js_1 = require("./result.js");
14
+ const types_js_1 = require("./types.js");
15
+ /**
16
+ * Compliance tools — the MCP surface over JupiterOne Continuous Control Monitoring (CCM).
17
+ *
18
+ * - get-compliance-summary the frameworks scorecard, optionally drilled into one framework
19
+ * - list-controls the controls status view and its filters
20
+ * - get-control one control with everything that explains its status
21
+ * - create-attestation / update-attestation / revoke-attestation the attestation lifecycle
22
+ *
23
+ * Every resolver behind them is gated by the account's CCM entitlement and by CCM's own
24
+ * per-resource-group permissions, so all six carry ACCESS_DENIED_HINT. Expected outcomes (not
25
+ * found, ambiguous) are discriminated success envelopes. A write the server refuses is an
26
+ * `isError` envelope that still carries its `outcome`, so refusals are countable without matching
27
+ * text. No `isError` text carries customer text — the chokepoint copies its first 200 characters
28
+ * into telemetry — so refusals name ids and enum values only.
29
+ */
30
+ // Written for the reason-led access-denied frame, which already leads with the backend's own
31
+ // sentence ("Feature access not allowed to CCM", "Live controls limit reached …"), so this does not
32
+ // restate it.
33
+ const ACCESS_DENIED_HINT = "The compliance tools also need the account's Compliance (CCM) feature and control read " +
34
+ "permission; attestation writes need edit permission on the control's resource group, and " +
35
+ 'listing attestations without a controlId needs CCM read-admin. If the message names a feature ' +
36
+ 'or a limit, that is the cause — ask an account admin rather than re-authenticating.';
37
+ /** The characters the API rejects in a control id since apps PR #782 relaxed it (2026-10-13). */
38
+ exports.CONTROL_ID_FORBIDDEN = /['"\\]/;
39
+ const DAY_MS = 86_400_000;
40
+ /**
41
+ * The smallest number read as epoch milliseconds (1e12 ms is 2001-09-09). Below it sit epoch
42
+ * seconds and compact dates such as 20270630, which would otherwise be read as dates in 1970.
43
+ */
44
+ const MIN_EPOCH_MS = 1e12;
45
+ /** The largest magnitude a JavaScript Date can hold; `toISOString` throws beyond it. */
46
+ const MAX_DATE_MS = 8.64e15;
47
+ /** `YYYY-MM-DD`, read by `Date.parse` as midnight UTC on every host; it means the whole day. */
48
+ const ISO_DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;
49
+ /** A date-time pinned to one instant: a `T`, then `Z` or a `±hh:mm` offset. */
50
+ const ISO_DATE_TIME_WITH_ZONE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/i;
51
+ /** Any other date-time shape: no zone, or a space where the `T` goes. */
52
+ const ISO_DATE_TIME_PREFIX = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/i;
53
+ /** Controls the summary names in its one graph read; the rest keep a null name. */
54
+ exports.MAX_NAMED_CONTROLS = 100;
55
+ /** Control tests whose latest evaluation `get-control` looks up; later tests are `skipped`. */
56
+ exports.MAX_EVALUATION_LOOKUPS = 10;
57
+ /** Failing controls whose requirements a summary drill reads; the rest are counted as skipped. */
58
+ exports.MAX_REQUIREMENT_LOOKUPS = 50;
59
+ /** Frameworks per scorecard-counts read; the summary issues every chunk at once. */
60
+ exports.STATS_CHUNK_SIZE = 10;
61
+ /** Expired attestations a summary lists, most recently expired first; past it, it says so. */
62
+ exports.MAX_EXPIRED_ATTESTATIONS = 50;
63
+ /**
64
+ * get-control's evaluation lookups: the time they get once the control read returns, the read-side
65
+ * diagnosis budget (`DIAGNOSIS_BUDGET_MS`, value-probe.ts). A lookup still running at the deadline
66
+ * is abandoned as skipped.
67
+ */
68
+ exports.READ_FANOUT_DEADLINE_MS = 20_000;
69
+ /**
70
+ * The latest get-control's evaluation lookups may run, from request start, so the handler returns
71
+ * inside the remote's 55 s abort. Counted from request start alone, the lookup budget went to the
72
+ * control read: one read took 37.7 s on j1dev and every lookup was skipped (2026-10-14).
73
+ */
74
+ exports.GET_CONTROL_DEADLINE_MS = 45_000;
75
+ /**
76
+ * The latest an attestation write's read of its control may run, from request start. On j1dev
77
+ * every create and revoke that hit the remote's 55 s abort had in fact been written, and the caller
78
+ * saw an error for a write that landed (2026-10-15); past this the write answers without the read.
79
+ */
80
+ exports.WRITE_READ_DEADLINE_MS = 45_000;
81
+ /**
82
+ * Race deadline, from request start, for the summary's decoration reads: the drill's requirement
83
+ * lookups, its no-data count, and the expiring attestations' names and framework scope. At 20 s
84
+ * every one of four drills on j1dev skipped every lookup (2026-10-14): the framework list took
85
+ * 3.9–4.3 s and the failing-controls read 10.6–19.3 s before any lookup ran. The remote aborts at
86
+ * 55 s, and the one unraced read, the stats, took 29 s at worst on dev's 63 frameworks and runs in
87
+ * parallel with these.
88
+ */
89
+ exports.SUMMARY_READ_DEADLINE_MS = 35_000;
90
+ /** A daily-polled test fits in one page either way the backend sorts. */
91
+ const EVALUATION_WINDOW_MS = 30 * DAY_MS;
92
+ const EVALUATION_PAGE_LIMIT = 50;
93
+ const EVALUATION_FAILURE_TAG = 'EVALUATION_FAILURE';
94
+ const DEFAULT_EXPIRING_WITHIN_DAYS = 30;
95
+ const FAILING_CONTROLS_PAGE_LIMIT = 250;
96
+ const MAX_FAILING_CONTROL_PAGES = 2;
97
+ const DEFAULT_CONTROL_PAGE_LIMIT = 50;
98
+ const MAX_OU_NAMESPACES = 10;
99
+ const CONTROL_SEARCH_PAGE_LIMIT = 50;
100
+ const MAX_CONTROL_SEARCH_PAGES = 4;
101
+ /**
102
+ * Candidates an `ambiguous` outcome returns. A short name matches hundreds of controls or units,
103
+ * and past a couple of dozen the list stops helping the caller choose; `candidateCount` keeps the
104
+ * total.
105
+ */
106
+ const MAX_CANDIDATES = 25;
107
+ const NOTE_CREATED = '`attestations` and `get-control` can lag this write by a few seconds, occasionally up to a ' +
108
+ 'minute — re-read before assuming it failed; do not create it again.';
109
+ const NOTE_ALREADY_EXISTS = 'This control already has an active attestation with this subject, so nothing was created. To ' +
110
+ 'extend or edit it, call `update-attestation` with its `id`.';
111
+ const NOTE_SEVERAL_MATCHES = 'Several active attestations on this control share this subject, all listed in `matches`: ' +
112
+ '`attestation` is the one whose subject matches yours exactly, or the most recently created ' +
113
+ 'when none or several do.';
114
+ const NOTE_UPDATED = '`attestations` and `get-control` can lag this write by a few seconds, occasionally up to a ' +
115
+ 'minute — re-read before assuming it failed.';
116
+ // A not_found is a result, not an error, so its recovery travels in a note, the way
117
+ // framework_not_found lists the ids to choose from. None echoes the id or name that was asked for.
118
+ const NOTE_CONTROL_NOT_FOUND = 'No control matched. Search with `list-controls` (`search`, plus `frameworkId` to narrow) and ' +
119
+ 'call again with the `id` it returns; a deleted control is not found either.';
120
+ const NOTE_SEARCH_INCOMPLETE = `The search stopped after ${CONTROL_SEARCH_PAGE_LIMIT * MAX_CONTROL_SEARCH_PAGES} controls, so ` +
121
+ 'this is not proof the control does not exist.';
122
+ const NOTE_ATTESTATION_NOT_FOUND = "No attestation has this id, and nothing changed. Read the control's current attestation ids " +
123
+ 'from `get-control` (`attestations`).';
124
+ const NOTE_UPDATE_NOT_FOUND = `${NOTE_ATTESTATION_NOT_FOUND} A revoked attestation is gone for good; attest again with ` +
125
+ '`create-attestation`.';
126
+ const NOTE_REVOKE_NOT_FOUND = `${NOTE_ATTESTATION_NOT_FOUND} An attestation that is already revoked is not found either, so ` +
127
+ 'there is nothing left to revoke.';
128
+ const NOTE_REVOKED = 'Revocation is permanent. `attestations` and `get-control` can lag this write by a few ' +
129
+ 'seconds, occasionally up to a minute — re-read before assuming it failed.';
130
+ // ---------------------------------------------------------------------------------------------
131
+ // Shared helpers
132
+ // ---------------------------------------------------------------------------------------------
133
+ /**
134
+ * The gateway's not-found rejection. Narrow on purpose: anything else is a real failure and must
135
+ * reach the generic envelope, not read as an absence.
136
+ */
137
+ function isNotFound(error) {
138
+ return (error instanceof sanitize_error_js_1.JupiterOneApiError &&
139
+ (error.code === 'NOT_FOUND' || /not found/i.test(error.message)));
140
+ }
141
+ /**
142
+ * The one condition under which a compliance sub-call degrades instead of failing the tool: a
143
+ * refusal of the attestations read, which needs more permission than the rest of the response.
144
+ * `'unavailable'` means "could not read", never "none".
145
+ */
146
+ function degradeOnAccessDenied(error) {
147
+ if ((0, errors_js_1.accessDeniedStatus)(error) !== null)
148
+ return 'unavailable';
149
+ throw error;
150
+ }
151
+ const DEADLINE_PASSED = Symbol('deadline-passed');
152
+ /** Settle with the promise, or with DEADLINE_PASSED at `deadlineAt`, whichever comes first. */
153
+ async function withDeadline(promise, deadlineAt) {
154
+ let timer;
155
+ const deadline = new Promise((resolve) => {
156
+ timer = setTimeout(() => resolve(DEADLINE_PASSED), Math.max(0, deadlineAt - Date.now()));
157
+ });
158
+ try {
159
+ return await Promise.race([promise, deadline]);
160
+ }
161
+ finally {
162
+ clearTimeout(timer);
163
+ }
164
+ }
165
+ async function timed(timings, phase, work) {
166
+ const started = Date.now();
167
+ try {
168
+ return await work();
169
+ }
170
+ finally {
171
+ timings[phase] = Date.now() - started;
172
+ }
173
+ }
174
+ /**
175
+ * The account subdomain app links are built on, read once per call alongside the other reads. A
176
+ * failed read gives every link `''`, constructAppUrl's own "no link", rather than failing a read
177
+ * whose answer does not depend on its links.
178
+ */
179
+ async function readSubdomain(client, timings = {}) {
180
+ try {
181
+ return (await timed(timings, 'account', () => client.getAccountInfo())).subdomain;
182
+ }
183
+ catch (error) {
184
+ console.error('Error reading the account subdomain for app links:', error);
185
+ return undefined;
186
+ }
187
+ }
188
+ /** The account subdomain, or none when its read is not back by `deadlineAt`. */
189
+ async function subdomainBy(read, deadlineAt) {
190
+ const settled = await withDeadline(read, deadlineAt);
191
+ return settled === DEADLINE_PASSED ? undefined : settled;
192
+ }
193
+ /**
194
+ * CCM's app pages, at the routes the web app serves (`artifacts/app/src/views/controls`). The route
195
+ * loaders pass the id straight to the CCM API, so these ids work as given; they are encoded because
196
+ * UPLOAD and JSON control ids can carry spaces (`ccm_c_JSON_A.5.1 Policies`).
197
+ */
198
+ function frameworkUrl(frameworkId, subdomain) {
199
+ return (0, appUrl_js_1.constructAppUrl)(`controls/frameworks/${encodeURIComponent(frameworkId)}`, subdomain);
200
+ }
201
+ function controlUrl(controlId, subdomain) {
202
+ return controlId
203
+ ? (0, appUrl_js_1.constructAppUrl)(`controls/controls/${encodeURIComponent(controlId)}`, subdomain)
204
+ : '';
205
+ }
206
+ /**
207
+ * An error result whose text leads with its outcome word. Hosts that show an error's text alone
208
+ * never see `structuredContent`, and the tester reported twice that refusals carried no visible
209
+ * outcome (2026-10-14).
210
+ */
211
+ function refusal(outcome, text, details = {}) {
212
+ return {
213
+ content: [{ type: 'text', text: `${outcome}: ${text}` }],
214
+ isError: true,
215
+ structuredContent: { outcome, ...details },
216
+ };
217
+ }
218
+ /** A cross-field input failure the schema cannot express. Nothing was called. */
219
+ function validationError(text) {
220
+ return refusal('invalid_input', text);
221
+ }
222
+ /** A write the server refused before making it. */
223
+ function writeRefusal(outcome, text, details = {}) {
224
+ return refusal(outcome, text, details);
225
+ }
226
+ /**
227
+ * A date-time with no zone is read by `Date.parse` in the host's local time zone — on stdio, the
228
+ * user's laptop — so the same input would expire at a different instant on each machine. Only
229
+ * forms that name one instant everywhere are read.
230
+ */
231
+ /**
232
+ * Whether a `YYYY-MM-DD` names a day that exists. `Date.parse` rolls an impossible day over
233
+ * ("2027-02-30" becomes 2027-03-02) and rejects an impossible month only as unreadable, so the date
234
+ * part is rebuilt in UTC and compared with itself. Only the date part is checked: the input's own
235
+ * calendar day, whatever its time and offset, so `T23:00:00-05:00` is not judged by its UTC date.
236
+ */
237
+ function isCalendarDate(datePart) {
238
+ const [year, month, day] = datePart.split('-').map(Number);
239
+ return new Date(Date.UTC(year, month - 1, day)).toISOString().slice(0, 10) === datePart;
240
+ }
241
+ const UNREADABLE_EXPIRY_REASONS = {
242
+ // Not "epoch seconds": "20270630" lands here too, and calling it seconds sent the caller looking
243
+ // for a unit conversion instead of a date format.
244
+ below_epoch_ms: 'is a number below 1e12, so it is not epoch milliseconds',
245
+ no_time_zone: 'is a date-time without `Z` or a `±hh:mm` offset after a `T`, so it would be read in the ' +
246
+ 'time zone of whichever machine runs the server',
247
+ not_a_calendar_date: 'names a day that does not exist (the month or the day is out of range)',
248
+ };
249
+ function toEpochMs(value) {
250
+ const text = typeof value === 'string' ? value.trim() : '';
251
+ const numeric = typeof value === 'number' ? value : /^\d+$/.test(text) ? Number(text) : null;
252
+ if (numeric !== null) {
253
+ if (!Number.isFinite(numeric) || numeric > MAX_DATE_MS)
254
+ return null;
255
+ return numeric < MIN_EPOCH_MS ? 'below_epoch_ms' : Math.round(numeric);
256
+ }
257
+ if (ISO_DATE_ONLY.test(text) || ISO_DATE_TIME_WITH_ZONE.test(text)) {
258
+ if (!isCalendarDate(text.slice(0, 10)))
259
+ return 'not_a_calendar_date';
260
+ const parsed = Date.parse(text);
261
+ if (!Number.isFinite(parsed))
262
+ return null;
263
+ // A bare date is the whole of that day, as the app stores it (`T23:59:59.999Z`). Read as its
264
+ // first instant, "valid through Jan 31" lapsed a day early (2026-10-14).
265
+ return ISO_DATE_ONLY.test(text) ? parsed + DAY_MS - 1 : parsed;
266
+ }
267
+ return ISO_DATE_TIME_PREFIX.test(text) ? 'no_time_zone' : null;
268
+ }
269
+ /**
270
+ * An attestation expiry as epoch milliseconds: `YYYY-MM-DD` (the end of that day, UTC), a
271
+ * date-time with `Z` or a `±hh:mm` offset, or epoch ms as a number or a digit string. A number
272
+ * below 1e12 is rejected rather than read as a 1970 date, a date-time with no zone rather than
273
+ * read in whatever zone the server runs in, and a day that does not exist rather than rolled over
274
+ * into the next month. The reason carries none of the caller's input.
275
+ */
276
+ function parseExpiresOn(value, now = Date.now()) {
277
+ const ms = toEpochMs(value);
278
+ if (typeof ms === 'string')
279
+ return { ok: false, reason: UNREADABLE_EXPIRY_REASONS[ms] };
280
+ if (ms === null)
281
+ return { ok: false, reason: 'is not an ISO 8601 date or epoch milliseconds' };
282
+ if (ms <= now) {
283
+ return { ok: false, reason: "is in the past; an attestation's expiry must be in the future" };
284
+ }
285
+ return { ok: true, ms };
286
+ }
287
+ function expiresOnError(operation, reason) {
288
+ return validationError(`Attestation not ${operation} — \`expiresOn\` ${reason}. Pass "YYYY-MM-DD", ` +
289
+ '"YYYY-MM-DDThh:mm:ssZ", "YYYY-MM-DDThh:mm:ss+hh:mm" or epoch milliseconds.');
290
+ }
291
+ /** An API timestamp (epoch ms as a number or a digit string, or a date string) as ISO 8601. */
292
+ function toIso(value) {
293
+ if (value === null || value === undefined || value === '')
294
+ return null;
295
+ const ms = typeof value === 'number' ? value : /^\d+$/.test(value) ? Number(value) : Date.parse(value);
296
+ return Number.isFinite(ms) && Math.abs(ms) <= MAX_DATE_MS ? new Date(ms).toISOString() : null;
297
+ }
298
+ function projectAttestation(attestation) {
299
+ return {
300
+ id: attestation.id,
301
+ subject: attestation.subject,
302
+ description: attestation.description,
303
+ state: attestation.state,
304
+ expiresOn: attestation.expiresOn,
305
+ expiresOnIso: toIso(attestation.expiresOn),
306
+ owner: attestation.owner,
307
+ author: attestation.author,
308
+ documentLink: attestation.documentLink,
309
+ createdOn: attestation.createdOn,
310
+ controlId: attestation.controlId,
311
+ };
312
+ }
313
+ function frameworkNameMap(frameworks) {
314
+ return new Map(frameworks.map((framework) => [framework.id, framework.name]));
315
+ }
316
+ function namesFor(ids, names) {
317
+ return (ids ?? []).map((id) => names.get(id) ?? null);
318
+ }
319
+ // ---------------------------------------------------------------------------------------------
320
+ // get-compliance-summary
321
+ // ---------------------------------------------------------------------------------------------
322
+ /** Passing share of the requirements that have a verdict; null when none has one. */
323
+ function healthPct(stats) {
324
+ const passing = stats?.numberOfPassingRequirements ?? 0;
325
+ const failing = stats?.numberOfFailingRequirements ?? 0;
326
+ const assessed = passing + failing;
327
+ return assessed > 0 ? Math.round((100 * passing) / assessed) : null;
328
+ }
329
+ function frameworkScore(framework, stats, subdomain) {
330
+ return {
331
+ id: framework.id,
332
+ name: framework.name,
333
+ url: frameworkUrl(framework.id, subdomain),
334
+ source: framework.source ?? null,
335
+ sourceId: framework.sourceId ?? null,
336
+ owner: framework.owner ?? null,
337
+ importStatus: framework.status?.status ?? null,
338
+ controls: stats
339
+ ? {
340
+ total: stats.numberOfControls,
341
+ passing: stats.numberOfPassingControls,
342
+ failing: stats.numberOfFailingControls,
343
+ attested: stats.numberOfAttestedControls,
344
+ withTests: stats.numberOfControlsWithTests,
345
+ }
346
+ : null,
347
+ requirements: stats
348
+ ? {
349
+ total: stats.numberOfRequirements,
350
+ passing: stats.numberOfPassingRequirements,
351
+ failing: stats.numberOfFailingRequirements,
352
+ failingCritical: stats.numberOfFailingCriticalRequirements,
353
+ }
354
+ : null,
355
+ healthPct: healthPct(stats),
356
+ };
357
+ }
358
+ /**
359
+ * The scorecard counts, STATS_CHUNK_SIZE frameworks per read, every read issued at once and raced
360
+ * against `deadlineAt`. The backend computes requirement stats per framework, and one read for all
361
+ * of j1dev's 62 frameworks took 37.9 s on the only one of five bare summaries that did not hit the
362
+ * remote's 55 s abort (2026-10-14). A chunk that times out or fails leaves its frameworks in
363
+ * `incomplete`. Only when every chunk failed outright does the call fail, so an access refusal
364
+ * still surfaces.
365
+ */
366
+ async function readStats(client, ids, deadlineAt, options) {
367
+ if (Date.now() >= deadlineAt)
368
+ return { stats: [], incomplete: ids, chunkMaxMs: null };
369
+ const chunks = [];
370
+ for (let start = 0; start < ids.length; start += exports.STATS_CHUNK_SIZE) {
371
+ chunks.push(ids.slice(start, start + exports.STATS_CHUNK_SIZE));
372
+ }
373
+ const settled = await Promise.allSettled(chunks.map(async (chunk) => {
374
+ const chunkStartedAt = Date.now();
375
+ const read = await withDeadline(client.getControlFrameworkStats(chunk, options), deadlineAt);
376
+ return read === DEADLINE_PASSED ? read : { stats: read, ms: Date.now() - chunkStartedAt };
377
+ }));
378
+ const stats = [];
379
+ const incomplete = [];
380
+ const failures = [];
381
+ let chunkMaxMs = null;
382
+ settled.forEach((result, index) => {
383
+ if (result.status === 'fulfilled' && result.value !== DEADLINE_PASSED) {
384
+ stats.push(...result.value.stats);
385
+ chunkMaxMs = Math.max(chunkMaxMs ?? 0, result.value.ms);
386
+ return;
387
+ }
388
+ incomplete.push(...chunks[index]);
389
+ if (result.status === 'rejected')
390
+ failures.push(result.reason);
391
+ });
392
+ if (failures.length > 0 && failures.length === chunks.length)
393
+ throw failures[0];
394
+ for (const failure of failures)
395
+ console.error('Error reading framework stats:', failure);
396
+ return { stats, incomplete, chunkMaxMs };
397
+ }
398
+ function compareRequirements(a, b) {
399
+ const critical = Number(b.priority === 'CRITICAL') - Number(a.priority === 'CRITICAL');
400
+ return (critical ||
401
+ (a.section ?? '').localeCompare(b.section ?? '') ||
402
+ (a.identifier ?? '').localeCompare(b.identifier ?? ''));
403
+ }
404
+ /**
405
+ * Up to `maxPages` pages of controls matching `filter`. `complete` is false when the cap stopped
406
+ * the walk with pages left. A page that claims a successor without a cursor cannot be followed:
407
+ * re-requesting with no cursor would return the first page again as if it were the next.
408
+ */
409
+ async function walkControls(client, filter, page) {
410
+ const items = [];
411
+ let cursor;
412
+ for (let read = 0; read < page.maxPages; read++) {
413
+ const result = await client.listControls({ limit: page.limit, cursor, filter });
414
+ items.push(...result.items);
415
+ if (!result.pageInfo.hasNextPage)
416
+ return { items, complete: true };
417
+ if (!result.pageInfo.endCursor) {
418
+ throw new Error('Invalid response structure from JupiterOne API: ' +
419
+ 'controls reports another page without an endCursor');
420
+ }
421
+ cursor = result.pageInfo.endCursor;
422
+ }
423
+ return { items, complete: false };
424
+ }
425
+ const DRILL_PAGES = { limit: FAILING_CONTROLS_PAGE_LIMIT, maxPages: MAX_FAILING_CONTROL_PAGES };
426
+ /**
427
+ * The framework's failing controls as CCM counts them: LIVE and FAIL, asked of the API directly. A
428
+ * DRAFT, REVIEW or RETIRED control keeps the status of its last evaluation, so on j1dev's SOC 2 the
429
+ * stale FAILs of draft controls made 36 requirements look failing where CCM's own count said 5
430
+ * (2026-10-14). Failing controls are few; past MAX_FAILING_CONTROL_PAGES pages the rest are cut.
431
+ */
432
+ async function failingLiveControls(client, frameworkId) {
433
+ const { items, complete } = await walkControls(client, { frameworkId: [frameworkId], status: ['FAIL'], states: ['LIVE'] }, DRILL_PAGES);
434
+ return { controls: items, truncated: !complete };
435
+ }
436
+ /**
437
+ * How many of the framework's LIVE controls pass on tests that saw no data. CCM counts them as
438
+ * passing, so the scorecard cannot tell a pass backed by evidence from one on no data: the AI-ASM
439
+ * session on j1dev needed list-controls and per-control reads to find 7 such passes behind 73%
440
+ * (2026-10-14). A count is decoration on the scorecard, so a failed or late read gives no count
441
+ * and says which: it came back null on most of the tester's drills with no reason given.
442
+ */
443
+ async function passingWithoutDataCount(client, frameworkId, deadlineAt) {
444
+ if (Date.now() >= deadlineAt)
445
+ return { skipped: 'time_budget' };
446
+ try {
447
+ const read = await withDeadline(walkControls(client, {
448
+ frameworkId: [frameworkId],
449
+ status: ['PASS'],
450
+ states: ['LIVE'],
451
+ effectiveness: 'NO_DATAPOINTS',
452
+ }, DRILL_PAGES), deadlineAt);
453
+ if (read === DEADLINE_PASSED)
454
+ return { skipped: 'time_budget' };
455
+ return { count: read.items.length, truncated: !read.complete };
456
+ }
457
+ catch (error) {
458
+ console.error('Error counting controls that pass without data:', error);
459
+ return { skipped: 'read_failed' };
460
+ }
461
+ }
462
+ /**
463
+ * The requirements of up to MAX_REQUIREMENT_LOOKUPS failing controls, read concurrently and raced
464
+ * against `deadlineAt`. A lookup that fails is logged and counted as skipped rather than failing
465
+ * the summary, unless every lookup failed: then there is nothing to report and it throws.
466
+ */
467
+ async function lookupRequirements(client, controls, deadlineAt) {
468
+ const admitted = controls.slice(0, exports.MAX_REQUIREMENT_LOOKUPS);
469
+ const settled = await Promise.allSettled(admitted.map(async (control) => {
470
+ if (Date.now() >= deadlineAt)
471
+ return DEADLINE_PASSED;
472
+ const walk = await withDeadline(client.listControlRequirements(control.id), deadlineAt);
473
+ return walk === DEADLINE_PASSED
474
+ ? walk
475
+ : { control, requirements: walk.requirements, complete: walk.complete };
476
+ }));
477
+ const failed = settled.filter((result) => result.status === 'rejected');
478
+ if (failed.length > 0 && failed.length === admitted.length)
479
+ throw failed[0].reason;
480
+ for (const failure of failed) {
481
+ console.error("Error reading a failing control's requirements:", failure.reason);
482
+ }
483
+ const answered = settled.flatMap((result) => result.status === 'fulfilled' && result.value !== DEADLINE_PASSED ? [result.value] : []);
484
+ // A control whose requirement pages ran past that read's own cap keeps the rows it has, but its
485
+ // requirements were not all read; it counts under `cap` with the controls past the lookup cap
486
+ // (PR #55 review).
487
+ const cut = answered.filter((lookup) => !lookup.complete).length;
488
+ const skippedBy = {
489
+ timeBudget: settled.length - answered.length - failed.length,
490
+ cap: controls.length - admitted.length + cut,
491
+ readFailed: failed.length,
492
+ };
493
+ const read = answered.map(({ control, requirements }) => ({ control, requirements }));
494
+ return { read, skipped: controls.length - answered.length + cut, skippedBy };
495
+ }
496
+ /** Requirements of this framework with the failing controls that make them fail. */
497
+ function groupByRequirement(lookups, frameworkId) {
498
+ const byRequirement = new Map();
499
+ for (const { control, requirements } of lookups) {
500
+ for (const requirement of requirements) {
501
+ if (!(requirement.frameworkIds ?? []).includes(frameworkId))
502
+ continue;
503
+ const entry = byRequirement.get(requirement.id) ?? { requirement, controls: [] };
504
+ entry.controls.push(control);
505
+ byRequirement.set(requirement.id, entry);
506
+ }
507
+ }
508
+ return [...byRequirement.values()]
509
+ .sort((a, b) => compareRequirements(a.requirement, b.requirement))
510
+ .map(({ requirement, controls }) => ({
511
+ id: requirement.id,
512
+ identifier: requirement.identifier,
513
+ title: requirement.title,
514
+ section: requirement.section,
515
+ priority: requirement.priority,
516
+ failingControls: controls.map((control) => ({
517
+ id: control.id,
518
+ identifier: control.identifier,
519
+ name: control.name,
520
+ })),
521
+ }));
522
+ }
523
+ /**
524
+ * One framework's sections and failing requirements. The requirements come from the failing LIVE
525
+ * controls, not from the framework's requirement tree: that tree, with a page of controls under
526
+ * every requirement, timed out past the remote's 55 s on j1dev's DORA framework (122 requirements,
527
+ * 104 controls) while SOC 2 (61 requirements) returned in seconds, and the same shape measured 8 MB
528
+ * in the terraform provider's notes.
529
+ */
530
+ async function apiDrill(client, frameworkId, deadlineAt, timings) {
531
+ const failing = await timed(timings, 'failingControls', () => failingLiveControls(client, frameworkId));
532
+ const lookups = failing.controls.length > 0
533
+ ? timed(timings, 'requirements', () => lookupRequirements(client, failing.controls, deadlineAt))
534
+ : Promise.resolve({
535
+ read: [],
536
+ skipped: 0,
537
+ skippedBy: { timeBudget: 0, cap: 0, readFailed: 0 },
538
+ });
539
+ // Not concurrent with the failing-controls read: when it ran beside that read, the read took
540
+ // 10.6–19.3 s on j1dev against 7.2–7.7 s without it (2026-10-14).
541
+ const noData = timed(timings, 'passingWithoutData', () => passingWithoutDataCount(client, frameworkId, deadlineAt));
542
+ const [{ read, skipped, skippedBy }, passingWithoutData] = await Promise.all([lookups, noData]);
543
+ return {
544
+ passingWithoutData,
545
+ failingRequirements: groupByRequirement(read, frameworkId),
546
+ // Kept whatever the lookups managed: on j1dev a slow drill skipped all 11 requirement lookups
547
+ // and returned nothing an agent could act on, and recovering took 11 get-control calls
548
+ // (2026-10-14).
549
+ failingControls: failing.controls.map((control) => ({
550
+ id: control.id,
551
+ identifier: control.identifier,
552
+ name: control.name,
553
+ })),
554
+ failingControlsTruncated: failing.truncated,
555
+ requirementLookupsSkipped: skipped,
556
+ ...(skipped > 0 ? { requirementLookupsSkippedBy: skippedBy } : {}),
557
+ };
558
+ }
559
+ /** A framework id the graph queries may interpolate: a UUID, or `ccm_f_` and a slug. */
560
+ const GRAPH_FRAMEWORK_ID = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|ccm_f_[A-Za-z0-9_-]+)$/i;
561
+ /**
562
+ * Rows per page of a graph query. The query service refuses a larger LIMIT: on ECS 186 both drill
563
+ * queries at LIMIT 1000 failed with `"limit" must be a value between 1 and 250`, and every drill
564
+ * fell back to the API (2026-10-15).
565
+ */
566
+ exports.GRAPH_PAGE_SIZE = 250;
567
+ /** Pages a drill query follows its cursor through: up to 1,000 rows. Past it, it is cut short. */
568
+ exports.GRAPH_MAX_PAGES = 4;
569
+ /**
570
+ * Each failing LIVE control of the framework with each requirement of it the control serves, as
571
+ * one row per pair: 103 ms for SOC 2 on j1dev, matching the five requirements and three controls
572
+ * the apps-api drill took 28 s to assemble (2026-10-15).
573
+ */
574
+ function failingPairsQuery(frameworkId) {
575
+ return (`FIND ccm_framework WITH id = '${frameworkId}' THAT HAS ccm_requirement AS r ` +
576
+ "THAT HAS ccm_control WITH state = 'LIVE' AND status = 'FAIL' AS c " +
577
+ 'RETURN r.id AS requirementId, r.identifier AS requirementIdentifier, ' +
578
+ 'r.title AS requirementTitle, r.section AS requirementSection, ' +
579
+ 'r.priority AS requirementPriority, c.id AS controlId, c.identifier AS controlIdentifier, ' +
580
+ `c.name AS controlName LIMIT ${exports.GRAPH_PAGE_SIZE}`);
581
+ }
582
+ /**
583
+ * The framework's passing LIVE controls, one row per test with whether it saw data, and one row
584
+ * with a null `testId` for a control with no tests. `effectiveStatus` is not in the graph, so the
585
+ * tests decide (`passesWithoutData`). Counting effective tests per control instead gave a control
586
+ * with no tests at all, one passing by attestation, a count of 0 and called it a no-data pass,
587
+ * which the API's NO_DATAPOINTS filter never does (PR #55 review). This shape took 283 ms for 12
588
+ * rows on j1dev's SOC 2 (2026-10-15).
589
+ */
590
+ function noDataQuery(frameworkId) {
591
+ return (`FIND ccm_control WITH frameworkId = '${frameworkId}' AND state = 'LIVE' ` +
592
+ "AND status = 'PASS' AS c (THAT DEFINES ccm_control_test AS t)? " +
593
+ `RETURN c.id AS controlId, t.id AS testId, t.effective AS effective LIMIT ${exports.GRAPH_PAGE_SIZE}`);
594
+ }
595
+ /** Passing controls with at least one test, none of which saw data: the no-data passes. */
596
+ function passesWithoutData(rows) {
597
+ const controls = new Map();
598
+ for (const row of rows) {
599
+ const controlId = textOf(row.controlId);
600
+ if (!controlId)
601
+ continue;
602
+ const control = controls.get(controlId) ?? { tested: false, sawData: false };
603
+ if (textOf(row.testId)) {
604
+ control.tested = true;
605
+ if (row.effective === true)
606
+ control.sawData = true;
607
+ }
608
+ controls.set(controlId, control);
609
+ }
610
+ return [...controls.values()].filter((control) => control.tested && !control.sawData).length;
611
+ }
612
+ function textOf(value) {
613
+ return typeof value === 'string' ? value : null;
614
+ }
615
+ /** Requirement–control pairs as failing requirements, critical first, and the distinct controls. */
616
+ function groupPairs(rows) {
617
+ const byRequirement = new Map();
618
+ const controls = new Map();
619
+ for (const row of rows) {
620
+ const requirementId = textOf(row.requirementId);
621
+ const controlId = textOf(row.controlId);
622
+ if (!requirementId || !controlId)
623
+ continue;
624
+ const control = {
625
+ id: controlId,
626
+ identifier: textOf(row.controlIdentifier),
627
+ name: textOf(row.controlName),
628
+ };
629
+ if (!controls.has(controlId))
630
+ controls.set(controlId, control);
631
+ const entry = byRequirement.get(requirementId) ?? {
632
+ requirement: {
633
+ id: requirementId,
634
+ identifier: textOf(row.requirementIdentifier),
635
+ title: textOf(row.requirementTitle),
636
+ section: textOf(row.requirementSection),
637
+ priority: textOf(row.requirementPriority),
638
+ },
639
+ controls: new Map(),
640
+ };
641
+ entry.controls.set(controlId, control);
642
+ byRequirement.set(requirementId, entry);
643
+ }
644
+ return {
645
+ failingRequirements: [...byRequirement.values()]
646
+ .sort((a, b) => compareRequirements(a.requirement, b.requirement))
647
+ .map(({ requirement, controls: failing }) => ({
648
+ ...requirement,
649
+ failingControls: [...failing.values()],
650
+ })),
651
+ failingControls: [...controls.values()],
652
+ };
653
+ }
654
+ function cutShort(read) {
655
+ return read.more;
656
+ }
657
+ /**
658
+ * The drill from two graph queries, run at once. On j1dev that morning the apps-api drill skipped
659
+ * every requirement lookup on time in every drill of a framework with failures, while J1QL over
660
+ * `ccm_*` answered in about 100 ms (2026-10-15). Null, for the apps-api path, when the id cannot
661
+ * be interpolated or either query failed; a query that ran out of time is a skip, since no time is
662
+ * left for another path either.
663
+ */
664
+ async function graphDrill(client, frameworkId, deadlineAt, timings) {
665
+ if (!GRAPH_FRAMEWORK_ID.test(frameworkId))
666
+ return null;
667
+ const [failing, noData] = await timed(timings, 'drillGraph', () => Promise.all([
668
+ runGraphQuery(client, failingPairsQuery(frameworkId), deadlineAt, exports.GRAPH_MAX_PAGES),
669
+ runGraphQuery(client, noDataQuery(frameworkId), deadlineAt, exports.GRAPH_MAX_PAGES),
670
+ ]));
671
+ const failed = [failing, noData].find((read) => read.kind === 'failed');
672
+ if (failed) {
673
+ console.error('Error reading the drill from the graph; reading it from the API:', failed);
674
+ return null;
675
+ }
676
+ const grouped = failing.kind === 'rows'
677
+ ? groupPairs(failing.rows)
678
+ : { failingRequirements: [], failingControls: [] };
679
+ return {
680
+ passingWithoutData: noData.kind === 'rows'
681
+ ? {
682
+ count: passesWithoutData(noData.rows),
683
+ truncated: cutShort(noData),
684
+ }
685
+ : { skipped: 'time_budget' },
686
+ ...grouped,
687
+ failingControlsTruncated: failing.kind !== 'rows' || cutShort(failing),
688
+ requirementLookupsSkipped: 0,
689
+ /** The scorecard then says how many failing controls went unread. */
690
+ failingTimedOut: failing.kind === 'timeout',
691
+ drillSource: 'graph',
692
+ };
693
+ }
694
+ /** The drill: from the graph, or from the API when the graph cannot answer. */
695
+ async function drillFramework(client, frameworkId, startedAt, timings) {
696
+ const deadlineAt = startedAt + exports.SUMMARY_READ_DEADLINE_MS;
697
+ const graph = await graphDrill(client, frameworkId, deadlineAt, timings);
698
+ if (graph)
699
+ return graph;
700
+ const api = await apiDrill(client, frameworkId, deadlineAt, timings);
701
+ return { ...api, failingTimedOut: false, drillSource: 'api' };
702
+ }
703
+ /**
704
+ * How many failing controls a timed-out graph read left unread: the scorecard's count, which is
705
+ * CCM's own, else none known. A completed read reports its own skips.
706
+ */
707
+ function lookupSkips(drill, stats) {
708
+ if (!drill.failingTimedOut) {
709
+ return {
710
+ requirementLookupsSkipped: drill.requirementLookupsSkipped,
711
+ ...('requirementLookupsSkippedBy' in drill
712
+ ? { requirementLookupsSkippedBy: drill.requirementLookupsSkippedBy }
713
+ : {}),
714
+ };
715
+ }
716
+ const unread = stats?.numberOfFailingControls ?? 0;
717
+ return {
718
+ requirementLookupsSkipped: unread,
719
+ ...(unread > 0
720
+ ? { requirementLookupsSkippedBy: { timeBudget: unread, cap: 0, readFailed: 0 } }
721
+ : {}),
722
+ };
723
+ }
724
+ /**
725
+ * A warning when the graph's failing controls and the scorecard's count disagree. The scorecard is
726
+ * CCM's own count; the graph is refreshed after each evaluation, so the two can differ until then.
727
+ */
728
+ function drillWarning(drill, stats) {
729
+ const counted = stats?.numberOfFailingControls;
730
+ if (drill.drillSource !== 'graph' || drill.failingControlsTruncated)
731
+ return null;
732
+ if (typeof counted !== 'number' || counted === drill.failingControls.length)
733
+ return null;
734
+ return (`The drill lists ${drill.failingControls.length} failing controls from the graph, and the ` +
735
+ `scorecard counts ${counted}. CCM refreshes the graph after each evaluation, so the two can ` +
736
+ 'differ until then.');
737
+ }
738
+ /** The drilled framework's scorecard, sections from its stats, and its failing requirements. */
739
+ function frameworkDrill(frameworkId, meta, stats, drill, subdomain) {
740
+ // `failingTimedOut` and `requirementLookupsSkipped` become `lookupSkips` below.
741
+ const { passingWithoutData, failingTimedOut, requirementLookupsSkipped, ...rest } = drill;
742
+ void failingTimedOut;
743
+ void requirementLookupsSkipped;
744
+ const score = frameworkScore(meta ?? { id: frameworkId, name: null }, stats, subdomain);
745
+ return {
746
+ ...score,
747
+ controls: score.controls && {
748
+ ...score.controls,
749
+ passingWithoutData: 'count' in passingWithoutData ? passingWithoutData.count : null,
750
+ },
751
+ ...('skipped' in passingWithoutData
752
+ ? { passingWithoutDataSkipped: passingWithoutData.skipped }
753
+ : {}),
754
+ ...('truncated' in passingWithoutData && passingWithoutData.truncated
755
+ ? { passingWithoutDataTruncated: true }
756
+ : {}),
757
+ // Null, not empty, when the stats were not read: an empty list beside unread stats read as
758
+ // "this framework has no sections" on j1dev (2026-10-15).
759
+ sections: stats
760
+ ? (stats.sectionStats ?? []).map((section) => ({
761
+ section: section.sectionName,
762
+ requirements: section.numberOfRequirements,
763
+ passing: section.numberOfPassingRequirements,
764
+ failing: section.numberOfFailingRequirements,
765
+ }))
766
+ : null,
767
+ ...rest,
768
+ ...lookupSkips(drill, stats),
769
+ failingControls: drill.failingControls.map((control) => ({
770
+ ...control,
771
+ url: controlUrl(control.id, subdomain),
772
+ })),
773
+ failingRequirements: drill.failingRequirements.map((requirement) => ({
774
+ ...requirement,
775
+ failingControls: requirement.failingControls.map((control) => ({
776
+ ...control,
777
+ url: controlUrl(control.id, subdomain),
778
+ })),
779
+ })),
780
+ };
781
+ }
782
+ /** `frameworkId` is an array on the graph entity; a lone string is read as a list of one. */
783
+ function idList(value) {
784
+ if (Array.isArray(value)) {
785
+ return value.filter((entry) => typeof entry === 'string');
786
+ }
787
+ return typeof value === 'string' ? [value] : [];
788
+ }
789
+ /**
790
+ * The J1QL that names controls, in the form apps' own control reads use. Every id has passed the
791
+ * CONTROL_ID_FORBIDDEN check, so none can close its quoted literal.
792
+ */
793
+ function controlNameQuery(controlIds) {
794
+ const literals = controlIds.map((id) => `'${id}'`);
795
+ const condition = literals.length === 1 ? literals[0] : `(${literals.join(' OR ')})`;
796
+ return (`FIND ccm_control WITH id = ${condition} AS c ` +
797
+ 'RETURN c.id AS controlId, c.name AS controlName, c.frameworkId AS frameworkIds LIMIT 250');
798
+ }
799
+ /**
800
+ * Names and framework membership for the listed attestations' controls, from one graph query.
801
+ * The control pages this replaces took 19–30 s on every real framework on j1dev and 13–19 s on a
802
+ * six-control fixture, so every real drill fell back to account scope with every name null; the
803
+ * tester's own J1QL over ccm_control answered in 2.4 s (2026-10-14). Null when the query fails or
804
+ * outlives the deadline.
805
+ */
806
+ async function readGraphControls(client, controlIds, deadlineAt) {
807
+ if (controlIds.length === 0)
808
+ return new Map();
809
+ const read = await runGraphQuery(client, controlNameQuery(controlIds), deadlineAt);
810
+ if (read.kind === 'failed') {
811
+ console.error('Error naming the controls of listed attestations:', read.error);
812
+ }
813
+ if (read.kind !== 'rows')
814
+ return null;
815
+ const controls = new Map();
816
+ for (const row of read.rows) {
817
+ if (typeof row.controlId !== 'string')
818
+ continue;
819
+ controls.set(row.controlId, {
820
+ name: typeof row.controlName === 'string' ? row.controlName : null,
821
+ frameworkIds: idList(row.frameworkIds),
822
+ });
823
+ }
824
+ return controls;
825
+ }
826
+ /**
827
+ * One page, raced against `deadlineAt` and polling no longer than the time left. A poll budget
828
+ * that runs out is a timeout, like the race; anything else, a malformed answer included, is a
829
+ * failure.
830
+ */
831
+ async function readGraphPage(client, query, cursor, deadlineAt) {
832
+ if (Date.now() >= deadlineAt)
833
+ return { kind: 'timeout' };
834
+ try {
835
+ const result = await withDeadline(client.executeJ1qlQuery({
836
+ query,
837
+ ...(cursor === undefined ? {} : { cursor }),
838
+ maxPollAttempts: Math.max(1, Math.ceil((deadlineAt - Date.now()) / 1000)),
839
+ }), deadlineAt);
840
+ if (result === DEADLINE_PASSED)
841
+ return { kind: 'timeout' };
842
+ const { data, cursor: next } = (result ?? {});
843
+ if (!Array.isArray(data)) {
844
+ throw new Error('Invalid response structure from JupiterOne API: a graph query returned no data');
845
+ }
846
+ const rows = data.filter((row) => typeof row === 'object' && row !== null);
847
+ return {
848
+ kind: 'page',
849
+ rows,
850
+ cursor: typeof next === 'string' && next.length > 0 ? next : null,
851
+ };
852
+ }
853
+ catch (error) {
854
+ return error instanceof j1ql_service_js_1.J1qlQueryTimeoutError ? { kind: 'timeout' } : { kind: 'failed', error };
855
+ }
856
+ }
857
+ /**
858
+ * A graph query's rows over up to `maxPages` pages of its cursor, every page inside `deadlineAt`.
859
+ * `more` says the rows may be cut short: a cursor left after the last page, a later page that ran
860
+ * out of time, or a page that came back full with no cursor after it, which the query's LIMIT may
861
+ * have cut (the cursor, as execute-j1ql-query reports it, is the authoritative "more" signal; a
862
+ * page can also come back short while more remain). A first page that runs out of time is a
863
+ * timeout, and a failed page fails the read.
864
+ */
865
+ async function runGraphQuery(client, query, deadlineAt, maxPages = 1) {
866
+ const rows = [];
867
+ let cursor;
868
+ for (let page = 0; page < maxPages; page++) {
869
+ const read = await readGraphPage(client, query, cursor, deadlineAt);
870
+ if (read.kind === 'failed')
871
+ return read;
872
+ if (read.kind === 'timeout')
873
+ return page === 0 ? read : { kind: 'rows', rows, more: true };
874
+ rows.push(...read.rows);
875
+ if (read.cursor === null) {
876
+ return { kind: 'rows', rows, more: read.rows.length >= exports.GRAPH_PAGE_SIZE };
877
+ }
878
+ cursor = read.cursor;
879
+ }
880
+ return { kind: 'rows', rows, more: true };
881
+ }
882
+ /** An unknown expiry sorts as the oldest, so it never pushes a dated lapse off the list. */
883
+ function expiryMs(attestation) {
884
+ return Number.isFinite(attestation.expiresOn) ? attestation.expiresOn : 0;
885
+ }
886
+ function wholeDays(ms) {
887
+ return Number.isFinite(ms) ? Math.max(0, Math.floor(ms / DAY_MS)) : null;
888
+ }
889
+ /**
890
+ * The control ids to name, in the order they matter: the expired attestations' controls first,
891
+ * most recently expired first, since they fail controls now; then the expiring ones, soonest
892
+ * first. An id the API would reject is never interpolated into the query.
893
+ */
894
+ function idsToName(lapsed, expiring) {
895
+ const soonest = expiring === 'unavailable' ? [] : [...expiring].sort((a, b) => expiryMs(a) - expiryMs(b));
896
+ const ordered = [...(lapsed === 'unavailable' ? [] : lapsed), ...soonest];
897
+ return [...new Set(ordered.map((attestation) => attestation.controlId))]
898
+ .filter(isString)
899
+ .filter((id) => !exports.CONTROL_ID_FORBIDDEN.test(id));
900
+ }
901
+ function controlNameOf(attestation, lookup) {
902
+ return attestation.controlId ? (lookup.controls?.get(attestation.controlId)?.name ?? null) : null;
903
+ }
904
+ /** Asked about, and the read has no row for it. */
905
+ function unresolved(attestation, lookup) {
906
+ const id = attestation.controlId;
907
+ return lookup.controls !== null && !(id && (lookup.controls.has(id) || lookup.beyondCap.has(id)));
908
+ }
909
+ /**
910
+ * The ACTIVE attestations expiring within the window and the EXPIRED ones nobody revoked, then
911
+ * one graph read naming their controls. Started with the request and depending on nothing else:
912
+ * on j1dev the lists waited 4–21 s for the framework list and then took 24–27 s themselves, so the
913
+ * names query, 1.9–3.3 s whenever it ran, never ran on a slow drill (2026-10-15).
914
+ */
915
+ async function readAttestations(client, expiringWithinDays, timings, deadlineAt, abandoned) {
916
+ const [expiring, expired] = await timed(timings, 'attestations', () => Promise.all([
917
+ client.listAttestations({ expiringWithinDays, state: 'ACTIVE' }).catch(degradeOnAccessDenied),
918
+ // EXPIRED is `revoked != true AND expiresOn <= now` on the API, so a revoked one is not here.
919
+ client.listAttestations({ state: 'EXPIRED' }).catch(degradeOnAccessDenied),
920
+ ]));
921
+ const lapsed = expired === 'unavailable' ? expired : [...expired].sort((a, b) => expiryMs(b) - expiryMs(a));
922
+ const listedAny = [expiring, lapsed].some((list) => list !== 'unavailable' && list.length > 0);
923
+ const ids = idsToName(lapsed, expiring);
924
+ const named = listedAny && !abandoned.value;
925
+ return {
926
+ expiring,
927
+ lapsed,
928
+ lookup: {
929
+ controls: named
930
+ ? await timed(timings, 'controlNames', () => readGraphControls(client, ids.slice(0, exports.MAX_NAMED_CONTROLS), deadlineAt))
931
+ : new Map(),
932
+ beyondCap: new Set(ids.slice(exports.MAX_NAMED_CONTROLS)),
933
+ },
934
+ };
935
+ }
936
+ /**
937
+ * Both attestation lists, on a drill kept to the framework's controls: listing them account-wide
938
+ * on a drill put another framework's attestation in the AI-ASM report on j1dev (2026-10-14). An
939
+ * attestation whose control the read has no row for stays listed with a null name: the graph can
940
+ * lag a control created moments ago, and dropping a real framework attestation is the worse
941
+ * error. When the read failed, nothing can be scoped, so both lists stay account-wide and `scope`
942
+ * says so. Past the naming cap, controls were never read, so their attestations could be in any
943
+ * framework: then the lists stay account-wide too, rather than claim a scope for attestations no
944
+ * read checked (PR #55 review). The expired list stops at MAX_EXPIRED_ATTESTATIONS after scoping.
945
+ */
946
+ function scopeAttestations(named, frameworkId) {
947
+ const { lookup, lapsed } = named;
948
+ const scoped = frameworkId !== undefined && lookup.controls !== null && lookup.beyondCap.size === 0;
949
+ const inScope = (attestation) => {
950
+ const control = attestation.controlId ? lookup.controls?.get(attestation.controlId) : undefined;
951
+ return !scoped || !control || control.frameworkIds.includes(frameworkId ?? '');
952
+ };
953
+ const now = Date.now();
954
+ const expiring = named.expiring === 'unavailable' ? [] : named.expiring.filter(inScope);
955
+ const expired = lapsed === 'unavailable' ? [] : lapsed.filter(inScope);
956
+ const shownExpired = expired.slice(0, exports.MAX_EXPIRED_ATTESTATIONS);
957
+ const row = (attestation) => ({
958
+ ...projectAttestation(attestation),
959
+ controlName: controlNameOf(attestation, lookup),
960
+ });
961
+ return {
962
+ expiring: named.expiring === 'unavailable'
963
+ ? named.expiring
964
+ : expiring.map((attestation) => ({
965
+ ...row(attestation),
966
+ daysUntilExpiry: wholeDays(attestation.expiresOn - now),
967
+ })),
968
+ expired: lapsed === 'unavailable'
969
+ ? lapsed
970
+ : shownExpired.map((attestation) => ({
971
+ ...row(attestation),
972
+ daysSinceExpiry: wholeDays(now - attestation.expiresOn),
973
+ })),
974
+ expiredTruncated: expired.length > exports.MAX_EXPIRED_ATTESTATIONS,
975
+ namesUnavailable: lookup.controls === null || lookup.beyondCap.size > 0,
976
+ unresolved: [...expiring, ...shownExpired].filter((attestation) => unresolved(attestation, lookup)).length,
977
+ scope: scoped ? 'framework' : 'account',
978
+ };
979
+ }
980
+ /**
981
+ * The attestation fields of the summary. The scope and the names flags describe whichever lists
982
+ * were read; `controlNamesUnavailable`, `controlNamesUnresolved` and
983
+ * `expiredAttestationsTruncated` appear only when set.
984
+ */
985
+ function attestationFields(read, subdomain) {
986
+ const linked = (rows) => rows === 'unavailable'
987
+ ? rows
988
+ : rows.map((row) => ({ ...row, url: controlUrl(row.controlId, subdomain) }));
989
+ const anyRead = read.expiring !== 'unavailable' || read.expired !== 'unavailable';
990
+ return {
991
+ expiringAttestations: linked(read.expiring),
992
+ expiredAttestations: linked(read.expired),
993
+ ...(read.expiredTruncated ? { expiredAttestationsTruncated: true } : {}),
994
+ ...(anyRead ? { expiringAttestationsScope: read.scope } : {}),
995
+ ...(read.namesUnavailable ? { controlNamesUnavailable: true } : {}),
996
+ ...(read.unresolved > 0 ? { controlNamesUnresolved: read.unresolved } : {}),
997
+ };
998
+ }
999
+ function isString(value) {
1000
+ return typeof value === 'string' && value.length > 0;
1001
+ }
1002
+ /**
1003
+ * A framework name against the list the summary already reads: an exact id, then an exact name
1004
+ * ignoring case, then a single partial match. Names repeat (j1dev holds "SOC 2 Trust Services
1005
+ * Criteria" twice and "CIS GitHub Benchmark v1.1.0" five times, 2026-10-14), so several exact
1006
+ * matches are `ambiguous` rather than a guess.
1007
+ */
1008
+ function pickByName(frameworks, name) {
1009
+ const byId = frameworks.find((framework) => framework.id === name);
1010
+ if (byId)
1011
+ return { kind: 'drill', id: byId.id, meta: byId, resolution: 'id' };
1012
+ const folded = name.toLowerCase();
1013
+ const named = (framework) => (framework.name ?? '').trim().toLowerCase();
1014
+ const exact = frameworks.filter((framework) => named(framework) === folded);
1015
+ if (exact.length === 1)
1016
+ return { kind: 'drill', id: exact[0].id, meta: exact[0], resolution: 'name' };
1017
+ if (exact.length > 1)
1018
+ return { kind: 'ambiguous', matches: exact };
1019
+ const partial = frameworks.filter((framework) => named(framework).includes(folded));
1020
+ if (partial.length === 1) {
1021
+ return { kind: 'drill', id: partial[0].id, meta: partial[0], resolution: 'partial' };
1022
+ }
1023
+ return partial.length > 1 ? { kind: 'ambiguous', matches: partial } : { kind: 'not_found' };
1024
+ }
1025
+ function pickFramework(frameworks, complete, request) {
1026
+ if (request.frameworkName !== undefined)
1027
+ return pickByName(frameworks, request.frameworkName);
1028
+ const { frameworkId } = request;
1029
+ if (frameworkId === undefined)
1030
+ return { kind: 'all' };
1031
+ const meta = frameworks.find((framework) => framework.id === frameworkId);
1032
+ // Only a complete walk proves absence; past the page cap the framework may still exist, so the
1033
+ // drill goes ahead and `frameworksComplete: false` says the list is partial.
1034
+ if (!meta && complete)
1035
+ return { kind: 'not_found' };
1036
+ return { kind: 'drill', id: frameworkId, meta, resolution: 'id' };
1037
+ }
1038
+ /** A framework to choose from: who it is and whether it imported, with no counts. */
1039
+ /**
1040
+ * A framework to choose from: who it is, where it came from and whether it imported, with no
1041
+ * counts. Two j1dev frameworks named "SOC 2 Trust Services Criteria" differed only by id until
1042
+ * source, sourceId and owner were shown (2026-10-15).
1043
+ */
1044
+ function frameworkListing(framework, subdomain) {
1045
+ return {
1046
+ id: framework.id,
1047
+ name: framework.name,
1048
+ source: framework.source ?? null,
1049
+ sourceId: framework.sourceId ?? null,
1050
+ owner: framework.owner ?? null,
1051
+ importStatus: framework.status?.status ?? null,
1052
+ url: frameworkUrl(framework.id, subdomain),
1053
+ };
1054
+ }
1055
+ /**
1056
+ * The `ambiguous` or `framework_not_found` answer: what was asked, and what to choose from. Both
1057
+ * list every framework in `frameworks`: a host that cached the schema from before `ambiguous`
1058
+ * existed requires the key, and rejected the by-name call that left it out (ECS 184, 2026-10-15).
1059
+ */
1060
+ function unresolvedFramework(pick, request, frameworks, subdomain) {
1061
+ const asked = request.frameworkName !== undefined
1062
+ ? { frameworkName: request.frameworkName }
1063
+ : { frameworkId: request.frameworkId };
1064
+ const listing = {
1065
+ frameworksComplete: frameworks.complete,
1066
+ frameworks: frameworks.frameworks.map((framework) => frameworkListing(framework, subdomain)),
1067
+ };
1068
+ if (pick.kind === 'not_found') {
1069
+ return {
1070
+ outcome: 'framework_not_found',
1071
+ ...asked,
1072
+ frameworkResolution: 'not_found',
1073
+ ...listing,
1074
+ };
1075
+ }
1076
+ return {
1077
+ outcome: 'ambiguous',
1078
+ ...asked,
1079
+ frameworkResolution: 'ambiguous',
1080
+ ...listing,
1081
+ candidates: pick.matches
1082
+ .slice(0, MAX_CANDIDATES)
1083
+ .map((framework) => frameworkListing(framework, subdomain)),
1084
+ candidateCount: pick.matches.length,
1085
+ };
1086
+ }
1087
+ async function complianceSummary(client, request, expiringWithinDays) {
1088
+ const startedAt = Date.now();
1089
+ const timings = {};
1090
+ const abandoned = { value: false };
1091
+ try {
1092
+ return await summarize(client, request, expiringWithinDays, {
1093
+ startedAt,
1094
+ timings,
1095
+ abandoned,
1096
+ });
1097
+ }
1098
+ finally {
1099
+ abandoned.value = true;
1100
+ }
1101
+ }
1102
+ async function summarize(client, request, expiringWithinDays, run) {
1103
+ const { startedAt, timings } = run;
1104
+ const subdomainRead = readSubdomain(client, timings);
1105
+ const attestationsRead = readAttestations(client, expiringWithinDays, timings, startedAt + exports.SUMMARY_READ_DEADLINE_MS, run.abandoned);
1106
+ // Awaited below on every path that uses it; this keeps an early answer, or a failed framework
1107
+ // read, from leaving its rejection unhandled.
1108
+ attestationsRead.catch(() => undefined);
1109
+ const early = request.frameworkId !== undefined ? startDrill(client, request.frameworkId, run) : undefined;
1110
+ const listed = await timed(timings, 'frameworks', () => client.listAllControlFrameworks());
1111
+ const { frameworks, complete } = listed;
1112
+ const pick = pickFramework(frameworks, complete, request);
1113
+ if (pick.kind === 'ambiguous' || pick.kind === 'not_found') {
1114
+ const subdomain = await subdomainRead;
1115
+ // A copy: the attestation reads still in flight would otherwise write into this answer.
1116
+ return { ...unresolvedFramework(pick, request, listed, subdomain), timingsMs: { ...timings } };
1117
+ }
1118
+ const frameworkId = pick.kind === 'drill' ? pick.id : undefined;
1119
+ const meta = pick.kind === 'drill' ? pick.meta : undefined;
1120
+ // A drill reads and scores one framework: a caller who names one is asking about that one.
1121
+ const scored = frameworkId ? [meta ?? { id: frameworkId, name: null }] : frameworks;
1122
+ const drillReads = frameworkId === undefined ? undefined : (early ?? startDrill(client, frameworkId, run));
1123
+ const [statsRead, named, drill] = await Promise.all([
1124
+ drillReads?.stats ?? scorecardStats(client, frameworks, run),
1125
+ attestationsRead,
1126
+ drillReads?.drill ?? Promise.resolve(null),
1127
+ ]);
1128
+ const attestations = scopeAttestations(named, frameworkId);
1129
+ const statsById = new Map(statsRead.stats.map((entry) => [entry.id, entry]));
1130
+ const drillWarned = drill && frameworkId ? drillWarning(drill, statsById.get(frameworkId)) : null;
1131
+ const warnings = [
1132
+ ...(drillWarned ? [drillWarned] : []),
1133
+ ...summaryWarnings(frameworkId, attestations),
1134
+ ];
1135
+ // Absent rather than null when no chunk finished: `timingsMs` is declared as numbers only, and
1136
+ // hosts validate against the schema they cached.
1137
+ if (statsRead.chunkMaxMs !== null)
1138
+ timings.statsChunkMaxMs = statsRead.chunkMaxMs;
1139
+ const subdomain = await subdomainRead;
1140
+ return {
1141
+ outcome: 'ok',
1142
+ ...(pick.kind === 'drill' ? { frameworkResolution: pick.resolution } : {}),
1143
+ frameworksComplete: complete,
1144
+ frameworks: scored.map((framework) => frameworkScore(framework, statsById.get(framework.id), subdomain)),
1145
+ ...(statsRead.incomplete.length > 0 ? { statsIncomplete: statsRead.incomplete } : {}),
1146
+ ...(frameworkId && drill
1147
+ ? {
1148
+ framework: frameworkDrill(frameworkId, meta, statsById.get(frameworkId), drill, subdomain),
1149
+ }
1150
+ : {}),
1151
+ ...attestationFields(attestations, subdomain),
1152
+ attestationsExpiringWithinDays: expiringWithinDays,
1153
+ ...(warnings.length > 0 ? { warnings } : {}),
1154
+ timingsMs: timings,
1155
+ };
1156
+ }
1157
+ /**
1158
+ * Starts a drill's reads. An id needs no framework list, so a `frameworkId` call starts them with
1159
+ * the request: the list took 4–21 s on j1dev before any drill read began (2026-10-15). A name
1160
+ * starts them once the list has resolved it.
1161
+ */
1162
+ function startDrill(client, frameworkId, run) {
1163
+ const stats = timed(run.timings, 'stats', () => readStats(client, [frameworkId], run.startedAt + exports.SUMMARY_READ_DEADLINE_MS, {
1164
+ withSections: true,
1165
+ }));
1166
+ const drill = drillFramework(client, frameworkId, run.startedAt, run.timings);
1167
+ // Awaited once the framework resolves; an early answer leaves them behind.
1168
+ stats.catch(() => undefined);
1169
+ drill.catch(() => undefined);
1170
+ return { stats, drill };
1171
+ }
1172
+ /**
1173
+ * Every framework's counts for the scorecard, without sections: a drill alone shows them. The
1174
+ * backend computes requirement stats per framework, so this read grows with every framework (the
1175
+ * bare summary took 39 s on j1dev's 60 frameworks, 2026-10-14).
1176
+ */
1177
+ function scorecardStats(client, frameworks, run) {
1178
+ if (frameworks.length === 0)
1179
+ return Promise.resolve({ stats: [], incomplete: [], chunkMaxMs: null });
1180
+ return timed(run.timings, 'stats', () => readStats(client, frameworks.map((framework) => framework.id), run.startedAt + exports.SUMMARY_READ_DEADLINE_MS, { withSections: false }));
1181
+ }
1182
+ const WARNING_ACCOUNT_WIDE_ATTESTATIONS = "The attestation lists are account-wide: the framework's controls could not be confirmed.";
1183
+ /**
1184
+ * Sentences an assistant should pass on with the answer. A drill whose attestation lists stayed
1185
+ * account-wide is the one the tester would have misreported: "what lapsed in SOC 2?" answered with
1186
+ * 15 attestations, none of them SOC 2's (j1dev, 2026-10-15).
1187
+ */
1188
+ function summaryWarnings(frameworkId, attestations) {
1189
+ return frameworkId !== undefined && attestations.scope === 'account'
1190
+ ? [WARNING_ACCOUNT_WIDE_ATTESTATIONS]
1191
+ : [];
1192
+ }
1193
+ /** The single hit an OU reference names, or every hit it could mean. */
1194
+ function matchOrgUnits(hits, wanted) {
1195
+ const byId = hits.filter((hit) => hit.ou._id === wanted);
1196
+ if (byId.length > 0)
1197
+ return byId.slice(0, 1);
1198
+ const folded = wanted.toLowerCase();
1199
+ const byName = hits.filter((hit) => hit.ou.displayName?.trim().toLowerCase() === folded);
1200
+ return byName.length > 0 ? byName : hits;
1201
+ }
1202
+ function orgUnitCandidate(hit) {
1203
+ return {
1204
+ id: hit.ou._id,
1205
+ displayName: hit.ou.displayName,
1206
+ namespace: hit.namespace.slug,
1207
+ active: hit.ou.active,
1208
+ assetCount: hit.ou.assetCount,
1209
+ };
1210
+ }
1211
+ /**
1212
+ * An OU reference as the API's `ou` filter takes it. A reference containing a colon is taken as an
1213
+ * `_id` and used as given, since entity OU tokens read `<namespace-slug>:<value>`. Anything else
1214
+ * is searched for in every enabled namespace (up to MAX_OU_NAMESPACES): an exact id, then an exact
1215
+ * display name, then a lone search hit. A namespace whose search fails is dropped and counted; if
1216
+ * every one fails there is nothing to report, so it throws.
1217
+ */
1218
+ async function resolveOrgUnit(client, orgUnit) {
1219
+ const startedAt = Date.now();
1220
+ const wanted = orgUnit.trim();
1221
+ if (wanted.includes(':')) {
1222
+ return {
1223
+ kind: 'resolved',
1224
+ orgUnit: { id: wanted, displayName: null, namespace: null, resolvedBy: 'id_unverified' },
1225
+ };
1226
+ }
1227
+ const namespaces = await client.listOuNamespaces();
1228
+ const searched = namespaces.filter((ns) => ns.enabled !== false).slice(0, MAX_OU_NAMESPACES);
1229
+ const settled = await Promise.allSettled(searched.map((ns) => client.listOusByNamespace(ns.slug, wanted)));
1230
+ const failed = settled.filter((result) => result.status === 'rejected');
1231
+ if (failed.length > 0 && failed.length === searched.length)
1232
+ throw failed[0].reason;
1233
+ const hits = settled.flatMap((result, index) => result.status === 'fulfilled'
1234
+ ? result.value.map((ou) => ({ ou, namespace: searched[index] }))
1235
+ : []);
1236
+ const matches = matchOrgUnits(hits, wanted);
1237
+ if (matches.length === 1) {
1238
+ const [{ ou, namespace }] = matches;
1239
+ return {
1240
+ kind: 'resolved',
1241
+ orgUnit: {
1242
+ id: ou._id,
1243
+ displayName: ou.displayName,
1244
+ namespace: namespace.slug,
1245
+ resolvedBy: ou._id === wanted ? 'id' : 'name',
1246
+ },
1247
+ };
1248
+ }
1249
+ if (matches.length > 1) {
1250
+ return {
1251
+ kind: 'outcome',
1252
+ payload: {
1253
+ outcome: 'ambiguous',
1254
+ ouResolution: 'ambiguous',
1255
+ candidates: matches.slice(0, MAX_CANDIDATES).map(orgUnitCandidate),
1256
+ candidateCount: matches.length,
1257
+ namespacesFailed: failed.length,
1258
+ },
1259
+ };
1260
+ }
1261
+ return {
1262
+ kind: 'outcome',
1263
+ payload: {
1264
+ outcome: 'org_unit_not_found',
1265
+ ouResolution: 'not_found',
1266
+ namespaces: searched.map((ns, index) => ({
1267
+ slug: ns.slug,
1268
+ name: ns.name,
1269
+ failed: settled[index].status === 'rejected',
1270
+ })),
1271
+ namespacesNotSearched: namespaces.length - searched.length,
1272
+ units: await suggestOrgUnits(client, searched, startedAt + ORG_UNIT_SUGGESTION_DEADLINE_MS),
1273
+ },
1274
+ };
1275
+ }
1276
+ /** Units an `org_unit_not_found` lists per searched namespace, to offer by name. */
1277
+ exports.ORG_UNIT_SUGGESTIONS = 10;
1278
+ /** From the start of the OU resolution; suggestions not back by then are left out. */
1279
+ const ORG_UNIT_SUGGESTION_DEADLINE_MS = 20_000;
1280
+ /**
1281
+ * Up to ORG_UNIT_SUGGESTIONS units of each searched namespace, unfiltered, so the assistant can
1282
+ * offer real names: on j1dev "AWS Production" matched nothing, and the tester found "Gaston AWS"
1283
+ * only from a unit token on a failing user (2026-10-15). A namespace whose read fails or is late
1284
+ * offers none; the answer does not depend on them.
1285
+ */
1286
+ async function suggestOrgUnits(client, namespaces, deadlineAt) {
1287
+ const reads = await Promise.all(namespaces.map(async (ns) => {
1288
+ if (Date.now() >= deadlineAt)
1289
+ return [];
1290
+ try {
1291
+ const units = await withDeadline(client.listOusByNamespace(ns.slug, undefined, exports.ORG_UNIT_SUGGESTIONS), deadlineAt);
1292
+ return units === DEADLINE_PASSED ? [] : units.slice(0, exports.ORG_UNIT_SUGGESTIONS);
1293
+ }
1294
+ catch (error) {
1295
+ console.error('Error listing organizational units to suggest:', error);
1296
+ return [];
1297
+ }
1298
+ }));
1299
+ return reads.flatMap((units, index) => units.map((ou) => ({
1300
+ id: ou._id,
1301
+ displayName: ou.displayName ?? null,
1302
+ namespace: namespaces[index].slug,
1303
+ })));
1304
+ }
1305
+ /** `ControlFilterInput` from the keys the caller set. An empty list filters nothing: dropped. */
1306
+ function controlFilter(params, ouId) {
1307
+ const filter = {
1308
+ searchText: params.search,
1309
+ status: params.status,
1310
+ states: params.states,
1311
+ effectiveness: params.effectiveness,
1312
+ hasValidAttestation: params.hasValidAttestation,
1313
+ owner: params.owner,
1314
+ catalogs: params.catalogs,
1315
+ mitreTechniques: params.mitreTechniques,
1316
+ frameworkId: params.frameworkId ? [params.frameworkId] : undefined,
1317
+ source: params.source,
1318
+ ou: ouId ? [ouId] : undefined,
1319
+ };
1320
+ const set = Object.entries(filter).filter(([, value]) => value !== undefined && !(Array.isArray(value) && value.length === 0));
1321
+ return set.length > 0 ? Object.fromEntries(set) : undefined;
1322
+ }
1323
+ function failingTestCount(tests) {
1324
+ return tests ? tests.filter((test) => !test.deleted && test.status === 'FAIL').length : null;
1325
+ }
1326
+ function controlRow(control, names, subdomain) {
1327
+ return {
1328
+ id: control.id,
1329
+ name: control.name,
1330
+ url: controlUrl(control.id, subdomain),
1331
+ identifier: control.identifier,
1332
+ catalog: control.catalog,
1333
+ source: control.source,
1334
+ sourceId: control.sourceId,
1335
+ state: control.state,
1336
+ status: control.status,
1337
+ effectiveStatus: control.effectiveStatus,
1338
+ hasValidAttestation: control.hasValidAttestation,
1339
+ owner: control.owner,
1340
+ lastEvaluatedOn: control.lastEvaluatedOn,
1341
+ lastEvaluatedOnIso: toIso(control.lastEvaluatedOn),
1342
+ numberOfTests: control.numberOfTests,
1343
+ failingTests: failingTestCount(control.controlTests),
1344
+ frameworkIds: control.frameworkIds ?? [],
1345
+ frameworkNames: namesFor(control.frameworkIds, names),
1346
+ mitreTechnique: control.mitreTechnique,
1347
+ deleted: control.deleted,
1348
+ };
1349
+ }
1350
+ /**
1351
+ * A page read that failed on a caller's cursor. The cursor encodes the query of the call that
1352
+ * returned it, so one reused with other filters, edited or made up fails upstream: on j1dev, all
1353
+ * three came back as a bare "Internal server error" (2026-10-14). Nothing is retried, since the
1354
+ * same cursor with the same filters would fail the same way.
1355
+ */
1356
+ function cursorRejected(error) {
1357
+ const reason = error instanceof Error ? error.message : 'Unknown error';
1358
+ return refusal('cursor_rejected', `Error listing controls with this cursor: ${reason}. A cursor works only with the exact ` +
1359
+ 'filters of the call that returned it. Call again with those filters and that cursor, or ' +
1360
+ 'without `cursor` for the first page.');
1361
+ }
1362
+ /**
1363
+ * The controls page and the framework list that names its frameworks, read together. A page read
1364
+ * that fails on a cursor is answered as `cursor_rejected`; without a cursor, or when access was
1365
+ * refused, the failure is not the cursor's and keeps its own frame.
1366
+ */
1367
+ async function readControlsPage(client, input, timings) {
1368
+ const [pageRead, frameworksRead] = await Promise.allSettled([
1369
+ timed(timings, 'controls', () => client.listControls(input)),
1370
+ timed(timings, 'frameworks', () => client.listAllControlFrameworks()),
1371
+ ]);
1372
+ if (pageRead.status === 'rejected') {
1373
+ if (input.cursor === undefined || (0, errors_js_1.accessDeniedStatus)(pageRead.reason) !== null) {
1374
+ throw pageRead.reason;
1375
+ }
1376
+ return { kind: 'cursor_rejected', result: cursorRejected(pageRead.reason) };
1377
+ }
1378
+ if (frameworksRead.status === 'rejected')
1379
+ throw frameworksRead.reason;
1380
+ return { kind: 'read', page: pageRead.value, frameworks: frameworksRead.value.frameworks };
1381
+ }
1382
+ // ---------------------------------------------------------------------------------------------
1383
+ // get-control
1384
+ // ---------------------------------------------------------------------------------------------
1385
+ exports.STATUS_EXPLANATIONS = [
1386
+ 'not_live',
1387
+ 'failing_test',
1388
+ 'failing_expired_attestation',
1389
+ 'undetermined',
1390
+ 'passing_by_tests',
1391
+ 'passing_by_attestation',
1392
+ 'no_tests',
1393
+ 'no_datapoints',
1394
+ ];
1395
+ function passesByTests({ liveTests }) {
1396
+ return liveTests.some((test) => test.status === 'PASS');
1397
+ }
1398
+ function passesByAttestation({ facts, attestations }) {
1399
+ return (facts.hasValidAttestation === true ||
1400
+ attestations.some((attestation) => attestation.state === 'ACTIVE'));
1401
+ }
1402
+ /**
1403
+ * Why CCM stored the status it did, first match wins. The order is CCM's own recomputation
1404
+ * (apps, `controlTest/controlTestRuleEvaluationCompleted/updateControlStatus.ts`,
1405
+ * `recomputeControlStatus`): any failing test or any expired, unrevoked attestation fails the
1406
+ * control; otherwise any test with status PASS passes it; otherwise a valid attestation passes it;
1407
+ * otherwise it has no status. Only LIVE controls are evaluated. CCM never consults effectiveness,
1408
+ * so a test whose query saw no data (a GOOD test with zero rows) passes and counts;
1409
+ * `passingWithoutData` flags that case rather than this explanation hiding it. A stored FAIL these
1410
+ * facts cannot account for is `undetermined` rather than a guess: when the attestations could not
1411
+ * be read, or when nothing read passes the control either. When the facts do pass it, they are
1412
+ * explained, and the caller reports the stored FAIL as stale.
1413
+ */
1414
+ const STATUS_RULES = [
1415
+ ['not_live', ({ facts }) => facts.state !== 'LIVE'],
1416
+ ['failing_test', ({ liveTests }) => liveTests.some((test) => test.status === 'FAIL')],
1417
+ [
1418
+ 'failing_expired_attestation',
1419
+ ({ attestations }) => attestations.some((attestation) => attestation.state === 'EXPIRED'),
1420
+ ],
1421
+ [
1422
+ 'undetermined',
1423
+ (evidence) => evidence.facts.status === 'FAIL' &&
1424
+ (evidence.facts.attestations === 'unavailable' ||
1425
+ !(passesByTests(evidence) || passesByAttestation(evidence))),
1426
+ ],
1427
+ ['passing_by_tests', passesByTests],
1428
+ ['passing_by_attestation', passesByAttestation],
1429
+ [
1430
+ 'no_tests',
1431
+ ({ facts, liveTests }) => liveTests.length === 0 || facts.effectiveStatus === 'NO_TESTS',
1432
+ ],
1433
+ [
1434
+ 'no_datapoints',
1435
+ ({ facts, liveTests }) => facts.effectiveStatus === 'NO_DATAPOINTS' || liveTests.every((test) => !test.status),
1436
+ ],
1437
+ ];
1438
+ /** The status an explanation stands for, where it stands for one. */
1439
+ const EXPECTED_STATUS = {
1440
+ failing_test: 'FAIL',
1441
+ failing_expired_attestation: 'FAIL',
1442
+ passing_by_tests: 'PASS',
1443
+ passing_by_attestation: 'PASS',
1444
+ };
1445
+ /**
1446
+ * The status the facts call for, when CCM's stored status disagrees with them. CCM re-scores an
1447
+ * attested control within a day of an expiry and on its next test run, so the stored status can
1448
+ * trail the facts: on j1dev a control whose last attestation had lapsed 20 s before still read
1449
+ * PASS beside a `failing_expired_attestation` explanation (2026-10-14).
1450
+ */
1451
+ function staleStatus(explanation, stored) {
1452
+ const expected = EXPECTED_STATUS[explanation];
1453
+ if (expected === 'FAIL')
1454
+ return stored === 'FAIL' ? null : expected;
1455
+ if (expected === 'PASS')
1456
+ return stored === 'FAIL' ? expected : null;
1457
+ return null;
1458
+ }
1459
+ /** Why a control has the status it has, as one of STATUS_EXPLANATIONS. */
1460
+ function explainControlStatus(facts) {
1461
+ const evidence = {
1462
+ facts,
1463
+ liveTests: facts.tests.filter((test) => !test.deleted),
1464
+ // Unreadable attestations prove nothing either way, so they can neither fail nor pass it.
1465
+ attestations: facts.attestations === 'unavailable' ? [] : facts.attestations,
1466
+ };
1467
+ const rule = STATUS_RULES.find(([, applies]) => applies(evidence));
1468
+ return rule ? rule[0] : 'undetermined';
1469
+ }
1470
+ const SKIPPED = { latestEvaluationStatus: 'skipped', latestEvaluation: null };
1471
+ /** A live test backed by a rule — the only kind with evaluations to look up. */
1472
+ function hasEvaluations(test) {
1473
+ return !test.deleted && typeof test.referencedRuleId === 'string' && test.referencedRuleId !== '';
1474
+ }
1475
+ /** The descriptor for the test's own query (a test persists only `queries[0]`), else the first. */
1476
+ function pickDescriptor(descriptors, queryName) {
1477
+ const list = descriptors ?? [];
1478
+ return list.find((descriptor) => descriptor.name === queryName) ?? list[0];
1479
+ }
1480
+ function latestFromPage(test, results, moreInWindow) {
1481
+ const window = { evaluationsInWindow: results.length, moreInWindow };
1482
+ if (results.length === 0) {
1483
+ return { latestEvaluationStatus: 'none', latestEvaluation: null, ...window };
1484
+ }
1485
+ // The page's sort order is unverified, so the newest is picked here rather than assumed first.
1486
+ const latest = results.reduce((newest, entry) => entry.timestamp > newest.timestamp ? entry : newest);
1487
+ // A failed run is still the latest evaluation, but it stored no results to read.
1488
+ const descriptor = latest.tag === EVALUATION_FAILURE_TAG
1489
+ ? undefined
1490
+ : pickDescriptor(latest.rawDataDescriptors, test.queries?.[0]?.name);
1491
+ return {
1492
+ latestEvaluationStatus: 'found',
1493
+ latestEvaluation: {
1494
+ rawDataKey: descriptor?.rawDataKey ?? null,
1495
+ resultCount: descriptor?.recordCount ?? null,
1496
+ evaluatedOn: toIso(latest.timestamp),
1497
+ timestamp: latest.timestamp,
1498
+ tag: latest.tag ?? null,
1499
+ },
1500
+ ...window,
1501
+ };
1502
+ }
1503
+ /**
1504
+ * The latest evaluation of the rule behind a control test: the `rawDataKey` that
1505
+ * `get-rule-evaluation-query-results` turns into the assets the test scored.
1506
+ *
1507
+ * One page of the rule's evaluations from 30 days before the test's `lastEvaluatedOn` to now,
1508
+ * raced against `deadlineAt` (see `evaluationDeadline`). `none` without a
1509
+ * call for a deleted test or one with no rule; `skipped` past the deadline; `error` on a failed
1510
+ * read, which never fails the control read around it.
1511
+ */
1512
+ async function lookupLatestEvaluation(client, test, deadlineAt) {
1513
+ if (!hasEvaluations(test))
1514
+ return { latestEvaluationStatus: 'none', latestEvaluation: null };
1515
+ const now = Date.now();
1516
+ if (now >= deadlineAt)
1517
+ return SKIPPED;
1518
+ try {
1519
+ const page = await withDeadline(client.listRuleEvaluations({
1520
+ collectionType: 'RULE_EVALUATION',
1521
+ collectionOwnerId: test.referencedRuleId,
1522
+ beginTimestamp: (test.lastEvaluatedOn ?? now) - EVALUATION_WINDOW_MS,
1523
+ endTimestamp: now,
1524
+ limit: EVALUATION_PAGE_LIMIT,
1525
+ }), deadlineAt);
1526
+ if (page === DEADLINE_PASSED)
1527
+ return SKIPPED;
1528
+ if (!Array.isArray(page?.results)) {
1529
+ throw new Error('Invalid response structure from JupiterOne API: ' +
1530
+ 'listCollectionResults.results is not an array');
1531
+ }
1532
+ return latestFromPage(test, page.results, page.pageInfo?.hasNextPage === true);
1533
+ }
1534
+ catch (error) {
1535
+ console.error('Error looking up the latest control-test evaluation:', error);
1536
+ return { latestEvaluationStatus: 'error', latestEvaluation: null };
1537
+ }
1538
+ }
1539
+ /**
1540
+ * Every test's lookup, timed together, for MAX_EVALUATION_LOOKUPS rule-backed tests: the failing
1541
+ * ones first, then the rest in list order. In list order alone, a 50-test SOC 2 control on j1dev
1542
+ * with 19 failing tests got lookups for 4 of them (2026-10-14).
1543
+ */
1544
+ async function lookupLatestEvaluations(client, tests, deadlineAt) {
1545
+ const startedAt = Date.now();
1546
+ const backed = tests.filter(hasEvaluations);
1547
+ const failingFirst = [
1548
+ ...backed.filter((test) => test.status === 'FAIL'),
1549
+ ...backed.filter((test) => test.status !== 'FAIL'),
1550
+ ];
1551
+ const admitted = new Set(failingFirst.slice(0, exports.MAX_EVALUATION_LOOKUPS));
1552
+ const lookups = await Promise.all(tests.map((test) => hasEvaluations(test) && !admitted.has(test)
1553
+ ? Promise.resolve(SKIPPED)
1554
+ : lookupLatestEvaluation(client, test, deadlineAt)));
1555
+ return { lookups, ms: Date.now() - startedAt };
1556
+ }
1557
+ const LOOKUP_KEYS = ['controlId', 'identifier', 'controlName'];
1558
+ /**
1559
+ * `includeDeletedTests` reaches only the control's test list: `control(id)` never returns a
1560
+ * deleted control, whatever the flag says.
1561
+ */
1562
+ async function fetchControl(client, id, lookupBy, includeDeletedTests) {
1563
+ try {
1564
+ const control = await client.getControl(id, includeDeletedTests);
1565
+ return { kind: 'control', control, lookupBy };
1566
+ }
1567
+ catch (error) {
1568
+ if (isNotFound(error)) {
1569
+ return {
1570
+ kind: 'outcome',
1571
+ payload: { outcome: 'not_found', lookupBy, note: NOTE_CONTROL_NOT_FOUND },
1572
+ };
1573
+ }
1574
+ throw error;
1575
+ }
1576
+ }
1577
+ /**
1578
+ * Up to MAX_CONTROL_SEARCH_PAGES pages of a control search. `searchText` is a substring match
1579
+ * over name, description, identifier and id, so a short identifier ("1.1") can bury its exact
1580
+ * match under dozens of partial ones; one page would report it missing.
1581
+ *
1582
+ * Non-deleted controls only, in any state: `control(id)` cannot read a deleted one, so a deleted
1583
+ * match could only turn a `found` into `ambiguous`, or end as a `not_found` after the read.
1584
+ */
1585
+ function searchControls(client, filter) {
1586
+ return walkControls(client, filter, {
1587
+ limit: CONTROL_SEARCH_PAGE_LIMIT,
1588
+ maxPages: MAX_CONTROL_SEARCH_PAGES,
1589
+ });
1590
+ }
1591
+ /** Exact identifier only; for a name, the exact matches when there are any, else every hit. */
1592
+ function matchControls(items, lookupBy, wanted) {
1593
+ const folded = wanted.toLowerCase();
1594
+ if (lookupBy === 'identifier') {
1595
+ return items.filter((control) => control.identifier?.trim().toLowerCase() === folded);
1596
+ }
1597
+ const exact = items.filter((control) => control.name?.trim().toLowerCase() === folded);
1598
+ return exact.length > 0 ? exact : items;
1599
+ }
1600
+ /**
1601
+ * One ambiguous match. Identifiers repeat across frameworks with the same name and often a null
1602
+ * catalog (three LIVE `ACCT.02` controls on j1dev, 2026-10-14), so the frameworks are what tells
1603
+ * them apart.
1604
+ */
1605
+ function controlCandidate(control, names, subdomain) {
1606
+ return {
1607
+ id: control.id,
1608
+ name: control.name,
1609
+ url: controlUrl(control.id, subdomain),
1610
+ identifier: control.identifier,
1611
+ catalog: control.catalog,
1612
+ state: control.state,
1613
+ status: control.status,
1614
+ frameworkIds: control.frameworkIds ?? [],
1615
+ frameworkNames: namesFor(control.frameworkIds, names),
1616
+ };
1617
+ }
1618
+ async function resolveControl(client, lookupBy, value, includeDeletedTests, context) {
1619
+ if (lookupBy === 'controlId') {
1620
+ return fetchControl(client, value, lookupBy, includeDeletedTests);
1621
+ }
1622
+ const filter = lookupBy === 'identifier' ? { searchText: value } : { nameContains: value };
1623
+ const search = await searchControls(client, filter);
1624
+ const matches = matchControls(search.items, lookupBy, value);
1625
+ // Only a complete search proves the match is the only one: past the search's cap a second match
1626
+ // can sit on a page it never read, so a lone match from a cut-short search is `ambiguous`
1627
+ // (PR #55 review).
1628
+ if (matches.length === 1 && search.complete) {
1629
+ return fetchControl(client, matches[0].id, lookupBy, includeDeletedTests);
1630
+ }
1631
+ // CCM evaluates only LIVE controls, so the one LIVE match is almost always the one meant:
1632
+ // `BEDROCK-009` matched a LIVE and a DRAFT control on j1dev and cost a second call (2026-10-14).
1633
+ // Only a complete search shows that no other LIVE match exists.
1634
+ const live = matches.filter((match) => match.state === 'LIVE');
1635
+ if (live.length === 1 && search.complete) {
1636
+ const resolved = await fetchControl(client, live[0].id, lookupBy, includeDeletedTests);
1637
+ if (resolved.kind === 'outcome')
1638
+ return resolved;
1639
+ return { ...resolved, otherCandidates: matches.filter((match) => match !== live[0]) };
1640
+ }
1641
+ if (matches.length === 0) {
1642
+ const note = search.complete
1643
+ ? NOTE_CONTROL_NOT_FOUND
1644
+ : `${NOTE_CONTROL_NOT_FOUND} ${NOTE_SEARCH_INCOMPLETE}`;
1645
+ return {
1646
+ kind: 'outcome',
1647
+ payload: { outcome: 'not_found', lookupBy, searchComplete: search.complete, note },
1648
+ };
1649
+ }
1650
+ const [subdomain, { frameworks }] = await Promise.all([
1651
+ context.subdomainRead,
1652
+ timed(context.timings, 'frameworks', () => client.listAllControlFrameworks()),
1653
+ ]);
1654
+ const names = frameworkNameMap(frameworks);
1655
+ return {
1656
+ kind: 'outcome',
1657
+ payload: {
1658
+ outcome: 'ambiguous',
1659
+ lookupBy,
1660
+ candidates: matches
1661
+ .slice(0, MAX_CANDIDATES)
1662
+ .map((match) => controlCandidate(match, names, subdomain)),
1663
+ candidateCount: matches.length,
1664
+ searchComplete: search.complete,
1665
+ },
1666
+ };
1667
+ }
1668
+ function projectControl(control) {
1669
+ return {
1670
+ id: control.id,
1671
+ name: control.name,
1672
+ identifier: control.identifier,
1673
+ catalog: control.catalog,
1674
+ source: control.source,
1675
+ sourceId: control.sourceId,
1676
+ state: control.state,
1677
+ status: control.status,
1678
+ effectiveStatus: control.effectiveStatus,
1679
+ hasValidAttestation: control.hasValidAttestation,
1680
+ owner: control.owner,
1681
+ description: control.description,
1682
+ remediation: control.remediation,
1683
+ exceptionProcess: control.exceptionProcess,
1684
+ mitreTechnique: control.mitreTechnique,
1685
+ resourceGroupId: control.resourceGroupId,
1686
+ frameworkIds: control.frameworkIds ?? [],
1687
+ numberOfTests: control.numberOfTests,
1688
+ configured: control.configured,
1689
+ lastEvaluatedOn: control.lastEvaluatedOn,
1690
+ lastEvaluatedOnIso: toIso(control.lastEvaluatedOn),
1691
+ createdOn: control.createdOn,
1692
+ deleted: control.deleted,
1693
+ };
1694
+ }
1695
+ function projectRequirement(requirement, names) {
1696
+ return {
1697
+ id: requirement.id,
1698
+ identifier: requirement.identifier,
1699
+ title: requirement.title,
1700
+ section: requirement.section,
1701
+ priority: requirement.priority,
1702
+ frameworkIds: requirement.frameworkIds ?? [],
1703
+ frameworkNames: namesFor(requirement.frameworkIds, names),
1704
+ };
1705
+ }
1706
+ /** A test persists only its first query (multi-query tests do not exist), so it is flattened. */
1707
+ function projectTest(test, lookup) {
1708
+ const query = test.queries?.[0];
1709
+ return {
1710
+ id: test.id,
1711
+ name: test.name,
1712
+ description: test.description,
1713
+ status: test.status,
1714
+ deleted: test.deleted,
1715
+ query: query?.query ?? null,
1716
+ resultsAre: query?.resultsAre ?? null,
1717
+ recordCount: query?.recordCount ?? null,
1718
+ effective: query?.effective ?? null,
1719
+ referencedRuleId: test.referencedRuleId,
1720
+ lastEvaluatedOn: test.lastEvaluatedOn,
1721
+ lastEvaluatedOnIso: toIso(test.lastEvaluatedOn),
1722
+ ...lookup,
1723
+ };
1724
+ }
1725
+ /**
1726
+ * A PASS that rests only on tests whose queries saw no data. CCM counts such a test as passing, so
1727
+ * the status is real, but nothing was checked: on j1dev, BEDROCK-001 stored PASS with both tests
1728
+ * `effective: false` (2026-10-14). An unknown `effective` counts as data.
1729
+ */
1730
+ function passingWithoutData(control, tests) {
1731
+ const passing = tests.filter((test) => !test.deleted && test.status === 'PASS');
1732
+ return (control.status === 'PASS' &&
1733
+ passing.length > 0 &&
1734
+ passing.every((test) => test.queries?.[0]?.effective === false));
1735
+ }
1736
+ /**
1737
+ * When get-control's evaluation lookups must stop: READ_FANOUT_DEADLINE_MS after the control read
1738
+ * returned, and never past GET_CONTROL_DEADLINE_MS from request start.
1739
+ */
1740
+ function evaluationDeadline(startedAt) {
1741
+ return Math.min(startedAt + exports.GET_CONTROL_DEADLINE_MS, Date.now() + exports.READ_FANOUT_DEADLINE_MS);
1742
+ }
1743
+ /**
1744
+ * A read get-control can answer without: raced against the budget, and skipped with its reason
1745
+ * rather than failing the call when it runs out of time or fails.
1746
+ */
1747
+ async function budgeted(work, deadlineAt, what) {
1748
+ if (Date.now() >= deadlineAt)
1749
+ return { kind: 'skipped', reason: 'time_budget' };
1750
+ try {
1751
+ const value = await withDeadline(work(), deadlineAt);
1752
+ return value === DEADLINE_PASSED
1753
+ ? { kind: 'skipped', reason: 'time_budget' }
1754
+ : { kind: 'read', value };
1755
+ }
1756
+ catch (error) {
1757
+ console.error(`Error reading ${what} for get-control:`, error);
1758
+ return { kind: 'skipped', reason: 'read_failed' };
1759
+ }
1760
+ }
1761
+ /** A control's attestations, `'unavailable'` when refused or not back by the deadline. */
1762
+ async function attestationsBy(read, deadlineAt) {
1763
+ const settled = await withDeadline(read, deadlineAt);
1764
+ return settled === DEADLINE_PASSED ? 'unavailable' : settled;
1765
+ }
1766
+ function readControlAttestations(client, controlId, timings) {
1767
+ return timed(timings, 'attestations', () => client.listAttestations({ controlId }).catch(degradeOnAccessDenied));
1768
+ }
1769
+ /**
1770
+ * Everything behind a found control, inside GET_CONTROL_DEADLINE_MS from the call's start. On
1771
+ * j1dev 20 of 27 get-control calls hit the remote's 55 s abort with single reads at 18–30 s
1772
+ * (2026-10-15). The control and its tests always come back; attestations that are not back in
1773
+ * time read as `'unavailable'`; requirements and frameworks are skipped with their reason.
1774
+ */
1775
+ async function describeControl(client, resolution, startedAt, context) {
1776
+ const { control, lookupBy } = resolution;
1777
+ const { timings } = context;
1778
+ const budgetAt = startedAt + exports.GET_CONTROL_DEADLINE_MS;
1779
+ const tests = control.controlTests ?? [];
1780
+ const evaluations = lookupLatestEvaluations(client, tests, evaluationDeadline(startedAt));
1781
+ const [requirementRead, attestations, frameworkRead, { lookups, ms }] = await Promise.all([
1782
+ timed(timings, 'requirements', () => budgeted(() => client.listControlRequirements(control.id), budgetAt, 'requirements')),
1783
+ attestationsBy(context.attestationsRead ?? readControlAttestations(client, control.id, timings), budgetAt),
1784
+ timed(timings, 'frameworks', () => budgeted(() => client.listAllControlFrameworks(), budgetAt, 'frameworks')),
1785
+ evaluations,
1786
+ ]);
1787
+ timings.evaluations = ms;
1788
+ const names = frameworkNameMap(frameworkRead.kind === 'read' ? frameworkRead.value.frameworks : []);
1789
+ const subdomain = await subdomainBy(context.subdomainRead, budgetAt);
1790
+ const skippedTests = lookups.filter((lookup) => lookup.latestEvaluationStatus === 'skipped').length;
1791
+ const statusExplanation = explainControlStatus({
1792
+ state: control.state,
1793
+ status: control.status,
1794
+ effectiveStatus: control.effectiveStatus,
1795
+ hasValidAttestation: control.hasValidAttestation,
1796
+ tests,
1797
+ attestations,
1798
+ });
1799
+ const expectedStatus = staleStatus(statusExplanation, control.status);
1800
+ return {
1801
+ outcome: 'found',
1802
+ lookupBy,
1803
+ ...(resolution.otherCandidates
1804
+ ? {
1805
+ otherCandidates: resolution.otherCandidates
1806
+ .slice(0, MAX_CANDIDATES)
1807
+ .map((candidate) => controlCandidate(candidate, names, subdomain)),
1808
+ }
1809
+ : {}),
1810
+ control: { ...projectControl(control), url: controlUrl(control.id, subdomain) },
1811
+ statusExplanation,
1812
+ ...(expectedStatus ? { storedStatusStale: true, expectedStatus } : {}),
1813
+ passingWithoutData: passingWithoutData(control, tests),
1814
+ // statusExplanation names the first cause; a control can fail for several, and fixing one
1815
+ // leaves it failing on the next (6.1 on j1dev: a failing test and an expired attestation).
1816
+ blockers: failureCauses(tests, attestations === 'unavailable' ? [] : attestations),
1817
+ ...(frameworkRead.kind === 'read'
1818
+ ? {
1819
+ // With its link: the instructions tell the assistant to give a framework's url whenever
1820
+ // it names one (PR #55 review).
1821
+ frameworks: (control.frameworkIds ?? []).map((id) => ({
1822
+ id,
1823
+ name: names.get(id) ?? null,
1824
+ url: frameworkUrl(id, subdomain),
1825
+ })),
1826
+ }
1827
+ : { frameworks: [], frameworksSkipped: frameworkRead.reason }),
1828
+ ...(requirementRead.kind === 'read'
1829
+ ? {
1830
+ requirements: requirementRead.value.requirements.map((entry) => projectRequirement(entry, names)),
1831
+ requirementsComplete: requirementRead.value.complete,
1832
+ }
1833
+ : {
1834
+ requirements: [],
1835
+ requirementsComplete: false,
1836
+ requirementsSkipped: requirementRead.reason,
1837
+ }),
1838
+ attestations: attestations === 'unavailable' ? attestations : attestations.map(projectAttestation),
1839
+ tests: tests.map((test, index) => projectTest(test, lookups[index])),
1840
+ ...(skippedTests > 0 ? { skippedTests } : {}),
1841
+ evaluationLookupMs: ms,
1842
+ timingsMs: timings,
1843
+ };
1844
+ }
1845
+ // ---------------------------------------------------------------------------------------------
1846
+ // Attestation writes
1847
+ // ---------------------------------------------------------------------------------------------
1848
+ function sameSubject(a, b) {
1849
+ return (a ?? '').trim().toLowerCase() === b.trim().toLowerCase();
1850
+ }
1851
+ /** An unknown creation time sorts as the oldest. */
1852
+ function createdMs(attestation) {
1853
+ const ms = attestation.createdOn ? Date.parse(attestation.createdOn) : Number.NaN;
1854
+ return Number.isFinite(ms) ? ms : 0;
1855
+ }
1856
+ /** The ACTIVE attestations whose subject matches `subject`, trimmed and folded, newest first. */
1857
+ function activeWithSubject(attestations, subject) {
1858
+ return attestations
1859
+ .filter((attestation) => attestation.state === 'ACTIVE' && sameSubject(attestation.subject, subject))
1860
+ .sort((a, b) => createdMs(b) - createdMs(a));
1861
+ }
1862
+ /**
1863
+ * Which of the matching attestations a create answers with: the one whose subject is exactly the
1864
+ * one asked for, when exactly one is, else the most recently created. CCM accepts a rename onto
1865
+ * another attestation's subject, and on j1dev `already_exists` then returned the renamed one
1866
+ * rather than the exact original (2026-10-14).
1867
+ */
1868
+ function pickDuplicate(matches, subject) {
1869
+ const exact = matches.filter((attestation) => attestation.subject?.trim() === subject.trim());
1870
+ return exact.length === 1 ? exact[0] : matches[0];
1871
+ }
1872
+ function expiryNotAppliedNote(requestedMs, existing) {
1873
+ return (`The requested expiry (${toIso(requestedMs)}) was not applied: this attestation expires ` +
1874
+ `${toIso(existing.expiresOn) ?? 'at an unknown time'}. Change it with \`update-attestation\`.`);
1875
+ }
1876
+ function duplicateMatch(attestation) {
1877
+ return {
1878
+ id: attestation.id,
1879
+ subject: attestation.subject,
1880
+ expiresOnIso: toIso(attestation.expiresOn),
1881
+ createdOn: attestation.createdOn,
1882
+ };
1883
+ }
1884
+ /**
1885
+ * The note sentence for an update that left two ACTIVE attestations on one control with the same
1886
+ * subject. It names the other attestation by id only.
1887
+ */
1888
+ function subjectCollisionNote(otherId) {
1889
+ return (`Active attestation \`${otherId}\` on this control has the same subject. CCM allows that, ` +
1890
+ 'but `create-attestation` finds an existing attestation by its subject, so give each one a ' +
1891
+ 'distinct subject.');
1892
+ }
1893
+ /** The control an attestation is for, or null when the gateway says it does not exist. */
1894
+ async function findControl(client, controlId) {
1895
+ try {
1896
+ return await client.getControl(controlId);
1897
+ }
1898
+ catch (error) {
1899
+ if (isNotFound(error))
1900
+ return null;
1901
+ throw error;
1902
+ }
1903
+ }
1904
+ /**
1905
+ * The refusal texts name no control. The chokepoint copies the first 200 characters of error text
1906
+ * into telemetry, and UPLOAD and JSON control ids embed the customer's control titles
1907
+ * (`ccm_c_JSON_A.5.1 Policies`), which is why `controlId` is not logged either. The id stays in
1908
+ * `structuredContent`.
1909
+ */
1910
+ function controlNotFound(controlId) {
1911
+ return writeRefusal('not_found', 'Attestation not created — no control has this id. Resolve the control with `get-control` ' +
1912
+ '(by `identifier` or `controlName`) and retry with the `id` it returns.', { controlId });
1913
+ }
1914
+ /** The API rejects an attestation on a control that is not LIVE; refused here before the write. */
1915
+ function controlNotLive(control) {
1916
+ return writeRefusal('not_live', `Attestation not created — this control is ${control.state ?? 'in no state'}, and ` +
1917
+ 'attestations apply only to LIVE controls. No tool on this connection can change a ' +
1918
+ "control's state, so the control has to be promoted to LIVE in JupiterOne Compliance " +
1919
+ 'before it can be attested; retrying will not help.', { controlId: control.id, control: { id: control.id, name: control.name, state: control.state } });
1920
+ }
1921
+ /**
1922
+ * Everything that fails a control by CCM's rules: each test that fails and is not deleted, and each
1923
+ * expired attestation (the API's EXPIRED state is `revoked != true AND expiresOn <= now`).
1924
+ */
1925
+ function failureCauses(tests, attestations) {
1926
+ return [
1927
+ ...tests
1928
+ .filter((test) => !test.deleted && test.status === 'FAIL')
1929
+ .map((test) => ({ type: 'failing_test', id: test.id, name: test.name })),
1930
+ ...attestations
1931
+ .filter((attestation) => attestation.state === 'EXPIRED')
1932
+ .map((attestation) => ({
1933
+ type: 'expired_attestation',
1934
+ id: attestation.id,
1935
+ subject: attestation.subject,
1936
+ expiresOnIso: toIso(attestation.expiresOn),
1937
+ })),
1938
+ ];
1939
+ }
1940
+ /**
1941
+ * What an attestation does to its control's stored status, by CCM's own order: a failing test or
1942
+ * an expired, unrevoked attestation fails the control whatever else is attested, a passing test
1943
+ * already passes it, and only a control with neither passes because of the attestation. In the
1944
+ * 2026-10-14 live run two attestations came back `created` on controls that stayed FAIL — one with
1945
+ * a failing test, one with an older expired attestation nobody had revoked — and nothing said so.
1946
+ *
1947
+ * `written` is the attestation just created or updated. Its state comes from the write's own
1948
+ * response, not from `attestations`, which can lag the write.
1949
+ */
1950
+ function statusImpact(control, attestations, written) {
1951
+ const tests = control.controlTests ?? [];
1952
+ const current = [...attestations.filter((attestation) => attestation.id !== written.id), written];
1953
+ const blockers = [
1954
+ ...(control.state === 'LIVE'
1955
+ ? []
1956
+ : [{ type: 'not_live', id: control.id, state: control.state }]),
1957
+ ...failureCauses(tests, current),
1958
+ ];
1959
+ if (blockers.length > 0)
1960
+ return { statusImpact: 'blocked', blockers };
1961
+ const passing = tests.some((test) => !test.deleted && test.status === 'PASS');
1962
+ return { statusImpact: passing ? 'already_passing' : 'passes_by_attestation', blockers };
1963
+ }
1964
+ /** One sentence per kind of blocker, naming what holds the control where it is. */
1965
+ function blockerNotes(blockers) {
1966
+ const notes = [];
1967
+ const notLive = blockers.find((blocker) => blocker.type === 'not_live');
1968
+ if (notLive) {
1969
+ notes.push(`The control is ${notLive.state ?? 'in no state'} and CCM evaluates only LIVE controls, so ` +
1970
+ 'the attestation does not change its status.');
1971
+ }
1972
+ const failing = blockers.flatMap((blocker) => blocker.type === 'failing_test' ? [`'${blocker.name}'`] : []);
1973
+ if (failing.length > 0) {
1974
+ notes.push(`This control has ${failing.length === 1 ? 'a failing test' : 'failing tests'} ` +
1975
+ `(${failing.join(', ')}), so the attestation does not change its status.`);
1976
+ }
1977
+ for (const blocker of blockers) {
1978
+ if (blocker.type !== 'expired_attestation')
1979
+ continue;
1980
+ notes.push(`Expired attestation '${blocker.subject}' (\`${blocker.id}\`) fails the control until it ` +
1981
+ 'is renewed with `update-attestation` or revoked.');
1982
+ }
1983
+ return notes;
1984
+ }
1985
+ function withBlockerNotes(note, impact) {
1986
+ return [note, ...blockerNotes(impact.blockers)].join(' ');
1987
+ }
1988
+ /**
1989
+ * The control a written attestation belongs to and its attestations, read after the write. The
1990
+ * write has already succeeded, so a failed read is null, reported as `statusImpact: 'unknown'`
1991
+ * rather than failing the call, which would invite a repeat of a write that went through.
1992
+ */
1993
+ async function readAfterWrite(client, controlId, deadlineAt) {
1994
+ if (!controlId || Date.now() >= deadlineAt)
1995
+ return null;
1996
+ try {
1997
+ const read = await withDeadline(Promise.all([client.getControl(controlId), client.listAttestations({ controlId })]), deadlineAt);
1998
+ if (read === DEADLINE_PASSED)
1999
+ return null;
2000
+ const [control, attestations] = read;
2001
+ return { control, attestations };
2002
+ }
2003
+ catch (error) {
2004
+ console.error('Error reading the control after an attestation write:', error);
2005
+ return null;
2006
+ }
2007
+ }
2008
+ /** The note sentence for a write whose control could not be read back in time, or at all. */
2009
+ function unreadAfterWrite(write) {
2010
+ return (`The control could not be re-read in time after the ${write}, so its effect on the ` +
2011
+ `control's status is unknown; the ${write} went through and does not need repeating.`);
2012
+ }
2013
+ /**
2014
+ * Whether a request was cut off by the host's abort signal: the remote's 55 s deadline. A write
2015
+ * cut off this way may have landed, so it is answered as `interrupted`, never as a failure.
2016
+ */
2017
+ function isAborted(error) {
2018
+ return error instanceof sanitize_error_js_1.JupiterOneApiError
2019
+ ? error.code === sanitize_error_js_1.ABORTED_CODE
2020
+ : error?.name === 'AbortError';
2021
+ }
2022
+ const INTERRUPTED_RECOVERY = {
2023
+ // Not "create it again": the duplicate check reads CCM, whose reads lag its writes by up to a
2024
+ // minute, so a retry inside that minute can make a second attestation (PR #55 review).
2025
+ create: 'it may have been created. Before deciding whether to create it again, read the control ' +
2026
+ 'with `get-control`: its `attestations` lists the subject once CCM can read it, which can ' +
2027
+ 'take up to a minute, so wait a minute if it is not there yet.',
2028
+ update: 'the update may have been applied. Read the attestation with `get-control` before repeating ' +
2029
+ 'the update.',
2030
+ revoke: 'it may have been revoked. To confirm, call `revoke-attestation` again: `not_found` means ' +
2031
+ 'it was revoked.',
2032
+ };
2033
+ /**
2034
+ * A write the request's deadline cut off. On j1dev every create and revoke that aborted had been
2035
+ * written, and the caller hunted for the new id through reads that were timing out too
2036
+ * (2026-10-15). The text names the write and how to confirm it, never the input.
2037
+ */
2038
+ function interrupted(write) {
2039
+ const verb = { create: 'created', update: 'updated', revoke: 'revoked' }[write];
2040
+ return refusal('interrupted', `The request was cut off while the attestation was being ${verb}, so ` +
2041
+ INTERRUPTED_RECOVERY[write]);
2042
+ }
2043
+ async function updateImpact(client, updated, subdomain, deadlineAt) {
2044
+ const link = { id: updated.controlId, url: controlUrl(updated.controlId, subdomain) };
2045
+ const read = await readAfterWrite(client, updated.controlId, deadlineAt);
2046
+ if (!read) {
2047
+ return {
2048
+ control: link,
2049
+ statusImpact: 'unknown',
2050
+ note: `${NOTE_UPDATED} ${unreadAfterWrite('update')}`,
2051
+ };
2052
+ }
2053
+ const { control, attestations } = read;
2054
+ const impact = statusImpact(control, attestations, updated);
2055
+ // CCM accepts a rename onto another attestation's subject (04067953 onto 2f508829 on j1dev,
2056
+ // 2026-10-14), after which create's duplicate check can answer with either one.
2057
+ const [collision] = activeWithSubject(attestations.filter((attestation) => attestation.id !== updated.id), updated.subject);
2058
+ const note = withBlockerNotes(NOTE_UPDATED, impact);
2059
+ return {
2060
+ control: { ...link, name: control.name, state: control.state },
2061
+ ...impact,
2062
+ ...(collision ? { subjectCollision: { id: collision.id, subject: collision.subject } } : {}),
2063
+ note: collision ? `${note} ${subjectCollisionNote(collision.id)}` : note,
2064
+ };
2065
+ }
2066
+ function revokeImpact(control, attestations, revoked, now) {
2067
+ const tests = control.controlTests ?? [];
2068
+ const others = attestations.filter((attestation) => attestation.id !== revoked.id);
2069
+ const causes = failureCauses(tests, others);
2070
+ const blockers = [
2071
+ ...(control.state === 'LIVE'
2072
+ ? []
2073
+ : [{ type: 'not_live', id: control.id, state: control.state }]),
2074
+ ...causes,
2075
+ ];
2076
+ const passesBy = tests.some((test) => !test.deleted && test.status === 'PASS')
2077
+ ? 'tests'
2078
+ : others.some((attestation) => attestation.state === 'ACTIVE')
2079
+ ? 'attestation'
2080
+ : null;
2081
+ if (causes.length > 0)
2082
+ return { statusImpact: 'still_failing', blockers, passesBy };
2083
+ const wasFailing = Number.isFinite(revoked.expiresOn) && revoked.expiresOn <= now;
2084
+ if (wasFailing) {
2085
+ return { statusImpact: passesBy ? 'now_passing' : 'no_longer_failing', blockers, passesBy };
2086
+ }
2087
+ return { statusImpact: passesBy ? 'still_passing' : 'no_longer_passing', blockers, passesBy };
2088
+ }
2089
+ const REVOKE_PASSES_BY = {
2090
+ tests: 'a passing test',
2091
+ attestation: 'another valid attestation',
2092
+ };
2093
+ /** The sentence naming what now decides the control's status after a revoke. */
2094
+ function revokeNote(impact) {
2095
+ const by = impact.passesBy ? REVOKE_PASSES_BY[impact.passesBy] : '';
2096
+ switch (impact.statusImpact) {
2097
+ case 'still_failing':
2098
+ return `The control still fails. ${blockerNotes(impact.blockers).join(' ')}`;
2099
+ case 'still_passing':
2100
+ return `The control still passes: ${by} keeps it passing.`;
2101
+ case 'now_passing':
2102
+ return ('The revoked attestation had expired, so a failure is cleared: once CCM re-scores the ' +
2103
+ `control, ${by} passes it.`);
2104
+ case 'no_longer_failing':
2105
+ return ('The revoked attestation had expired, so a failure is cleared, and nothing else passes ' +
2106
+ 'the control: once CCM re-scores it, it is not evaluated.');
2107
+ default:
2108
+ return ('No passing test and no other valid attestation remain, so the control no longer ' +
2109
+ 'passes: once CCM re-scores it, it is not evaluated.');
2110
+ }
2111
+ }
2112
+ async function revokeEffect(client, revoked, subdomain, deadlineAt) {
2113
+ const link = { id: revoked.controlId, url: controlUrl(revoked.controlId, subdomain) };
2114
+ const read = await readAfterWrite(client, revoked.controlId, deadlineAt);
2115
+ if (!read) {
2116
+ return {
2117
+ control: link,
2118
+ statusImpact: 'unknown',
2119
+ note: `${NOTE_REVOKED} ${unreadAfterWrite('revoke')}`,
2120
+ };
2121
+ }
2122
+ const impact = revokeImpact(read.control, read.attestations, revoked, Date.now());
2123
+ const notLive = impact.blockers.find((blocker) => blocker.type === 'not_live');
2124
+ return {
2125
+ control: { ...link, name: read.control.name, state: read.control.state },
2126
+ statusImpact: impact.statusImpact,
2127
+ blockers: impact.blockers,
2128
+ note: [
2129
+ NOTE_REVOKED,
2130
+ revokeNote(impact),
2131
+ ...(notLive && impact.statusImpact !== 'still_failing' ? blockerNotes([notLive]) : []),
2132
+ ].join(' '),
2133
+ };
2134
+ }
2135
+ /** `null` clears a field; an empty or blank string is sent as that clear, never as "". */
2136
+ function clearable(value) {
2137
+ return typeof value === 'string' && value.trim() === '' ? null : value;
2138
+ }
2139
+ function nonEmpty(value) {
2140
+ return value?.trim() ? value : undefined;
2141
+ }
2142
+ // ---------------------------------------------------------------------------------------------
2143
+ // Schemas
2144
+ // ---------------------------------------------------------------------------------------------
2145
+ const ownerEmail = () => zod_1.z.email();
2146
+ // http(s) only, as the API requires; zod's `protocol` option matches the scheme without its colon.
2147
+ // The tester got "expected string to have >=1 characters" for a subject of three spaces
2148
+ // (2026-10-14); the SDK prefixes the parameter, so this reads "subject: Must not be blank."
2149
+ const BLANK_SUBJECT = 'Must not be blank.';
2150
+ // The message replaces zod's "Invalid URL", which the tester got for an ftp:// link (2026-10-14).
2151
+ const evidenceLink = () => zod_1.z.url({ protocol: /^https?$/, error: 'Must be an http or https URL.' });
2152
+ const expiresOnInput = () => zod_1.z.union([zod_1.z.string(), zod_1.z.number()]);
2153
+ const attestationIdInput = () => zod_1.z.string().min(1).describe("The attestation's `id`, from `get-control` or `create-attestation`.");
2154
+ // Discriminators are plain strings, never enums: hosts cache tools/list across deploys, so a value
2155
+ // added in a later release would fail validation against the cached schema (the sweep in
2156
+ // output-schema-openness.test.ts). Their values are documented in each tool's description.
2157
+ const str = () => zod_1.z.string().nullish();
2158
+ const num = () => zod_1.z.number().nullish();
2159
+ const attestationOutput = () => zod_1.z.looseObject({
2160
+ id: str(),
2161
+ subject: str(),
2162
+ state: str(),
2163
+ expiresOn: num(),
2164
+ expiresOnIso: str(),
2165
+ owner: str(),
2166
+ author: str(),
2167
+ documentLink: str(),
2168
+ controlId: str(),
2169
+ });
2170
+ const blockersOutput = () => zod_1.z.array(zod_1.z.looseObject({
2171
+ type: zod_1.z.string(), // failing_test | expired_attestation | not_live
2172
+ id: str(),
2173
+ name: str(),
2174
+ subject: str(),
2175
+ expiresOnIso: str(),
2176
+ state: str(),
2177
+ }));
2178
+ const frameworkScoreOutput = () => zod_1.z.looseObject({
2179
+ id: str(),
2180
+ name: str(),
2181
+ url: zod_1.z.string().optional(),
2182
+ importStatus: str(),
2183
+ controls: zod_1.z
2184
+ .looseObject({
2185
+ total: num(),
2186
+ passing: num(),
2187
+ failing: num(),
2188
+ attested: num(),
2189
+ withTests: num(),
2190
+ passingWithoutData: num(),
2191
+ })
2192
+ .nullish(),
2193
+ requirements: zod_1.z
2194
+ .looseObject({ total: num(), passing: num(), failing: num(), failingCritical: num() })
2195
+ .nullish(),
2196
+ healthPct: num(),
2197
+ });
2198
+ const complianceSummaryOutput = {
2199
+ outcome: zod_1.z.string(), // ok | ambiguous | framework_not_found
2200
+ frameworkResolution: zod_1.z.string().optional(), // id | name | partial | ambiguous | not_found
2201
+ candidates: zod_1.z
2202
+ .array(zod_1.z.looseObject({
2203
+ id: str(),
2204
+ name: str(),
2205
+ source: str(),
2206
+ sourceId: str(),
2207
+ owner: str(),
2208
+ importStatus: str(),
2209
+ url: zod_1.z.string().optional(),
2210
+ }))
2211
+ .optional(),
2212
+ candidateCount: zod_1.z.number().optional(),
2213
+ frameworksComplete: zod_1.z.boolean(),
2214
+ // Required: every outcome sends it, and hosts validate against the schema they cached.
2215
+ frameworks: zod_1.z.array(frameworkScoreOutput()),
2216
+ statsIncomplete: zod_1.z.array(zod_1.z.string()).optional(),
2217
+ framework: zod_1.z
2218
+ .looseObject({
2219
+ id: str(),
2220
+ name: str(),
2221
+ url: zod_1.z.string().optional(),
2222
+ healthPct: num(),
2223
+ sections: zod_1.z
2224
+ .array(zod_1.z.looseObject({ section: str(), requirements: num(), passing: num(), failing: num() }))
2225
+ .nullable(),
2226
+ failingRequirements: zod_1.z.array(zod_1.z.looseObject({
2227
+ id: str(),
2228
+ identifier: str(),
2229
+ title: str(),
2230
+ section: str(),
2231
+ priority: str(),
2232
+ failingControls: zod_1.z.array(zod_1.z.looseObject({ id: str(), identifier: str(), name: str(), url: zod_1.z.string().optional() })),
2233
+ })),
2234
+ failingControls: zod_1.z
2235
+ .array(zod_1.z.looseObject({ id: str(), identifier: str(), name: str(), url: zod_1.z.string().optional() }))
2236
+ .optional(),
2237
+ failingControlsTruncated: zod_1.z.boolean().optional(),
2238
+ requirementLookupsSkipped: zod_1.z.number().optional(),
2239
+ drillSource: zod_1.z.string().optional(), // graph | api
2240
+ requirementLookupsSkippedBy: zod_1.z
2241
+ .looseObject({ timeBudget: num(), cap: num(), readFailed: num() })
2242
+ .optional(),
2243
+ passingWithoutDataSkipped: zod_1.z.string().optional(), // time_budget | read_failed
2244
+ passingWithoutDataTruncated: zod_1.z.boolean().optional(),
2245
+ })
2246
+ .optional(),
2247
+ expiringAttestations: zod_1.z
2248
+ .union([
2249
+ zod_1.z.array(attestationOutput().extend({
2250
+ controlName: str(),
2251
+ daysUntilExpiry: num(),
2252
+ url: zod_1.z.string().optional(),
2253
+ })),
2254
+ zod_1.z.string(), // 'unavailable'
2255
+ ])
2256
+ .optional(),
2257
+ expiredAttestations: zod_1.z
2258
+ .union([
2259
+ zod_1.z.array(attestationOutput().extend({
2260
+ controlName: str(),
2261
+ daysSinceExpiry: num(),
2262
+ url: zod_1.z.string().optional(),
2263
+ })),
2264
+ zod_1.z.string(), // 'unavailable'
2265
+ ])
2266
+ .optional(),
2267
+ expiredAttestationsTruncated: zod_1.z.boolean().optional(),
2268
+ expiringAttestationsScope: zod_1.z.string().optional(), // framework | account
2269
+ controlNamesUnavailable: zod_1.z.boolean().optional(),
2270
+ controlNamesUnresolved: zod_1.z.number().optional(),
2271
+ attestationsExpiringWithinDays: zod_1.z.number().optional(),
2272
+ warnings: zod_1.z.array(zod_1.z.string()).optional(),
2273
+ timingsMs: zod_1.z.record(zod_1.z.string(), zod_1.z.number()).optional(),
2274
+ };
2275
+ const listControlsOutput = {
2276
+ outcome: zod_1.z.string(), // ok | ambiguous | org_unit_not_found | cursor_rejected (an error)
2277
+ returned: zod_1.z.number().optional(),
2278
+ controls: zod_1.z
2279
+ .array(zod_1.z.looseObject({
2280
+ id: str(),
2281
+ name: str(),
2282
+ url: zod_1.z.string().optional(),
2283
+ identifier: str(),
2284
+ state: str(),
2285
+ status: str(),
2286
+ effectiveStatus: str(),
2287
+ hasValidAttestation: zod_1.z.boolean().nullish(),
2288
+ lastEvaluatedOn: str(),
2289
+ lastEvaluatedOnIso: str(),
2290
+ numberOfTests: num(),
2291
+ failingTests: num(),
2292
+ frameworkIds: zod_1.z.array(zod_1.z.string()).nullish(),
2293
+ frameworkNames: zod_1.z.array(zod_1.z.string().nullable()).nullish(),
2294
+ }))
2295
+ .optional(),
2296
+ pageInfo: zod_1.z.looseObject({ endCursor: str(), hasNextPage: zod_1.z.boolean().nullish() }).nullish(),
2297
+ ouResolution: zod_1.z.string().optional(), // id | id_unverified | name | ambiguous | not_found
2298
+ orgUnit: zod_1.z
2299
+ .looseObject({
2300
+ id: str(),
2301
+ displayName: str(),
2302
+ namespace: str(),
2303
+ resolvedBy: zod_1.z.string().nullish(), // id | id_unverified | name
2304
+ })
2305
+ .optional(),
2306
+ candidates: zod_1.z
2307
+ .array(zod_1.z.looseObject({
2308
+ id: str(),
2309
+ displayName: str(),
2310
+ namespace: str(),
2311
+ active: zod_1.z.boolean().nullish(),
2312
+ assetCount: num(),
2313
+ }))
2314
+ .optional(),
2315
+ candidateCount: zod_1.z.number().optional(),
2316
+ namespaces: zod_1.z
2317
+ .array(zod_1.z.looseObject({ slug: str(), name: str(), failed: zod_1.z.boolean().nullish() }))
2318
+ .optional(),
2319
+ units: zod_1.z.array(zod_1.z.looseObject({ id: str(), displayName: str(), namespace: str() })).optional(),
2320
+ timingsMs: zod_1.z.record(zod_1.z.string(), zod_1.z.number()).optional(),
2321
+ };
2322
+ const controlCandidateOutput = () => zod_1.z.looseObject({
2323
+ id: str(),
2324
+ name: str(),
2325
+ identifier: str(),
2326
+ catalog: str(),
2327
+ state: str(),
2328
+ status: str(),
2329
+ url: zod_1.z.string().optional(),
2330
+ frameworkIds: zod_1.z.array(zod_1.z.string()).nullish(),
2331
+ frameworkNames: zod_1.z.array(zod_1.z.string().nullable()).nullish(),
2332
+ });
2333
+ const getControlOutput = {
2334
+ outcome: zod_1.z.string(), // found | not_found | ambiguous
2335
+ lookupBy: zod_1.z.string().optional(), // controlId | identifier | controlName
2336
+ searchComplete: zod_1.z.boolean().optional(),
2337
+ candidates: zod_1.z.array(controlCandidateOutput()).optional(),
2338
+ candidateCount: zod_1.z.number().optional(),
2339
+ otherCandidates: zod_1.z.array(controlCandidateOutput()).optional(),
2340
+ note: zod_1.z.string().optional(), // the recovery, on not_found
2341
+ control: zod_1.z
2342
+ .looseObject({
2343
+ id: str(),
2344
+ name: str(),
2345
+ url: zod_1.z.string().optional(),
2346
+ identifier: str(),
2347
+ state: str(),
2348
+ status: str(),
2349
+ effectiveStatus: str(),
2350
+ hasValidAttestation: zod_1.z.boolean().nullish(),
2351
+ lastEvaluatedOn: str(),
2352
+ lastEvaluatedOnIso: str(),
2353
+ })
2354
+ .optional(),
2355
+ statusExplanation: zod_1.z.string().optional(), // one of STATUS_EXPLANATIONS
2356
+ storedStatusStale: zod_1.z.boolean().optional(),
2357
+ expectedStatus: zod_1.z.string().optional(), // PASS | FAIL
2358
+ passingWithoutData: zod_1.z.boolean().optional(),
2359
+ blockers: blockersOutput().optional(), // failing_test | expired_attestation
2360
+ frameworks: zod_1.z
2361
+ .array(zod_1.z.looseObject({ id: str(), name: str(), url: zod_1.z.string().optional() }))
2362
+ .optional(),
2363
+ frameworksSkipped: zod_1.z.string().optional(), // time_budget | read_failed
2364
+ requirementsSkipped: zod_1.z.string().optional(), // time_budget | read_failed
2365
+ requirements: zod_1.z
2366
+ .array(zod_1.z.looseObject({
2367
+ id: str(),
2368
+ identifier: str(),
2369
+ title: str(),
2370
+ section: str(),
2371
+ priority: str(),
2372
+ }))
2373
+ .optional(),
2374
+ requirementsComplete: zod_1.z.boolean().optional(),
2375
+ attestations: zod_1.z.union([zod_1.z.array(attestationOutput()), zod_1.z.string()]).optional(), // or 'unavailable'
2376
+ tests: zod_1.z
2377
+ .array(zod_1.z.looseObject({
2378
+ id: str(),
2379
+ name: str(),
2380
+ status: str(),
2381
+ query: str(),
2382
+ resultsAre: str(),
2383
+ referencedRuleId: str(),
2384
+ latestEvaluationStatus: zod_1.z.string(), // found | none | skipped | error
2385
+ latestEvaluation: zod_1.z
2386
+ .looseObject({
2387
+ rawDataKey: str(),
2388
+ resultCount: num(),
2389
+ evaluatedOn: str(),
2390
+ timestamp: num(),
2391
+ tag: str(),
2392
+ })
2393
+ .nullish(),
2394
+ evaluationsInWindow: zod_1.z.number().optional(),
2395
+ moreInWindow: zod_1.z.boolean().optional(),
2396
+ }))
2397
+ .optional(),
2398
+ skippedTests: zod_1.z.number().optional(),
2399
+ evaluationLookupMs: zod_1.z.number().optional(),
2400
+ timingsMs: zod_1.z.record(zod_1.z.string(), zod_1.z.number()).optional(),
2401
+ };
2402
+ const controlSummaryOutput = () => zod_1.z.looseObject({ id: str(), name: str(), state: str(), url: zod_1.z.string().optional() });
2403
+ const controlLinkOutput = () => zod_1.z.looseObject({ id: str(), url: zod_1.z.string().optional() });
2404
+ // blocked | passes_by_attestation | already_passing (| unknown on update)
2405
+ const statusImpactOutput = {
2406
+ statusImpact: zod_1.z.string().optional(),
2407
+ blockers: blockersOutput().optional(),
2408
+ };
2409
+ const createAttestationOutput = {
2410
+ outcome: zod_1.z.string(), // created | already_exists
2411
+ attestation: attestationOutput(),
2412
+ requestedExpiresOnIso: zod_1.z.string().nullish(),
2413
+ requestedExpiresOnApplied: zod_1.z.boolean().optional(),
2414
+ matches: zod_1.z
2415
+ .array(zod_1.z.looseObject({ id: str(), subject: str(), expiresOnIso: str(), createdOn: str() }))
2416
+ .optional(),
2417
+ control: controlSummaryOutput(),
2418
+ ...statusImpactOutput,
2419
+ note: zod_1.z.string(),
2420
+ };
2421
+ const updateAttestationOutput = {
2422
+ outcome: zod_1.z.string(), // updated | not_found
2423
+ attestationId: zod_1.z.string().optional(),
2424
+ attestation: attestationOutput().optional(),
2425
+ control: controlLinkOutput().optional(),
2426
+ ...statusImpactOutput,
2427
+ subjectCollision: zod_1.z.looseObject({ id: str(), subject: str() }).optional(),
2428
+ note: zod_1.z.string().optional(),
2429
+ };
2430
+ const revokeAttestationOutput = {
2431
+ outcome: zod_1.z.string(), // revoked | not_found
2432
+ attestationId: zod_1.z.string().optional(),
2433
+ attestation: attestationOutput().optional(),
2434
+ control: controlLinkOutput().optional(),
2435
+ // no_longer_passing | still_passing | still_failing | now_passing | no_longer_failing | unknown
2436
+ statusImpact: zod_1.z.string().optional(),
2437
+ blockers: blockersOutput().optional(),
2438
+ note: zod_1.z.string().optional(),
2439
+ };
2440
+ // ---------------------------------------------------------------------------------------------
2441
+ // Tools
2442
+ // ---------------------------------------------------------------------------------------------
2443
+ exports.complianceTools = [
2444
+ (0, types_js_1.defineTool)({
2445
+ name: 'get-compliance-summary',
2446
+ title: 'Compliance Summary',
2447
+ description: (0, load_description_js_1.loadDescription)('get-compliance-summary.md'),
2448
+ inputSchema: {
2449
+ frameworkId: zod_1.z
2450
+ .string()
2451
+ .min(1)
2452
+ .optional()
2453
+ .describe("A framework `id` from this tool's `frameworks` list. When set, the response adds that " +
2454
+ "framework's section scores and its failing requirements with the controls failing " +
2455
+ 'them.'),
2456
+ frameworkName: zod_1.z
2457
+ .string()
2458
+ .trim()
2459
+ .min(1)
2460
+ .optional()
2461
+ .describe('A framework name, instead of `frameworkId`: matched exactly ignoring case, else as ' +
2462
+ 'the single framework whose name contains it. Several matches return ' +
2463
+ '`outcome: "ambiguous"` with candidates.'),
2464
+ attestationsExpiringWithinDays: zod_1.z
2465
+ .number()
2466
+ .int()
2467
+ .min(1)
2468
+ .max(365)
2469
+ .optional()
2470
+ .describe('How far ahead to look for active attestations about to expire, in days (1–365, ' +
2471
+ `default ${DEFAULT_EXPIRING_WITHIN_DAYS}).`),
2472
+ },
2473
+ outputSchema: complianceSummaryOutput,
2474
+ annotations: types_js_1.READ_ONLY,
2475
+ accessDeniedHint: ACCESS_DENIED_HINT,
2476
+ errorContext: 'Error fetching the compliance summary',
2477
+ handler: async ({ frameworkId, frameworkName, attestationsExpiringWithinDays }, client) => {
2478
+ if (frameworkId !== undefined && frameworkName !== undefined) {
2479
+ return validationError('Pass at most one of `frameworkId` or `frameworkName`.');
2480
+ }
2481
+ return (0, result_js_1.structuredResult)(await complianceSummary(client, { frameworkId, frameworkName }, attestationsExpiringWithinDays ?? DEFAULT_EXPIRING_WITHIN_DAYS));
2482
+ },
2483
+ }),
2484
+ (0, types_js_1.defineTool)({
2485
+ name: 'list-controls',
2486
+ title: 'List Controls',
2487
+ description: (0, load_description_js_1.loadDescription)('list-controls.md'),
2488
+ inputSchema: {
2489
+ search: zod_1.z
2490
+ .string()
2491
+ .min(1)
2492
+ .optional()
2493
+ .describe('Case-insensitive text matched against control name, description, identifier and id.'),
2494
+ status: zod_1.z
2495
+ .array(zod_1.z.enum(['PASS', 'FAIL']))
2496
+ .optional()
2497
+ .describe('Only controls whose evaluated status is one of these.'),
2498
+ states: zod_1.z
2499
+ .array(zod_1.z.enum(['DRAFT', 'REVIEW', 'LIVE', 'RETIRED']))
2500
+ .optional()
2501
+ .describe('Only controls in one of these lifecycle states. Only LIVE controls are evaluated.'),
2502
+ effectiveness: zod_1.z
2503
+ .enum(['NO_TESTS', 'NO_DATAPOINTS'])
2504
+ .optional()
2505
+ .describe('NO_TESTS: controls with no tests. NO_DATAPOINTS: controls whose tests have produced ' +
2506
+ 'no results.'),
2507
+ hasValidAttestation: zod_1.z
2508
+ .boolean()
2509
+ .optional()
2510
+ .describe('true: controls covered by at least one valid attestation; false: those with none.'),
2511
+ owner: ownerEmail().optional().describe("The control owner's email address (exact match)."),
2512
+ catalogs: zod_1.z
2513
+ .array(zod_1.z.string().min(1))
2514
+ .optional()
2515
+ .describe('Only controls from these catalogs.'),
2516
+ mitreTechniques: zod_1.z
2517
+ .array(zod_1.z.string().regex(/^T\d{4}(\.\d{3})?$/))
2518
+ .optional()
2519
+ .describe('MITRE ATT&CK technique ids, e.g. "T1078" or "T1078.004".'),
2520
+ frameworkId: zod_1.z
2521
+ .string()
2522
+ .min(1)
2523
+ .optional()
2524
+ .describe('Only controls mapped to this framework (an `id` from `get-compliance-summary`).'),
2525
+ source: zod_1.z
2526
+ .enum(['J1', 'UCF', 'UPLOAD', 'JSON'])
2527
+ .optional()
2528
+ .describe('Only controls from this source.'),
2529
+ orgUnit: zod_1.z
2530
+ .string()
2531
+ .trim()
2532
+ .min(1)
2533
+ .optional()
2534
+ .describe('An organizational unit, by its id (contains a ":"; used unchecked, reported as ' +
2535
+ '`ouResolution: "id_unverified"`) or its display name. A name that matches several ' +
2536
+ 'units returns `outcome: "ambiguous"` with the candidates and their ids.'),
2537
+ sort: zod_1.z
2538
+ .object({
2539
+ field: zod_1.z.enum(['NAME', 'SOURCE', 'STATUS', 'LAST_EVALUATED_ON', 'OWNER']),
2540
+ order: zod_1.z.enum(['ASC', 'DESC']),
2541
+ })
2542
+ .optional()
2543
+ .describe('Sort field and direction.'),
2544
+ limit: zod_1.z
2545
+ .number()
2546
+ .int()
2547
+ .min(1)
2548
+ .max(250)
2549
+ .optional()
2550
+ .describe(`Rows per page, 1–250 (default ${DEFAULT_CONTROL_PAGE_LIMIT}).`),
2551
+ cursor: zod_1.z.string().optional().describe('`pageInfo.endCursor` from the previous page.'),
2552
+ includeDeleted: zod_1.z.boolean().optional().describe('Include deleted controls.'),
2553
+ },
2554
+ outputSchema: listControlsOutput,
2555
+ annotations: types_js_1.READ_ONLY,
2556
+ accessDeniedHint: ACCESS_DENIED_HINT,
2557
+ errorContext: 'Error listing controls',
2558
+ handler: async (params, client) => {
2559
+ const timings = {};
2560
+ let orgUnit;
2561
+ if (params.orgUnit !== undefined) {
2562
+ const wanted = params.orgUnit;
2563
+ const resolution = await timed(timings, 'orgUnit', () => resolveOrgUnit(client, wanted));
2564
+ if (resolution.kind === 'outcome') {
2565
+ return (0, result_js_1.structuredResult)({ ...resolution.payload, timingsMs: timings });
2566
+ }
2567
+ orgUnit = resolution.orgUnit;
2568
+ }
2569
+ const subdomainRead = readSubdomain(client, timings);
2570
+ const read = await readControlsPage(client, {
2571
+ cursor: params.cursor,
2572
+ limit: params.limit ?? DEFAULT_CONTROL_PAGE_LIMIT,
2573
+ sort: params.sort,
2574
+ includeDeleted: params.includeDeleted,
2575
+ filter: controlFilter(params, orgUnit?.id),
2576
+ }, timings);
2577
+ if (read.kind === 'cursor_rejected')
2578
+ return read.result;
2579
+ const { page, frameworks } = read;
2580
+ const names = frameworkNameMap(frameworks);
2581
+ const subdomain = await subdomainRead;
2582
+ const controls = page.items.map((control) => controlRow(control, names, subdomain));
2583
+ return (0, result_js_1.structuredResult)({
2584
+ outcome: 'ok',
2585
+ returned: controls.length,
2586
+ controls,
2587
+ pageInfo: page.pageInfo,
2588
+ ...(orgUnit ? { orgUnit, ouResolution: orgUnit.resolvedBy } : {}),
2589
+ timingsMs: timings,
2590
+ });
2591
+ },
2592
+ }),
2593
+ (0, types_js_1.defineTool)({
2594
+ name: 'get-control',
2595
+ title: 'Control Details',
2596
+ description: (0, load_description_js_1.loadDescription)('get-control.md'),
2597
+ inputSchema: {
2598
+ controlId: zod_1.z
2599
+ .string()
2600
+ .trim()
2601
+ .min(1)
2602
+ .optional()
2603
+ .describe('The exact control id (`ccm_c_<SOURCE>_<sourceId>`), e.g. from `list-controls`.'),
2604
+ identifier: zod_1.z
2605
+ .string()
2606
+ .trim()
2607
+ .min(1)
2608
+ .optional()
2609
+ .describe('The control identifier the framework shows, e.g. "AC-2" or "CC6.1". Matched exactly, ' +
2610
+ 'ignoring case.'),
2611
+ controlName: zod_1.z
2612
+ .string()
2613
+ .trim()
2614
+ .min(1)
2615
+ .optional()
2616
+ .describe('The control name. An exact match (ignoring case) wins; otherwise a single partial ' +
2617
+ 'match is used, and several return `outcome: "ambiguous"` with candidates.'),
2618
+ includeDeleted: zod_1.z.boolean().optional().describe("Also return the control's deleted tests."),
2619
+ },
2620
+ outputSchema: getControlOutput,
2621
+ annotations: types_js_1.READ_ONLY,
2622
+ accessDeniedHint: ACCESS_DENIED_HINT,
2623
+ errorContext: 'Error fetching control',
2624
+ handler: async (params, client) => {
2625
+ const startedAt = Date.now();
2626
+ const given = LOOKUP_KEYS.filter((key) => params[key] !== undefined);
2627
+ if (given.length !== 1) {
2628
+ return validationError('Pass exactly one of `controlId`, `identifier` or `controlName` to look up a control.');
2629
+ }
2630
+ const [lookupBy] = given;
2631
+ const timings = {};
2632
+ const subdomainRead = readSubdomain(client, timings);
2633
+ // An id is all the attestation read needs, so it runs beside the control read.
2634
+ const attestationsRead = lookupBy === 'controlId'
2635
+ ? readControlAttestations(client, params.controlId, timings)
2636
+ : undefined;
2637
+ // Awaited once the control is found; a not_found or a failed read leaves it behind.
2638
+ attestationsRead?.catch(() => undefined);
2639
+ const context = { subdomainRead, timings, attestationsRead };
2640
+ const resolution = await timed(timings, 'control', () => resolveControl(client, lookupBy, params[lookupBy], params.includeDeleted ?? false, context));
2641
+ if (resolution.kind === 'outcome') {
2642
+ await subdomainRead;
2643
+ return (0, result_js_1.structuredResult)({ ...resolution.payload, timingsMs: { ...timings } });
2644
+ }
2645
+ return (0, result_js_1.structuredResult)(await describeControl(client, resolution, startedAt, context));
2646
+ },
2647
+ }),
2648
+ (0, types_js_1.defineTool)({
2649
+ name: 'create-attestation',
2650
+ title: 'Create Attestation',
2651
+ description: (0, load_description_js_1.loadDescription)('create-attestation.md'),
2652
+ inputSchema: {
2653
+ controlId: zod_1.z
2654
+ .string()
2655
+ .trim()
2656
+ .min(1)
2657
+ .refine((value) => !exports.CONTROL_ID_FORBIDDEN.test(value), {
2658
+ message: 'A control id never contains a quote or a backslash.',
2659
+ })
2660
+ .describe('The exact control id — resolve it with `get-control` first. Attestations apply only ' +
2661
+ 'to LIVE controls.'),
2662
+ subject: zod_1.z
2663
+ .string()
2664
+ .trim()
2665
+ .min(1, { error: BLANK_SUBJECT })
2666
+ .describe('What is attested, e.g. "Annual penetration test 2026". An active attestation with the ' +
2667
+ 'same subject on this control is returned instead of creating a duplicate.'),
2668
+ expiresOn: expiresOnInput().describe('When the attestation expires: "YYYY-MM-DD" (the end of that day, UTC), a date-time ' +
2669
+ 'with Z or an offset ("YYYY-MM-DDThh:mm:ssZ", "YYYY-MM-DDThh:mm:ss+hh:mm"), or epoch ' +
2670
+ 'milliseconds. ' +
2671
+ 'Must be in the future.'),
2672
+ description: zod_1.z.string().optional().describe('Optional detail, in markdown.'),
2673
+ owner: ownerEmail().optional().describe("Optional email address of the attestation's owner."),
2674
+ documentLink: evidenceLink()
2675
+ .optional()
2676
+ .describe('Optional http(s) link to the supporting evidence.'),
2677
+ },
2678
+ outputSchema: createAttestationOutput,
2679
+ // CREATE keeps idempotentHint false: inside the read-back lag a repeat would not see the first
2680
+ // attestation and would make a second one.
2681
+ annotations: types_js_1.CREATE,
2682
+ accessDeniedHint: ACCESS_DENIED_HINT,
2683
+ errorContext: 'Error creating attestation',
2684
+ handler: async (params, client) => {
2685
+ const expiresOn = parseExpiresOn(params.expiresOn);
2686
+ if (!expiresOn.ok)
2687
+ return expiresOnError('created', expiresOn.reason);
2688
+ const startedAt = Date.now();
2689
+ const subdomainRead = readSubdomain(client);
2690
+ // Implan's agent re-submitted the attestation form after reads that lagged the write. Any
2691
+ // failure of this read fails the call: a create without it could be that duplicate. Every
2692
+ // state but revoked comes back, so the same read finds the expired attestations that would
2693
+ // keep this control failing; the duplicate check still looks at ACTIVE ones only. It keys on
2694
+ // the id the caller passed, so it runs beside the control read: on j1dev each took 18-30 s
2695
+ // (2026-10-15).
2696
+ const attestationsRead = client.listAttestations({ controlId: params.controlId });
2697
+ // Awaited once the control is known to be LIVE; a refusal before then leaves it behind.
2698
+ attestationsRead.catch(() => undefined);
2699
+ const control = await findControl(client, params.controlId);
2700
+ if (!control)
2701
+ return controlNotFound(params.controlId);
2702
+ if (control.state !== 'LIVE')
2703
+ return controlNotLive(control);
2704
+ const attestations = await attestationsRead;
2705
+ const duplicates = activeWithSubject(attestations, params.subject);
2706
+ const controlSummary = {
2707
+ id: control.id,
2708
+ name: control.name,
2709
+ state: control.state,
2710
+ url: controlUrl(control.id, await subdomainBy(subdomainRead, startedAt + exports.WRITE_READ_DEADLINE_MS)),
2711
+ };
2712
+ if (duplicates.length > 0) {
2713
+ const existing = pickDuplicate(duplicates, params.subject);
2714
+ const impact = statusImpact(control, attestations, existing);
2715
+ const several = duplicates.length > 1;
2716
+ // On j1dev a retry asking for 2027-02-28 got back an attestation expiring three minutes
2717
+ // later, with nothing saying the requested date was dropped (2026-10-14).
2718
+ const applied = existing.expiresOn === expiresOn.ms;
2719
+ const notes = [
2720
+ NOTE_ALREADY_EXISTS,
2721
+ ...(several ? [NOTE_SEVERAL_MATCHES] : []),
2722
+ ...(applied ? [] : [expiryNotAppliedNote(expiresOn.ms, existing)]),
2723
+ ];
2724
+ return (0, result_js_1.structuredResult)({
2725
+ outcome: 'already_exists',
2726
+ attestation: projectAttestation(existing),
2727
+ requestedExpiresOnIso: toIso(expiresOn.ms),
2728
+ ...(applied ? {} : { requestedExpiresOnApplied: false }),
2729
+ ...(several ? { matches: duplicates.map(duplicateMatch) } : {}),
2730
+ control: controlSummary,
2731
+ ...impact,
2732
+ note: withBlockerNotes(notes.join(' '), impact),
2733
+ });
2734
+ }
2735
+ let created;
2736
+ try {
2737
+ created = await client.createAttestation({
2738
+ controlId: control.id,
2739
+ subject: params.subject,
2740
+ expiresOn: expiresOn.ms,
2741
+ description: nonEmpty(params.description),
2742
+ owner: params.owner,
2743
+ documentLink: params.documentLink,
2744
+ });
2745
+ }
2746
+ catch (error) {
2747
+ if (isAborted(error))
2748
+ return interrupted('create');
2749
+ throw error;
2750
+ }
2751
+ const impact = statusImpact(control, attestations, created);
2752
+ return (0, result_js_1.structuredResult)({
2753
+ outcome: 'created',
2754
+ attestation: projectAttestation(created),
2755
+ control: controlSummary,
2756
+ ...impact,
2757
+ note: withBlockerNotes(NOTE_CREATED, impact),
2758
+ });
2759
+ },
2760
+ }),
2761
+ (0, types_js_1.defineTool)({
2762
+ name: 'update-attestation',
2763
+ title: 'Update Attestation',
2764
+ description: (0, load_description_js_1.loadDescription)('update-attestation.md'),
2765
+ inputSchema: {
2766
+ attestationId: attestationIdInput(),
2767
+ subject: zod_1.z
2768
+ .string()
2769
+ .trim()
2770
+ .min(1, { error: BLANK_SUBJECT })
2771
+ .optional()
2772
+ .describe('A new subject.'),
2773
+ description: zod_1.z
2774
+ .string()
2775
+ .nullable()
2776
+ .optional()
2777
+ .describe('New detail, in markdown; null clears it.'),
2778
+ expiresOn: expiresOnInput()
2779
+ .optional()
2780
+ .describe('A new expiry — how an attestation is renewed: "YYYY-MM-DD" (the end of that day, ' +
2781
+ 'UTC), a date-time with Z or an offset, or epoch milliseconds. Must be in the future.'),
2782
+ owner: ownerEmail()
2783
+ .nullable()
2784
+ .optional()
2785
+ .describe("A new owner's email address; null clears it."),
2786
+ documentLink: evidenceLink()
2787
+ .nullable()
2788
+ .optional()
2789
+ .describe('A new http(s) evidence link; null clears it.'),
2790
+ },
2791
+ outputSchema: updateAttestationOutput,
2792
+ annotations: types_js_1.MUTATE,
2793
+ accessDeniedHint: ACCESS_DENIED_HINT,
2794
+ errorContext: 'Error updating attestation',
2795
+ handler: async ({ attestationId, ...changes }, client) => {
2796
+ const startedAt = Date.now();
2797
+ if (Object.values(changes).every((value) => value === undefined)) {
2798
+ return validationError('Attestation not updated — pass at least one field to change: `subject`, ' +
2799
+ '`description`, `expiresOn`, `owner` or `documentLink`.');
2800
+ }
2801
+ let expiresOn;
2802
+ if (changes.expiresOn !== undefined) {
2803
+ const parsed = parseExpiresOn(changes.expiresOn);
2804
+ if (!parsed.ok)
2805
+ return expiresOnError('updated', parsed.reason);
2806
+ expiresOn = parsed.ms;
2807
+ }
2808
+ const subdomainRead = readSubdomain(client);
2809
+ let updated;
2810
+ try {
2811
+ updated = await client.updateAttestation({
2812
+ id: attestationId,
2813
+ subject: changes.subject,
2814
+ description: clearable(changes.description),
2815
+ expiresOn,
2816
+ owner: changes.owner,
2817
+ documentLink: changes.documentLink,
2818
+ });
2819
+ }
2820
+ catch (error) {
2821
+ if (isNotFound(error)) {
2822
+ return (0, result_js_1.structuredResult)({
2823
+ outcome: 'not_found',
2824
+ attestationId,
2825
+ note: NOTE_UPDATE_NOT_FOUND,
2826
+ });
2827
+ }
2828
+ if (isAborted(error))
2829
+ return interrupted('update');
2830
+ throw error;
2831
+ }
2832
+ // The update has landed: nothing after it may turn the answer into an error.
2833
+ const deadlineAt = startedAt + exports.WRITE_READ_DEADLINE_MS;
2834
+ const subdomain = await subdomainBy(subdomainRead, deadlineAt);
2835
+ return (0, result_js_1.structuredResult)({
2836
+ outcome: 'updated',
2837
+ attestation: projectAttestation(updated),
2838
+ note: NOTE_UPDATED,
2839
+ ...(await updateImpact(client, updated, subdomain, deadlineAt)),
2840
+ });
2841
+ },
2842
+ }),
2843
+ (0, types_js_1.defineTool)({
2844
+ name: 'revoke-attestation',
2845
+ title: 'Revoke Attestation',
2846
+ description: (0, load_description_js_1.loadDescription)('revoke-attestation.md'),
2847
+ inputSchema: {
2848
+ attestationId: attestationIdInput(),
2849
+ },
2850
+ outputSchema: revokeAttestationOutput,
2851
+ // Confirmed on dev (2026-10-14): a second revoke of the same id gets the backend's not-found,
2852
+ // returned as outcome not_found, and changes nothing, so repeating the call is harmless.
2853
+ annotations: { ...types_js_1.MUTATE, idempotentHint: true },
2854
+ accessDeniedHint: ACCESS_DENIED_HINT,
2855
+ errorContext: 'Error revoking attestation',
2856
+ handler: async ({ attestationId }, client) => {
2857
+ const startedAt = Date.now();
2858
+ const subdomainRead = readSubdomain(client);
2859
+ let revoked;
2860
+ try {
2861
+ revoked = await client.revokeAttestation({ id: attestationId });
2862
+ }
2863
+ catch (error) {
2864
+ if (isNotFound(error)) {
2865
+ return (0, result_js_1.structuredResult)({
2866
+ outcome: 'not_found',
2867
+ attestationId,
2868
+ note: NOTE_REVOKE_NOT_FOUND,
2869
+ });
2870
+ }
2871
+ if (isAborted(error))
2872
+ return interrupted('revoke');
2873
+ throw error;
2874
+ }
2875
+ // The revoke has landed: nothing after it may turn the answer into an error.
2876
+ const deadlineAt = startedAt + exports.WRITE_READ_DEADLINE_MS;
2877
+ const subdomain = await subdomainBy(subdomainRead, deadlineAt);
2878
+ return (0, result_js_1.structuredResult)({
2879
+ outcome: 'revoked',
2880
+ attestation: projectAttestation(revoked),
2881
+ ...(await revokeEffect(client, revoked, subdomain, deadlineAt)),
2882
+ });
2883
+ },
2884
+ }),
2885
+ ];
2886
+ //# sourceMappingURL=compliance.js.map