@ygrishajev/jig 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +135 -2
- package/dist/adapters/find-symlink.js +23 -0
- package/dist/adapters/git/git-workspace.js +297 -0
- package/dist/adapters/local-store/credentials-file.js +51 -0
- package/dist/adapters/local-store/local-run-store.js +45 -0
- package/dist/adapters/local-store/local-state.js +12 -0
- package/dist/adapters/local-store/metrics-log.js +119 -0
- package/dist/adapters/local-store/run-artefacts.js +76 -0
- package/dist/adapters/local-store/run-lock.js +51 -0
- package/dist/adapters/local-store/run-paths.js +49 -0
- package/dist/adapters/logging/create-logger.js +29 -0
- package/dist/adapters/run-store/composite-run-store.js +57 -0
- package/dist/adapters/run-store/git-remote-run-store.js +239 -0
- package/dist/adapters/sandbox-image/docker-images.js +93 -0
- package/dist/adapters/sandbox-image/image-recipe.js +96 -0
- package/dist/adapters/sandbox-image/latest-agent-versions.js +9 -0
- package/dist/adapters/sandcastle/agents.js +100 -0
- package/dist/adapters/sandcastle/codex-auth.js +191 -0
- package/dist/adapters/sandcastle/git-hooks.js +20 -0
- package/dist/adapters/sandcastle/open-session.js +67 -0
- package/dist/adapters/sandcastle/private-clone-docker.js +232 -0
- package/dist/adapters/sandcastle/sandcastle-env.js +17 -0
- package/dist/adapters/sandcastle/sandcastle-session.js +338 -0
- package/dist/adapters/sandcastle/structured-output.js +35 -0
- package/dist/adapters/sandcastle/usage.js +65 -0
- package/dist/adapters/telemetry/open-telemetry.js +29 -0
- package/dist/adapters/terminal/ask-for-agents.js +61 -0
- package/dist/adapters/terminal/ask-for-credential.js +32 -0
- package/dist/adapters/terminal/ask-for-preset.js +15 -0
- package/dist/adapters/terminal/standard-input.js +7 -0
- package/dist/adapters/terminal/terminal.js +45 -0
- package/dist/app/container.js +131 -0
- package/dist/app/init-sandbox.js +185 -0
- package/dist/app/observed-events.js +10 -0
- package/dist/app/report-cleanup.js +10 -0
- package/dist/app/run-jig.js +101 -0
- package/dist/app/run-status.js +20 -0
- package/dist/app/run-stores.js +107 -0
- package/dist/app/sandbox-image.js +151 -0
- package/dist/app/throwaway-sandbox.js +49 -0
- package/dist/cli/app-action.js +18 -0
- package/dist/cli/commands/presets.js +32 -0
- package/dist/cli/commands/run.js +82 -0
- package/dist/cli/commands/sandbox.js +54 -0
- package/dist/cli/commands/status.js +41 -0
- package/dist/cli/config-option.js +18 -0
- package/dist/cli/exit-when-done.js +11 -0
- package/dist/cli/log-format-option.js +14 -0
- package/dist/cli/main.js +33 -0
- package/dist/cli/read-request.js +36 -0
- package/dist/cli/with-app.js +73 -0
- package/dist/cli/with-error-handling.js +31 -0
- package/dist/cli/with-input.js +27 -0
- package/dist/config/describe-issues.js +6 -0
- package/dist/config/environment.js +53 -0
- package/dist/config/load-config.js +122 -0
- package/dist/config/presets.js +150 -0
- package/dist/config/write-config.js +39 -0
- package/dist/domain/agent-role.js +12 -0
- package/dist/domain/apply-outcome.js +132 -0
- package/dist/domain/completion-reuse.js +176 -0
- package/dist/domain/design-docs.js +3 -0
- package/dist/domain/design-review-report.js +86 -0
- package/dist/domain/design-review.js +193 -0
- package/dist/domain/errors.js +139 -0
- package/dist/domain/events.js +8 -0
- package/dist/domain/final-check.js +133 -0
- package/dist/domain/outcome.js +26 -0
- package/dist/domain/plan-coverage.js +129 -0
- package/dist/domain/protected-paths.js +35 -0
- package/dist/domain/retry.js +21 -0
- package/dist/domain/run-id.js +42 -0
- package/dist/domain/run-state.js +147 -0
- package/dist/domain/settings.js +49 -0
- package/dist/domain/slice.js +63 -0
- package/dist/domain/usage.js +1 -0
- package/dist/domain/work-facts.js +22 -0
- package/dist/flow/define-flow.js +11 -0
- package/dist/flow/engine.js +255 -0
- package/dist/flow/run-flow.js +129 -0
- package/dist/git/branch.js +26 -0
- package/dist/git/merge.js +92 -0
- package/dist/git/repository.js +48 -0
- package/dist/git/throwaway-branch.js +64 -0
- package/dist/observers/logging-observer.js +51 -0
- package/dist/observers/metrics.js +109 -0
- package/dist/observers/run-events.js +25 -0
- package/dist/observers/tracing-observer.js +86 -0
- package/dist/ports/agent-session.js +1 -0
- package/dist/ports/observability.js +1 -0
- package/dist/ports/run-store.js +1 -0
- package/dist/ports/sandbox-git.js +1 -0
- package/dist/ports/sandbox-images.js +1 -0
- package/dist/ports/workspace.js +1 -0
- package/dist/prompts/design-review.js +172 -0
- package/dist/prompts/final-check.js +58 -0
- package/dist/prompts/planning.js +111 -0
- package/dist/prompts/pull-request.js +78 -0
- package/dist/prompts/slice.js +254 -0
- package/dist/prompts/toolchain.js +37 -0
- package/dist/steps/completion-reuse.js +32 -0
- package/dist/steps/design-review.js +38 -0
- package/dist/steps/final-check.js +39 -0
- package/dist/steps/finishing.js +72 -0
- package/dist/steps/planning.js +77 -0
- package/dist/steps/pull-request-description.js +142 -0
- package/dist/steps/slice.js +149 -0
- package/package.json +95 -4
- package/presets/cheap-volume.json +7 -0
- package/presets/claude-only.json +7 -0
- package/presets/codex-only.json +7 -0
- package/presets/codex-reviewed-opencode.json +7 -0
- package/presets/full-power-codex.json +7 -0
- package/presets/full-power.json +7 -0
- package/presets/long-claude.json +7 -0
- package/presets/open-weight.json +7 -0
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { Result } from 'better-result';
|
|
2
|
+
import { readCredentialsFile } from '../adapters/local-store/credentials-file.js';
|
|
3
|
+
import { askForPreset } from '../adapters/terminal/ask-for-preset.js';
|
|
4
|
+
import { processStandardInput } from '../adapters/terminal/standard-input.js';
|
|
5
|
+
import { createAppContainer } from '../app/container.js';
|
|
6
|
+
import { parseEnvironment, withCredentials } from '../config/environment.js';
|
|
7
|
+
import { configFileFor, loadConfig } from '../config/load-config.js';
|
|
8
|
+
import { configWithPreset, discoverPresets, } from '../config/presets.js';
|
|
9
|
+
import { ConfigInvalid } from '../domain/errors.js';
|
|
10
|
+
import { ensureRepositoryRoot } from '../git/repository.js';
|
|
11
|
+
/** Runs a command against the repository in the working directory, then releases what it opened. */
|
|
12
|
+
export async function withApp(options, command, invocation = processInvocation()) {
|
|
13
|
+
const app = await openApp(options, invocation);
|
|
14
|
+
if (app.isErr())
|
|
15
|
+
return Result.err(app.error);
|
|
16
|
+
try {
|
|
17
|
+
return await command(app.value);
|
|
18
|
+
}
|
|
19
|
+
finally {
|
|
20
|
+
await app.value.dispose();
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export function processInvocation() {
|
|
24
|
+
return {
|
|
25
|
+
cwd: process.cwd(),
|
|
26
|
+
environment: process.env,
|
|
27
|
+
askForPreset,
|
|
28
|
+
createAppContainer,
|
|
29
|
+
standardInput: processStandardInput(),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
function openApp({ logFormat, config: configPath, preset }, { cwd, environment, askForPreset: ask, createAppContainer: createApp, builtinPresetsDirectory, }) {
|
|
33
|
+
return Result.gen(async function* () {
|
|
34
|
+
yield* Result.await(ensureRepositoryRoot(cwd));
|
|
35
|
+
const parsedEnvironment = yield* parseEnvironment(environment);
|
|
36
|
+
const savedCredentials = yield* readCredentialsFile(cwd);
|
|
37
|
+
const jigEnvironment = withCredentials(parsedEnvironment, savedCredentials);
|
|
38
|
+
const configFile = configFileFor(cwd, configPath);
|
|
39
|
+
const projectConfig = yield* loadConfig(configFile);
|
|
40
|
+
const presetLocations = {
|
|
41
|
+
repoRoot: cwd,
|
|
42
|
+
builtinDirectory: builtinPresetsDirectory,
|
|
43
|
+
...jigEnvironment,
|
|
44
|
+
};
|
|
45
|
+
const presetName = yield* Result.await(selectedPreset(preset, presetLocations, ask));
|
|
46
|
+
const config = yield* configWithPreset(projectConfig, presetLocations, presetName);
|
|
47
|
+
const app = createApp({
|
|
48
|
+
repoRoot: cwd,
|
|
49
|
+
logFormat,
|
|
50
|
+
environment: jigEnvironment,
|
|
51
|
+
configFile,
|
|
52
|
+
config,
|
|
53
|
+
});
|
|
54
|
+
if (presetName !== undefined) {
|
|
55
|
+
app.cradle.logger.info({ preset: presetName }, `Using preset ${presetName}`);
|
|
56
|
+
}
|
|
57
|
+
return Result.ok(app);
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
function selectedPreset(selection, locations, ask) {
|
|
61
|
+
return Result.gen(async function* () {
|
|
62
|
+
if (selection?.kind !== 'ask')
|
|
63
|
+
return Result.ok(selection?.name);
|
|
64
|
+
const presets = yield* discoverPresets(locations);
|
|
65
|
+
const pick = presets.length > 0 ? await ask(presets) : undefined;
|
|
66
|
+
if (pick === undefined) {
|
|
67
|
+
return Result.err(new ConfigInvalid({
|
|
68
|
+
message: 'No preset was picked — pass --preset <name>; jig presets lists them.',
|
|
69
|
+
}));
|
|
70
|
+
}
|
|
71
|
+
return Result.ok(pick.kind === 'preset' ? pick.name : undefined);
|
|
72
|
+
});
|
|
73
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { messageOf, rootCause } from '../domain/errors.js';
|
|
2
|
+
/**
|
|
3
|
+
* An expected failure comes back as an `Err` and is printed as its message alone. Anything
|
|
4
|
+
* thrown surfaces as it was first thrown, with its own stack, not the panics wrapped around it.
|
|
5
|
+
*/
|
|
6
|
+
export function withErrorHandling(fn, output = processFailureOutput) {
|
|
7
|
+
return async (...args) => {
|
|
8
|
+
try {
|
|
9
|
+
const result = await fn(...args);
|
|
10
|
+
if (result.isErr())
|
|
11
|
+
fail(output, result.error.message);
|
|
12
|
+
}
|
|
13
|
+
catch (error) {
|
|
14
|
+
fail(output, stackOf(rootCause(error)));
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
/** Sets `exitCode` rather than calling `process.exit()`, so pending output still flushes. */
|
|
19
|
+
const processFailureOutput = {
|
|
20
|
+
printError: (message) => console.error(message),
|
|
21
|
+
setExitCode: (code) => {
|
|
22
|
+
process.exitCode = code;
|
|
23
|
+
},
|
|
24
|
+
};
|
|
25
|
+
function fail(output, message) {
|
|
26
|
+
output.printError(message);
|
|
27
|
+
output.setExitCode(1);
|
|
28
|
+
}
|
|
29
|
+
function stackOf(error) {
|
|
30
|
+
return error instanceof Error && error.stack ? error.stack : messageOf(error);
|
|
31
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { panic, Result } from 'better-result';
|
|
2
|
+
import { Command } from 'commander';
|
|
3
|
+
import { describeIssues } from '../config/describe-issues.js';
|
|
4
|
+
import { CommandInputInvalid } from '../domain/errors.js';
|
|
5
|
+
/**
|
|
6
|
+
* A commander action that receives the command's arguments and options as one object, parsed
|
|
7
|
+
* by `schema`: named arguments by their declared names, options by their camel-cased ones.
|
|
8
|
+
*/
|
|
9
|
+
export function withInput(schema, run) {
|
|
10
|
+
return async (...actionArguments) => {
|
|
11
|
+
const command = actionArguments.at(-1);
|
|
12
|
+
if (!(command instanceof Command))
|
|
13
|
+
panic('withInput must wrap a commander action');
|
|
14
|
+
const parsed = schema.safeParse(inputOf(command));
|
|
15
|
+
if (!parsed.success) {
|
|
16
|
+
return Result.err(new CommandInputInvalid({ message: describeIssues(parsed.error, '\n') }));
|
|
17
|
+
}
|
|
18
|
+
return run(parsed.data);
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
function inputOf(command) {
|
|
22
|
+
const named = command.registeredArguments.map((argument, index) => [
|
|
23
|
+
argument.name(),
|
|
24
|
+
command.processedArgs[index],
|
|
25
|
+
]);
|
|
26
|
+
return { ...Object.fromEntries(named), ...command.opts() };
|
|
27
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** `path: message` for each issue, the one format every config failure uses. */
|
|
2
|
+
export function describeIssues(error, separator = '; ') {
|
|
3
|
+
return error.issues
|
|
4
|
+
.map((issue) => issue.path.length > 0 ? `${issue.path.join('.')}: ${issue.message}` : issue.message)
|
|
5
|
+
.join(separator);
|
|
6
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { Result } from 'better-result';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { ConfigInvalid } from '../domain/errors.js';
|
|
5
|
+
import { describeIssues } from './describe-issues.js';
|
|
6
|
+
/** An empty variable counts as unset, as it does for a shell's `${VAR:-default}`. */
|
|
7
|
+
export function parseEnvironment(raw) {
|
|
8
|
+
const variables = setVariables(raw);
|
|
9
|
+
const parsed = knownVariablesSchema.safeParse(variables);
|
|
10
|
+
if (!parsed.success) {
|
|
11
|
+
return Result.err(new ConfigInvalid({
|
|
12
|
+
message: `The environment is not valid — ${describeIssues(parsed.error)}`,
|
|
13
|
+
}));
|
|
14
|
+
}
|
|
15
|
+
const known = parsed.data;
|
|
16
|
+
return Result.ok({
|
|
17
|
+
imageCache: known.JIG_IMAGE_CACHE,
|
|
18
|
+
codexAuthDirectory: known.JIG_CODEX_AUTH_DIR,
|
|
19
|
+
homeDirectory: known.HOME ?? homedir(),
|
|
20
|
+
xdgConfigHome: known.XDG_CONFIG_HOME,
|
|
21
|
+
telemetry: known.OTEL_EXPORTER_OTLP_ENDPOINT || known.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT
|
|
22
|
+
? { serviceName: known.OTEL_SERVICE_NAME ?? 'jig', forwarded: otelVariables(variables) }
|
|
23
|
+
: undefined,
|
|
24
|
+
credential: (name) => variables[name],
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
function setVariables(raw) {
|
|
28
|
+
return Object.fromEntries(Object.entries(raw).filter((entry) => Boolean(entry[1])));
|
|
29
|
+
}
|
|
30
|
+
const knownVariablesSchema = z.object({
|
|
31
|
+
JIG_IMAGE_CACHE: z.enum(['gha']).optional(),
|
|
32
|
+
JIG_CODEX_AUTH_DIR: z.string().optional(),
|
|
33
|
+
HOME: z.string().optional(),
|
|
34
|
+
XDG_CONFIG_HOME: z.string().optional(),
|
|
35
|
+
OTEL_EXPORTER_OTLP_ENDPOINT: z.string().url().optional(),
|
|
36
|
+
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: z.string().url().optional(),
|
|
37
|
+
OTEL_SERVICE_NAME: z.string().optional(),
|
|
38
|
+
});
|
|
39
|
+
function otelVariables(variables) {
|
|
40
|
+
return Object.fromEntries(Object.entries(variables).filter(([name]) => name.startsWith('OTEL_')));
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Adds credentials from outside the process environment, which still wins. Only credentials: a
|
|
44
|
+
* file in the repository must not be able to set anything else jig reads.
|
|
45
|
+
*/
|
|
46
|
+
export function withCredentials(environment, credentials) {
|
|
47
|
+
const known = setVariables(credentials);
|
|
48
|
+
return {
|
|
49
|
+
...environment,
|
|
50
|
+
codexAuthDirectory: environment.codexAuthDirectory ?? known.JIG_CODEX_AUTH_DIR,
|
|
51
|
+
credential: (name) => environment.credential(name) ?? known[name],
|
|
52
|
+
};
|
|
53
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { Result } from 'better-result';
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
import { AGENTS, DEFAULT_CLAUDE_MODEL, isAgentName } from '../adapters/sandcastle/agents.js';
|
|
6
|
+
import { agentRoleSchema, byRole } from '../domain/agent-role.js';
|
|
7
|
+
import { ConfigInvalid, messageOf } from '../domain/errors.js';
|
|
8
|
+
import { MAX_STEP_RETRIES, RETRY_DELAY_MS } from '../domain/settings.js';
|
|
9
|
+
import { describeIssues } from './describe-issues.js';
|
|
10
|
+
/** A named preset resolves against the repository root, where every command starts. */
|
|
11
|
+
export function configFileFor(repoRoot, preset) {
|
|
12
|
+
return preset === undefined
|
|
13
|
+
? { path: path.join(repoRoot, CONFIG_FILE), name: CONFIG_FILE, named: false }
|
|
14
|
+
: { path: path.resolve(repoRoot, preset), name: preset, named: true };
|
|
15
|
+
}
|
|
16
|
+
export const CONFIG_FILE = 'jig.config.json';
|
|
17
|
+
export function loadConfig(file) {
|
|
18
|
+
return readConfigFile(file).andThen((contents) => parseConfig(file, contents));
|
|
19
|
+
}
|
|
20
|
+
function readConfigFile(file) {
|
|
21
|
+
if (!file.named && !existsSync(file.path))
|
|
22
|
+
return Result.ok('{}');
|
|
23
|
+
return Result.try({
|
|
24
|
+
try: () => readFileSync(file.path, 'utf-8'),
|
|
25
|
+
catch: (cause) => new ConfigInvalid({ message: `Cannot read ${file.name}: ${messageOf(cause)}` }),
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
function parseConfig(file, contents) {
|
|
29
|
+
return Result.try({
|
|
30
|
+
try: () => JSON.parse(contents),
|
|
31
|
+
catch: (cause) => new ConfigInvalid({
|
|
32
|
+
message: `${file.name} is not valid JSON: ${messageOf(cause)}`,
|
|
33
|
+
}),
|
|
34
|
+
}).andThen((json) => {
|
|
35
|
+
const parsed = configSchema.safeParse(json);
|
|
36
|
+
return parsed.success
|
|
37
|
+
? Result.ok(parsed.data)
|
|
38
|
+
: Result.err(new ConfigInvalid({
|
|
39
|
+
message: `${file.name} is not valid — ${describeIssues(parsed.error)}`,
|
|
40
|
+
}));
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
const agentNameSchema = z
|
|
44
|
+
.string()
|
|
45
|
+
.refine(isAgentName, { message: `the agent must be one of ${Object.keys(AGENTS).join(', ')}` });
|
|
46
|
+
export const stepConfigSchema = z.object({
|
|
47
|
+
provider: agentNameSchema,
|
|
48
|
+
/** Passed to the agent CLI; claude falls back to a default, opencode requires one ("provider/model"). */
|
|
49
|
+
model: z.string().optional(),
|
|
50
|
+
});
|
|
51
|
+
/** Strict, so a misspelled key fails at load instead of silently falling back to a default. */
|
|
52
|
+
const configSchema = z
|
|
53
|
+
.object({
|
|
54
|
+
mergeMode: z.enum(['manual', 'auto']).default('manual'),
|
|
55
|
+
reviewCycleCap: z.number().int().positive().default(3),
|
|
56
|
+
/** Runs once per run, before any agent starts, e.g. `npm ci`. */
|
|
57
|
+
setupCommand: z.string().optional(),
|
|
58
|
+
setupTimeoutSeconds: z.number().int().positive().default(900),
|
|
59
|
+
/** Must pass inside the sandbox before a reviewed slice counts as approved. */
|
|
60
|
+
verifyCommand: z.string().optional(),
|
|
61
|
+
/** `skip` disables signing in the run's worktree, for repos that sign through an agent the sandbox cannot reach. */
|
|
62
|
+
commitSigning: z.enum(['repo', 'skip']).default('skip'),
|
|
63
|
+
/** `checkpoint` stops after planning so a person can read the design and plan before any code is written. */
|
|
64
|
+
designGate: z.enum(['auto', 'checkpoint']).default('auto'),
|
|
65
|
+
/** An image managed elsewhere: jig starts it as it is and never builds it. */
|
|
66
|
+
sandboxImage: z.string().optional(),
|
|
67
|
+
/** Where run state is saved: `local`, `git-remote` (push to origin), or a path to a store module. */
|
|
68
|
+
runStores: z.array(z.string()).min(1).default(['local']),
|
|
69
|
+
/** Exact agent CLI versions to install; an agent without a pin follows `agentUpdates`. */
|
|
70
|
+
agents: z.record(agentNameSchema, z.string()).default({}),
|
|
71
|
+
/** `auto` rebuilds the agent layer when a newer release is out, `warn` only says so, `off` never checks. */
|
|
72
|
+
agentUpdates: z.enum(['auto', 'warn', 'off']).default('auto'),
|
|
73
|
+
/** Silence this long means the agent hung; it is stopped. */
|
|
74
|
+
agentIdleTimeoutSeconds: z.number().int().positive().default(600),
|
|
75
|
+
...byRole(() => stepConfigSchema.optional()),
|
|
76
|
+
})
|
|
77
|
+
.strict();
|
|
78
|
+
/** The agent of every step; a run cannot start, nor its image be built, until each has one. */
|
|
79
|
+
export function configuredSteps(config) {
|
|
80
|
+
const parsed = requiredStepsSchema.safeParse(config);
|
|
81
|
+
if (parsed.success)
|
|
82
|
+
return Result.ok(parsed.data);
|
|
83
|
+
return Result.err(new ConfigInvalid({
|
|
84
|
+
message: `No agent set for ${stepsWithoutAgent(config).join(', ')} — set each in the config to { "provider": "${Object.keys(AGENTS).join(' | ')}", "model": "..." }.`,
|
|
85
|
+
}));
|
|
86
|
+
}
|
|
87
|
+
const requiredStepsSchema = z.object(byRole(() => stepConfigSchema));
|
|
88
|
+
export function stepsWithoutAgent(config) {
|
|
89
|
+
return agentRoleSchema.options.filter((role) => !config[role]);
|
|
90
|
+
}
|
|
91
|
+
/** Risks a config can run with; jig names them on every start or resume and carries on. */
|
|
92
|
+
export function validationWarnings(config) {
|
|
93
|
+
return [reviewerSharesImplementerModel(config), approvalWithoutVerify(config)].filter((warning) => warning !== undefined);
|
|
94
|
+
}
|
|
95
|
+
function reviewerSharesImplementerModel({ implementer, reviewer }) {
|
|
96
|
+
if (!implementer || !reviewer || implementer.provider !== reviewer.provider)
|
|
97
|
+
return undefined;
|
|
98
|
+
const model = resolvedModel(implementer);
|
|
99
|
+
if (model === undefined || model !== resolvedModel(reviewer))
|
|
100
|
+
return undefined;
|
|
101
|
+
return `The implementer and reviewer are the same model (${implementer.provider}/${model}); a different reviewer catches more.`;
|
|
102
|
+
}
|
|
103
|
+
/** Only claude has a model of its own to fall back to; the others run without one only to fail. */
|
|
104
|
+
function resolvedModel(step) {
|
|
105
|
+
return step.model ?? (step.provider === 'claude' ? DEFAULT_CLAUDE_MODEL : undefined);
|
|
106
|
+
}
|
|
107
|
+
function approvalWithoutVerify({ verifyCommand }) {
|
|
108
|
+
if (verifyCommand !== undefined)
|
|
109
|
+
return undefined;
|
|
110
|
+
return "No verifyCommand is set: slices are approved on the reviewer's word alone. Run `jig init` to have one proposed, or set it in jig.config.json.";
|
|
111
|
+
}
|
|
112
|
+
/** The parts of the config that decide how a run moves, with the retry policy jig fixes. */
|
|
113
|
+
export function runSettingsFrom(config) {
|
|
114
|
+
return {
|
|
115
|
+
reviewCycleCap: config.reviewCycleCap,
|
|
116
|
+
maxStepRetries: MAX_STEP_RETRIES,
|
|
117
|
+
retryDelayMs: RETRY_DELAY_MS,
|
|
118
|
+
designGate: config.designGate,
|
|
119
|
+
mergeMode: config.mergeMode,
|
|
120
|
+
verifyCommand: config.verifyCommand,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { Result } from 'better-result';
|
|
2
|
+
import { lstatSync, readdirSync, readFileSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { JIG_DIR } from '../adapters/local-store/run-paths.js';
|
|
7
|
+
import { byRole } from '../domain/agent-role.js';
|
|
8
|
+
import { ConfigInvalid, messageOf } from '../domain/errors.js';
|
|
9
|
+
import { describeIssues } from './describe-issues.js';
|
|
10
|
+
import { stepConfigSchema } from './load-config.js';
|
|
11
|
+
export function discoverPresets(locations) {
|
|
12
|
+
return presetFiles(presetDirectories(locations)).andThen((files) => Result.all(files.map(readPreset)));
|
|
13
|
+
}
|
|
14
|
+
function presetFiles(directories) {
|
|
15
|
+
return Result.all(directories.map(presetFilesIn)).map((perDirectory) => shadowedRemoved(perDirectory.flat()));
|
|
16
|
+
}
|
|
17
|
+
function presetFilesIn(directory) {
|
|
18
|
+
return Result.gen(function* () {
|
|
19
|
+
if (!(yield* existsAt(directory.path)))
|
|
20
|
+
return Result.ok([]);
|
|
21
|
+
const entries = yield* Result.try({
|
|
22
|
+
try: () => readdirSync(directory.path),
|
|
23
|
+
catch: (cause) => new ConfigInvalid({
|
|
24
|
+
message: `Cannot list presets in ${directory.path}: ${messageOf(cause)}`,
|
|
25
|
+
}),
|
|
26
|
+
});
|
|
27
|
+
return Result.ok(presetNamesAmong(entries).map((name) => presetFileIn(directory, name)));
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* lstat, so a dangling link is a present entry that then fails to read, and only ENOENT counts as
|
|
32
|
+
* absent: an unreadable or misplaced winner never yields to a lower-precedence preset.
|
|
33
|
+
*/
|
|
34
|
+
function existsAt(entryPath) {
|
|
35
|
+
return Result.try({ try: () => lstatSync(entryPath), catch: (cause) => cause }).match({
|
|
36
|
+
ok: () => Result.ok(true),
|
|
37
|
+
err: (cause) => cause instanceof Error && 'code' in cause && cause.code === 'ENOENT'
|
|
38
|
+
? Result.ok(false)
|
|
39
|
+
: Result.err(new ConfigInvalid({ message: `Cannot look for ${entryPath}: ${messageOf(cause)}` })),
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
function presetNamesAmong(entries) {
|
|
43
|
+
return entries
|
|
44
|
+
.filter((entry) => entry.endsWith(PRESET_EXTENSION))
|
|
45
|
+
.map((entry) => presetNameSchema.safeParse(entry.slice(0, -PRESET_EXTENSION.length)))
|
|
46
|
+
.flatMap((parsed) => (parsed.success ? [parsed.data] : []))
|
|
47
|
+
.sort();
|
|
48
|
+
}
|
|
49
|
+
const PRESET_EXTENSION = '.json';
|
|
50
|
+
/** A preset name becomes a file name, so nothing that could leave the presets directory gets through. */
|
|
51
|
+
export const presetNameSchema = z
|
|
52
|
+
.string()
|
|
53
|
+
.max(64)
|
|
54
|
+
.regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, 'a preset name is lowercase letters and digits, joined by single hyphens')
|
|
55
|
+
.brand();
|
|
56
|
+
function presetFileIn(directory, name) {
|
|
57
|
+
return {
|
|
58
|
+
name,
|
|
59
|
+
source: directory.source,
|
|
60
|
+
path: path.join(directory.path, `${name}${PRESET_EXTENSION}`),
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
function shadowedRemoved(files) {
|
|
64
|
+
return files.filter((file, index) => files.findIndex(({ name }) => name === file.name) === index);
|
|
65
|
+
}
|
|
66
|
+
export function presetDirectories(locations) {
|
|
67
|
+
const paths = directoryPaths(locations);
|
|
68
|
+
const directories = PRESET_SOURCES.map((source) => ({
|
|
69
|
+
source,
|
|
70
|
+
path: path.resolve(paths[source]),
|
|
71
|
+
}));
|
|
72
|
+
return directories.filter((directory, index) => directories.findIndex(({ path }) => path === directory.path) === index);
|
|
73
|
+
}
|
|
74
|
+
function directoryPaths({ repoRoot, homeDirectory, xdgConfigHome, builtinDirectory = BUILTIN_PRESETS_DIRECTORY, }) {
|
|
75
|
+
const xdgRoot = xdgConfigHome && path.isAbsolute(xdgConfigHome)
|
|
76
|
+
? xdgConfigHome
|
|
77
|
+
: path.join(homeDirectory, '.config');
|
|
78
|
+
return {
|
|
79
|
+
repository: path.join(repoRoot, JIG_DIR, 'presets'),
|
|
80
|
+
home: path.join(homeDirectory, JIG_DIR, 'presets'),
|
|
81
|
+
xdg: path.join(xdgRoot, 'jig', 'presets'),
|
|
82
|
+
builtin: builtinDirectory,
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
/** The starters ship in the package's `presets/`, two levels up from both `src/config/` and `dist/config/`. */
|
|
86
|
+
const BUILTIN_PRESETS_DIRECTORY = fileURLToPath(new URL('../../presets', import.meta.url));
|
|
87
|
+
/** Where presets are looked for, highest precedence first: a name found earlier shadows the rest. */
|
|
88
|
+
export const PRESET_SOURCES = ['repository', 'home', 'xdg', 'builtin'];
|
|
89
|
+
function readPreset(file) {
|
|
90
|
+
return Result.gen(function* () {
|
|
91
|
+
const contents = yield* Result.try({
|
|
92
|
+
try: () => readFileSync(file.path, 'utf-8'),
|
|
93
|
+
catch: (cause) => new ConfigInvalid({ message: `Cannot read ${file.path}: ${messageOf(cause)}` }),
|
|
94
|
+
});
|
|
95
|
+
const json = yield* Result.try({
|
|
96
|
+
try: () => JSON.parse(contents),
|
|
97
|
+
catch: (cause) => new ConfigInvalid({ message: `${file.path} is not valid JSON: ${messageOf(cause)}` }),
|
|
98
|
+
});
|
|
99
|
+
return parsePresetFile(file, json);
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
function parsePresetFile(file, json) {
|
|
103
|
+
const parsed = presetFileSchema.safeParse(json);
|
|
104
|
+
if (!parsed.success) {
|
|
105
|
+
return Result.err(new ConfigInvalid({
|
|
106
|
+
message: `${file.path} is not valid — ${describeIssues(parsed.error)}`,
|
|
107
|
+
}));
|
|
108
|
+
}
|
|
109
|
+
const { description, ...steps } = parsed.data;
|
|
110
|
+
return Result.ok({ ...file, description, steps });
|
|
111
|
+
}
|
|
112
|
+
/** Strict, so a misspelled step fails at load instead of silently leaving the project's agent. */
|
|
113
|
+
const presetFileSchema = z
|
|
114
|
+
.object({
|
|
115
|
+
description: z.string().optional(),
|
|
116
|
+
...byRole(() => stepConfigSchema.strict().optional()),
|
|
117
|
+
})
|
|
118
|
+
.strict();
|
|
119
|
+
export function configWithPreset(config, locations, name) {
|
|
120
|
+
if (name === undefined)
|
|
121
|
+
return Result.ok(config);
|
|
122
|
+
return loadPreset(locations, name).map((preset) => applyPreset(config, preset));
|
|
123
|
+
}
|
|
124
|
+
/** Reads only the files that could hold `name`, so a broken unrelated preset does not get in the way. */
|
|
125
|
+
export function loadPreset(locations, name) {
|
|
126
|
+
const directories = presetDirectories(locations);
|
|
127
|
+
return Result.gen(function* () {
|
|
128
|
+
for (const directory of directories) {
|
|
129
|
+
const candidate = presetFileIn(directory, name);
|
|
130
|
+
if (yield* existsAt(candidate.path))
|
|
131
|
+
return readPreset(candidate);
|
|
132
|
+
}
|
|
133
|
+
return missingPreset(name, directories);
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
function missingPreset(name, directories) {
|
|
137
|
+
return presetFiles(directories).andThen((available) => {
|
|
138
|
+
const searched = directories.map((directory) => directory.path).join(', ');
|
|
139
|
+
const offered = available.length > 0
|
|
140
|
+
? `available: ${available.map((file) => file.name).join(', ')}`
|
|
141
|
+
: 'there are none';
|
|
142
|
+
return Result.err(new ConfigInvalid({
|
|
143
|
+
message: `No preset named ${name} — looked in ${searched}; ${offered}.`,
|
|
144
|
+
}));
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
/** The preset's steps replace the project's whole, so no model carries over to another provider. */
|
|
148
|
+
function applyPreset(config, preset) {
|
|
149
|
+
return { ...config, ...preset.steps };
|
|
150
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { Result } from 'better-result';
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { readFile } from 'node:fs/promises';
|
|
4
|
+
import writeFileAtomic from 'write-file-atomic';
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { ConfigInvalid, messageOf } from '../domain/errors.js';
|
|
7
|
+
/** Sets the given keys in the config file, keeping every other key as the operator wrote it. */
|
|
8
|
+
export async function updateConfigFile({ path: file, name }, values) {
|
|
9
|
+
const current = existsSync(file)
|
|
10
|
+
? (await onConfigFile(file, () => readFile(file, 'utf-8'))).andThen((contents) => parseConfigObject(name, contents))
|
|
11
|
+
: Result.ok({});
|
|
12
|
+
if (current.isErr())
|
|
13
|
+
return Result.err(current.error);
|
|
14
|
+
const contents = `${JSON.stringify({ ...current.value, ...values }, null, 2)}\n`;
|
|
15
|
+
return onConfigFile(file, () => writeFileAtomic(file, contents));
|
|
16
|
+
}
|
|
17
|
+
function onConfigFile(file, operation) {
|
|
18
|
+
return Result.tryPromise({
|
|
19
|
+
try: operation,
|
|
20
|
+
catch: (cause) => new ConfigInvalid({ message: `Cannot read or write ${file}: ${messageOf(cause)}` }),
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
/** Only an object can take more keys; anything else is left for the operator to fix, not overwritten. */
|
|
24
|
+
function parseConfigObject(name, contents) {
|
|
25
|
+
const parsed = z.record(z.unknown()).safeParse(parseJson(contents));
|
|
26
|
+
return parsed.success
|
|
27
|
+
? Result.ok(parsed.data)
|
|
28
|
+
: Result.err(new ConfigInvalid({
|
|
29
|
+
message: `${name} must hold a JSON object to add settings to.`,
|
|
30
|
+
}));
|
|
31
|
+
}
|
|
32
|
+
function parseJson(contents) {
|
|
33
|
+
try {
|
|
34
|
+
return JSON.parse(contents);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
/** The jobs an agent does in a run; each can be served by a different agent and model. */
|
|
3
|
+
export const agentRoleSchema = z.enum(['planner', 'implementer', 'reviewer', 'describer']);
|
|
4
|
+
/** One value for every role; a role added to `agentRoleSchema` fails to compile here until it has one. */
|
|
5
|
+
export function byRole(valueFor) {
|
|
6
|
+
return {
|
|
7
|
+
planner: valueFor('planner'),
|
|
8
|
+
implementer: valueFor('implementer'),
|
|
9
|
+
reviewer: valueFor('reviewer'),
|
|
10
|
+
describer: valueFor('describer'),
|
|
11
|
+
};
|
|
12
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { panic } from 'better-result';
|
|
2
|
+
import { recordDesignReview, recordDesignRevision } from './design-review.js';
|
|
3
|
+
import { recordFinalCheck } from './final-check.js';
|
|
4
|
+
import { currentSlice, enterPhase } from './run-state.js';
|
|
5
|
+
import { sliceFromPlan } from './slice.js';
|
|
6
|
+
/**
|
|
7
|
+
* Folds a step's outcome into run state. Only data changes here — which phase or slice
|
|
8
|
+
* status comes next is the flow's decision, not this reducer's.
|
|
9
|
+
*/
|
|
10
|
+
export function applyOutcome(state, outcome) {
|
|
11
|
+
if (isSendBack(outcome))
|
|
12
|
+
return sendSliceBack(state, outcome);
|
|
13
|
+
if (isDesignOutcome(outcome))
|
|
14
|
+
return applyDesignOutcome(state, outcome);
|
|
15
|
+
if (outcome.type === 'completionReused')
|
|
16
|
+
return { ...state, completionReuseAuthorized: true };
|
|
17
|
+
if (outcome.type === 'completionInvalidated')
|
|
18
|
+
return revokeCompletionReuse(state);
|
|
19
|
+
return foldStepData(state, outcome);
|
|
20
|
+
}
|
|
21
|
+
function isSendBack(outcome) {
|
|
22
|
+
return outcome.type in ATTEMPT_COUNTER_OF;
|
|
23
|
+
}
|
|
24
|
+
/** Each way a slice goes back to its implementer counts against its own cap. */
|
|
25
|
+
const ATTEMPT_COUNTER_OF = {
|
|
26
|
+
changesRequested: 'reviewCycles',
|
|
27
|
+
hookRejected: 'hookFailures',
|
|
28
|
+
verificationFailed: 'verificationFailures',
|
|
29
|
+
nothingChanged: 'emptyAttempts',
|
|
30
|
+
rulesFixRequested: 'ruleFixCycles',
|
|
31
|
+
};
|
|
32
|
+
function sendSliceBack(state, outcome) {
|
|
33
|
+
const counter = ATTEMPT_COUNTER_OF[outcome.type];
|
|
34
|
+
return withCompletionEvidence(updateCurrentSlice(state, (slice) => ({
|
|
35
|
+
...slice,
|
|
36
|
+
[counter]: slice[counter] + 1,
|
|
37
|
+
lastFeedback: outcome.feedback,
|
|
38
|
+
feedbackHistory: [...slice.feedbackHistory, outcome.feedback],
|
|
39
|
+
verification: undefined,
|
|
40
|
+
failedVerification: failedVerificationOf(outcome, slice),
|
|
41
|
+
})), outcome.completion);
|
|
42
|
+
}
|
|
43
|
+
/** The whole-request evidence a review leaves, kept as the run's record of its latest one. */
|
|
44
|
+
function withCompletionEvidence(state, completion) {
|
|
45
|
+
if (completion === undefined && state.completionReuse === undefined)
|
|
46
|
+
return state;
|
|
47
|
+
return { ...state, completionReuse: completion };
|
|
48
|
+
}
|
|
49
|
+
export function updateCurrentSlice(state, update) {
|
|
50
|
+
const target = currentSlice(state);
|
|
51
|
+
if (!target)
|
|
52
|
+
panic('No current slice to update');
|
|
53
|
+
return {
|
|
54
|
+
...state,
|
|
55
|
+
slices: state.slices.map((slice) => (slice.id === target.id ? update(slice) : slice)),
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* The facts of the verification that just failed, beside the counter it spent; a failure that
|
|
60
|
+
* recorded none leaves whatever earlier failure the slice already holds.
|
|
61
|
+
*/
|
|
62
|
+
function failedVerificationOf(outcome, slice) {
|
|
63
|
+
if (outcome.type !== 'verificationFailed')
|
|
64
|
+
return slice.failedVerification;
|
|
65
|
+
const { command, observed } = outcome;
|
|
66
|
+
return command !== undefined && observed !== undefined
|
|
67
|
+
? { command, observed }
|
|
68
|
+
: slice.failedVerification;
|
|
69
|
+
}
|
|
70
|
+
function isDesignOutcome(outcome) {
|
|
71
|
+
return DESIGN_OUTCOME_TYPES.some((type) => type === outcome.type);
|
|
72
|
+
}
|
|
73
|
+
/** The outcomes that write, review and revise the design documents before slicing. */
|
|
74
|
+
const DESIGN_OUTCOME_TYPES = [
|
|
75
|
+
'designWritten',
|
|
76
|
+
'designReviewed',
|
|
77
|
+
'designRevised',
|
|
78
|
+
];
|
|
79
|
+
function applyDesignOutcome(state, outcome) {
|
|
80
|
+
switch (outcome.type) {
|
|
81
|
+
case 'designWritten':
|
|
82
|
+
return { ...state, docs: outcome.docs };
|
|
83
|
+
case 'designReviewed':
|
|
84
|
+
return recordDesignReview(state, outcome.review);
|
|
85
|
+
case 'designRevised':
|
|
86
|
+
return recordDesignRevision(state, outcome.revision);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Withdraws the run's authority to finish on its evidence, with the description written from it,
|
|
91
|
+
* and puts the run back in its final check, which still owes its one repair. The run leaves
|
|
92
|
+
* finishing here because a phase past describing cannot hold a run without its description.
|
|
93
|
+
*/
|
|
94
|
+
function revokeCompletionReuse(state) {
|
|
95
|
+
const { completionReuseAuthorized: _authorized, prDescription: _described, ...revoked } = state;
|
|
96
|
+
return enterPhase(revoked, 'finalCheck');
|
|
97
|
+
}
|
|
98
|
+
function foldStepData(state, outcome) {
|
|
99
|
+
switch (outcome.type) {
|
|
100
|
+
case 'contextBuilt':
|
|
101
|
+
return { ...state, context: outcome.context };
|
|
102
|
+
case 'featurePlanned':
|
|
103
|
+
return { ...state, plan: outcome.plan };
|
|
104
|
+
case 'sliced':
|
|
105
|
+
return { ...state, slices: outcome.slices.map(sliceFromPlan) };
|
|
106
|
+
case 'implemented':
|
|
107
|
+
return updateCurrentSlice(state, (slice) => ({
|
|
108
|
+
...slice,
|
|
109
|
+
commit: outcome.commit.sha,
|
|
110
|
+
}));
|
|
111
|
+
case 'verified':
|
|
112
|
+
return updateCurrentSlice(state, (slice) => verifiedSlice(slice, outcome));
|
|
113
|
+
case 'approved':
|
|
114
|
+
return withCompletionEvidence(state, outcome.completion);
|
|
115
|
+
case 'finalChecked':
|
|
116
|
+
return recordFinalCheck(state, outcome);
|
|
117
|
+
case 'described':
|
|
118
|
+
return { ...state, prDescription: outcome.body };
|
|
119
|
+
default:
|
|
120
|
+
return state;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
/** What a passed verification leaves on the slice: its command, the work it ran on, and no feedback left to address. */
|
|
124
|
+
function verifiedSlice(slice, outcome) {
|
|
125
|
+
return {
|
|
126
|
+
...slice,
|
|
127
|
+
lastFeedback: undefined,
|
|
128
|
+
verification: outcome.command
|
|
129
|
+
? { command: outcome.command, observed: outcome.observed }
|
|
130
|
+
: undefined,
|
|
131
|
+
};
|
|
132
|
+
}
|