@ygrishajev/jig 0.0.0-stage → 1.0.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 (117) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +135 -2
  3. package/dist/adapters/find-symlink.js +23 -0
  4. package/dist/adapters/git/git-workspace.js +297 -0
  5. package/dist/adapters/local-store/credentials-file.js +51 -0
  6. package/dist/adapters/local-store/local-run-store.js +45 -0
  7. package/dist/adapters/local-store/local-state.js +12 -0
  8. package/dist/adapters/local-store/metrics-log.js +119 -0
  9. package/dist/adapters/local-store/run-artefacts.js +76 -0
  10. package/dist/adapters/local-store/run-lock.js +51 -0
  11. package/dist/adapters/local-store/run-paths.js +49 -0
  12. package/dist/adapters/logging/create-logger.js +29 -0
  13. package/dist/adapters/run-store/composite-run-store.js +57 -0
  14. package/dist/adapters/run-store/git-remote-run-store.js +239 -0
  15. package/dist/adapters/sandbox-image/docker-images.js +93 -0
  16. package/dist/adapters/sandbox-image/image-recipe.js +96 -0
  17. package/dist/adapters/sandbox-image/latest-agent-versions.js +9 -0
  18. package/dist/adapters/sandcastle/agents.js +100 -0
  19. package/dist/adapters/sandcastle/codex-auth.js +191 -0
  20. package/dist/adapters/sandcastle/git-hooks.js +20 -0
  21. package/dist/adapters/sandcastle/open-session.js +67 -0
  22. package/dist/adapters/sandcastle/private-clone-docker.js +232 -0
  23. package/dist/adapters/sandcastle/sandcastle-env.js +17 -0
  24. package/dist/adapters/sandcastle/sandcastle-session.js +338 -0
  25. package/dist/adapters/sandcastle/structured-output.js +35 -0
  26. package/dist/adapters/sandcastle/usage.js +65 -0
  27. package/dist/adapters/telemetry/open-telemetry.js +29 -0
  28. package/dist/adapters/terminal/ask-for-agents.js +61 -0
  29. package/dist/adapters/terminal/ask-for-credential.js +32 -0
  30. package/dist/adapters/terminal/ask-for-preset.js +15 -0
  31. package/dist/adapters/terminal/standard-input.js +7 -0
  32. package/dist/adapters/terminal/terminal.js +45 -0
  33. package/dist/app/container.js +131 -0
  34. package/dist/app/init-sandbox.js +185 -0
  35. package/dist/app/observed-events.js +10 -0
  36. package/dist/app/report-cleanup.js +10 -0
  37. package/dist/app/run-jig.js +101 -0
  38. package/dist/app/run-status.js +20 -0
  39. package/dist/app/run-stores.js +107 -0
  40. package/dist/app/sandbox-image.js +151 -0
  41. package/dist/app/throwaway-sandbox.js +49 -0
  42. package/dist/cli/app-action.js +18 -0
  43. package/dist/cli/commands/presets.js +32 -0
  44. package/dist/cli/commands/run.js +82 -0
  45. package/dist/cli/commands/sandbox.js +54 -0
  46. package/dist/cli/commands/status.js +41 -0
  47. package/dist/cli/config-option.js +18 -0
  48. package/dist/cli/exit-when-done.js +11 -0
  49. package/dist/cli/log-format-option.js +14 -0
  50. package/dist/cli/main.js +33 -0
  51. package/dist/cli/read-request.js +36 -0
  52. package/dist/cli/with-app.js +73 -0
  53. package/dist/cli/with-error-handling.js +31 -0
  54. package/dist/cli/with-input.js +27 -0
  55. package/dist/config/describe-issues.js +6 -0
  56. package/dist/config/environment.js +53 -0
  57. package/dist/config/load-config.js +122 -0
  58. package/dist/config/presets.js +150 -0
  59. package/dist/config/write-config.js +39 -0
  60. package/dist/domain/agent-role.js +12 -0
  61. package/dist/domain/apply-outcome.js +132 -0
  62. package/dist/domain/completion-reuse.js +176 -0
  63. package/dist/domain/design-docs.js +3 -0
  64. package/dist/domain/design-review-report.js +86 -0
  65. package/dist/domain/design-review.js +193 -0
  66. package/dist/domain/errors.js +139 -0
  67. package/dist/domain/events.js +8 -0
  68. package/dist/domain/final-check.js +133 -0
  69. package/dist/domain/outcome.js +26 -0
  70. package/dist/domain/plan-coverage.js +129 -0
  71. package/dist/domain/protected-paths.js +35 -0
  72. package/dist/domain/retry.js +21 -0
  73. package/dist/domain/run-id.js +42 -0
  74. package/dist/domain/run-state.js +147 -0
  75. package/dist/domain/settings.js +49 -0
  76. package/dist/domain/slice.js +63 -0
  77. package/dist/domain/usage.js +1 -0
  78. package/dist/domain/work-facts.js +22 -0
  79. package/dist/flow/define-flow.js +11 -0
  80. package/dist/flow/engine.js +255 -0
  81. package/dist/flow/run-flow.js +129 -0
  82. package/dist/git/branch.js +26 -0
  83. package/dist/git/merge.js +92 -0
  84. package/dist/git/repository.js +48 -0
  85. package/dist/git/throwaway-branch.js +64 -0
  86. package/dist/observers/logging-observer.js +51 -0
  87. package/dist/observers/metrics.js +109 -0
  88. package/dist/observers/run-events.js +25 -0
  89. package/dist/observers/tracing-observer.js +86 -0
  90. package/dist/ports/agent-session.js +1 -0
  91. package/dist/ports/observability.js +1 -0
  92. package/dist/ports/run-store.js +1 -0
  93. package/dist/ports/sandbox-git.js +1 -0
  94. package/dist/ports/sandbox-images.js +1 -0
  95. package/dist/ports/workspace.js +1 -0
  96. package/dist/prompts/design-review.js +172 -0
  97. package/dist/prompts/final-check.js +58 -0
  98. package/dist/prompts/planning.js +111 -0
  99. package/dist/prompts/pull-request.js +78 -0
  100. package/dist/prompts/slice.js +254 -0
  101. package/dist/prompts/toolchain.js +37 -0
  102. package/dist/steps/completion-reuse.js +32 -0
  103. package/dist/steps/design-review.js +38 -0
  104. package/dist/steps/final-check.js +39 -0
  105. package/dist/steps/finishing.js +72 -0
  106. package/dist/steps/planning.js +77 -0
  107. package/dist/steps/pull-request-description.js +142 -0
  108. package/dist/steps/slice.js +149 -0
  109. package/package.json +95 -4
  110. package/presets/cheap-volume.json +7 -0
  111. package/presets/claude-only.json +7 -0
  112. package/presets/codex-only.json +7 -0
  113. package/presets/codex-reviewed-opencode.json +7 -0
  114. package/presets/full-power-codex.json +7 -0
  115. package/presets/full-power.json +7 -0
  116. package/presets/long-claude.json +7 -0
  117. package/presets/open-weight.json +7 -0
@@ -0,0 +1,107 @@
1
+ import { Result } from 'better-result';
2
+ import path from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { z } from 'zod';
5
+ import { LocalRunStore } from '../adapters/local-store/local-run-store.js';
6
+ import { CompositeRunStore } from '../adapters/run-store/composite-run-store.js';
7
+ import { GitRemoteRunStore } from '../adapters/run-store/git-remote-run-store.js';
8
+ import { ConfigInvalid, messageOf } from '../domain/errors.js';
9
+ import { runStateSchema } from '../domain/run-state.js';
10
+ /**
11
+ * The one place that decides where a run's state is read from and written to: every store named
12
+ * in `runStores` — `local`, `git-remote`, or a path to a module — holding a copy, the freshest
13
+ * copy winning on load. Every reader and writer of run state goes through it. What else sits in
14
+ * `.jig/<id>/state/` — `result.json`, `metrics.jsonl`, the logs and the markdown documents — is
15
+ * this machine's record of the invocations it ran, not part of the run, and stays local.
16
+ */
17
+ export async function openRunStore({ repoRoot, config, }) {
18
+ const stores = [];
19
+ for (const name of config.runStores) {
20
+ const store = await storeNamed(name, repoRoot);
21
+ if (store.isErr())
22
+ return Result.err(store.error);
23
+ stores.push(store.value);
24
+ }
25
+ return Result.ok(new CompositeRunStore(stores));
26
+ }
27
+ async function storeNamed(name, repoRoot) {
28
+ if (name === 'local')
29
+ return Result.ok(new LocalRunStore(repoRoot));
30
+ if (name === 'git-remote')
31
+ return Result.ok(new GitRemoteRunStore(repoRoot));
32
+ const imported = await Result.tryPromise({
33
+ try: () => import(pathToFileURL(path.resolve(repoRoot, name)).href),
34
+ catch: (cause) => moduleFailure(name, cause),
35
+ });
36
+ if (imported.isErr())
37
+ return Result.err(imported.error);
38
+ const factory = imported.value.default;
39
+ if (typeof factory !== 'function') {
40
+ return Result.err(new ConfigInvalid({
41
+ message: `Run store "${name}" must default-export a function that returns a store.`,
42
+ }));
43
+ }
44
+ const store = await Result.tryPromise({
45
+ try: async () => factory({ repoRoot }),
46
+ catch: (cause) => moduleFailure(name, cause),
47
+ });
48
+ if (store.isErr())
49
+ return Result.err(store.error);
50
+ if (!isModuleStore(store.value)) {
51
+ return Result.err(new ConfigInvalid({
52
+ message: `Run store "${name}" must return an object with load and save methods.`,
53
+ }));
54
+ }
55
+ return Result.ok(new ModuleRunStore(name, store.value));
56
+ }
57
+ /** A custom store is the operator's code: when it throws, the operator's config is what to fix. */
58
+ function moduleFailure(name, cause) {
59
+ return new ConfigInvalid({ message: `Run store "${name}" failed: ${messageOf(cause)}` });
60
+ }
61
+ /** Checks the shape only; the store itself is kept, so its methods still see their own `this`. */
62
+ function isModuleStore(value) {
63
+ return moduleStoreShape.safeParse(value).success;
64
+ }
65
+ const moduleStoreShape = z.object({
66
+ load: z.function(),
67
+ save: z.function(),
68
+ peek: z.function().optional(),
69
+ });
70
+ /** Parses what a module store hands back, so a malformed run fails where it came in. */
71
+ class ModuleRunStore {
72
+ name;
73
+ store;
74
+ constructor(name, store) {
75
+ this.name = name;
76
+ this.store = store;
77
+ }
78
+ async load(runId) {
79
+ return this.parsed(await this.call(() => this.store.load(runId)));
80
+ }
81
+ parsed(loaded) {
82
+ if (loaded.isErr())
83
+ return Result.err(loaded.error);
84
+ if (loaded.value === undefined || loaded.value === null)
85
+ return Result.ok(undefined);
86
+ const parsed = runStateSchema.safeParse(loaded.value);
87
+ if (parsed.success)
88
+ return Result.ok(parsed.data);
89
+ return Result.err(new ConfigInvalid({
90
+ message: `Run store "${this.name}" returned a malformed run: ${parsed.error.message}`,
91
+ }));
92
+ }
93
+ call(operation) {
94
+ return Result.tryPromise({
95
+ try: async () => operation(),
96
+ catch: (cause) => moduleFailure(this.name, cause),
97
+ });
98
+ }
99
+ async peek(runId) {
100
+ const peeked = await this.call(() => this.store.peek ? this.store.peek(runId) : this.store.load(runId));
101
+ return this.parsed(peeked);
102
+ }
103
+ async save(state) {
104
+ const saved = await this.call(() => this.store.save(state));
105
+ return saved.map(() => undefined);
106
+ }
107
+ }
@@ -0,0 +1,151 @@
1
+ import { defaultImageName } from '@ai-hero/sandcastle/sandboxes/docker';
2
+ import { Result } from 'better-result';
3
+ import { existsSync } from 'node:fs';
4
+ import { readFile } from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import { agentLayerDockerfile, DOCKERFILE, imageLabels, LABELS, parseAgentVersions, recipeHash, SANDBOX_DIRECTORY, } from '../adapters/sandbox-image/image-recipe.js';
7
+ import { AGENTS } from '../adapters/sandcastle/agents.js';
8
+ import { configuredSteps } from '../config/load-config.js';
9
+ import { ConfigInvalid, messageOf } from '../domain/errors.js';
10
+ /**
11
+ * Makes sure the sandbox image matches the repository's Dockerfile and the agents the config
12
+ * uses, building only what changed. An image named in `sandboxImage` is managed elsewhere and
13
+ * used as it is.
14
+ */
15
+ export async function ensureSandboxImage(d, options = {}) {
16
+ const image = sandboxImageName(d.repoRoot, d.config);
17
+ if (d.config.sandboxImage)
18
+ return Result.ok(image);
19
+ return Result.gen(async function* () {
20
+ const steps = yield* configuredSteps(d.config);
21
+ const recipe = yield* Result.await(readRecipe(d.repoRoot));
22
+ const policy = options.pullAgents ? 'auto' : d.config.agentUpdates;
23
+ const plan = planImageBuild({
24
+ labels: yield* Result.await(d.images.labels(image)),
25
+ dockerfileHash: recipe.dockerfileHash,
26
+ agentsNeeded: await agentsNeeded(d, Object.values(steps), policy),
27
+ policy,
28
+ });
29
+ for (const warning of plan.warnings)
30
+ d.logger.warn(warning);
31
+ if (plan.action !== 'none') {
32
+ yield* Result.await(buildImage(d, image, plan, recipe.buildArgs));
33
+ }
34
+ return Result.ok(image);
35
+ });
36
+ }
37
+ export function sandboxImageName(repoRoot, config) {
38
+ return config.sandboxImage ?? defaultImageName(repoRoot);
39
+ }
40
+ /** The image is built for the host user, so files the agent writes in the worktree stay the operator's. */
41
+ async function readRecipe(repoRoot) {
42
+ const dockerfile = await readSandboxDockerfile(repoRoot);
43
+ if (dockerfile.isErr())
44
+ return Result.err(dockerfile.error);
45
+ const uid = process.getuid?.() ?? 1000;
46
+ const gid = process.getgid?.() ?? 1000;
47
+ return Result.ok({
48
+ dockerfileHash: recipeHash(dockerfile.value, uid, gid),
49
+ buildArgs: { AGENT_UID: uid, AGENT_GID: gid },
50
+ });
51
+ }
52
+ export async function readSandboxDockerfile(repoRoot) {
53
+ const file = path.join(sandboxDirectory(repoRoot), DOCKERFILE);
54
+ const shown = path.join(SANDBOX_DIRECTORY, DOCKERFILE);
55
+ if (!existsSync(file)) {
56
+ return Result.err(new ConfigInvalid({ message: `No sandbox Dockerfile at ${shown} — run jig init first.` }));
57
+ }
58
+ return Result.tryPromise({
59
+ try: () => readFile(file, 'utf-8'),
60
+ catch: (cause) => new ConfigInvalid({
61
+ message: `Could not read the sandbox Dockerfile at ${shown}: ${messageOf(cause)}`,
62
+ }),
63
+ });
64
+ }
65
+ function sandboxDirectory(repoRoot) {
66
+ return path.join(repoRoot, SANDBOX_DIRECTORY);
67
+ }
68
+ /**
69
+ * Decides what to rebuild from the image's labels: everything when the Dockerfile changed or
70
+ * there is no image, only the agent layer when the agents or their versions changed, nothing
71
+ * otherwise.
72
+ */
73
+ export function planImageBuild(input) {
74
+ const installed = parseAgentVersions(input.labels?.[LABELS.agentVersions]);
75
+ const agents = input.agentsNeeded.map((agent) => ({
76
+ name: agent.name,
77
+ npmPackage: agent.npmPackage,
78
+ version: agentVersion(agent, installed[agent.name], input.policy),
79
+ }));
80
+ const warnings = input.agentsNeeded.flatMap((agent) => newerReleaseWarning(agent, installed[agent.name], input.policy));
81
+ const labels = imageLabels(input.dockerfileHash, agents);
82
+ const decision = rebuildDecision(input.labels, labels, versionChanges(installed, agents));
83
+ return { ...decision, agents, labels, warnings };
84
+ }
85
+ /**
86
+ * A pin always wins. Without one, `auto` takes the latest release, `warn` and `off` keep the
87
+ * installed one; either falls back to the other, and to npm's `latest` when neither is known.
88
+ */
89
+ export function agentVersion(agent, installed, policy) {
90
+ if (agent.pinned !== undefined)
91
+ return agent.pinned;
92
+ const preferred = policy === 'auto' ? [agent.latest, installed] : [installed, agent.latest];
93
+ return preferred.find((version) => version !== undefined) ?? 'latest';
94
+ }
95
+ function newerReleaseWarning(agent, installed, policy) {
96
+ if (agent.pinned !== undefined || policy !== 'warn')
97
+ return [];
98
+ if (!agent.latest || !installed || agent.latest === installed)
99
+ return [];
100
+ return [
101
+ `${agent.name} ${agent.latest} is available (installed: ${installed}) — run jig build --pull-agents`,
102
+ ];
103
+ }
104
+ function rebuildDecision(installed, wanted, changedVersions) {
105
+ if (!installed)
106
+ return { action: 'all', reason: 'no sandbox image yet' };
107
+ if (installed[LABELS.dockerfileHash] !== wanted[LABELS.dockerfileHash])
108
+ return { action: 'all', reason: 'the sandbox Dockerfile changed' };
109
+ if (installed[LABELS.agents] !== wanted[LABELS.agents])
110
+ return { action: 'agents', reason: `agents changed to ${wanted[LABELS.agents]}` };
111
+ if (installed[LABELS.agentVersions] !== wanted[LABELS.agentVersions])
112
+ return { action: 'agents', reason: changedVersions };
113
+ return { action: 'none', reason: 'the sandbox image is up to date' };
114
+ }
115
+ function versionChanges(installed, agents) {
116
+ return agents
117
+ .filter((agent) => installed[agent.name] !== agent.version)
118
+ .map((agent) => `${agent.name} ${installed[agent.name] ?? 'none'} → ${agent.version}`)
119
+ .join(', ');
120
+ }
121
+ async function agentsNeeded(d, steps, policy) {
122
+ const names = [...new Set(steps.map((step) => step.provider))];
123
+ const packages = names.map((name) => AGENTS[name].npmPackage);
124
+ const latest = policy === 'off' ? {} : await d.latestVersions(packages);
125
+ return names.map((name) => ({
126
+ name,
127
+ npmPackage: AGENTS[name].npmPackage,
128
+ pinned: d.config.agents[name],
129
+ latest: latest[AGENTS[name].npmPackage],
130
+ }));
131
+ }
132
+ async function buildImage(d, image, plan, buildArgs) {
133
+ return Result.gen(async function* () {
134
+ d.logger.info(`building the sandbox image ${image}: ${plan.reason}`);
135
+ const base = baseImageName(image);
136
+ if (plan.action === 'all' || !(yield* Result.await(d.images.labels(base)))) {
137
+ yield* Result.await(d.images.build({ tag: base, contextDirectory: sandboxDirectory(d.repoRoot), buildArgs }));
138
+ }
139
+ yield* Result.await(d.images.build({
140
+ tag: image,
141
+ dockerfile: agentLayerDockerfile(base, plan.agents),
142
+ buildArgs,
143
+ labels: plan.labels,
144
+ }));
145
+ return Result.ok();
146
+ });
147
+ }
148
+ export function baseImageName(image) {
149
+ const lastSlash = image.lastIndexOf('/');
150
+ return image.lastIndexOf(':') > lastSlash ? `${image}-base` : `${image}:base`;
151
+ }
@@ -0,0 +1,49 @@
1
+ import { Result } from 'better-result';
2
+ import { randomBytes } from 'node:crypto';
3
+ import { runIdSchema } from '../domain/run-id.js';
4
+ import { runBranchFor } from '../domain/run-state.js';
5
+ import { getCurrentBranch } from '../git/branch.js';
6
+ import { discardBranch, discardBranchOnExit } from '../git/throwaway-branch.js';
7
+ import { LoggingObserver } from '../observers/logging-observer.js';
8
+ import { observedEvents } from './observed-events.js';
9
+ import { reportCleanup } from './report-cleanup.js';
10
+ /**
11
+ * A sandbox for a one-off check, on a branch of its own that is removed afterwards, even when the
12
+ * process is interrupted; its events are logged to the console. It is never retried: a setup command that fails is the answer the
13
+ * caller is waiting for, not a hiccup.
14
+ */
15
+ export async function withThrowawaySandbox(app, setupCommand, use) {
16
+ const { repoRoot } = app.cradle;
17
+ const baseBranch = await getCurrentBranch(repoRoot);
18
+ if (baseBranch.isErr())
19
+ return Result.err(baseBranch.error);
20
+ const run = {
21
+ runId: runIdSchema.parse(`init-${randomBytes(3).toString('hex')}`),
22
+ baseBranch: baseBranch.value,
23
+ };
24
+ return discardBranchOnExit(repoRoot, runBranchFor(run.runId), () => useThrowawaySandbox(app, run, setupCommand, use));
25
+ }
26
+ async function useThrowawaySandbox(app, run, setupCommand, use) {
27
+ const { repoRoot, logger, openSession } = app.cradle;
28
+ const events = observedEvents(logger, [new LoggingObserver(logger)]);
29
+ const session = await openSession({ run, events, setupCommand });
30
+ if (session.isErr())
31
+ return Result.err(session.error);
32
+ let used;
33
+ let closed;
34
+ let discarded;
35
+ try {
36
+ used = await use(session.value);
37
+ }
38
+ finally {
39
+ closed = await session.value.close();
40
+ discarded = await discardBranch(repoRoot, runBranchFor(run.runId));
41
+ }
42
+ if (closed.isErr() && discarded.isErr()) {
43
+ logger.warn({ err: discarded.error }, 'removing the throwaway branch failed as well');
44
+ }
45
+ const cleaned = closed.isErr()
46
+ ? closed
47
+ : discarded;
48
+ return reportCleanup(used, cleaned, logger);
49
+ }
@@ -0,0 +1,18 @@
1
+ import { Result } from 'better-result';
2
+ import { processInvocation, withApp } from './with-app.js';
3
+ import { withErrorHandling } from './with-error-handling.js';
4
+ import { withInput } from './with-input.js';
5
+ /**
6
+ * Every app command parses, prepares, opens the app and reports a failure in this one order, so
7
+ * none can skip a step. `prepare` reads what the command needs from outside the app, such as
8
+ * piped text, so a refusal comes before the app opens.
9
+ */
10
+ export function appAction(schema, run, { invocation, failureOutput } = {}, prepare) {
11
+ const commandInvocation = invocation ?? processInvocation();
12
+ return withErrorHandling(withInput(schema, async (input) => {
13
+ const prepared = prepare ? await prepare(input, commandInvocation) : Result.ok(undefined);
14
+ if (prepared.isErr())
15
+ return Result.err(prepared.error);
16
+ return withApp(input, (app) => run(input, app, prepared.value), commandInvocation);
17
+ }), failureOutput);
18
+ }
@@ -0,0 +1,32 @@
1
+ import { Result } from 'better-result';
2
+ import { defaultLogFormat } from '../../adapters/logging/create-logger.js';
3
+ import { discoverPresets } from '../../config/presets.js';
4
+ import { withApp } from '../with-app.js';
5
+ import { withErrorHandling } from '../with-error-handling.js';
6
+ export function registerPresetsCommand(program) {
7
+ program
8
+ .command('presets')
9
+ .description('List the presets --preset can name, and where each is read from')
10
+ .action(withErrorHandling(async () => {
11
+ return withApp({ logFormat: defaultLogFormat() }, async (app) => {
12
+ const presets = discoverPresets({
13
+ repoRoot: app.cradle.repoRoot,
14
+ ...app.cradle.environment,
15
+ });
16
+ if (presets.isErr())
17
+ return Result.err(presets.error);
18
+ console.log(describePresets(presets.value));
19
+ return Result.ok();
20
+ });
21
+ }));
22
+ }
23
+ export function describePresets(presets) {
24
+ if (presets.length === 0)
25
+ return 'No presets found.';
26
+ return presets
27
+ .map(({ name, source, path, description }) => {
28
+ const line = `${name.padEnd(20)} ${source.padEnd(10)} ${path}`;
29
+ return description ? `${line}\n ${description}` : line;
30
+ })
31
+ .join('\n');
32
+ }
@@ -0,0 +1,82 @@
1
+ import { Result } from 'better-result';
2
+ import { z } from 'zod';
3
+ import { runJig } from '../../app/run-jig.js';
4
+ import { runIdSchema } from '../../domain/run-id.js';
5
+ import { runBranchFor, runStopReason } from '../../domain/run-state.js';
6
+ import { appAction } from '../app-action.js';
7
+ import { configInputSchema, configOption, presetInputSchema, presetOption, } from '../config-option.js';
8
+ import { logFormatInputSchema, logFormatOption } from '../log-format-option.js';
9
+ import { readRequest } from '../read-request.js';
10
+ export function registerRunCommand(program, io) {
11
+ program
12
+ .command('run')
13
+ .description('Start a run from a request file (or - for standard input), or resume one with --id')
14
+ .argument('[request]', 'markdown file describing what to build, or - to read it from standard input')
15
+ .option('--id <id>', 'run id: resumes that run if it exists, otherwise names the new one')
16
+ .addOption(configOption())
17
+ .addOption(presetOption())
18
+ .addOption(logFormatOption())
19
+ .action(appAction(runInputSchema, async (_input, app, runInput) => {
20
+ const report = await runJig(app, runInput);
21
+ if (report.isErr())
22
+ return Result.err(report.error);
23
+ app.cradle.logger.info({ runId: report.value.state.runId, branch: runBranchFor(report.value.state.runId) }, nextStep(report.value));
24
+ return Result.ok();
25
+ }, io, prepareRun));
26
+ }
27
+ /** The argument that asks for the request to be read from standard input. */
28
+ const STANDARD_INPUT_ARGUMENT = '-';
29
+ /**
30
+ * `jig run [request | -] [--id <id>]`: a request file, or `-` for standard input, starts a run,
31
+ * named by `--id` when given; an id alone resumes that run.
32
+ */
33
+ export const runInputSchema = logFormatInputSchema
34
+ .merge(configInputSchema)
35
+ .merge(presetInputSchema)
36
+ .extend({ request: z.string().optional(), id: runIdSchema.optional() })
37
+ .transform(({ request, id, ...options }, context) => {
38
+ const run = runToDo(request, id);
39
+ if (run)
40
+ return { run, ...options };
41
+ context.addIssue({
42
+ code: z.ZodIssueCode.custom,
43
+ message: 'Pass a request file (or - for standard input) to start a run, or --id to resume one.',
44
+ });
45
+ return z.NEVER;
46
+ });
47
+ function runToDo(request, id) {
48
+ if (request !== undefined) {
49
+ const start = request === STANDARD_INPUT_ARGUMENT ? { stdin: true } : { file: request };
50
+ return id ? { start, runId: id } : { start };
51
+ }
52
+ if (id)
53
+ return { resume: id };
54
+ return undefined;
55
+ }
56
+ /** What the operator does next, for where the run stopped. */
57
+ export function nextStep(report) {
58
+ const { state } = report;
59
+ switch (report.status) {
60
+ case 'done':
61
+ return 'Run complete.';
62
+ case 'halted':
63
+ return state.phase === 'paused'
64
+ ? `Planning done — review the design and plan, then resume with: jig run --id ${state.runId}`
65
+ : `Ready to merge "${runBranchFor(state.runId)}" — merge it, then resume with: jig run --id ${state.runId}`;
66
+ case 'blocked':
67
+ return `Blocked: ${report.reason} — resume with: jig run --id ${state.runId}`;
68
+ case 'stuck':
69
+ return stuckMessage(state);
70
+ }
71
+ }
72
+ function stuckMessage(state) {
73
+ return (`Stuck: ${runStopReason(state) ?? 'the run exhausted its attempts'}, so jig has ended this run and will not resume it. ` +
74
+ `Finish that slice and the rest by hand on "${runBranchFor(state.runId)}" (its pull request description is in .jig/${state.runId}/state/PR_DESCRIPTION.md), ` +
75
+ `or start a new run with a sharper request. The failure feedback: jig status ${state.runId}`);
76
+ }
77
+ async function prepareRun({ run }, { cwd, standardInput }) {
78
+ if ('resume' in run)
79
+ return Result.ok(run);
80
+ const start = await readRequest(run.start, { cwd, standardInput });
81
+ return start.map((request) => run.runId ? { start: request, runId: run.runId } : { start: request });
82
+ }
@@ -0,0 +1,54 @@
1
+ import { Result } from 'better-result';
2
+ import { z } from 'zod';
3
+ import { initSandbox } from '../../app/init-sandbox.js';
4
+ import { ensureSandboxImage } from '../../app/sandbox-image.js';
5
+ import { appAction } from '../app-action.js';
6
+ import { configInputSchema, configOption, presetInputSchema, presetOption, } from '../config-option.js';
7
+ import { logFormatInputSchema, logFormatOption } from '../log-format-option.js';
8
+ export function registerSandboxCommands(program, io) {
9
+ program
10
+ .command('init')
11
+ .description("Set up this repository's sandbox and check its setup and verify commands in it")
12
+ .option('--no-agent', 'only write the starter files and check what is already configured')
13
+ .addOption(configOption())
14
+ .addOption(logFormatOption())
15
+ .action(appAction(initInputSchema, async ({ agent }, app) => {
16
+ const result = await initSandbox(app, { useAgent: agent });
17
+ if (result.isErr())
18
+ return Result.err(result.error);
19
+ app.cradle.logger.info(initSummary(result.value, app.cradle.configFile.name));
20
+ if (result.value.status === 'failed')
21
+ process.exitCode = 1;
22
+ return Result.ok();
23
+ }, io));
24
+ program
25
+ .command('build')
26
+ .description('Build the sandbox image if the Dockerfile or the agents changed')
27
+ .option('--pull-agents', 'install the latest agent releases even if updates are off')
28
+ .addOption(configOption())
29
+ .addOption(presetOption())
30
+ .addOption(logFormatOption())
31
+ .action(appAction(buildInputSchema, async ({ pullAgents }, app) => {
32
+ const image = await ensureSandboxImage(app.cradle, { pullAgents });
33
+ if (image.isErr())
34
+ return Result.err(image.error);
35
+ app.cradle.logger.info(`Sandbox image ready: ${image.value}`);
36
+ return Result.ok();
37
+ }, io));
38
+ }
39
+ const initInputSchema = logFormatInputSchema
40
+ .merge(configInputSchema)
41
+ .extend({ agent: z.boolean() });
42
+ export function initSummary(result, configName) {
43
+ return INIT_SUMMARY[result.status](result, configName);
44
+ }
45
+ const INIT_SUMMARY = {
46
+ 'needs-agents': (result, configName) => `Wrote .sandcastle/Dockerfile and ${configName}. ${'instruction' in result ? result.instruction : ''} Then run jig init again.`,
47
+ written: (_result, configName) => `Wrote .sandcastle/Dockerfile and ${configName} — add your toolchain and a verifyCommand, then run jig init --no-agent to check them.`,
48
+ verified: (result, configName) => `Sandbox ready: setup and verify pass inside it${'attempts' in result && result.attempts > 1 ? ` (after ${result.attempts} attempts)` : ''}. Review and commit .sandcastle/Dockerfile and ${configName}.`,
49
+ failed: (result) => `Setup or verify did not pass in the sandbox${'attempts' in result && result.attempts > 1 ? ` after ${result.attempts} attempts` : ''} — fix what this shows, then run jig init --no-agent:\n${'failure' in result ? result.failure : ''}`,
50
+ };
51
+ export const buildInputSchema = logFormatInputSchema
52
+ .merge(configInputSchema)
53
+ .merge(presetInputSchema)
54
+ .extend({ pullAgents: z.boolean().optional() });
@@ -0,0 +1,41 @@
1
+ import { Result } from 'better-result';
2
+ import { defaultLogFormat } from '../../adapters/logging/create-logger.js';
3
+ import { readRunStatus } from '../../app/run-status.js';
4
+ import { runIdSchema } from '../../domain/run-id.js';
5
+ import { runBranchFor } from '../../domain/run-state.js';
6
+ import { slicesInOrder } from '../../domain/slice.js';
7
+ import { formatSummary } from '../../observers/metrics.js';
8
+ import { configInputSchema, configOption } from '../config-option.js';
9
+ import { withApp } from '../with-app.js';
10
+ import { withErrorHandling } from '../with-error-handling.js';
11
+ import { withInput } from '../with-input.js';
12
+ export function registerStatusCommand(program) {
13
+ program
14
+ .command('status')
15
+ .description('Show where a run is, without changing anything')
16
+ .argument('<id>', 'run id')
17
+ .addOption(configOption())
18
+ .action(withErrorHandling(withInput(configInputSchema.extend({ id: runIdSchema }), async ({ id, config }) => {
19
+ return withApp({ logFormat: defaultLogFormat(), config }, async (app) => {
20
+ const status = await readRunStatus(app, id);
21
+ if (status.isErr())
22
+ return Result.err(status.error);
23
+ console.log(describeRun(status.value));
24
+ return Result.ok();
25
+ });
26
+ })));
27
+ }
28
+ export function describeRun({ state, documents, metrics }) {
29
+ const slices = slicesInOrder(state.slices).map((slice) => {
30
+ const line = ` [${slice.status}] ${slice.id} — ${slice.title}`;
31
+ return slice.lastFeedback ? `${line}\n feedback: ${slice.lastFeedback}` : line;
32
+ });
33
+ return [
34
+ `Run ${state.runId} — ${state.phase} (base: ${state.baseBranch})`,
35
+ ...(state.blockedReason ? [`Blocked: ${state.blockedReason}`] : []),
36
+ `${'branch'.padEnd(18)} ${runBranchFor(state.runId)}`,
37
+ ...documents.map((document) => `${document.name.padEnd(18)} ${document.path}`),
38
+ ...(slices.length > 0 ? ['Slices:', ...slices] : []),
39
+ ...(metrics.steps > 0 ? [`So far: ${formatSummary(metrics)}`] : []),
40
+ ].join('\n');
41
+ }
@@ -0,0 +1,18 @@
1
+ import { Option } from 'commander';
2
+ import { z } from 'zod';
3
+ import { presetNameSchema } from '../config/presets.js';
4
+ /** The input of a command that reads the config; its input schema extends this one. */
5
+ export const configInputSchema = z.object({ config: z.string().min(1).optional() });
6
+ export function configOption() {
7
+ return new Option('--config <path>', 'config file to use instead of jig.config.json, e.g. a preset for this kind of run');
8
+ }
9
+ /** Commander hands a bare `--preset` over as `true`, which here means "ask". */
10
+ const presetSelectionSchema = z.union([
11
+ z.literal(true).transform(() => ({ kind: 'ask' })),
12
+ presetNameSchema.transform((name) => ({ kind: 'named', name })),
13
+ ]);
14
+ /** The input of a command that can swap in a preset's agents; its input schema extends this one. */
15
+ export const presetInputSchema = z.object({ preset: presetSelectionSchema.optional() });
16
+ export function presetOption() {
17
+ return new Option('--preset [name]', "preset whose agents replace the config's; without a name, pick one from a list");
18
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Ends the process once its output is written. A library can leave a timer running after the
3
+ * command is done (sandcastle's idle warning once did), and that alone keeps Node alive.
4
+ */
5
+ export async function exitWhenDone(outputs = [process.stdout, process.stderr], exit = () => process.exit()) {
6
+ await Promise.all(outputs.map(drained));
7
+ exit();
8
+ }
9
+ function drained(output) {
10
+ return new Promise((resolve) => output.write('', () => resolve()));
11
+ }
@@ -0,0 +1,14 @@
1
+ import { Option } from 'commander';
2
+ import { z } from 'zod';
3
+ import { defaultLogFormat, logFormatSchema } from '../adapters/logging/create-logger.js';
4
+ /** The input of a command that takes `--log-format`; its input schema extends this one. */
5
+ export const logFormatInputSchema = z.object({ logFormat: logFormatSchema });
6
+ /**
7
+ * Lists the choices in `--help` without commander's `.choices()`, which would also reject a value
8
+ * before `withInput` sees it; the schema is the one place the value is checked.
9
+ */
10
+ export function logFormatOption() {
11
+ const option = new Option('--log-format <format>', 'pretty for a terminal, json for CI and files').default(defaultLogFormat());
12
+ option.argChoices = [...logFormatSchema.options];
13
+ return option;
14
+ }
@@ -0,0 +1,33 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from 'commander';
3
+ import { readFileSync, realpathSync } from 'node:fs';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { z } from 'zod';
6
+ import { registerPresetsCommand } from './commands/presets.js';
7
+ import { registerRunCommand } from './commands/run.js';
8
+ import { registerSandboxCommands } from './commands/sandbox.js';
9
+ import { registerStatusCommand } from './commands/status.js';
10
+ import { exitWhenDone } from './exit-when-done.js';
11
+ const packageManifestSchema = z.object({ version: z.string() });
12
+ export function buildCli() {
13
+ const program = new Command();
14
+ program.name('jig').description('Agentic SDLC pipeline orchestrator').version(packageVersion());
15
+ registerSandboxCommands(program);
16
+ registerRunCommand(program);
17
+ registerStatusCommand(program);
18
+ registerPresetsCommand(program);
19
+ return program;
20
+ }
21
+ function packageVersion() {
22
+ const manifest = new URL('../../package.json', import.meta.url);
23
+ return packageManifestSchema.parse(JSON.parse(readFileSync(manifest, 'utf-8'))).version;
24
+ }
25
+ /**
26
+ * A globally installed CLI is invoked through a symlink, so the invoked path is resolved
27
+ * before comparing it with this module's own path.
28
+ */
29
+ const isMainModule = process.argv[1] !== undefined && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
30
+ if (isMainModule) {
31
+ await buildCli().parseAsync(process.argv);
32
+ await exitWhenDone();
33
+ }
@@ -0,0 +1,36 @@
1
+ import { Result } from 'better-result';
2
+ import { readFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { messageOf, RunRequestInvalid } from '../domain/errors.js';
5
+ export async function readRequest(source, { cwd, standardInput }) {
6
+ if ('stdin' in source) {
7
+ const piped = await readPipedText(standardInput);
8
+ return piped.andThen((text) => nonBlank({ text }, 'standard input'));
9
+ }
10
+ const file = path.resolve(cwd, source.file);
11
+ const text = await Result.tryPromise({
12
+ try: () => readFile(file, 'utf-8'),
13
+ catch: (error) => new RunRequestInvalid({
14
+ message: `Cannot read the request file "${file}": ${messageOf(error)}`,
15
+ }),
16
+ });
17
+ return text.andThen((read) => nonBlank({ text: read, file: source.file }, `"${file}"`));
18
+ }
19
+ async function readPipedText(standardInput) {
20
+ if (standardInput.isTerminal) {
21
+ return Result.err(new RunRequestInvalid({
22
+ message: 'Cannot read the request from standard input: it is a terminal. Pipe the request in, for example: cat request.md | jig run -',
23
+ }));
24
+ }
25
+ return Result.tryPromise({
26
+ try: () => standardInput.readAll(),
27
+ catch: (error) => new RunRequestInvalid({
28
+ message: `Cannot read the request from standard input: ${messageOf(error)}`,
29
+ }),
30
+ });
31
+ }
32
+ function nonBlank(request, origin) {
33
+ if (request.text.trim() !== '')
34
+ return Result.ok(request);
35
+ return Result.err(new RunRequestInvalid({ message: `The request is empty: ${origin} has no text.` }));
36
+ }