@jini-ai/devops 0.4.0 → 0.5.1

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 (94) hide show
  1. package/CHANGELOG.md +125 -0
  2. package/README.md +62 -2
  3. package/dist/agent-jobs/entry.d.ts +4 -0
  4. package/dist/agent-jobs/entry.js +4 -0
  5. package/dist/agent-jobs/jobs.d.ts +25 -0
  6. package/dist/agent-jobs/jobs.js +115 -0
  7. package/dist/agent-jobs/node.d.ts +12 -0
  8. package/dist/agent-jobs/node.js +53 -0
  9. package/dist/agent-jobs/ports.d.ts +69 -0
  10. package/dist/agent-jobs/ports.js +2 -0
  11. package/dist/checks/coverage/diff.d.ts +57 -0
  12. package/dist/checks/coverage/diff.js +48 -0
  13. package/dist/checks/coverage/disk.d.ts +65 -0
  14. package/dist/checks/coverage/disk.js +136 -0
  15. package/dist/checks/coverage/floors.d.ts +31 -0
  16. package/dist/checks/coverage/floors.js +24 -0
  17. package/dist/checks/coverage/index.d.ts +7 -0
  18. package/dist/checks/coverage/index.js +6 -0
  19. package/dist/checks/coverage/integrity.d.ts +79 -0
  20. package/dist/checks/coverage/integrity.js +140 -0
  21. package/dist/checks/coverage/lcov.d.ts +65 -0
  22. package/dist/checks/coverage/lcov.js +64 -0
  23. package/dist/checks/node.d.ts +19 -0
  24. package/dist/checks/node.js +40 -0
  25. package/dist/checks/ports.d.ts +67 -0
  26. package/dist/checks/ports.js +2 -0
  27. package/dist/checks/published-types/index.d.ts +77 -0
  28. package/dist/checks/published-types/index.js +186 -0
  29. package/dist/deploy/host-kit.d.ts +27 -10
  30. package/dist/deploy/naming.d.ts +8 -4
  31. package/dist/deploy/naming.js +4 -5
  32. package/dist/deploy/node.d.ts +18 -0
  33. package/dist/deploy/node.js +57 -0
  34. package/dist/deploy/reachability.d.ts +42 -12
  35. package/dist/deploy/reachability.js +75 -69
  36. package/dist/deploy/redirect-guard.d.ts +7 -2
  37. package/dist/deploy/redirect-guard.js +3 -3
  38. package/dist/deploy/tokens.d.ts +14 -11
  39. package/dist/deploy/tokens.js +13 -13
  40. package/dist/deploy/tool.d.ts +9 -5
  41. package/dist/deploy/tool.js +5 -6
  42. package/dist/deploy/types.d.ts +22 -10
  43. package/dist/deploy/types.js +2 -2
  44. package/dist/index.d.ts +2 -1
  45. package/dist/index.js +2 -1
  46. package/dist/local-dev/index.d.ts +55 -0
  47. package/dist/local-dev/index.js +68 -0
  48. package/dist/packaging/electron/archive.d.ts +41 -0
  49. package/dist/packaging/electron/archive.js +77 -0
  50. package/dist/packaging/electron/asar-adapter.d.ts +13 -0
  51. package/dist/packaging/electron/asar-adapter.js +5 -0
  52. package/dist/packaging/electron/entry.d.ts +9 -0
  53. package/dist/packaging/electron/entry.js +9 -0
  54. package/dist/packaging/electron/imports.d.ts +13 -0
  55. package/dist/packaging/electron/imports.js +44 -0
  56. package/dist/packaging/electron/node.d.ts +8 -0
  57. package/dist/packaging/electron/node.js +51 -0
  58. package/dist/packaging/electron/policies.d.ts +64 -0
  59. package/dist/packaging/electron/policies.js +63 -0
  60. package/dist/packaging/electron/ports.d.ts +113 -0
  61. package/dist/packaging/electron/ports.js +2 -0
  62. package/dist/packaging/electron/stability.d.ts +9 -0
  63. package/dist/packaging/electron/stability.js +12 -0
  64. package/dist/packaging/electron/staging.d.ts +108 -0
  65. package/dist/packaging/electron/staging.js +249 -0
  66. package/dist/packaging/electron/typescript.d.ts +7 -0
  67. package/dist/packaging/electron/typescript.js +18 -0
  68. package/dist/source-control/commit.d.ts +11 -0
  69. package/dist/source-control/commit.js +71 -0
  70. package/dist/source-control/contracts.d.ts +327 -0
  71. package/dist/source-control/contracts.js +2 -0
  72. package/dist/source-control/entry.d.ts +6 -0
  73. package/dist/source-control/entry.js +6 -0
  74. package/dist/source-control/kit.d.ts +15 -0
  75. package/dist/source-control/kit.js +17 -0
  76. package/dist/source-control/registry.d.ts +100 -0
  77. package/dist/source-control/registry.js +174 -0
  78. package/dist/source-control/repository-target.d.ts +13 -0
  79. package/dist/source-control/repository-target.js +28 -0
  80. package/dist/static-export/contracts.d.ts +138 -0
  81. package/dist/static-export/contracts.js +5 -0
  82. package/dist/static-export/entry.d.ts +6 -0
  83. package/dist/static-export/entry.js +6 -0
  84. package/dist/static-export/failure-summary.d.ts +12 -0
  85. package/dist/static-export/failure-summary.js +12 -0
  86. package/dist/static-export/fetch-adapter.d.ts +6 -0
  87. package/dist/static-export/fetch-adapter.js +5 -0
  88. package/dist/static-export/node-adapters.d.ts +11 -0
  89. package/dist/static-export/node-adapters.js +111 -0
  90. package/dist/static-export/runner.d.ts +6 -0
  91. package/dist/static-export/runner.js +135 -0
  92. package/dist/static-export/transforms.d.ts +53 -0
  93. package/dist/static-export/transforms.js +154 -0
  94. package/package.json +82 -5
package/CHANGELOG.md ADDED
@@ -0,0 +1,125 @@
1
+ # @jini-ai/devops
2
+
3
+ ## 0.5.1 — 2026-10-04
4
+
5
+ - `@jini-ai/devops/local-dev` exports `listenServer`.
6
+ - Internal `@jini-ai/*` dependencies are caret ranges (`workspace:^`) instead of exact pins, so a host on a newer patch resolves a single copy without an override.
7
+
8
+ ## 0.5.0 — 2026-10-02
9
+
10
+ ### BREAKING
11
+
12
+ - Published source-control, deployment, static-export and packaging targets use concept paths. Clock-only sleeping uses SleepPort and HTTP contracts use core; Node deployment guards are isolated in ./deploy/node.
13
+ - Distribution includes runtime output, release documentation and required assets only. Process records and per-job neutrality checks are no longer part of the package surface.
14
+
15
+ ## Unreleased
16
+
17
+ - BREAKING: reachability requires a paired `guard` and `fetch`. Move concrete URL/DNS/undici wiring and `lookupImpl` overrides to new `./deploy/node` default adapter `createNodeReachabilityPorts`; existing probe and polling budgets remain.
18
+
19
+ ### Added
20
+
21
+ - `./source-control`: trusted provider catalog, provider kit, repository validation,
22
+ preview and credentialed commit orchestration with isolated artifact cleanup.
23
+ - `./static-export` and `./static-export/node`: injected manifest/app/asset/export
24
+ orchestration and explicit loopback, writer and theme-inventory Node adapters.
25
+ - `./packaging/electron` and `./packaging/electron/typescript`: dependency staging,
26
+ archive byte verification, reachable-import and stability policies; host-bound
27
+ archive/parser/packer adapters. TypeScript is an optional peer.
28
+ - `./agent-jobs`: bounded, resumable CLI jobs with host-supplied execution and
29
+ filesystem ports, stream-based completion and retained raw logs.
30
+ - Package integration, object-fetch adapter and whole-source neutrality contracts.
31
+
32
+ ### Fixed
33
+
34
+ - Compilation: published-type checks sort copies of readonly directory listings;
35
+ deployment integration tests use the daemon executor's object arguments. The
36
+ Node reachability adapter attaches its validating Agent at runtime without
37
+ intersecting incompatible Node and undici dispatcher types.
38
+ - `./agent-jobs`: resume only from regular report files (following file symlinks).
39
+ Final-artifact write/removal failures fail the affected job and leave the pool scheduling.
40
+ - `./packaging/electron`: native-magic inspection reads at most four bytes per file
41
+ through a bounded `readPrefix` filesystem port. Custom npm staging adapters must
42
+ supply this capability; no whole-file fallback is allowed. Other packaging adapters
43
+ retain their existing shape. Node descriptor cleanup includes read failures.
44
+ - Regression tests cover resume, each final-artifact persistence failure, sparse/short
45
+ prefix reads and missing-capability refusal. Verification deferred by owner directive.
46
+
47
+ ### Breaking
48
+
49
+ - Source directories now name their capabilities: `source-control`, `static-export`,
50
+ `deploy`, `packaging/electron` and `agent-jobs`. All package export keys are retained;
51
+ only source/output targets move. Internal job-path imports are removed.
52
+ - `./packaging/electron`: rename the delay-only `ClockPort` type to `SleepPort`;
53
+ its method and the `observeMovingPaths` argument shape remain unchanged.
54
+ - `./deploy`: rename the loose `JsonObject` type to `UnknownRecord`, retaining
55
+ `Record<string, unknown>` rather than tightening provider metadata/config values.
56
+ - `./source-control`: adopt core/primitives' canonical `HttpClientPort` without a
57
+ local declaration. `send({ request }, { redirect })` replaces `send(request)`;
58
+ import `HttpRequest`/`HttpResponse` from core in place of the removed
59
+ `SourceControlHttpRequest`/`SourceControlHttpResponse` declarations.
60
+
61
+ - `./deploy`: helpers, factories, `DeployError` construction and deploy/host/SigV4
62
+ port methods now take required argument objects followed by optional argument
63
+ objects. Publish metadata/response headers and registration options move to
64
+ the second object. Reachability requires object-argument fetch; polling also
65
+ requires object-argument clock/delay ports. Protected-response detectors take
66
+ `{ resp, body }`. Export names are retained; no positional adapter is supplied.
67
+ - The newly extracted source-control and static-export fetch dependencies also
68
+ take `({ url }, { init })`. Host-selected native fetch is bound through
69
+ `createSourceControlFetchAdapter({ fetch })` or `createExportFetchAdapter({ fetch })`.
70
+
71
+ ### Additional checks
72
+
73
+ - `./checks/published-types`: registry drift, published typecheck, linked-package checks,
74
+ and captured-log diagnosis with explicit filesystem, runner, installer and project ports.
75
+ - `./local-dev`: environment-file loading and listener parsing/lookup with host-supplied paths and commands.
76
+ - `./checks/coverage`: LCOV parsing, contamination/baseline evaluation, aggregate and two-tier floors,
77
+ disk-inventory gap ratchets, and runner/glob drift policies with caller-supplied roots and classifiers.
78
+ - `./checks/node`: optional Node filesystem/environment/process and npm executable adapters.
79
+ - Generalized regression suites and a consumer-reference guard. Verification deferred by owner directive.
80
+
81
+ ## 0.4.0
82
+
83
+ ### Breaking
84
+
85
+ - `./deploy`: the four hosting-vendor targets are removed, with their constants
86
+ and helpers: `VercelDeployTarget`, `NetlifyDeployTarget`,
87
+ `CloudflarePagesDeployTarget`, `GitHubPagesDeployTarget`, `*_TARGET_ID`,
88
+ `CLOUDFLARE_PAGES_ASSET_*`, `isVercelProtectedResponse`,
89
+ `chunkCloudflarePagesAssetUploads`, `cloudflarePagesAssetHash`,
90
+ `listCloudflarePagesZones` and their config/metadata types. A host now
91
+ supplies its own targets as `DeployTargetModule`s built on `DeployHostKit`.
92
+ - `deploy.publish`'s tool description no longer names any provider.
93
+
94
+ ### Unchanged
95
+
96
+ - `DeployTarget`, `DeployTargetToken`, `publishDeploy`, `deploy.publish`
97
+ (`createDeployPublishToolRegistration` and its policies), the host-kit types,
98
+ and the naming, reachability and redirect-guard helpers.
99
+
100
+ ### Added
101
+
102
+ - A guard test that fails if a hosting-vendor name appears anywhere under
103
+ `packages/devops/src`.
104
+
105
+ ## 0.3.3
106
+
107
+ ### Added
108
+
109
+ - `./deploy`: `DeployPublishInput.responseHeaders` (`ResponseHeaderSet`), the header
110
+ set a caller wants every published page served with; each target renders it
111
+ into its own host format or ignores it.
112
+ - `./deploy`: the injection contract for host-supplied targets:
113
+ `DeployTargetModule` (`create({ credential, config, kit })` returning a
114
+ `DeployTarget`, plus optional `validateConfig`, `basePath`,
115
+ `verifyCredential`) and `DeployHostKit` (timed `fetch`, timeouts, `sleep`,
116
+ reachability, naming and redirect-guard helpers, a SigV4 client factory,
117
+ `DeployError`), with their context and result types. Type-only; additive.
118
+
119
+ ## Earlier
120
+
121
+ ### Added
122
+
123
+ - `./deploy`: deploy targets for Vercel, Cloudflare Pages, Netlify, and GitHub
124
+ Pages, plus typed DI composition, guarded `deploy.publish`, naming, and
125
+ reachability checks.
package/README.md CHANGED
@@ -9,7 +9,16 @@ public subpath and permission boundary.
9
9
  | subpath | purpose |
10
10
  |---|---|
11
11
  | `./deploy` | The generic deploy seam: the `DeployTarget` port, the `DeployTargetToken` many-token, the guarded `deploy.publish` tool, and the `DeployTargetModule`/`DeployHostKit` contract. Ships no hosting vendor. |
12
- | `./source-control` | Reserved for repository, branch, commit, and pull-request operations. |
12
+ | `./source-control` | Trusted provider catalogs, repository validation, export preview and commit orchestration. |
13
+ | `./static-export` | Manifest/app/writer-driven static export, path transforms and route/asset failure summaries. |
14
+ | `./static-export/node` | Explicit Node loopback app, artifact writer and theme-file inventory adapters. |
15
+ | `./packaging/electron` | Dependency staging, archive byte verification, reachable-import, freshness and quiet-tree policies. |
16
+ | `./packaging/electron/typescript` | Host-supplied TypeScript AST adapter; TypeScript is an optional peer. |
17
+ | `./agent-jobs` | Bounded CLI jobs with resume, stdin prompts, raw logs and stream-based completion. |
18
+ | `./checks/published-types` | Published type-surface, registry-drift, linked-package and captured-log checks. |
19
+ | `./checks/coverage` | LCOV, floor, diff, disk-inventory and contamination/baseline policies. |
20
+ | `./checks/node` | Explicit filesystem, process, environment-loader and installer adapters. |
21
+ | `./local-dev` | Environment-file and listener lookup helpers with host-supplied paths/commands. |
13
22
  | `./ci-cd` | Reserved for pipeline definitions, run status, logs, cancellation, and deployment orchestration. |
14
23
 
15
24
  ```ts
@@ -23,9 +32,60 @@ Hosting targets live in the host, not in this package: the host writes each
23
32
  target as a `DeployTargetModule` and hands it a `DeployHostKit` (the outbound
24
33
  `fetch`, timeouts, and this package's naming, reachability and redirect-guard
25
34
  helpers), so the module needs no imports of its own. `create()` returns a plain
26
- `DeployTarget`. `DeployPublishInput.responseHeaders` carries the headers every
35
+ `DeployTarget`. `DeployPublishOptions.responseHeaders` carries the headers every
27
36
  published page should be served with; each target renders them its own way.
28
37
 
38
+ Public helpers and ports accept required argument objects followed by optional
39
+ argument objects. For example:
40
+
41
+ ```ts
42
+ const registration = createDeployPublishToolRegistration(
43
+ { targets },
44
+ { policy, timeoutMs: 30_000 },
45
+ );
46
+ await target.publish({ files, projectName }, { responseHeaders });
47
+ ```
48
+
49
+ Reachability requires a transport port with `fetch({ url }, { init })`. Polling
50
+ also requires `now({})` and `sleep({ ms })` ports. See
51
+ [API.md](https://github.com/AINSEP/Jini/blob/main/packages/devops/API.md) for the current port contracts.
52
+
29
53
  Deployment stays independent from CI/CD: a pipeline may invoke a deployment,
30
54
  but the two have different credentials, approval policies, lifecycle, and audit
31
55
  requirements.
56
+
57
+ The root entry stays a domain marker. Import individual capabilities from their
58
+ subpaths; filesystem/process/archive port names are local to their capability.
59
+ See [API.md](https://github.com/AINSEP/Jini/blob/main/packages/devops/API.md) for composition examples and port requirements. No helper
60
+ selects an application root, credential name or plugin descriptor filename for
61
+ the caller. Targets/ops/static-publish registries remain a separate extraction
62
+ design; only the generic `./deploy` seam ships here today.
63
+
64
+ Source control uses `HttpClientPort` from `@jini-ai/core/primitives`; the kit
65
+ passes the host's guarded client through unchanged. Packaging's delay-only port
66
+ is `SleepPort`. Deploy provider option bags use `UnknownRecord`, whose values
67
+ remain `unknown` rather than being restricted to JSON values. Public subpath
68
+ keys stay stable when source directories move.
69
+
70
+ ## Deployment outbound policy
71
+
72
+ Reachability now requires `{ url, fetch, guard }` (polling also requires clock/sleep).
73
+ `DeploymentUrlGuard.assertSafeUrl({ raw, label })` supplies synchronous URL policy;
74
+ the paired fetch port MUST enforce DNS policy at connection time. A separate DNS
75
+ preflight is insufficient because it allows rebinding before the socket connects.
76
+ The deploy core imports neither platform nor undici.
77
+
78
+ ```ts
79
+ import { checkDeploymentUrl } from '@jini-ai/devops/deploy';
80
+ import { createNodeReachabilityPorts } from '@jini-ai/devops/deploy/node';
81
+ const ports = createNodeReachabilityPorts({});
82
+ await checkDeploymentUrl({ url: 'https://example.com', ...ports });
83
+ ```
84
+
85
+ The Node defaults reject unsafe public URLs and pin validation to the connection
86
+ through platform's validating lookup. `lookupImpl` overrides move from probe
87
+ options to `createNodeReachabilityPorts({}, { lookupImpl?, fetch? })`.
88
+ Default dispatchers remain shared; each override binding retains its own lazy
89
+ pool. HTTPS-only probes, manual redirects and existing deadlines are preserved.
90
+ The Node adapter attaches the validating Agent as a native fetch runtime extension,
91
+ preserving its identity across differing Node and undici dispatcher type versions.
@@ -0,0 +1,4 @@
1
+ export * from './ports.js';
2
+ export * from './jobs.js';
3
+ export * from './node.js';
4
+ //# sourceMappingURL=entry.d.ts.map
@@ -0,0 +1,4 @@
1
+ export * from './ports.js';
2
+ export * from './jobs.js';
3
+ export * from './node.js';
4
+ //# sourceMappingURL=entry.js.map
@@ -0,0 +1,25 @@
1
+ import type { AgentJob, AgentJobOptions, CodexInvocation, AgentCliRunnerPort, JobFilesystemPort, AgentEventDecoderPort, ParsedCodexRun, AgentJobResult } from './ports.js';
2
+ /** Original stream rule: exit status cannot replace completion, no errors, and a final message. */
3
+ export declare function parseCodexRun({ jsonl }: {
4
+ jsonl: string;
5
+ }, optional?: {
6
+ decoder?: AgentEventDecoderPort;
7
+ }): ParsedCodexRun;
8
+ /** Construct argv without a shell; prompt content goes only on stdin. Effort is a TOML string. */
9
+ export declare function buildCodexInvocation({ options, prompt }: {
10
+ options: AgentJobOptions;
11
+ prompt: string;
12
+ }): CodexInvocation;
13
+ /** Run a bounded batch. The host owns output-directory exclusivity across concurrent batches. */
14
+ export declare function runAgentJobs(required: {
15
+ jobs: readonly AgentJob[];
16
+ options: AgentJobOptions;
17
+ fs: JobFilesystemPort;
18
+ runner: AgentCliRunnerPort;
19
+ }, optional?: {
20
+ decoder?: AgentEventDecoderPort;
21
+ }): Promise<{
22
+ success: boolean;
23
+ results: AgentJobResult[];
24
+ }>;
25
+ //# sourceMappingURL=jobs.d.ts.map
@@ -0,0 +1,115 @@
1
+ import path from 'node:path';
2
+ const jsonDecoder = { decode: ({ line }) => JSON.parse(line) };
3
+ function record(value) { return value !== null && typeof value === 'object' && !Array.isArray(value); }
4
+ /** Original stream rule: exit status cannot replace completion, no errors, and a final message. */
5
+ export function parseCodexRun({ jsonl }, optional = {}) {
6
+ let completed = false;
7
+ let lastMessage;
8
+ let usage = null;
9
+ const errors = [];
10
+ for (const line of jsonl.split('\n')) {
11
+ if (!line.trim())
12
+ continue;
13
+ let event;
14
+ try {
15
+ event = (optional.decoder ?? jsonDecoder).decode({ line });
16
+ }
17
+ catch {
18
+ continue;
19
+ }
20
+ if (!record(event))
21
+ continue;
22
+ if (event.type === 'turn.completed') {
23
+ completed = true;
24
+ usage = event.usage ?? null;
25
+ }
26
+ else if (event.type === 'turn.failed')
27
+ errors.push(`turn.failed: ${JSON.stringify(event.error ?? event)}`);
28
+ else if (event.type === 'error')
29
+ errors.push(`error: ${event.message ?? JSON.stringify(event)}`);
30
+ else if (event.type === 'item.completed' && record(event.item) && event.item.type === 'agent_message')
31
+ lastMessage = typeof event.item.text === 'string' ? event.item.text : undefined;
32
+ }
33
+ if (completed && errors.length === 0 && lastMessage)
34
+ return { success: true, finalMessage: lastMessage.endsWith('\n') ? lastMessage : lastMessage + '\n', usage };
35
+ return { success: false, reason: errors.length ? errors.join('\n') : !completed ? 'no turn.completed event' : 'no agent_message' };
36
+ }
37
+ /** Construct argv without a shell; prompt content goes only on stdin. Effort is a TOML string. */
38
+ export function buildCodexInvocation({ options, prompt }) {
39
+ validateOptions(options);
40
+ return {
41
+ executable: options.executable, cwd: options.repository,
42
+ args: ['exec', '--ignore-rules', '--ignore-user-config', '--ephemeral', '--json', '-s', options.sandbox, '-m', options.model,
43
+ '-c', `model_reasoning_effort=${JSON.stringify(options.effort)}`, ...options.addDirs.flatMap(dir => ['--add-dir', dir]), '-C', options.repository, '-'],
44
+ stdin: options.dispatchPrefix + '\n\n' + prompt,
45
+ };
46
+ }
47
+ /** Run a bounded batch. The host owns output-directory exclusivity across concurrent batches. */
48
+ export async function runAgentJobs(required, optional = {}) {
49
+ const { jobs, options, fs, runner } = required;
50
+ validateOptions(options);
51
+ if (jobs.length === 0)
52
+ throw new Error('No prompt jobs.');
53
+ const ids = new Set();
54
+ for (const job of jobs) {
55
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(job.id) || ids.has(job.id))
56
+ throw new Error(`Unsafe or duplicate job id: ${job.id}`);
57
+ ids.add(job.id);
58
+ }
59
+ await fs.mkdir({ path: options.outputDirectory });
60
+ const results = new Array(jobs.length);
61
+ let cursor = 0;
62
+ async function runOne(job) {
63
+ const base = path.join(options.outputDirectory, job.id);
64
+ if (await fs.exists({ path: base + '.md' }))
65
+ return { id: job.id, status: 'skipped' };
66
+ let exitCode;
67
+ let parsed;
68
+ try {
69
+ // Clear stale logs even when a custom runner fails before opening them.
70
+ await fs.write({ path: base + '.jsonl', text: '' });
71
+ await fs.write({ path: base + '.err', text: '' });
72
+ ({ exitCode } = await runner.run({ ...buildCodexInvocation({ options, prompt: job.prompt }), jsonlPath: base + '.jsonl', stderrPath: base + '.err' }));
73
+ parsed = parseCodexRun({ jsonl: await fs.read({ path: base + '.jsonl' }) }, optional);
74
+ }
75
+ catch (error) {
76
+ parsed = { success: false, reason: `runner: ${error instanceof Error ? error.message : String(error)}` };
77
+ }
78
+ const exit = exitCode === undefined ? {} : { exitCode };
79
+ // Persistence belongs to this job: an unavailable artifact must not strand the worker pool.
80
+ try {
81
+ if (parsed.success) {
82
+ await fs.write({ path: base + '.md', text: parsed.finalMessage });
83
+ await fs.remove({ path: base + '.failed' });
84
+ return { id: job.id, status: 'succeeded', ...exit };
85
+ }
86
+ await fs.remove({ path: base + '.md' });
87
+ await fs.write({ path: base + '.failed', text: parsed.reason + '\n' });
88
+ return { id: job.id, status: 'failed', reason: parsed.reason, ...exit };
89
+ }
90
+ catch (error) {
91
+ // The filesystem may also reject a failure marker; retain the failure in the batch result.
92
+ return { id: job.id, status: 'failed', reason: `artifact: ${error instanceof Error ? error.message : String(error)}`, ...exit };
93
+ }
94
+ }
95
+ async function worker() {
96
+ while (cursor < jobs.length) {
97
+ const index = cursor++;
98
+ results[index] = await runOne(jobs[index]);
99
+ }
100
+ }
101
+ await Promise.all(Array.from({ length: Math.min(options.concurrency, jobs.length) }, worker));
102
+ return { success: results.every(result => result.status !== 'failed'), results };
103
+ }
104
+ function validateOptions(options) {
105
+ if (!Number.isInteger(options.concurrency) || options.concurrency < 1)
106
+ throw new Error('concurrency must be a positive integer');
107
+ if (!['read-only', 'workspace-write'].includes(options.sandbox))
108
+ throw new Error('sandbox must be read-only or workspace-write');
109
+ if (!path.isAbsolute(options.repository) || !path.isAbsolute(options.outputDirectory) || options.addDirs.some(dir => !path.isAbsolute(dir)))
110
+ throw new Error('repository, outputDirectory and addDirs must be absolute paths');
111
+ for (const field of ['executable', 'model', 'effort', 'dispatchPrefix'])
112
+ if (!options[field].trim())
113
+ throw new Error(`${field} is required`);
114
+ }
115
+ //# sourceMappingURL=jobs.js.map
@@ -0,0 +1,12 @@
1
+ import type { AgentCliRunnerPort, JobFilesystemPort, AgentJob } from './ports.js';
2
+ /** Environment is required: the host explicitly chooses which credentials/config reach the CLI. */
3
+ export declare function createNodeAgentCliRunner({ env }: {
4
+ env: NodeJS.ProcessEnv;
5
+ }): AgentCliRunnerPort;
6
+ /** Writes final/failed artifacts; raw logs are streamed by the CLI adapter. */
7
+ export declare function createNodeJobFilesystem(_required: Record<string, never>): JobFilesystemPort;
8
+ /** Read regular prompt files in stable order; duplicate basename IDs are rejected by runAgentJobs. */
9
+ export declare function readPromptJobs({ directory }: {
10
+ directory: string;
11
+ }): Promise<AgentJob[]>;
12
+ //# sourceMappingURL=node.d.ts.map
@@ -0,0 +1,53 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createWriteStream } from 'node:fs';
3
+ import { stat, mkdir, readFile, writeFile, rm, readdir } from 'node:fs/promises';
4
+ import { pipeline } from 'node:stream/promises';
5
+ import path from 'node:path';
6
+ /** Environment is required: the host explicitly chooses which credentials/config reach the CLI. */
7
+ export function createNodeAgentCliRunner({ env }) {
8
+ const environment = { ...env };
9
+ return { async run(request) {
10
+ const child = spawn(request.executable, [...request.args], { cwd: request.cwd, env: environment, shell: false, stdio: ['pipe', 'pipe', 'pipe'] });
11
+ const exited = new Promise((resolve, reject) => { child.once('error', reject); child.once('close', resolve); });
12
+ const input = new Promise((resolve, reject) => {
13
+ child.stdin.once('error', reject);
14
+ child.stdin.end(request.stdin, () => resolve());
15
+ });
16
+ const pending = [exited, input, pipeline(child.stdout, createWriteStream(request.jsonlPath)), pipeline(child.stderr, createWriteStream(request.stderrPath))];
17
+ try {
18
+ const [exitCode] = await Promise.all(pending);
19
+ return { exitCode };
20
+ }
21
+ catch (error) {
22
+ child.kill();
23
+ await Promise.allSettled(pending);
24
+ throw error;
25
+ }
26
+ } };
27
+ }
28
+ /** Writes final/failed artifacts; raw logs are streamed by the CLI adapter. */
29
+ export function createNodeJobFilesystem(_required) {
30
+ return {
31
+ mkdir: async ({ path }) => { await mkdir(path, { recursive: true }); },
32
+ exists: async ({ path }) => {
33
+ try {
34
+ return (await stat(path)).isFile();
35
+ }
36
+ catch (error) {
37
+ const code = error.code;
38
+ if (code === 'ENOENT' || code === 'ENOTDIR')
39
+ return false;
40
+ throw error;
41
+ }
42
+ },
43
+ read: ({ path }) => readFile(path, 'utf8'),
44
+ write: ({ path, text }) => writeFile(path, text, 'utf8'),
45
+ remove: async ({ path }) => { await rm(path, { force: true }); },
46
+ };
47
+ }
48
+ /** Read regular prompt files in stable order; duplicate basename IDs are rejected by runAgentJobs. */
49
+ export async function readPromptJobs({ directory }) {
50
+ const entries = (await readdir(directory, { withFileTypes: true })).filter(entry => entry.isFile()).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
51
+ return Promise.all(entries.map(async (entry) => ({ id: path.parse(entry.name).name, prompt: await readFile(path.join(directory, entry.name), 'utf8') })));
52
+ }
53
+ //# sourceMappingURL=node.js.map
@@ -0,0 +1,69 @@
1
+ export interface AgentJob {
2
+ readonly id: string;
3
+ readonly prompt: string;
4
+ }
5
+ export interface AgentJobOptions {
6
+ readonly repository: string;
7
+ readonly executable: string;
8
+ readonly model: string;
9
+ readonly effort: string;
10
+ readonly sandbox: 'read-only' | 'workspace-write';
11
+ readonly addDirs: readonly string[];
12
+ readonly concurrency: number;
13
+ readonly dispatchPrefix: string;
14
+ readonly outputDirectory: string;
15
+ }
16
+ export interface CodexInvocation {
17
+ readonly executable: string;
18
+ readonly cwd: string;
19
+ readonly args: readonly string[];
20
+ readonly stdin: string;
21
+ }
22
+ /** Runner streams logs into the supplied files and resolves only after both logs are closed. */
23
+ export interface AgentCliRunnerPort {
24
+ run(required: CodexInvocation & {
25
+ jsonlPath: string;
26
+ stderrPath: string;
27
+ }): Promise<{
28
+ exitCode: number | null;
29
+ }>;
30
+ }
31
+ export interface JobFilesystemPort {
32
+ mkdir(required: {
33
+ path: string;
34
+ }): Promise<void>;
35
+ /** True only for a regular file, following symlinks; directories are not completed reports. */
36
+ exists(required: {
37
+ path: string;
38
+ }): Promise<boolean>;
39
+ read(required: {
40
+ path: string;
41
+ }): Promise<string>;
42
+ write(required: {
43
+ path: string;
44
+ text: string;
45
+ }): Promise<void>;
46
+ remove(required: {
47
+ path: string;
48
+ }): Promise<void>;
49
+ }
50
+ export interface AgentEventDecoderPort {
51
+ decode(required: {
52
+ line: string;
53
+ }): unknown;
54
+ }
55
+ export type ParsedCodexRun = {
56
+ success: true;
57
+ finalMessage: string;
58
+ usage: unknown;
59
+ } | {
60
+ success: false;
61
+ reason: string;
62
+ };
63
+ export interface AgentJobResult {
64
+ id: string;
65
+ status: 'skipped' | 'succeeded' | 'failed';
66
+ exitCode?: number | null;
67
+ reason?: string;
68
+ }
69
+ //# sourceMappingURL=ports.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ports.js.map
@@ -0,0 +1,57 @@
1
+ import type { FileCoverage, SourceClassifier } from './lcov.js';
2
+ import type { SourceReaderPort } from '../ports.js';
3
+ export interface TierResult {
4
+ ok: boolean;
5
+ pctValue: number;
6
+ detail: string;
7
+ }
8
+ export interface FileTierEvaluation {
9
+ file: string;
10
+ unit: TierResult;
11
+ integration: TierResult;
12
+ ok: boolean;
13
+ }
14
+ export interface TierThresholds {
15
+ unit: number;
16
+ integration: number;
17
+ }
18
+ export interface DiffPort {
19
+ changedFiles(args: {
20
+ baseRef: string;
21
+ repoRoot: string;
22
+ sourceRoots: readonly string[];
23
+ }): Promise<readonly string[]>;
24
+ }
25
+ /** Resolve event inputs without global environment access or a repository-specific fallback. */
26
+ export declare function resolveBaseRef({ fallbackRef, remote }: {
27
+ fallbackRef: string;
28
+ remote: string;
29
+ }, { override, positional, pullRequestBase, eventBefore, }?: {
30
+ override?: string;
31
+ positional?: string;
32
+ pullRequestBase?: string;
33
+ eventBefore?: string;
34
+ }): string;
35
+ /** Evaluate two independent tiers; missing records differ from a known branchless source file. */
36
+ export declare function evaluateFileTiers({ file, unitRec, integrationRec, thresholds }: {
37
+ file: string;
38
+ unitRec: FileCoverage | undefined;
39
+ integrationRec: FileCoverage | undefined;
40
+ thresholds: TierThresholds;
41
+ }): FileTierEvaluation;
42
+ /** Query a diff port, then parse supplied coverage artifacts only when measurable files changed. */
43
+ export declare function checkCoverageDiff({ baseRef, repoRoot, sourceRoots, diff, reader, isMeasurable, unitCoveragePath, integrationCoveragePath, thresholds }: {
44
+ baseRef: string;
45
+ repoRoot: string;
46
+ sourceRoots: readonly string[];
47
+ diff: DiffPort;
48
+ reader: SourceReaderPort;
49
+ isMeasurable: SourceClassifier;
50
+ unitCoveragePath: string;
51
+ integrationCoveragePath: string;
52
+ thresholds: TierThresholds;
53
+ }): Promise<{
54
+ ok: boolean;
55
+ files: readonly FileTierEvaluation[];
56
+ }>;
57
+ //# sourceMappingURL=diff.d.ts.map
@@ -0,0 +1,48 @@
1
+ import { loadRouteCoverage, pct } from './lcov.js';
2
+ /** Resolve event inputs without global environment access or a repository-specific fallback. */
3
+ export function resolveBaseRef({ fallbackRef, remote }, { override, positional, pullRequestBase, eventBefore, } = {}) {
4
+ if (override)
5
+ return override;
6
+ if (positional)
7
+ return positional;
8
+ if (pullRequestBase)
9
+ return pullRequestBase.includes('/') ? pullRequestBase : `${remote}/${pullRequestBase}`;
10
+ if (eventBefore && !/^0+$/.test(eventBefore))
11
+ return eventBefore;
12
+ return fallbackRef;
13
+ }
14
+ function tier(record, threshold, label) {
15
+ if (!record)
16
+ return { ok: false, pctValue: 0, detail: `no ${label} coverage record` };
17
+ const pctValue = pct({ hit: record.brh, found: record.brf });
18
+ return { ok: pctValue >= threshold, pctValue, detail: `${pctValue.toFixed(2)}% branch` };
19
+ }
20
+ /** Evaluate two independent tiers; missing records differ from a known branchless source file. */
21
+ export function evaluateFileTiers({ file, unitRec, integrationRec, thresholds }) {
22
+ for (const value of Object.values(thresholds))
23
+ if (!Number.isFinite(value) || value < 0 || value > 100)
24
+ throw new RangeError('tier thresholds must be percentages from 0 to 100');
25
+ const brf = unitRec?.brf ?? integrationRec?.brf;
26
+ if (brf === undefined || (unitRec && integrationRec && unitRec.brf !== integrationRec.brf)) {
27
+ const detail = brf === undefined ? 'no coverage record on either tier' : 'inconsistent branch totals between tiers';
28
+ return { file, unit: { ok: false, pctValue: 0, detail }, integration: { ok: false, pctValue: 0, detail }, ok: false };
29
+ }
30
+ if (brf === 0) {
31
+ const result = { ok: true, pctValue: 100, detail: '0 branches in this file (vacuously passes both tiers)' };
32
+ return { file, unit: { ...result }, integration: { ...result }, ok: true };
33
+ }
34
+ const unit = tier(unitRec, thresholds.unit, 'unit');
35
+ const integration = tier(integrationRec, thresholds.integration, 'integration');
36
+ return { file, unit, integration, ok: unit.ok && integration.ok };
37
+ }
38
+ /** Query a diff port, then parse supplied coverage artifacts only when measurable files changed. */
39
+ export async function checkCoverageDiff({ baseRef, repoRoot, sourceRoots, diff, reader, isMeasurable, unitCoveragePath, integrationCoveragePath, thresholds }) {
40
+ const changed = [...new Set(await diff.changedFiles({ baseRef, repoRoot, sourceRoots }))].filter((file) => isMeasurable({ file }));
41
+ if (changed.length === 0)
42
+ return { ok: true, files: [] };
43
+ const unit = new Map(loadRouteCoverage({ lcovPath: unitCoveragePath, repoRoot, reader, isMeasurable }).map((record) => [record.file, record]));
44
+ const integration = new Map(loadRouteCoverage({ lcovPath: integrationCoveragePath, repoRoot, reader, isMeasurable }).map((record) => [record.file, record]));
45
+ const files = changed.map((file) => evaluateFileTiers({ file, unitRec: unit.get(file), integrationRec: integration.get(file), thresholds }));
46
+ return { ok: files.every((file) => file.ok), files };
47
+ }
48
+ //# sourceMappingURL=diff.js.map