code60-transmission-server 0.0.0-stage → 0.1.0-staging.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/LICENSE +180 -0
  2. package/README.engine.md +401 -0
  3. package/README.md +291 -2
  4. package/dist/src/broker/filesystem.js +385 -0
  5. package/dist/src/broker/index.js +734 -0
  6. package/dist/src/broker/native/README.md +192 -0
  7. package/dist/src/broker/native/build.js +43 -0
  8. package/dist/src/broker/native/fs-helper.c +529 -0
  9. package/dist/src/broker/native/git-helper.c +205 -0
  10. package/dist/src/broker/policy.js +149 -0
  11. package/dist/src/broker/startup-lock.js +14 -0
  12. package/dist/src/broker/types.js +11 -0
  13. package/dist/src/cli/daemon.js +365 -0
  14. package/dist/src/cli/helpers.js +104 -0
  15. package/dist/src/cli/main.js +180 -0
  16. package/dist/src/config/deployment.js +163 -0
  17. package/dist/src/config/documents.js +29 -0
  18. package/dist/src/config/profile-validation.js +123 -0
  19. package/dist/src/config/schema-graph.js +237 -0
  20. package/dist/src/config/schema-loader.js +185 -0
  21. package/dist/src/config/validation-pool.js +105 -0
  22. package/dist/src/config/validation-protocol.js +1 -0
  23. package/dist/src/config/validation-worker.js +106 -0
  24. package/dist/src/config/workflow-language.js +9 -0
  25. package/dist/src/config/workflow-schema.json +534 -0
  26. package/dist/src/config/workflow-types.js +1 -0
  27. package/dist/src/config/workflow-validation.js +95 -0
  28. package/dist/src/engine/budgets.js +50 -0
  29. package/dist/src/engine/clocks.js +27 -0
  30. package/dist/src/engine/commands.js +441 -0
  31. package/dist/src/engine/contracts.js +11 -0
  32. package/dist/src/engine/drain-state.js +31 -0
  33. package/dist/src/engine/effective-permissions.js +120 -0
  34. package/dist/src/engine/instruction-pins.js +205 -0
  35. package/dist/src/engine/retries.js +50 -0
  36. package/dist/src/engine/state.js +1 -0
  37. package/dist/src/engine/timing.js +23 -0
  38. package/dist/src/engine/tool-observations.js +87 -0
  39. package/dist/src/engine/workflow-engine.js +1807 -0
  40. package/dist/src/main.js +25 -0
  41. package/dist/src/mcp/catalog.js +71 -0
  42. package/dist/src/mcp/main.js +24 -0
  43. package/dist/src/mcp/server.js +104 -0
  44. package/dist/src/runtime/codex-app-server.js +91 -0
  45. package/dist/src/runtime/containment.js +82 -0
  46. package/dist/src/runtime/engine-driver.js +212 -0
  47. package/dist/src/runtime/json-line-writer.js +192 -0
  48. package/dist/src/runtime/pinned-instruction-sources.js +24 -0
  49. package/dist/src/runtime/protocol-client.js +264 -0
  50. package/dist/src/runtime/protocol-pool.js +183 -0
  51. package/dist/src/runtime/protocol-projection.js +393 -0
  52. package/dist/src/runtime/protocol-types.js +1 -0
  53. package/dist/src/runtime/protocol-worker.js +18 -0
  54. package/dist/src/runtime/provider-bridge.js +288 -0
  55. package/dist/src/runtime/provider-credentials.js +41 -0
  56. package/dist/src/runtime/provider-transport.js +404 -0
  57. package/dist/src/runtime/runtime-broker.js +213 -0
  58. package/dist/src/runtime/workspace-instructions.js +120 -0
  59. package/dist/src/runtime/workspace-view.js +74 -0
  60. package/dist/src/server/api-contract.json +11078 -0
  61. package/dist/src/server/api-types.js +1 -0
  62. package/dist/src/server/application.js +38 -0
  63. package/dist/src/server/auth.js +67 -0
  64. package/dist/src/server/broker-handlers.js +242 -0
  65. package/dist/src/server/control-plane.js +50 -0
  66. package/dist/src/server/deployment.js +237 -0
  67. package/dist/src/server/errors.js +22 -0
  68. package/dist/src/server/history-handlers.js +113 -0
  69. package/dist/src/server/http.js +124 -0
  70. package/dist/src/server/paging.js +56 -0
  71. package/dist/src/server/publication.js +119 -0
  72. package/dist/src/server/tool-event-handler.js +77 -0
  73. package/dist/src/server/workspace-handlers.js +34 -0
  74. package/dist/src/storage/coordinator.js +224 -0
  75. package/dist/src/storage/startup-lock.js +71 -0
  76. package/dist/src/storage/store.js +167 -0
  77. package/dist/src/tools/check-worker.js +81 -0
  78. package/dist/src/tools/checks.js +106 -0
  79. package/dist/src/tools/dns.js +248 -0
  80. package/dist/src/tools/http-contract.js +38 -0
  81. package/dist/src/tools/http.js +358 -0
  82. package/dist/src/tools/index.js +177 -0
  83. package/dist/src/tools/worker-check.js +73 -0
  84. package/dist/src/workspaces/git.js +227 -0
  85. package/dist/src/workspaces/index.js +715 -0
  86. package/examples/deployment.local.json +22 -0
  87. package/package.json +68 -4
  88. package/scripts/postinstall.mjs +25 -0
@@ -0,0 +1,185 @@
1
+ import { setTimeout as delay } from 'node:timers/promises';
2
+ import { AdminHttpFetcher } from '../tools/http.js';
3
+ import { EngineStore } from '../storage/store.js';
4
+ import { canonical, digest } from '../broker/policy.js';
5
+ import { runSqlCommitHook } from '../engine/contracts.js';
6
+ import { durationMs, abortAt } from '../engine/timing.js';
7
+ import { ApiError } from '../server/errors.js';
8
+ import { ValidationPool } from './validation-pool.js';
9
+ const activeOperations = new WeakMap();
10
+ /** Pre-session admin GET only. Never an agent tool, ambient DNS client or
11
+ * cross-run cache. Parsing/graph compilation remain bounded pure worker jobs. */
12
+ export class SchemaLoader {
13
+ store;
14
+ validation;
15
+ fetcher;
16
+ #active;
17
+ limits;
18
+ constructor(store, validation, fetcher, limits = { maxResources: 128, maxBytes: 16_777_216 }) {
19
+ this.store = store;
20
+ this.validation = validation;
21
+ this.fetcher = fetcher;
22
+ if (!Object.values(limits).every(n => Number.isSafeInteger(n) && n > 0))
23
+ throw new Error('Invalid schema graph resource bounds');
24
+ this.limits = Object.freeze({ ...limits });
25
+ this.#active = activeOperations.get(store.coordinator) ?? new Set();
26
+ activeOperations.set(store.coordinator, this.#active);
27
+ }
28
+ activeWork(operationId) { return this.#active.has(operationId) ? 1 : 0; }
29
+ async load(input, checks, options) {
30
+ this.store.coordinator.assertOutsideTransaction();
31
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(options.operationId))
32
+ throw new ApiError(422, 'invalid_schema_operation', 'A stable startup operation identity is required.');
33
+ if (this.#active.has(options.operationId))
34
+ throw new ApiError(409, 'schema_load_active', 'This schema startup operation is already active.');
35
+ const timeout = durationMs(options.timeout ?? '30s');
36
+ const waits = (options.retryDelays ?? ['1s', '2s']).map(durationMs);
37
+ if (waits.length !== 2)
38
+ throw new ApiError(422, 'invalid_schema_fetch_policy', 'Schema fetching requires exactly two retry delays.');
39
+ const policyDigest = digest({ timeout, waits });
40
+ const operationDigest = digest({ source: input.source, resources: input.resources ?? [], policyDigest, checks: [...checks].sort() });
41
+ this.store.coordinator.atomic(() => {
42
+ const prior = this.store.private('schema_startup', options.operationId);
43
+ if (prior && prior.digest !== operationDigest)
44
+ throw new ApiError(409, 'schema_operation_conflict', 'An existing startup operation is pinned to a different package or policy.');
45
+ if (!prior)
46
+ this.store.setPrivate('schema_startup', options.operationId, { digest: operationDigest });
47
+ });
48
+ const scope = `schema_fetch:${options.operationId}`;
49
+ const archived = this.store.coordinator.db.prepare(`SELECT body FROM engine_private WHERE scope=?
50
+ AND json_extract(body,'$.state')='pinned' ORDER BY rowid`).all(scope)
51
+ .map(row => JSON.parse(row.body).resource);
52
+ const remote = [];
53
+ for (const resource of [...archived, ...options.pinned ?? []]) {
54
+ const prior = remote.find(item => item.uri === resource.uri);
55
+ if (prior && canonical(prior) !== canonical(resource))
56
+ throw new ApiError(409, 'schema_pin_conflict', 'Pinned schema content cannot change within a startup operation.');
57
+ if (!prior)
58
+ remote.push(structuredClone(resource));
59
+ }
60
+ const global = options.deadlineAt === undefined ? undefined : abortAt(options.deadlineAt);
61
+ const signal = AbortSignal.any([...(options.signal ? [options.signal] : []), ...(global ? [global.signal] : [])]);
62
+ const seen = new Set(remote.map(resource => resource.uri));
63
+ let size = remote.reduce((n, resource) => n + Buffer.byteLength(resource.document.content), 0);
64
+ const check = () => {
65
+ if (options.deadlineAt !== undefined && Date.now() >= options.deadlineAt)
66
+ throw new ApiError(409, 'global_deadline_exceeded', 'The global workflow deadline expired during startup.');
67
+ if (signal.aborted)
68
+ throw new ApiError(409, 'startup_interrupted', 'Startup was interrupted.');
69
+ };
70
+ this.#active.add(options.operationId);
71
+ try {
72
+ for (;;) {
73
+ check();
74
+ if (remote.length > this.limits.maxResources || size > this.limits.maxBytes)
75
+ throw new ApiError(422, 'schema_graph_limit', 'Schema graph exceeds the deployment resource bound.');
76
+ const result = await this.validation.run({ kind: 'workflow', input, checks, remote }, { signal, runId: options.operationId });
77
+ check();
78
+ const plan = result.workflowResult;
79
+ if (!plan?.report.valid || !plan.graph || !plan.definition)
80
+ throw new ApiError(422, 'invalid_schema_graph', 'The workflow schema graph is invalid.', false, result.errors);
81
+ if (!plan.graph.unresolvedRemote.length)
82
+ return { ...plan, remote };
83
+ if (remote.length >= this.limits.maxResources || size > this.limits.maxBytes)
84
+ throw new ApiError(422, 'schema_graph_limit', 'Schema graph exceeds the deployment resource bound.');
85
+ const uri = plan.graph.unresolvedRemote[0];
86
+ if (seen.has(uri))
87
+ throw new ApiError(422, 'schema_resolution_failed', 'A required schema reference cannot be resolved.');
88
+ let ledger = this.store.private(scope, uri);
89
+ if (ledger && ledger.policyDigest !== policyDigest)
90
+ throw new ApiError(409, 'schema_fetch_policy_changed', 'An existing startup retry policy cannot change.');
91
+ // A crash cannot refund a durably started, possibly completed GET.
92
+ if (ledger?.state === 'started') {
93
+ ledger = { ...ledger, state: 'failed', nextAttemptAt: Date.now() + (waits[ledger.attemptsUsed - 1] ?? 0) };
94
+ this.store.setPrivate(scope, uri, ledger);
95
+ }
96
+ if (ledger?.state === 'permanent')
97
+ throw new ApiError(422, ledger.code, 'A required schema previously failed permanently.');
98
+ while (!ledger?.response && (ledger?.attemptsUsed ?? 0) < 3) {
99
+ check();
100
+ this.store.coordinator.atomic(() => runSqlCommitHook(options.beforeFetch, undefined));
101
+ const remaining = (ledger?.nextAttemptAt ?? 0) - Date.now();
102
+ if (remaining > 0) {
103
+ await delay(Math.min(remaining, 2_147_483_647), undefined, { signal });
104
+ check();
105
+ this.store.coordinator.atomic(() => runSqlCommitHook(options.beforeFetch, undefined));
106
+ if (Date.now() < ledger.nextAttemptAt)
107
+ continue;
108
+ }
109
+ const attemptDeadlineAt = Date.now() + timeout;
110
+ const attemptsUsed = (ledger?.attemptsUsed ?? 0) + 1;
111
+ ledger = { attemptsUsed, policyDigest, state: 'started' };
112
+ this.store.setPrivate(scope, uri, ledger); // Durable intent BEFORE protected IO.
113
+ check();
114
+ const attemptDeadline = abortAt(attemptDeadlineAt);
115
+ try {
116
+ const response = await this.fetcher.fetch(uri, AbortSignal.any([signal, attemptDeadline.signal]));
117
+ check();
118
+ if (Date.now() >= attemptDeadlineAt || attemptDeadline.signal.aborted)
119
+ throw new Error('schema_fetch_timeout');
120
+ if (response.status >= 200 && response.status < 300) {
121
+ ledger = { ...ledger, state: 'downloaded', response: { status: response.status,
122
+ headers: { ...response.headers }, bodyBase64: response.body.toString('base64') } };
123
+ this.store.setPrivate(scope, uri, ledger);
124
+ break;
125
+ }
126
+ if (response.status !== 408 && response.status !== 429 && response.status < 500)
127
+ throw new ApiError(422, 'schema_fetch_rejected', 'A required schema returned a permanent HTTP failure.');
128
+ }
129
+ catch (error) {
130
+ check();
131
+ if (error instanceof ApiError) {
132
+ this.store.setPrivate(scope, uri, { ...ledger, state: 'permanent', code: error.code });
133
+ throw error;
134
+ }
135
+ const code = error && typeof error === 'object' && 'code' in error ? String(error.code) : '';
136
+ if (['admin_network_denied', 'dns_not_configured', 'unsupported_http_url', 'http_redirect_refused', 'invalid_http_arguments'].includes(code)) {
137
+ this.store.setPrivate(scope, uri, { ...ledger, state: 'permanent', code: 'schema_fetch_denied' });
138
+ throw new ApiError(422, 'schema_fetch_denied', 'A required schema cannot be retrieved under the deployment policy.');
139
+ }
140
+ }
141
+ finally {
142
+ attemptDeadline.close();
143
+ }
144
+ ledger = { attemptsUsed, policyDigest, state: 'failed', nextAttemptAt: Date.now() + (waits[attemptsUsed - 1] ?? 0) };
145
+ this.store.setPrivate(scope, uri, ledger);
146
+ }
147
+ if (!ledger?.response)
148
+ throw new ApiError(422, 'schema_fetch_exhausted', 'A required schema failed all three fetch attempts.');
149
+ const response = { ...ledger.response, body: Buffer.from(ledger.response.bodyBase64, 'base64') };
150
+ size += response.body.byteLength;
151
+ if (size > this.limits.maxBytes)
152
+ throw new ApiError(422, 'schema_graph_limit', 'Schema graph exceeds the deployment byte bound.');
153
+ let content;
154
+ try {
155
+ content = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(response.body);
156
+ }
157
+ catch {
158
+ throw new ApiError(422, 'invalid_schema_encoding', 'Remote schemas must be valid UTF-8.');
159
+ }
160
+ const type = response.headers['content-type']?.split(';')[0]?.trim().toLowerCase();
161
+ const yaml = type !== 'application/json' && !type?.endsWith('+json');
162
+ const document = { mediaType: yaml ? 'application/yaml' : 'application/json', content };
163
+ const decoded = await this.validation.run({ kind: 'decode', content, format: yaml ? 'yaml' : 'json' }, { signal, runId: options.operationId });
164
+ if (!decoded.valid)
165
+ throw new ApiError(422, 'invalid_remote_schema', 'A required remote schema is not a valid document.', false, decoded.errors);
166
+ check();
167
+ const resource = { uri, document };
168
+ this.store.coordinator.atomic(() => {
169
+ runSqlCommitHook(options.onPinnedSql, resource);
170
+ this.store.setPrivate(scope, uri, { ...ledger, state: 'pinned', resource });
171
+ });
172
+ remote.push(resource);
173
+ seen.add(uri);
174
+ }
175
+ }
176
+ catch (error) {
177
+ check();
178
+ throw error;
179
+ }
180
+ finally {
181
+ global?.close();
182
+ this.#active.delete(options.operationId);
183
+ }
184
+ }
185
+ }
@@ -0,0 +1,105 @@
1
+ import { Worker } from 'node:worker_threads';
2
+ import { ApiError } from '../server/errors.js';
3
+ /** Trusted pure workers, never an in-process evaluation of hostile schemas.
4
+ * Each job gets a fresh heap and one total wall-time deadline, no silent pass. */
5
+ export class ValidationPool {
6
+ coordinator;
7
+ #queue = [];
8
+ #active = new Map();
9
+ #terminating = new Set();
10
+ #closed = false;
11
+ options;
12
+ constructor(coordinator, options = { concurrency: 2, maxQueued: 64, timeoutMs: 2000, memoryMb: 128 }) {
13
+ this.coordinator = coordinator;
14
+ if (!Object.values(options).every(value => Number.isSafeInteger(value) && value > 0) || options.timeoutMs > 2_147_483_647)
15
+ throw new Error('Validation bounds must be positive finite integers within supported timer limits');
16
+ this.options = Object.freeze({ ...options });
17
+ }
18
+ activeWork(runId) {
19
+ return [...this.#queue, ...this.#active.values()].filter(job => job.runId === runId).length;
20
+ }
21
+ run(task, options = {}) {
22
+ this.coordinator.assertOutsideTransaction();
23
+ if (this.#closed || this.#queue.length >= this.options.maxQueued)
24
+ return Promise.reject(new ApiError(503, 'validation_unavailable', 'Validation capacity is unavailable.', true));
25
+ if (options.signal?.aborted)
26
+ return Promise.reject(new ApiError(503, 'validation_cancelled', 'Validation was cancelled before completion.', true));
27
+ return new Promise((resolve, reject) => {
28
+ const job = { task, resolve, reject, settled: false,
29
+ ...(options.runId === undefined ? {} : { runId: options.runId }),
30
+ timer: setTimeout(() => this.#finish(job, new ApiError(422, 'validation_timeout', 'Validation exceeded its configured total time bound.')), this.options.timeoutMs) };
31
+ if (options.signal) {
32
+ job.signal = options.signal;
33
+ job.abort = () => this.#finish(job, new ApiError(503, 'validation_cancelled', 'Validation was cancelled before completion.', true));
34
+ job.signal.addEventListener('abort', job.abort, { once: true });
35
+ }
36
+ this.#queue.push(job);
37
+ this.#pump();
38
+ });
39
+ }
40
+ #pump() {
41
+ while (!this.#closed && this.#active.size < this.options.concurrency && this.#queue.length) {
42
+ const job = this.#queue.shift();
43
+ // Both source tests and the production server execute the emitted worker.
44
+ // The normal test command builds first; no TS loader runs in a worker.
45
+ const workerUrl = new URL(import.meta.url.endsWith('.ts')
46
+ ? '../../dist/src/config/validation-worker.js' : './validation-worker.js', import.meta.url);
47
+ let worker;
48
+ try {
49
+ worker = new Worker(workerUrl, {
50
+ workerData: job.task, resourceLimits: { maxOldGenerationSizeMb: this.options.memoryMb, maxYoungGenerationSizeMb: 16, stackSizeMb: 4 },
51
+ });
52
+ }
53
+ catch {
54
+ this.#finish(job, new ApiError(503, 'validation_unavailable', 'Validation worker could not be started.', true));
55
+ continue;
56
+ }
57
+ job.worker = worker;
58
+ this.#active.set(worker, job);
59
+ worker.once('message', (result) => this.#finish(job, undefined, result));
60
+ worker.once('error', (error) => this.#finish(job, error.code === 'ERR_WORKER_OUT_OF_MEMORY'
61
+ ? new ApiError(422, 'validation_resource_limit', 'Validation could not complete within its configured worker limits.')
62
+ : new ApiError(503, 'validation_unavailable', 'Validation worker failed before completing its task.', true)));
63
+ worker.once('exit', () => {
64
+ if (!job.settled)
65
+ this.#finish(job, new ApiError(503, 'validation_unavailable', 'Validation worker exited before returning a result.', true));
66
+ });
67
+ }
68
+ }
69
+ #finish(job, error, result) {
70
+ if (job.settled)
71
+ return;
72
+ job.settled = true;
73
+ clearTimeout(job.timer);
74
+ if (job.signal && job.abort)
75
+ job.signal.removeEventListener('abort', job.abort);
76
+ this.#queue = this.#queue.filter(pending => pending !== job);
77
+ const settle = () => { if (error)
78
+ job.reject(error);
79
+ else
80
+ job.resolve(result); };
81
+ if (job.worker) {
82
+ const worker = job.worker;
83
+ const exited = worker.threadId === -1 ? Promise.resolve() : new Promise(resolve => { worker.once('exit', () => resolve()); });
84
+ // A rejected terminate request is NOT proof of quiescence. Keep the
85
+ // active slot and caller pending until the independent exit is observed.
86
+ const stopping = Promise.all([exited, worker.terminate().catch(() => exited)]).then(() => {
87
+ this.#active.delete(worker);
88
+ this.#terminating.delete(stopping);
89
+ this.#pump();
90
+ settle();
91
+ });
92
+ this.#terminating.add(stopping);
93
+ }
94
+ else
95
+ settle();
96
+ }
97
+ async close() {
98
+ this.coordinator.assertOutsideTransaction();
99
+ this.#closed = true;
100
+ const error = new ApiError(503, 'validation_unavailable', 'Validation is shutting down.', true);
101
+ for (const job of [...this.#queue, ...this.#active.values()])
102
+ this.#finish(job, error);
103
+ await Promise.all([...this.#terminating]);
104
+ }
105
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,106 @@
1
+ import { parentPort, workerData } from 'node:worker_threads';
2
+ import { createRequire } from 'node:module';
3
+ import { Ajv2020 } from 'ajv/dist/2020.js';
4
+ import contract from '../server/api-contract.json' with { type: 'json' };
5
+ import { decodeDocument } from './documents.js';
6
+ import { validateProfile } from './profile-validation.js';
7
+ import { validateWorkflow } from './workflow-validation.js';
8
+ import { effectivePermissions } from '../engine/effective-permissions.js';
9
+ import { ApiError } from '../server/errors.js';
10
+ import { decodeStrictJsonBytes } from '../runtime/protocol-projection.js';
11
+ import { createHash } from 'node:crypto';
12
+ const addFormats = createRequire(import.meta.url)('ajv-formats');
13
+ const ajv = new Ajv2020({ strict: false, allErrors: true, coerceTypes: false, useDefaults: false, removeAdditional: false });
14
+ addFormats(ajv);
15
+ const errors = (issues) => (issues ?? []).map(issue => ({ path: issue.instancePath, code: issue.keyword, message: issue.message ?? 'Validation failed.' }));
16
+ async function execute(task) {
17
+ if (task.kind === 'provider_request') {
18
+ try {
19
+ const value = decodeStrictJsonBytes(task.bytes);
20
+ if (!value || typeof value !== 'object' || Array.isArray(value) || value.model !== task.model ||
21
+ !value.reasoning || typeof value.reasoning !== 'object' || Array.isArray(value.reasoning) || value.reasoning.effort !== task.effort)
22
+ throw new Error();
23
+ return { valid: true, errors: [], providerRequestDigest: `sha256:${createHash('sha256').update(task.bytes).digest('hex')}` };
24
+ }
25
+ catch {
26
+ return { valid: false, errors: [{ path: '', code: 'invalid_provider_request', message: 'Provider request does not match the current model grant.' }] };
27
+ }
28
+ }
29
+ if (task.kind === 'effective_permissions') {
30
+ try {
31
+ return { valid: true, errors: [], effectivePolicy: effectivePermissions(task.profile, task.deployment, task.role, task.configuredTools) };
32
+ }
33
+ catch (error) {
34
+ return { valid: false, errors: [{ path: '/configuredTools', code: error instanceof ApiError ? error.code : 'invalid_effective_permissions',
35
+ message: 'Effective permissions cannot be compiled from this configuration.' }] };
36
+ }
37
+ }
38
+ if (task.kind === 'verdict') {
39
+ ajv.addSchema({ ...contract, $id: 'urn:code60:api' });
40
+ const validate = ajv.compile({ $ref: 'urn:code60:api#/components/schemas/VerifierReport' });
41
+ if (!validate(task.value))
42
+ return { valid: false, errors: errors(validate.errors) };
43
+ const report = task.value;
44
+ const expected = new Set(task.criterionIds), seen = new Set(), evidence = new Set(task.evidenceArtifactIds);
45
+ const issues = [];
46
+ for (const [index, criterion] of report.criteria.entries()) {
47
+ if (!expected.has(criterion.criterionId) || seen.has(criterion.criterionId) || !criterion.explanation.trim())
48
+ issues.push({ path: `/criteria/${index}`, code: 'criterion_correspondence', message: 'Criteria must correspond exactly once to the assigned criteria, with explanations.' });
49
+ seen.add(criterion.criterionId);
50
+ if (criterion.evidenceArtifactIds?.some(id => !evidence.has(id)))
51
+ issues.push({ path: `/criteria/${index}/evidenceArtifactIds`, code: 'evidence_scope', message: 'Evidence is not in the current assignment.' });
52
+ }
53
+ if (seen.size !== expected.size || report.criteria.length !== expected.size)
54
+ issues.push({ path: '/criteria', code: 'criterion_correspondence', message: 'Every assigned criterion needs exactly one result.' });
55
+ if (report.decision === 'approve' && report.criteria.some(criterion => criterion.status !== 'pass'))
56
+ issues.push({ path: '/decision', code: 'approval_requires_all_pass', message: 'Approval requires every criterion to pass.' });
57
+ if (report.decision === 'revise' && !report.guidance?.trim())
58
+ issues.push({ path: '/guidance', code: 'revision_guidance_required', message: 'Revision requires nonempty actionable guidance.' });
59
+ return { valid: !issues.length, errors: issues, ...(issues.length ? {} : { value: task.value }) };
60
+ }
61
+ if (task.kind === 'decode') {
62
+ try {
63
+ return { valid: true, errors: [], value: decodeDocument(task.content, task.format) };
64
+ }
65
+ catch {
66
+ return { valid: false, errors: [{ path: '', code: 'invalid_document', message: 'Document must be acyclic JSON-compatible data with unique string keys.' }] };
67
+ }
68
+ }
69
+ if (task.kind === 'profile') {
70
+ const profileReport = validateProfile(task.input, task.runtimes, task.credentialIds, ajv);
71
+ return { valid: profileReport.valid, errors: profileReport.issues, profileReport };
72
+ }
73
+ if (task.kind === 'workflow') {
74
+ const workflowResult = validateWorkflow(task.input, task.checks, ajv, task.remote);
75
+ return { valid: workflowResult.report.valid, errors: workflowResult.report.issues, workflowResult };
76
+ }
77
+ if (task.kind === 'schema') {
78
+ if (typeof task.schema !== 'boolean' && (task.schema === null || typeof task.schema !== 'object' || Array.isArray(task.schema)))
79
+ return { valid: false, errors: [{ path: '', code: 'type', message: 'A schema must be an object or boolean.' }] };
80
+ const valid = ajv.validateSchema(task.schema);
81
+ return { valid: valid === true, errors: errors(ajv.errors) };
82
+ }
83
+ let validate;
84
+ if (task.kind === 'wire') {
85
+ ajv.addSchema({ ...contract, $id: 'urn:code60:api' });
86
+ validate = ajv.compile({ $ref: `urn:code60:api#/components/schemas/${task.schema}` });
87
+ }
88
+ else {
89
+ for (const resource of task.resources) {
90
+ if (typeof resource.schema !== 'boolean' && (resource.schema === null || typeof resource.schema !== 'object' || Array.isArray(resource.schema)))
91
+ return { valid: false, errors: [{ path: '', code: 'type', message: 'A schema must be an object or boolean.' }] };
92
+ ajv.addSchema(resource.schema, resource.uri);
93
+ }
94
+ validate = ajv.compile({ $ref: task.rootUri });
95
+ }
96
+ const result = await validate(task.value);
97
+ return { valid: '$async' in validate ? true : result === true, errors: errors(validate.errors) };
98
+ }
99
+ try {
100
+ parentPort.postMessage(await execute(workerData));
101
+ }
102
+ catch (error) {
103
+ const issues = error && typeof error === 'object' && 'errors' in error ? error.errors : undefined;
104
+ parentPort.postMessage({ valid: false, errors: issues ? errors(issues) :
105
+ [{ path: '', code: 'invalid_schema', message: 'The schema cannot be compiled or validated.' }] });
106
+ }
@@ -0,0 +1,9 @@
1
+ import workflowSchema from './workflow-schema.json' with { type: 'json' };
2
+ export function workflowLanguageSchema() {
3
+ const effectiveSchema = structuredClone(workflowSchema);
4
+ // Agreed runtime policies supersede these provisional offline restrictions:
5
+ // remote references and explicitly empty semantic criteria are supported.
6
+ effectiveSchema.$defs.artifact.oneOf[0].properties.$ref.pattern = '^(?:#/types/[A-Za-z_][A-Za-z0-9_-]*|https?://[^\\r\\n]+|[^/#?:\\\\\\r\\n][^#?:\\\\\\r\\n]*(?:#[^#\\r\\n]*)?)$';
7
+ effectiveSchema.$defs.step.properties.exitCriteria.properties.semantic.properties.criteria.minItems = 0;
8
+ return effectiveSchema;
9
+ }