@skrr-ai/cli 0.1.93 → 0.1.94

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/dist/commands/agents/operating-plan.d.ts +11 -0
  2. package/dist/commands/agents/operating-plan.js +54 -0
  3. package/dist/commands/agents/roles/example.d.ts +11 -0
  4. package/dist/commands/agents/roles/example.js +30 -0
  5. package/dist/commands/{commitments/mode.d.ts → agents/roles/export.d.ts} +5 -5
  6. package/dist/commands/agents/roles/export.js +81 -0
  7. package/dist/commands/agents/roles/install.d.ts +12 -0
  8. package/dist/commands/agents/roles/install.js +48 -0
  9. package/dist/commands/agents/roles/list.d.ts +11 -0
  10. package/dist/commands/agents/roles/list.js +36 -0
  11. package/dist/commands/agents/roles/preview.d.ts +14 -0
  12. package/dist/commands/agents/roles/preview.js +49 -0
  13. package/dist/commands/agents/roles/withdraw.d.ts +13 -0
  14. package/dist/commands/agents/roles/withdraw.js +43 -0
  15. package/dist/commands/commitments/{autonomy-requests → cadence-requests}/decide.d.ts +5 -7
  16. package/dist/commands/commitments/{autonomy-requests → cadence-requests}/decide.js +13 -15
  17. package/dist/commands/commitments/cost.d.ts +1 -1
  18. package/dist/commands/commitments/cost.js +1 -1
  19. package/dist/commands/commitments/create.d.ts +0 -7
  20. package/dist/commands/commitments/create.js +9 -98
  21. package/dist/commands/commitments/delivery.js +3 -21
  22. package/dist/commands/commitments/doctor.js +28 -27
  23. package/dist/commands/commitments/effective-policy.js +5 -36
  24. package/dist/commands/commitments/evaluations.d.ts +15 -0
  25. package/dist/commands/commitments/evaluations.js +54 -0
  26. package/dist/commands/commitments/pack/activate.d.ts +11 -0
  27. package/dist/commands/commitments/pack/activate.js +22 -0
  28. package/dist/commands/commitments/pack/bind.js +1 -1
  29. package/dist/commands/commitments/remediate.js +2 -5
  30. package/dist/commands/commitments/show.js +1 -1
  31. package/dist/commands/commitments/update.js +9 -9
  32. package/dist/commands/commitments/wake-capabilities.d.ts +1 -3
  33. package/dist/commands/commitments/wake-capabilities.js +5 -21
  34. package/dist/lib/commitment-product.d.ts +0 -6
  35. package/dist/lib/commitment-product.js +1 -30
  36. package/dist/lib/commitments.d.ts +9 -45
  37. package/dist/lib/commitments.js +24 -95
  38. package/dist/lib/northstars.js +1 -1
  39. package/dist/lib/roles.d.ts +98 -0
  40. package/dist/lib/roles.js +45 -0
  41. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/commitmentExecutionContract.d.ts +45 -0
  42. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/commitmentExecutionContract.js +550 -0
  43. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/sessionPermissionAuthority.d.ts +7 -44
  44. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/sessionPermissionAuthority.js +8 -47
  45. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/commitmentExecutionContract.d.ts +45 -0
  46. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/commitmentExecutionContract.js +545 -0
  47. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/sessionPermissionAuthority.d.ts +7 -44
  48. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/sessionPermissionAuthority.js +8 -47
  49. package/dist/node_modules/@skrr-ai/auth-core/package.json +11 -1
  50. package/dist/node_modules/@skrr-ai/data-provider/index.js +7316 -7203
  51. package/dist/node_modules/@skrr-ai/data-provider/package.json +2 -2
  52. package/oclif.manifest.json +22528 -22170
  53. package/package.json +5 -2
  54. package/dist/commands/commitments/autonomy.d.ts +0 -30
  55. package/dist/commands/commitments/autonomy.js +0 -67
  56. package/dist/commands/commitments/mode.js +0 -58
  57. package/dist/commands/commitments/pack/promote.d.ts +0 -19
  58. package/dist/commands/commitments/pack/promote.js +0 -46
  59. package/dist/commands/commitments/pack/shadow.d.ts +0 -20
  60. package/dist/commands/commitments/pack/shadow.js +0 -42
@@ -1,34 +1,6 @@
1
1
  "use strict";
2
- /**
3
- * Session permission authority — the ONE rule that decides whether a session's
4
- * execution contract governs the run's permissions, shared by the server and
5
- * the daemon (OSK-11975 introduced it; it was implemented twice — the server
6
- * read `kind !== 'commitment'`, the daemon read the `permissionSource` marker —
7
- * which is exactly how a new contract kind or a new source value would drift
8
- * them apart).
9
- *
10
- * The wire model:
11
- *
12
- * - The contract is closed (`hasOnlyKeys` on the daemon), so "whose
13
- * permissions govern" can never ride INSIDE it. It is a top-level session
14
- * field: `permissionSource`.
15
- * - `'agent'` means the Agent's own configured permission mode, tool policy,
16
- * Grants, session env, MCP servers and machine consent govern the run,
17
- * exactly as for an unattended Task of the same Agent. Today only a
18
- * `commitment` contract may carry it.
19
- * - A `commitment` contract WITHOUT the marker (an older server mid-deploy)
20
- * still governs permissions — the marker is the version signal, so its
21
- * absence must keep the legacy fence, not silently lift it.
22
- * - `task_delivery` contracts always govern, marker or not.
23
- *
24
- * Server vs daemon asymmetry, on purpose: the server STAMPS the marker
25
- * (`permissionSourceForContract`), so on its own side the predicate reduces to
26
- * "a commitment never governs" — `contractGovernsPermissions(c,
27
- * permissionSourceForContract(c))` is exactly `kind !== 'commitment'`. The
28
- * daemon reads the marker it received, because it cannot distinguish "new
29
- * server, agent permissions" from "old server, contract fence" any other way.
30
- * Both call the same function; only the input differs.
31
- */
2
+ /** Commitment context never overrides Agent permissions. Version 3 admission
3
+ * rejects old contracts; typed Task delivery is a separate frozen operation. */
32
4
  Object.defineProperty(exports, "__esModule", { value: true });
33
5
  exports.COMMITMENT_AGENT_PERMISSIONS_CAPABILITY = exports.SESSION_PERMISSION_SOURCES = void 0;
34
6
  exports.normalizeSessionPermissionSource = normalizeSessionPermissionSource;
@@ -43,11 +15,10 @@ exports.SESSION_PERMISSION_SOURCES = ['agent'];
43
15
  * a daemon without it (`COMMITMENT_AGENT_PERMISSIONS_RUNTIME_UNSUPPORTED`), so
44
16
  * the marker never reaches a daemon that would ignore it.
45
17
  */
46
- exports.COMMITMENT_AGENT_PERMISSIONS_CAPABILITY = 'commitment_execution_contract_v2_agent_permissions';
18
+ exports.COMMITMENT_AGENT_PERMISSIONS_CAPABILITY = 'commitment_execution_contract_v3';
47
19
  /**
48
20
  * Untrusted wire input: anything but an exact vocabulary literal reads as
49
- * absent. Never widen by coercion — an unrecognized future value must degrade
50
- * to "contract governs", the conservative answer.
21
+ * absent. An unknown marker carries no authority. Contract admission is validated separately.
51
22
  */
52
23
  function normalizeSessionPermissionSource(value) {
53
24
  return exports.SESSION_PERMISSION_SOURCES.includes(value)
@@ -62,21 +33,11 @@ function normalizeSessionPermissionSource(value) {
62
33
  function permissionSourceForContract(contract) {
63
34
  return contract?.kind === 'commitment' ? 'agent' : undefined;
64
35
  }
65
- /**
66
- * Whether the contract is the run's PERMISSION authority — the single place
67
- * this rule lives.
68
- *
69
- * True for a non-commitment contract regardless of marker, and for a
70
- * commitment whose server did not declare agent permissions. False for no
71
- * contract at all, and for a commitment carrying `permissionSource: 'agent'`,
72
- * which then follows the Agent's own permissions exactly as a Task does while
73
- * the contract keeps its non-permission roles (normalized shape, ephemeral
74
- * worktree, result validation, `GIT_OPTIONAL_LOCKS`, provider restriction).
36
+ /** Only typed Task delivery owns an effect-specific permission boundary.
37
+ * A Commitment is context for the Agent and cannot grant or restrict tools.
75
38
  */
76
- function contractGovernsPermissions(contract, permissionSource) {
77
- if (!contract)
78
- return false;
79
- return !(contract.kind === 'commitment' && normalizeSessionPermissionSource(permissionSource) === 'agent');
39
+ function contractGovernsPermissions(contract, _permissionSource) {
40
+ return Boolean(contract && contract.kind !== 'commitment');
80
41
  }
81
42
  /**
82
43
  * The contract when it governs permissions, else `undefined` — for the sites
@@ -0,0 +1,45 @@
1
+ /** Mode-free responsibility context. Tool permissions belong to the Agent runtime. */
2
+ export declare const COMMITMENT_EXECUTION_CONTRACT_VERSION: 3;
3
+ export declare const COMMITMENT_EXECUTION_CONTRACT_CAPABILITY = "commitment_execution_contract_v3";
4
+ export interface CommitmentExecutionContract {
5
+ version: 3;
6
+ kind: 'commitment' | 'task_delivery';
7
+ responsibilityRef: {
8
+ kind: 'commitment' | 'task';
9
+ id: string;
10
+ version: number;
11
+ };
12
+ responsibility: string;
13
+ event: Record<string, unknown> | null;
14
+ workspace: {
15
+ kind: 'ephemeral';
16
+ base: string;
17
+ fetchBase?: true;
18
+ };
19
+ delivery: {
20
+ version: 1;
21
+ mode: 'report_only' | 'local_patch' | 'draft_pr' | 'push_branch' | 'direct_branch';
22
+ [key: string]: unknown;
23
+ };
24
+ capabilitySources: unknown[];
25
+ evidence?: {
26
+ version: 1;
27
+ ci: unknown[];
28
+ };
29
+ workspacePolicy: Record<string, unknown>;
30
+ deliverySource?: {
31
+ parentTaskId: string;
32
+ branch: string;
33
+ headSha: string;
34
+ baseCommit: string;
35
+ runtime: {
36
+ kind: 'local_daemon' | 'hosted_machine';
37
+ id: string;
38
+ };
39
+ };
40
+ mustNot: string[];
41
+ return: 'commitment_result_v1' | 'task_output';
42
+ }
43
+ export declare function eventRepository(event: Record<string, unknown> | null | undefined): string;
44
+ /** One strict parser used at storage admission and at runtime admission. */
45
+ export declare function normalizeCommitmentExecutionContract(value: unknown): CommitmentExecutionContract | null;
@@ -0,0 +1,545 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ /** Mode-free responsibility context. Tool permissions belong to the Agent runtime. */
3
+ export const COMMITMENT_EXECUTION_CONTRACT_VERSION = 3;
4
+ export const COMMITMENT_EXECUTION_CONTRACT_CAPABILITY = 'commitment_execution_contract_v3';
5
+ const DELIVERY_MODES = new Set([
6
+ 'report_only',
7
+ 'local_patch',
8
+ 'draft_pr',
9
+ 'push_branch',
10
+ 'direct_branch',
11
+ ]);
12
+ const FACT_KEYS = new Set([
13
+ 'id',
14
+ 'source',
15
+ 'type',
16
+ 'eventType',
17
+ 'checkName',
18
+ 'workflowName',
19
+ 'workflowRunId',
20
+ 'revision',
21
+ 'appId',
22
+ 'appSlug',
23
+ 'slug',
24
+ 'app',
25
+ 'action',
26
+ 'status',
27
+ 'conclusion',
28
+ 'sha',
29
+ 'headSha',
30
+ 'head_sha',
31
+ 'branch',
32
+ 'headBranch',
33
+ 'head_branch',
34
+ 'repo',
35
+ 'repository',
36
+ 'fullName',
37
+ 'full_name',
38
+ 'repoFullName',
39
+ 'prNumber',
40
+ 'owner',
41
+ 'name',
42
+ 'number',
43
+ 'checkRunId',
44
+ 'check_run_id',
45
+ 'runId',
46
+ 'run_id',
47
+ 'url',
48
+ 'runUrl',
49
+ 'htmlUrl',
50
+ 'html_url',
51
+ 'createdAt',
52
+ 'updatedAt',
53
+ 'occurredAt',
54
+ 'completed_at',
55
+ 'started_at',
56
+ 'check_run',
57
+ 'check_suite',
58
+ 'workflow_run',
59
+ 'pull_request',
60
+ 'base',
61
+ 'head',
62
+ 'ref',
63
+ 'eventId',
64
+ 'rerun',
65
+ 'checkAnnotations',
66
+ 'path',
67
+ 'startLine',
68
+ 'endLine',
69
+ 'level',
70
+ 'message',
71
+ 'title',
72
+ ]);
73
+ const CAPABILITY_SOURCE_KEYS = new Set([
74
+ 'source',
75
+ 'provider',
76
+ 'capability',
77
+ 'scope',
78
+ 'status',
79
+ 'attestation',
80
+ 'accountFingerprint',
81
+ 'testedAt',
82
+ 'expiresAt',
83
+ 'runtimeId',
84
+ 'reason',
85
+ ]);
86
+ const WORKSPACE_CONSTRAINT_KEYS = new Set([
87
+ 'allowedCommitmentDeliveryModes',
88
+ 'requireAttestedAccessForDeliveryModes',
89
+ 'maxInitiativesPerDay',
90
+ 'maxAutoRunsPerDay',
91
+ 'maxCommitmentActionRunsPerDay',
92
+ 'maxCommitmentObservationRunsPerDay',
93
+ 'maxCommitmentConcurrentRuns',
94
+ 'maxCommitmentCostUsdPerDay',
95
+ 'requireApprovalRiskLevels',
96
+ 'requireApprovalActionClasses',
97
+ 'blockedSourceKinds',
98
+ ]);
99
+ const CAPABILITY_SOURCES = new Set([
100
+ 'event_payload',
101
+ 'cloud_runtime',
102
+ 'local_harness',
103
+ 'platform_grant',
104
+ ]);
105
+ const CAPABILITY_STATUSES = new Set(['available', 'unavailable', 'unknown', 'stale']);
106
+ const CAPABILITY_ATTESTATIONS = new Set(['platform', 'runtime', 'machine', 'none']);
107
+ function plainObject(value) {
108
+ if (!value || typeof value !== 'object' || Array.isArray(value))
109
+ return false;
110
+ const prototype = Object.getPrototypeOf(value);
111
+ return prototype === Object.prototype || prototype === null;
112
+ }
113
+ function hasOnlyKeys(value, allowed) {
114
+ return plainObject(value) && Object.keys(value).every((key) => allowed.has(key));
115
+ }
116
+ function boundedString(value, max = 1000) {
117
+ return typeof value === 'string' && value.length > 0 && value.length <= max;
118
+ }
119
+ function optionalString(value, max = 1000) {
120
+ return typeof value === 'string' && value.length <= max;
121
+ }
122
+ function isoTimestamp(value) {
123
+ return (typeof value === 'string' &&
124
+ value.length <= 40 &&
125
+ Number.isFinite(Date.parse(value)) &&
126
+ new Date(value).toISOString() === value);
127
+ }
128
+ function normalizedEventFactValue(item, depth) {
129
+ if (typeof item === 'string') {
130
+ if (containsCredentialSignature(item))
131
+ return undefined;
132
+ return item.slice(0, 1000);
133
+ }
134
+ if (typeof item === 'number' || typeof item === 'boolean')
135
+ return item;
136
+ if (Array.isArray(item)) {
137
+ return item
138
+ .slice(0, 20)
139
+ .map((entry) => normalizedEventFacts(entry, depth + 1))
140
+ .filter((entry) => entry !== undefined);
141
+ }
142
+ return normalizedEventFacts(item, depth + 1);
143
+ }
144
+ const CREDENTIAL_SIGNATURE_RE = /(?:bearer\s+(?!\[REDACTED\](?:\s|$))\S{8,}|github_pat_[A-Za-z0-9_]{8,}|gh[pousr]_[A-Za-z0-9_]{8,}|xox[baprs]-[A-Za-z0-9-]{8,}|sk_(?:live|test)_[A-Za-z0-9]{8,}|(?:AKIA|ASIA)[A-Z0-9]{16}|eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}|[a-z][a-z0-9+.-]*:\/\/[^\s:/@]+:(?!\[REDACTED\]@)[^\s/@]+@|-----BEGIN [A-Z ]*PRIVATE KEY-----)/i;
145
+ function containsCredentialSignature(value) {
146
+ return typeof value === 'string' && CREDENTIAL_SIGNATURE_RE.test(value);
147
+ }
148
+ function normalizedEventFacts(value, depth = 0) {
149
+ if (!plainObject(value) || depth > 3)
150
+ return undefined;
151
+ return Object.fromEntries(Object.entries(value)
152
+ .filter(([key]) => FACT_KEYS.has(key))
153
+ .slice(0, 30)
154
+ .map(([key, item]) => [key, normalizedEventFactValue(item, depth)])
155
+ .filter(([, item]) => item !== undefined));
156
+ }
157
+ const CI_LOG_EVIDENCE_KEYS = new Set([
158
+ 'version',
159
+ 'provider',
160
+ 'kind',
161
+ 'repoFullName',
162
+ 'checkRunId',
163
+ 'workflowRunId',
164
+ 'jobId',
165
+ 'capability',
166
+ 'attestation',
167
+ 'fetchedAt',
168
+ 'status',
169
+ 'reason',
170
+ 'byteLength',
171
+ 'lineCount',
172
+ 'excerptLines',
173
+ 'excerpt',
174
+ 'digest',
175
+ // Attribution facts, taken off the job row the server had to fetch to prove
176
+ // identity. Allowed on an UNREADABLE row: attribution happens before the
177
+ // download, so the failing step name survives a log the server could not
178
+ // read. Only text FROM the log is withheld when the read failed.
179
+ 'jobName',
180
+ 'failedStepName',
181
+ 'failedStepNumber',
182
+ ]);
183
+ const CI_LOG_EVIDENCE_STATUSES = new Set(['available', 'truncated', 'unavailable', 'unauthorized']);
184
+ const CI_LOG_EVIDENCE_READABLE = new Set(['available', 'truncated']);
185
+ const CI_LOG_EXCERPT_MAX_CHARS = 12_000;
186
+ function validCiLogEvidence(value) {
187
+ if (!hasOnlyKeys(value, CI_LOG_EVIDENCE_KEYS))
188
+ return false;
189
+ if (value.version !== 1 ||
190
+ value.provider !== 'github' ||
191
+ value.kind !== 'actions_job_log' ||
192
+ value.capability !== 'github:actions:read' ||
193
+ value.attestation !== 'platform' ||
194
+ !CI_LOG_EVIDENCE_STATUSES.has(String(value.status)) ||
195
+ !isoTimestamp(value.fetchedAt) ||
196
+ !/^[\w.-]+\/[\w.-]+$/.test(String(value.repoFullName || '')) ||
197
+ !/^\d{1,20}$/.test(String(value.checkRunId || '')))
198
+ return false;
199
+ for (const key of ['workflowRunId', 'jobId']) {
200
+ if (value[key] !== undefined && !/^\d{1,20}$/.test(String(value[key])))
201
+ return false;
202
+ }
203
+ for (const key of ['byteLength', 'lineCount', 'excerptLines', 'failedStepNumber']) {
204
+ const item = value[key];
205
+ if (item !== undefined && (!Number.isSafeInteger(item) || item < 0))
206
+ return false;
207
+ }
208
+ for (const key of ['jobName', 'failedStepName']) {
209
+ if (value[key] !== undefined && !boundedString(value[key], 200))
210
+ return false;
211
+ }
212
+ if (value.reason !== undefined && !/^[a-z0-9_]{1,80}$/.test(String(value.reason)))
213
+ return false;
214
+ if (value.digest !== undefined && !/^[a-f0-9]{16}$/.test(String(value.digest)))
215
+ return false;
216
+ // A read that failed carries no text: an unreadable log must not be able to
217
+ // arrive looking like a readable one.
218
+ if (!CI_LOG_EVIDENCE_READABLE.has(String(value.status))) {
219
+ return value.excerpt === undefined && value.digest === undefined && Boolean(value.reason);
220
+ }
221
+ return boundedString(value.excerpt, CI_LOG_EXCERPT_MAX_CHARS) && value.jobId !== undefined;
222
+ }
223
+ function validEvidence(value) {
224
+ if (!hasOnlyKeys(value, new Set(['version', 'ci'])))
225
+ return false;
226
+ return (value.version === 1 &&
227
+ Array.isArray(value.ci) &&
228
+ value.ci.length >= 1 &&
229
+ value.ci.length <= 4 &&
230
+ value.ci.every(validCiLogEvidence));
231
+ }
232
+ // Mirror of `validObserve` in
233
+ // api/server/services/Commitments/CommitmentExecutionContract.js. The daemon
234
+ // has no projector, so canonical form is part of validity on both sides:
235
+ // `egress` must be strictly ascending (sorted AND unique). The shared parity
236
+ // fixture holds the two to one verdict.
237
+ const OBSERVE_KEYS = new Set(['egress', 'web', 'shell', 'browser']);
238
+ const OBSERVE_EGRESS_MAX = 32;
239
+ const OBSERVE_HOST_PATTERN = /^(\*\.)?[a-z0-9.-]+$/;
240
+ const OBSERVE_HOST_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
241
+ function evidenceMatchesEvent(row, event) {
242
+ if (!plainObject(row) || !plainObject(event))
243
+ return true;
244
+ const same = (a, b) => String(a).toLowerCase() === String(b).toLowerCase();
245
+ if (event.repoFullName !== undefined && !same(row.repoFullName, event.repoFullName))
246
+ return false;
247
+ if (event.checkRunId !== undefined && !same(row.checkRunId, event.checkRunId))
248
+ return false;
249
+ if (row.workflowRunId !== undefined &&
250
+ event.workflowRunId !== undefined &&
251
+ !same(row.workflowRunId, event.workflowRunId))
252
+ return false;
253
+ return true;
254
+ }
255
+ function validCapabilitySource(value) {
256
+ if (!hasOnlyKeys(value, CAPABILITY_SOURCE_KEYS))
257
+ return false;
258
+ if (!CAPABILITY_SOURCES.has(String(value.source)) ||
259
+ !boundedString(value.provider, 80) ||
260
+ !/^[a-z0-9_.-]{1,80}$/i.test(value.provider) ||
261
+ !boundedString(value.capability, 120) ||
262
+ !/^[a-z0-9_:.-]{1,120}$/i.test(value.capability) ||
263
+ !CAPABILITY_STATUSES.has(String(value.status)) ||
264
+ !CAPABILITY_ATTESTATIONS.has(String(value.attestation)))
265
+ return false;
266
+ if (value.scope !== undefined && !optionalString(value.scope, 500))
267
+ return false;
268
+ if (value.accountFingerprint !== undefined &&
269
+ !/^[a-f0-9]{64}$/i.test(String(value.accountFingerprint)))
270
+ return false;
271
+ if (value.testedAt !== undefined && !isoTimestamp(value.testedAt))
272
+ return false;
273
+ if (value.expiresAt !== undefined && !isoTimestamp(value.expiresAt))
274
+ return false;
275
+ if (value.testedAt &&
276
+ value.expiresAt &&
277
+ Date.parse(String(value.expiresAt)) <= Date.parse(String(value.testedAt)))
278
+ return false;
279
+ if (value.runtimeId !== undefined && !boundedString(value.runtimeId, 200))
280
+ return false;
281
+ if (value.reason !== undefined && !optionalString(value.reason, 1000))
282
+ return false;
283
+ if (value.source === 'event_payload' && value.attestation !== 'platform')
284
+ return false;
285
+ if (value.source === 'platform_grant' && value.attestation !== 'platform')
286
+ return false;
287
+ if (value.source === 'local_harness' &&
288
+ (!['machine', 'none'].includes(String(value.attestation)) ||
289
+ (value.status === 'available' &&
290
+ (value.attestation !== 'machine' ||
291
+ !value.accountFingerprint ||
292
+ !value.testedAt ||
293
+ !value.expiresAt ||
294
+ !value.runtimeId))))
295
+ return false;
296
+ if (value.source === 'cloud_runtime' &&
297
+ (!['runtime', 'none'].includes(String(value.attestation)) ||
298
+ (value.status === 'available' &&
299
+ (value.attestation !== 'runtime' ||
300
+ !value.accountFingerprint ||
301
+ !value.testedAt ||
302
+ !value.expiresAt ||
303
+ !value.runtimeId))))
304
+ return false;
305
+ return true;
306
+ }
307
+ function validStringArray(value, max, values) {
308
+ return (Array.isArray(value) &&
309
+ value.length <= max &&
310
+ value.every((item) => boundedString(item, 120) && (!values || values.has(item))));
311
+ }
312
+ function validWorkspacePolicy(value) {
313
+ if (!hasOnlyKeys(value, new Set(['hardStop', 'hardConstraints'])))
314
+ return false;
315
+ if (value.hardStop !== undefined && value.hardStop !== null) {
316
+ if (!hasOnlyKeys(value.hardStop, new Set(['enabled', 'reason', 'scope'])))
317
+ return false;
318
+ if (typeof value.hardStop.enabled !== 'boolean')
319
+ return false;
320
+ if (value.hardStop.reason !== undefined && !optionalString(value.hardStop.reason, 1000))
321
+ return false;
322
+ if (value.hardStop.scope !== undefined && !optionalString(value.hardStop.scope, 100))
323
+ return false;
324
+ }
325
+ if (value.hardConstraints === undefined)
326
+ return true;
327
+ if (!hasOnlyKeys(value.hardConstraints, WORKSPACE_CONSTRAINT_KEYS))
328
+ return false;
329
+ for (const [key, item] of Object.entries(value.hardConstraints)) {
330
+ if (item === null)
331
+ continue;
332
+ if (key === 'allowedCommitmentDeliveryModes' ||
333
+ key === 'requireAttestedAccessForDeliveryModes') {
334
+ if (!validStringArray(item, 5, DELIVERY_MODES))
335
+ return false;
336
+ }
337
+ else if (key === 'maxCommitmentCostUsdPerDay') {
338
+ if (typeof item !== 'number' || !Number.isFinite(item) || item < 0)
339
+ return false;
340
+ }
341
+ else if (key.startsWith('max')) {
342
+ if (!Number.isSafeInteger(item) || Number(item) < 0)
343
+ return false;
344
+ }
345
+ else if (key === 'requireApprovalRiskLevels') {
346
+ if (!validStringArray(item, 3, new Set(['low', 'medium', 'high'])))
347
+ return false;
348
+ }
349
+ else if (!validStringArray(item, key === 'blockedSourceKinds' ? 50 : 20))
350
+ return false;
351
+ }
352
+ return true;
353
+ }
354
+ function validBranch(value) {
355
+ return (boundedString(value, 255) &&
356
+ value !== 'HEAD' &&
357
+ !value.startsWith('refs/') &&
358
+ !value.startsWith('origin/') &&
359
+ !value.startsWith('-') &&
360
+ !value.startsWith('/') &&
361
+ !value.endsWith('/') &&
362
+ !value.endsWith('.') &&
363
+ // Control characters are exactly what this rejects: a Git ref name may not
364
+ // contain them, so the class is deliberate rather than an oversight.
365
+ // eslint-disable-next-line no-control-regex
366
+ !/[\s~^:?*[\\\x00-\x1f\x7f]/.test(value) &&
367
+ !value.includes('..') &&
368
+ !value.includes('@{') &&
369
+ !value.includes('//') &&
370
+ value !== '@' &&
371
+ !value.split('/').some((part) => part.startsWith('.') || part.endsWith('.lock')));
372
+ }
373
+ function validDelivery(value) {
374
+ if (!hasOnlyKeys(value, new Set(['version', 'mode', 'repo', 'baseBranch', 'expectations'])))
375
+ return false;
376
+ if (value.version !== 1 || !DELIVERY_MODES.has(String(value.mode)))
377
+ return false;
378
+ if (value.repo !== undefined &&
379
+ (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(String(value.repo)) ||
380
+ String(value.repo) !== String(value.repo).toLowerCase()))
381
+ return false;
382
+ if (value.baseBranch !== undefined && !validBranch(value.baseBranch))
383
+ return false;
384
+ if (['draft_pr', 'push_branch', 'direct_branch'].includes(String(value.mode)) &&
385
+ (!value.repo || !value.baseBranch))
386
+ return false;
387
+ if (value.expectations !== undefined) {
388
+ if (!Array.isArray(value.expectations) || value.expectations.length > 20)
389
+ return false;
390
+ const ids = new Set();
391
+ const allowed = new Set([
392
+ 'id',
393
+ 'shape',
394
+ 'kind',
395
+ 'format',
396
+ 'target',
397
+ 'minimumAuthority',
398
+ 'description',
399
+ 'presetKey',
400
+ ]);
401
+ for (const expectation of value.expectations) {
402
+ if (!hasOnlyKeys(expectation, allowed) ||
403
+ !['code', 'page', 'url', 'file', 'message', 'dataset'].includes(String(expectation.kind)))
404
+ return false;
405
+ if (expectation.id !== undefined) {
406
+ if (!boundedString(expectation.id, 64) ||
407
+ expectation.id === 'commitment-delivery' ||
408
+ ids.has(expectation.id))
409
+ return false;
410
+ ids.add(expectation.id);
411
+ }
412
+ if (expectation.shape !== undefined &&
413
+ !['checkable', 'judged'].includes(String(expectation.shape)))
414
+ return false;
415
+ if (expectation.minimumAuthority !== undefined &&
416
+ !['self_reported', 'human_confirmed', 'observation_backed'].includes(String(expectation.minimumAuthority)))
417
+ return false;
418
+ for (const [key, max] of [
419
+ ['format', 40],
420
+ ['target', 500],
421
+ ['description', 500],
422
+ ['presetKey', 64],
423
+ ]) {
424
+ if (expectation[key] !== undefined && !optionalString(expectation[key], max))
425
+ return false;
426
+ }
427
+ }
428
+ }
429
+ return true;
430
+ }
431
+ function validDeliverySource(value) {
432
+ if (!hasOnlyKeys(value, new Set(['parentTaskId', 'branch', 'headSha', 'baseCommit', 'runtime'])))
433
+ return false;
434
+ return (typeof value.parentTaskId === 'string' &&
435
+ value.parentTaskId.length > 0 &&
436
+ value.parentTaskId.length <= 200 &&
437
+ typeof value.branch === 'string' &&
438
+ /^[A-Za-z0-9][A-Za-z0-9_./-]{0,239}$/.test(value.branch) &&
439
+ !value.branch.includes('..') &&
440
+ !value.branch.includes('@{') &&
441
+ /^[a-f0-9]{40,64}$/i.test(value.headSha) &&
442
+ typeof value.baseCommit === 'string' &&
443
+ /^[a-f0-9]{40,64}$/i.test(value.baseCommit) &&
444
+ hasOnlyKeys(value.runtime, new Set(['kind', 'id'])) &&
445
+ ['local_daemon', 'hosted_machine'].includes(String(value.runtime.kind)) &&
446
+ boundedString(value.runtime.id, 200) &&
447
+ (value.runtime.kind !== 'hosted_machine' || value.runtime.id.startsWith('sbs_')));
448
+ }
449
+ function eventSourceRevision(event) {
450
+ if (!event)
451
+ return '';
452
+ const nestedCheck = event.check_run;
453
+ const nestedWorkflow = event.workflow_run;
454
+ const value = event.headSha ||
455
+ event.head_sha ||
456
+ event.sha ||
457
+ nestedCheck?.head_sha ||
458
+ nestedWorkflow?.head_sha;
459
+ return /^[a-f0-9]{40,64}$/i.test(String(value || '')) ? String(value).toLowerCase() : '';
460
+ }
461
+ export function eventRepository(event) {
462
+ if (!event)
463
+ return '';
464
+ const repository = event.repository;
465
+ const value = event.repoFullName || repository?.full_name || repository?.fullName;
466
+ return /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(String(value || ''))
467
+ ? String(value).toLowerCase()
468
+ : '';
469
+ }
470
+ function failedGitHubCheck(event) {
471
+ const eventType = String(event?.eventType || event?.type || '').toLowerCase();
472
+ return eventType === 'github.check_run_failed' || eventType === 'check_run_failed';
473
+ }
474
+ /** One strict parser used at storage admission and at runtime admission. */
475
+ export function normalizeCommitmentExecutionContract(value) {
476
+ if (!hasOnlyKeys(value, new Set([
477
+ 'version',
478
+ 'kind',
479
+ 'responsibilityRef',
480
+ 'responsibility',
481
+ 'event',
482
+ 'workspace',
483
+ 'delivery',
484
+ 'capabilitySources',
485
+ 'evidence',
486
+ 'workspacePolicy',
487
+ 'deliverySource',
488
+ 'mustNot',
489
+ 'return',
490
+ ])))
491
+ return null;
492
+ const contract = value;
493
+ const event = contract.event === undefined ? null : contract.event;
494
+ const eventSha = eventSourceRevision(event);
495
+ const eventRepo = eventRepository(event);
496
+ const taskDelivery = contract.kind === 'task_delivery';
497
+ if (contract.version !== COMMITMENT_EXECUTION_CONTRACT_VERSION ||
498
+ !['commitment', 'task_delivery'].includes(contract.kind) ||
499
+ !hasOnlyKeys(contract.responsibilityRef, new Set(['kind', 'id', 'version'])) ||
500
+ contract.responsibilityRef.kind !== (taskDelivery ? 'task' : 'commitment') ||
501
+ !boundedString(contract.responsibilityRef.id, 240) ||
502
+ !Number.isSafeInteger(contract.responsibilityRef.version) ||
503
+ contract.responsibilityRef.version < 1 ||
504
+ !boundedString(contract.responsibility, 2000) ||
505
+ !hasOnlyKeys(contract.workspace, new Set(['kind', 'base', 'fetchBase'])) ||
506
+ contract.workspace.kind !== 'ephemeral' ||
507
+ !boundedString(contract.workspace.base, 255) ||
508
+ (contract.workspace.fetchBase !== undefined &&
509
+ (contract.workspace.fetchBase !== true || contract.workspace.kind !== 'ephemeral')) ||
510
+ !validDelivery(contract.delivery) ||
511
+ !Array.isArray(contract.capabilitySources) ||
512
+ contract.capabilitySources.length > 32 ||
513
+ !contract.capabilitySources.every(validCapabilitySource) ||
514
+ !validWorkspacePolicy(contract.workspacePolicy ?? {}) ||
515
+ !isDeepStrictEqual(contract.mustNot, [
516
+ 'change_workspace_administration',
517
+ 'broaden_credentials',
518
+ ...(taskDelivery ? ['reimplement_source_work'] : []),
519
+ ]) ||
520
+ (taskDelivery
521
+ ? contract.return !== 'task_output'
522
+ : contract.return !== 'commitment_result_v1') ||
523
+ (event !== null &&
524
+ (!plainObject(event) || !isDeepStrictEqual(event, normalizedEventFacts(event)))) ||
525
+ (eventSha && contract.workspace.base.toLowerCase() !== eventSha) ||
526
+ (eventRepo &&
527
+ contract.delivery.repo &&
528
+ String(contract.delivery.repo).toLowerCase() !== eventRepo) ||
529
+ (failedGitHubCheck(event) && (!eventSha || !eventRepo)) ||
530
+ (contract.evidence !== undefined &&
531
+ (taskDelivery ||
532
+ !validEvidence(contract.evidence) ||
533
+ !contract.evidence.ci.every((row) => evidenceMatchesEvent(row, event)))) ||
534
+ (taskDelivery &&
535
+ (event !== null ||
536
+ !['draft_pr', 'push_branch', 'direct_branch'].includes(contract.delivery.mode) ||
537
+ contract.workspace.kind !== 'ephemeral' ||
538
+ !validDeliverySource(contract.deliverySource) ||
539
+ contract.responsibilityRef.id !== contract.deliverySource?.parentTaskId ||
540
+ contract.workspace.base.toLowerCase() !==
541
+ String(contract.deliverySource?.baseCommit).toLowerCase())) ||
542
+ (!taskDelivery && contract.deliverySource !== undefined))
543
+ return null;
544
+ return JSON.parse(JSON.stringify(contract));
545
+ }