wachiman 1.10.0 → 1.13.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/README.md +139 -79
- package/package.json +1 -1
- package/skills/wachiman-loop/SKILL.md +91 -0
- package/skills/wachiman-review/SKILL.md +23 -1
- package/src/accounts/commands.ts +6 -2
- package/src/ask.ts +240 -0
- package/src/call-message.ts +26 -3
- package/src/cli.ts +157 -13
- package/src/config.ts +40 -5
- package/src/connectors/local-git.ts +119 -21
- package/src/connectors/working-tree.ts +333 -0
- package/src/cost.ts +20 -0
- package/src/doctor/checks.ts +1 -1
- package/src/engine.ts +988 -104
- package/src/estimate.ts +64 -0
- package/src/fidelity/block.ts +263 -0
- package/src/fidelity/claims-call.ts +172 -0
- package/src/fidelity/claims.ts +69 -0
- package/src/fidelity/digest.ts +80 -0
- package/src/fidelity/grade.ts +242 -0
- package/src/fidelity/inert.ts +25 -0
- package/src/fidelity/rules.ts +166 -0
- package/src/fidelity/sink.ts +135 -0
- package/src/fidelity/summary.ts +16 -0
- package/src/fidelity/types.ts +93 -0
- package/src/formats.ts +36 -9
- package/src/history/fingerprint.ts +1 -1
- package/src/history/index.ts +3 -0
- package/src/history/store.ts +39 -1
- package/src/init/options.ts +1 -1
- package/src/init/prompt.ts +4 -1
- package/src/init/run.ts +38 -27
- package/src/local-ask.ts +231 -0
- package/src/local.ts +274 -74
- package/src/loop/command.ts +441 -0
- package/src/loop/state.ts +88 -0
- package/src/loop/stop-rule.ts +98 -0
- package/src/providers/claude-code.ts +47 -12
- package/src/providers/codex.ts +20 -1
- package/src/providers/index.ts +5 -2
- package/src/providers/types.ts +10 -0
- package/src/risk.ts +264 -0
- package/src/setup/prompt.ts +28 -15
- package/src/setup/run.ts +14 -2
- package/src/sinks/common.ts +5 -1
- package/src/sinks/json.ts +13 -2
- package/src/sinks/markdown.ts +2 -0
- package/src/sinks/terminal.ts +2 -0
- package/src/skills/install.ts +4 -4
- package/src/status/command.ts +202 -0
- package/src/store/command.ts +109 -0
- package/src/store/figures.ts +153 -0
- package/src/store/html.ts +138 -0
- package/src/store/index.ts +298 -0
- package/src/wizard/command.ts +23 -0
- package/src/wizard/prompt.ts +22 -9
- package/src/wizard/style.ts +19 -0
- package/templates/caller-workflow.yml +90 -25
- package/templates/wachiman-review-caller.yml +12 -1
package/src/formats.ts
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
import { UsageError } from "./config";
|
|
9
9
|
import type { Contract } from "./contracts";
|
|
10
10
|
import type { TokenUsage } from "./cost";
|
|
11
|
+
import type { Fidelity } from "./fidelity/types";
|
|
11
12
|
import type {
|
|
12
13
|
BaseInstructions,
|
|
13
14
|
BatchReport,
|
|
@@ -20,8 +21,10 @@ import type {
|
|
|
20
21
|
Unreviewable,
|
|
21
22
|
} from "./engine";
|
|
22
23
|
import type { ProviderErrorClass } from "./providers/errors";
|
|
24
|
+
import type { RiskMap } from "./risk";
|
|
23
25
|
|
|
24
26
|
export const REVIEW_INPUT_FORMAT = "wachiman.review-input/1";
|
|
27
|
+
export const REVIEW_INPUT_V2 = "wachiman.review-input/2";
|
|
25
28
|
/** The result as committed-change JSON consumers know it: closed root, no verification block. */
|
|
26
29
|
export const REVIEW_RESULT_V1 = "wachiman.review-result/1";
|
|
27
30
|
/** The result the core produces: `/1` plus origin, per-finding verification and the verification record. */
|
|
@@ -29,7 +32,7 @@ export const REVIEW_RESULT_V2 = "wachiman.review-result/2";
|
|
|
29
32
|
|
|
30
33
|
export type { ReviewFile };
|
|
31
34
|
|
|
32
|
-
export interface
|
|
35
|
+
export interface CommittedReviewChange {
|
|
33
36
|
kind: "pull-request" | "branch";
|
|
34
37
|
/** One sentence for the prompt's first line and every report's headline. */
|
|
35
38
|
describe: string;
|
|
@@ -44,8 +47,15 @@ export interface ReviewChange {
|
|
|
44
47
|
identifier?: string;
|
|
45
48
|
}
|
|
46
49
|
|
|
50
|
+
export type ReviewChange =
|
|
51
|
+
| CommittedReviewChange
|
|
52
|
+
| (Omit<CommittedReviewChange, "kind"> & {
|
|
53
|
+
kind: "working-tree";
|
|
54
|
+
workingTree: { mode: "staged" | "all"; baseCommit: string; tree: string };
|
|
55
|
+
});
|
|
56
|
+
|
|
47
57
|
export interface ReviewInput {
|
|
48
|
-
format: typeof REVIEW_INPUT_FORMAT;
|
|
58
|
+
format: typeof REVIEW_INPUT_FORMAT | typeof REVIEW_INPUT_V2;
|
|
49
59
|
change: ReviewChange;
|
|
50
60
|
files: ReviewFile[];
|
|
51
61
|
/** Read from `change.base.sha` by the connector (ADR 0006). */
|
|
@@ -56,9 +66,11 @@ export interface ReviewInput {
|
|
|
56
66
|
scope: string[];
|
|
57
67
|
/**
|
|
58
68
|
* Incremental context: the last reviewed commit, whether the change was rebased since, and
|
|
59
|
-
* (optional) the commits since it, oldest first, for the report's headline.
|
|
69
|
+
* (optional) the commits since it, oldest first, for the report's headline. `carried` names
|
|
70
|
+
* the files of `files` that the previous review did not reach: they carry their whole diff, not
|
|
71
|
+
* only what changed since, and are reviewed whole.
|
|
60
72
|
*/
|
|
61
|
-
since?: { sha: string; rebased: boolean; commits?: string[] };
|
|
73
|
+
since?: { sha: string; rebased: boolean; commits?: string[]; carried?: string[] };
|
|
62
74
|
/** Open threads for the model to answer. */
|
|
63
75
|
conversation?: Thread[];
|
|
64
76
|
}
|
|
@@ -111,7 +123,7 @@ type Execution = {
|
|
|
111
123
|
/** `wachiman.review-result/1`: the closed shape committed-change JSON keeps by default. */
|
|
112
124
|
export interface ReviewResultV1 {
|
|
113
125
|
format: typeof REVIEW_RESULT_V1;
|
|
114
|
-
change:
|
|
126
|
+
change: CommittedReviewChange & { snapshot?: string };
|
|
115
127
|
engine: { version: string };
|
|
116
128
|
provider: { label: string; model: string; effort: string; profile: Profile };
|
|
117
129
|
coverage: Coverage;
|
|
@@ -172,6 +184,11 @@ export interface VerifiedFields {
|
|
|
172
184
|
export interface ResultFindingV2 extends Finding, VerifiedFields {
|
|
173
185
|
/** Whether the line is one a diff-anchored comment can target (`commentableLines`). */
|
|
174
186
|
anchor: "diff" | "outside";
|
|
187
|
+
/**
|
|
188
|
+
* The finding's history id, the one `wachiman history --verdict` takes (ADR 0034). Only a
|
|
189
|
+
* `local` JSON `/2` written with history on carries it; the core never sets it.
|
|
190
|
+
*/
|
|
191
|
+
id?: string;
|
|
175
192
|
}
|
|
176
193
|
|
|
177
194
|
export interface VerificationEntryV2 {
|
|
@@ -236,6 +253,13 @@ export interface ReviewResultV2 {
|
|
|
236
253
|
findings: ResultFindingV2[];
|
|
237
254
|
contracts: Contract[];
|
|
238
255
|
summary: string;
|
|
256
|
+
/** The risk map (ADR 0031). Only `/2` has it: `toResultV1` leaves it out. */
|
|
257
|
+
riskMap?: RiskMap;
|
|
258
|
+
/**
|
|
259
|
+
* PR Confidence (ADR 0033): the claims, the unexplained files and the grade. Only the `/2` result
|
|
260
|
+
* of a GitHub pull request review has it; a local review never does, and `toResultV1` leaves it out.
|
|
261
|
+
*/
|
|
262
|
+
fidelity?: Fidelity;
|
|
239
263
|
batches: BatchReport[];
|
|
240
264
|
threadReplies: ReviewOutput["thread_replies"];
|
|
241
265
|
instructionChanges: { files: string[]; baseSha: string };
|
|
@@ -250,10 +274,12 @@ export type ReviewResult = ReviewResultV2;
|
|
|
250
274
|
export type ResultFinding = ResultFindingV2;
|
|
251
275
|
|
|
252
276
|
/** The core refuses a version it does not know (D15). A usage error, not an engine error. */
|
|
253
|
-
export function assertReviewInputFormat(input: { format?: unknown }): asserts input is {
|
|
254
|
-
|
|
277
|
+
export function assertReviewInputFormat(input: { format?: unknown }): asserts input is {
|
|
278
|
+
format: typeof REVIEW_INPUT_FORMAT | typeof REVIEW_INPUT_V2;
|
|
279
|
+
} {
|
|
280
|
+
if (input.format !== REVIEW_INPUT_FORMAT && input.format !== REVIEW_INPUT_V2) {
|
|
255
281
|
throw new UsageError(
|
|
256
|
-
`Unknown review input format ${JSON.stringify(input.format)}; this engine reads ${REVIEW_INPUT_FORMAT}.`,
|
|
282
|
+
`Unknown review input format ${JSON.stringify(input.format)}; this engine reads ${REVIEW_INPUT_FORMAT} and ${REVIEW_INPUT_V2}.`,
|
|
257
283
|
);
|
|
258
284
|
}
|
|
259
285
|
}
|
|
@@ -296,10 +322,11 @@ export function toResultV1(result: ReviewResultV2): ReviewResultV1 {
|
|
|
296
322
|
throw new UsageError("A working-tree review has no result /1: its head is a tree id, not a commit. Use --result-version 2.");
|
|
297
323
|
}
|
|
298
324
|
const { account: _account, ...provider } = result.provider;
|
|
299
|
-
const { verification, ...rest } = result;
|
|
325
|
+
const { verification, riskMap: _riskMap, fidelity: _fidelity, ...rest } = result;
|
|
300
326
|
return {
|
|
301
327
|
...rest,
|
|
302
328
|
format: REVIEW_RESULT_V1,
|
|
329
|
+
change: result.change as CommittedReviewChange & { snapshot?: string },
|
|
303
330
|
provider,
|
|
304
331
|
findings: result.findings.map((f) => ({
|
|
305
332
|
path: f.path,
|
|
@@ -11,7 +11,7 @@ const sha256 = (text: string) => createHash("sha256").update(text).digest("hex")
|
|
|
11
11
|
export const stripWhitespace = (s: string) => s.replace(/\s+/g, "");
|
|
12
12
|
|
|
13
13
|
/** A cited line shorter than this, once stripped, is too common to identify anything. */
|
|
14
|
-
const MIN_LINE_CHARS = 8;
|
|
14
|
+
export const MIN_LINE_CHARS = 8;
|
|
15
15
|
|
|
16
16
|
/** The title lowercased, backticks and punctuation removed, every digit run a `#`, whitespace collapsed. */
|
|
17
17
|
export function titleKey(title: string): string {
|
package/src/history/index.ts
CHANGED
|
@@ -37,8 +37,11 @@ export function saveRun(p: SaveRunParams): HistoryAnnotation {
|
|
|
37
37
|
|
|
38
38
|
const head = p.result.change.head.sha;
|
|
39
39
|
const ancestors = new Map<string, boolean>();
|
|
40
|
+
const treeHeads = new Set(runs.filter(r => r.result.change.kind === "working-tree").map(r => r.result.change.head.sha));
|
|
40
41
|
// Exit 0 = ancestor (or the same commit); 1 = not; anything else (an unknown commit) cannot be proven.
|
|
41
42
|
const isAncestor = (lastHead: string) => {
|
|
43
|
+
// Fingerprints still match; missing findings on ephemeral trees stay unknown.
|
|
44
|
+
if (p.result.change.kind === "working-tree" || treeHeads.has(lastHead)) return false;
|
|
42
45
|
let known = ancestors.get(lastHead);
|
|
43
46
|
if (known === undefined) {
|
|
44
47
|
known = git(["merge-base", "--is-ancestor", lastHead, head], { cwd: p.repoDir, timeoutMs: 30_000 }).status === 0;
|
package/src/history/store.ts
CHANGED
|
@@ -208,7 +208,7 @@ function parseRun(path: string): HistoryRun {
|
|
|
208
208
|
return parsed as HistoryRun;
|
|
209
209
|
}
|
|
210
210
|
|
|
211
|
-
const runFiles = (root: string, key: string) => {
|
|
211
|
+
export const runFiles = (root: string, key: string) => {
|
|
212
212
|
const dir = runsDir(root, key);
|
|
213
213
|
if (!existsSync(dir)) return [];
|
|
214
214
|
return readdirSync(dir)
|
|
@@ -316,6 +316,44 @@ export function readVerdicts(root: string, key: string): Map<string, VerdictLine
|
|
|
316
316
|
return out;
|
|
317
317
|
}
|
|
318
318
|
|
|
319
|
+
/**
|
|
320
|
+
* One file per branch under `<root>/<repo-key>/loops/` for `wachiman loop` (ADR 0034): the loop's
|
|
321
|
+
* state lives beside the runs it reads, so `history --forget` removes both. The branch name is only
|
|
322
|
+
* a label in the file name; the hash keeps two names that sanitise alike apart.
|
|
323
|
+
*/
|
|
324
|
+
const loopPath = (root: string, key: string, branch: string) =>
|
|
325
|
+
join(keyDir(root, key), "loops", `${safeName(branch)}-${sha256(branch).slice(0, 8)}.json`);
|
|
326
|
+
|
|
327
|
+
/** Every loop state file of a repository, in name order: what the local index replays. */
|
|
328
|
+
export function loopFiles(root: string, key: string): string[] {
|
|
329
|
+
const dir = join(keyDir(root, key), "loops");
|
|
330
|
+
if (!existsSync(dir)) return [];
|
|
331
|
+
return readdirSync(dir)
|
|
332
|
+
.filter((n) => n.endsWith(".json"))
|
|
333
|
+
.sort()
|
|
334
|
+
.map((n) => join(dir, n));
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** The stored loop state of a branch as parsed JSON, or undefined when there is none. A file that is not JSON is an error naming it. */
|
|
338
|
+
export function readLoopFile(root: string, key: string, branch: string): unknown | undefined {
|
|
339
|
+
const path = loopPath(root, key, branch);
|
|
340
|
+
if (!existsSync(path)) return undefined;
|
|
341
|
+
try {
|
|
342
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
343
|
+
} catch (error) {
|
|
344
|
+
throw new UsageError(`${path} is not a loop state file (${error instanceof Error ? error.message : error}); remove it to start the loop again.`);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
export function writeLoopFile(root: string, key: string, branch: string, state: unknown): string {
|
|
349
|
+
ensureKeyDirs(root, key);
|
|
350
|
+
privateDirs(join(keyDir(root, key), "loops"));
|
|
351
|
+
chmodSync(join(keyDir(root, key), "loops"), 0o700);
|
|
352
|
+
const path = loopPath(root, key, branch);
|
|
353
|
+
writeAtomic(path, `${JSON.stringify(state, null, 2)}\n`);
|
|
354
|
+
return path;
|
|
355
|
+
}
|
|
356
|
+
|
|
319
357
|
/** Removes one repository's history, or all of it; returns what was removed. Never leaves `root`. */
|
|
320
358
|
export function forget(root: string, key?: string): string[] {
|
|
321
359
|
const target = key === undefined ? root : keyDir(root, key);
|
package/src/init/options.ts
CHANGED
|
@@ -34,7 +34,7 @@ export type ResolveResult<T> = { ok: true; options: T } | { ok: false; error: st
|
|
|
34
34
|
* docs/releasing.md); the CLI's own version is never a substitute,
|
|
35
35
|
* because an unreleased or unrelated version would pin a workflow that does not exist.
|
|
36
36
|
*/
|
|
37
|
-
export const DEFAULT_WORKFLOW_REF: string | undefined = "v1.
|
|
37
|
+
export const DEFAULT_WORKFLOW_REF: string | undefined = "v1.13.0"; // x-release-please-version
|
|
38
38
|
|
|
39
39
|
export const DEFAULT_WORKFLOW_PATH = ".github/workflows/wachiman-review.yml";
|
|
40
40
|
const WORKFLOWS_DIR = ".github/workflows/";
|
package/src/init/prompt.ts
CHANGED
|
@@ -3,7 +3,7 @@ import type { Prompter } from "../wizard/prompt";
|
|
|
3
3
|
import { DEFAULT_WORKFLOW_PATH, initModes, normaliseWorkflowPath, operatorProblem, tagProblem, type InitMode, type RawInitFlags } from "./options";
|
|
4
4
|
|
|
5
5
|
/** The values given on the command line are held to the same rules as answers: a bad one is exit 2, never silently asked again. */
|
|
6
|
-
function checkSupplied(flags: RawInitFlags) {
|
|
6
|
+
export function checkSupplied(flags: RawInitFlags) {
|
|
7
7
|
if (flags.mode !== undefined && !initModes.includes(flags.mode as InitMode)) throw new UsageError(`--mode must be github, local or both, got "${flags.mode}".`);
|
|
8
8
|
const problem =
|
|
9
9
|
(flags.operator !== undefined ? operatorProblem(flags.operator) : undefined) ??
|
|
@@ -19,6 +19,7 @@ function checkSupplied(flags: RawInitFlags) {
|
|
|
19
19
|
*/
|
|
20
20
|
export async function promptForInit(flags: RawInitFlags, ctx: { defaultWorkflowRef?: string }, prompter: Prompter): Promise<RawInitFlags | null> {
|
|
21
21
|
checkSupplied(flags);
|
|
22
|
+
prompter.step("Review mode", 2);
|
|
22
23
|
let mode = flags.mode as InitMode | undefined;
|
|
23
24
|
if (mode === undefined) {
|
|
24
25
|
const picked = await prompter.select<InitMode>(
|
|
@@ -35,6 +36,8 @@ export async function promptForInit(flags: RawInitFlags, ctx: { defaultWorkflowR
|
|
|
35
36
|
}
|
|
36
37
|
if (mode === "local") return { ...flags, mode };
|
|
37
38
|
|
|
39
|
+
prompter.step("GitHub workflow", 3, mode === "both" ? 6 : 4);
|
|
40
|
+
|
|
38
41
|
const operator =
|
|
39
42
|
flags.operator ?? (await prompter.text("GitHub login of the operator (the one person whose /wachiman comments start a run)", undefined, (v) => operatorProblem(v)));
|
|
40
43
|
if (operator === null) return null;
|
package/src/init/run.ts
CHANGED
|
@@ -12,8 +12,10 @@ import { spawnGit, type GitRunner } from "../evidence";
|
|
|
12
12
|
import { repositoryKey } from "../history/store";
|
|
13
13
|
import { isInteractive, type TerminalStreams } from "../wizard/interactive";
|
|
14
14
|
import { createPrompter, type Prompter, type PromptIO } from "../wizard/prompt";
|
|
15
|
+
import { wizardIo } from "../wizard/style";
|
|
16
|
+
import { projectCommands } from "../wizard/command";
|
|
15
17
|
import { DEFAULT_WORKFLOW_REF, resolveInitOptions, type InitOptions, type RawInitFlags } from "./options";
|
|
16
|
-
import { promptForInit } from "./prompt";
|
|
18
|
+
import { checkSupplied, promptForInit } from "./prompt";
|
|
17
19
|
import { callerHeader, renderCallerWorkflow } from "./render";
|
|
18
20
|
import { inspectTarget, writeWorkflow, type WriteHooks } from "./write";
|
|
19
21
|
|
|
@@ -33,7 +35,7 @@ export interface InitDeps {
|
|
|
33
35
|
/** An open prompt session; the caller closes it. Otherwise one is opened over `promptIO` or the terminal. */
|
|
34
36
|
prompter?: Prompter;
|
|
35
37
|
/** What `wachiman setup` means from here: runs the setup wizard in the same process, sharing `prompter`. */
|
|
36
|
-
bindNow?: (prompter: Prompter) => Promise<number>;
|
|
38
|
+
bindNow?: (prompter: Prompter, mode: "local" | "both") => Promise<number>;
|
|
37
39
|
/** The directory a relative `--repo-dir` was resolved against, for the `setup` line. Default: `process.cwd()`. */
|
|
38
40
|
cwd?: string;
|
|
39
41
|
hooks?: WriteHooks;
|
|
@@ -42,25 +44,26 @@ export interface InitDeps {
|
|
|
42
44
|
const TEMPLATE = join(import.meta.dir, "..", "..", "templates", "wachiman-review-caller.yml");
|
|
43
45
|
const readDefaultTemplate = () => readFileSync(TEMPLATE, "utf8");
|
|
44
46
|
|
|
45
|
-
|
|
46
|
-
export function setupLine(repoDir: string, cwd: string) {
|
|
47
|
-
return repoDir === cwd ? "wachiman setup" : `wachiman setup --repo-dir ${repoDir}`;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
const openSession = (deps: InitDeps) => {
|
|
47
|
+
const openSession = (deps: InitDeps, env: Record<string, string | undefined>) => {
|
|
51
48
|
if (deps.prompter) return { prompter: deps.prompter, close: () => {} };
|
|
52
|
-
const prompter = createPrompter(deps.promptIO ?? { input: process.stdin, output: process.stderr });
|
|
49
|
+
const prompter = createPrompter(deps.promptIO ?? { input: process.stdin, output: process.stderr }, env);
|
|
53
50
|
return { prompter, close: () => prompter.close() };
|
|
54
51
|
};
|
|
55
52
|
|
|
56
53
|
/** From the parsed flags: asks what is missing when a person can be asked, resolves, and runs. */
|
|
57
54
|
export async function runInitCommand(flags: RawInitFlags, env: Record<string, string | undefined>, io: CommandIo, deps: InitDeps = {}): Promise<number> {
|
|
55
|
+
// Fail before asking for an operator or account in an unusable target.
|
|
56
|
+
const root = worktreeRoot(flags.repoDir ?? ".", deps.git);
|
|
58
57
|
const interactive = deps.interactive ?? isInteractive(flags, env, deps.streams ?? { stdin: process.stdin, stdout: process.stdout });
|
|
58
|
+
if (interactive) io = wizardIo(io, (deps.promptIO?.output ?? process.stderr) as { isTTY?: boolean }, env);
|
|
59
59
|
const defaultWorkflowRef = "defaultWorkflowRef" in deps ? deps.defaultWorkflowRef : DEFAULT_WORKFLOW_REF;
|
|
60
|
-
const session = interactive ? openSession(deps) : undefined;
|
|
60
|
+
const session = interactive ? openSession(deps, env) : undefined;
|
|
61
61
|
try {
|
|
62
62
|
let answered = flags;
|
|
63
63
|
if (session) {
|
|
64
|
+
checkSupplied(flags);
|
|
65
|
+
session.prompter.step("Project", 1);
|
|
66
|
+
session.prompter.say(root, "muted");
|
|
64
67
|
const asked = await promptForInit(flags, { defaultWorkflowRef }, session.prompter);
|
|
65
68
|
if (asked === null) {
|
|
66
69
|
io.stderr("cancelled: nothing was written.");
|
|
@@ -80,14 +83,7 @@ export async function runInitCommand(flags: RawInitFlags, env: Record<string, st
|
|
|
80
83
|
export async function runInit(options: InitOptions, io: CommandIo, deps: InitDeps = {}): Promise<number> {
|
|
81
84
|
const cwd = deps.cwd ?? process.cwd();
|
|
82
85
|
// Before anything is rendered or written: this must be a git repository.
|
|
83
|
-
|
|
84
|
-
// `--path` is relative to the repository top level: GitHub only runs workflows under <top level>/.github/workflows.
|
|
85
|
-
const top = (deps.git ?? spawnGit)(["rev-parse", "--show-toplevel"], { cwd: options.repoDir, timeoutMs: 10_000 });
|
|
86
|
-
if (top.status !== 0 || top.stdout.trim() === "") {
|
|
87
|
-
// A bare repository or a directory inside .git: there is no work tree for GitHub to run a workflow from.
|
|
88
|
-
throw new UsageError(`${options.repoDir} is not inside a git work tree; run init from the repository or pass --repo-dir <its top level>.`);
|
|
89
|
-
}
|
|
90
|
-
const root = top.stdout.trim();
|
|
86
|
+
const root = worktreeRoot(options.repoDir, deps.git);
|
|
91
87
|
const { github } = options;
|
|
92
88
|
const prompter = options.interactive ? deps.prompter : undefined;
|
|
93
89
|
let written: string | undefined;
|
|
@@ -128,25 +124,40 @@ export async function runInit(options: InitOptions, io: CommandIo, deps: InitDep
|
|
|
128
124
|
const result = writeWorkflow({ repoDir: root, relativePath: github.path, content: rendered, inspected, now, hooks: deps.hooks });
|
|
129
125
|
written = shown;
|
|
130
126
|
io.stderr(`wrote ${shown}${result.backup ? `; the earlier file is kept as ${join(dirname(github.path), basename(result.backup))}` : ""}.`);
|
|
127
|
+
if (options.mode === "github") prompter?.step("Checks and next actions", 4, 4);
|
|
131
128
|
io.stderr("Two things are left to do in GitHub:");
|
|
132
129
|
io.stderr(" 1. Add the repository secret ANTHROPIC_API_KEY (a Console key; Actions runs are billed to it): Settings, Secrets and variables, Actions.");
|
|
133
130
|
io.stderr(` 2. Open a pull request that adds ${shown}. init does not commit, push or open one.`);
|
|
134
131
|
io.stderr("Local runs use your signed-in claude, never this key.");
|
|
135
132
|
}
|
|
136
133
|
|
|
137
|
-
if (options.mode === "github")
|
|
134
|
+
if (options.mode === "github") {
|
|
135
|
+
io.stderr("github: pending; workflow written, add the secret and submit the workflow. Remote readiness was not checked.");
|
|
136
|
+
return 0;
|
|
137
|
+
}
|
|
138
138
|
if (prompter && deps.bindNow) {
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
io.stderr(written ? `cancelled: ${written} was written and stays; nothing else was changed.` : "cancelled: nothing was written.");
|
|
142
|
-
return 130;
|
|
143
|
-
}
|
|
144
|
-
if (answer) {
|
|
145
|
-
const code = await deps.bindNow(prompter);
|
|
139
|
+
try {
|
|
140
|
+
const code = await deps.bindNow(prompter, options.mode);
|
|
146
141
|
if (code === 130 && written) io.stderr(`${written} was written before setup was cancelled and stays in place.`);
|
|
142
|
+
if (code !== 130 && written) io.stderr(`github: pending; ${written} is written. Secret and workflow submission still require action in GitHub.`);
|
|
147
143
|
return code;
|
|
144
|
+
} catch (error) {
|
|
145
|
+
if (written) io.stderr(`${written} was written before setup failed and stays in place.`);
|
|
146
|
+
throw error;
|
|
148
147
|
}
|
|
149
148
|
}
|
|
150
|
-
|
|
149
|
+
|
|
150
|
+
if (written) io.stderr(`github: pending; ${written} is written. Secret and workflow submission still require action in GitHub.`);
|
|
151
|
+
for (const command of projectCommands("setup", options.repoDir, cwd)) io.stderr(`Next, on this machine: ${command} (binds this repository to a Claude account)`);
|
|
151
152
|
return 0;
|
|
152
153
|
}
|
|
154
|
+
|
|
155
|
+
/** Workflows belong at the Git top level, including when init starts below it. */
|
|
156
|
+
function worktreeRoot(repoDir: string, git: GitRunner = spawnGit): string {
|
|
157
|
+
repositoryKey(repoDir, git);
|
|
158
|
+
const top = git(["rev-parse", "--show-toplevel"], { cwd: repoDir, timeoutMs: 10_000 });
|
|
159
|
+
if (top.status !== 0 || top.stdout.trim() === "") {
|
|
160
|
+
throw new UsageError(`${repoDir} is not inside a git work tree; run init from the repository or pass --repo-dir <its top level>.`);
|
|
161
|
+
}
|
|
162
|
+
return top.stdout.trim();
|
|
163
|
+
}
|
package/src/local-ask.ts
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `wachiman ask` (ADR 0032, decisions 1, 6, 7 and 8): one question about the local change, or its
|
|
3
|
+
* walkthrough when no question is given. It is the same core a pull request comment uses, fed with
|
|
4
|
+
* the change the scope flags select and with the latest stored review of that change (ADR 0020).
|
|
5
|
+
*
|
|
6
|
+
* One provider call, on the signed-in `claude` as `local` runs (ADR 0019 decision 4), and no GitHub
|
|
7
|
+
* call: this module never builds a `gh` function. The command never runs a review. It reads the
|
|
8
|
+
* repository, reads the history store, and writes its material to a temporary directory it removes.
|
|
9
|
+
*
|
|
10
|
+
* Exit codes: 0 answered (an answer that says what it could not answer is still an answer); 1 no
|
|
11
|
+
* answer (the call failed, or its output was not an answer); 2 usage error; 130 after Ctrl-C.
|
|
12
|
+
*/
|
|
13
|
+
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
14
|
+
import { tmpdir } from "node:os";
|
|
15
|
+
import { join, resolve } from "node:path";
|
|
16
|
+
import { wachimanHome } from "./accounts/config";
|
|
17
|
+
import { ASK_SCHEMA, buildAskPrompt, checkRefs, isAskAnswer, renderAnswer } from "./ask";
|
|
18
|
+
import { repoLineCounter } from "./contracts";
|
|
19
|
+
import { UsageError } from "./config";
|
|
20
|
+
import { annotateDiff, DEFAULT_EXCLUDE, filterFiles, renderInstructions, runProvider, type ReviewInput, type ReviewResult } from "./engine";
|
|
21
|
+
import { historyRoot, readRuns, repositoryKey } from "./history/store";
|
|
22
|
+
import { type LocalArgs, type LocalDeps, localScopeInput, openLocalSession, parseFlags } from "./local";
|
|
23
|
+
import { costSentence } from "./sinks/common";
|
|
24
|
+
import { renderJson } from "./sinks/json";
|
|
25
|
+
import { renderMarkdown } from "./sinks/markdown";
|
|
26
|
+
|
|
27
|
+
export const ASK_FORMAT = "wachiman.ask-result/1";
|
|
28
|
+
|
|
29
|
+
export const askUsage = `wachiman ask [question…] [--base <ref> | --from <commit> | --commit <commit> | --working-tree staged|all]
|
|
30
|
+
[--max-depth <n>] [--repo-dir <dir>] [--profile <name>]
|
|
31
|
+
[--format terminal|markdown|json] [--output <file>]`;
|
|
32
|
+
|
|
33
|
+
/** The flags `ask` takes: the scope flags `local` has, and the output and account ones. */
|
|
34
|
+
const ASK_FLAGS = ["--base", "--from", "--commit", "--working-tree", "--max-depth", "--profile", "--format", "--output"] as const;
|
|
35
|
+
|
|
36
|
+
export interface AskArgs extends LocalArgs {
|
|
37
|
+
/** The question's words joined with spaces; "" asks for the walkthrough. */
|
|
38
|
+
question: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The arguments after `ask` (`--repo-dir` is already taken out). Every word that is not a flag is the question. */
|
|
42
|
+
export function parseAskArgs(argv: string[]): AskArgs {
|
|
43
|
+
const args = parseFlags(argv, "ask", ASK_FLAGS);
|
|
44
|
+
return { ...args, paths: [], question: args.paths.join(" ").trim() };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export const NO_REVIEW_NOTICE =
|
|
48
|
+
'No stored review of this change: answering from the diff alone. Run "wachiman local --history" first to ground answers in a review.';
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The latest stored review of this change, or undefined. It must be of the same repository (the
|
|
52
|
+
* store's key), the same kind of change, the same base and head commits (a tree for `--working-tree`),
|
|
53
|
+
* and the same files kept for review. A review of another range, another head or another scope is
|
|
54
|
+
* not this change, so it is not used.
|
|
55
|
+
*/
|
|
56
|
+
export function storedReviewOf(
|
|
57
|
+
root: string,
|
|
58
|
+
repoDir: string,
|
|
59
|
+
input: ReviewInput,
|
|
60
|
+
keptFiles: string[],
|
|
61
|
+
warn: (line: string) => void,
|
|
62
|
+
): ReviewResult | undefined {
|
|
63
|
+
const runs = readRuns(root, repositoryKey(repoDir).key, warn);
|
|
64
|
+
const files = [...keptFiles].sort();
|
|
65
|
+
for (let i = runs.length - 1; i >= 0; i--) {
|
|
66
|
+
const { result } = runs[i];
|
|
67
|
+
if (
|
|
68
|
+
result.change.kind !== input.change.kind ||
|
|
69
|
+
result.change.base.sha !== input.change.base.sha ||
|
|
70
|
+
result.change.head.sha !== input.change.head.sha
|
|
71
|
+
)
|
|
72
|
+
continue;
|
|
73
|
+
// The files the review was given: its expected ones and the binaries it left out of them.
|
|
74
|
+
const expected = [...result.coverage.expected, ...(result.coverage.unreviewable ?? []).map((u) => u.path)].sort();
|
|
75
|
+
if (expected.length === files.length && expected.every((f, j) => f === files[j])) return result;
|
|
76
|
+
}
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function runAsk(
|
|
81
|
+
args: AskArgs,
|
|
82
|
+
repoDir: string,
|
|
83
|
+
env: Record<string, string | undefined>,
|
|
84
|
+
io: {
|
|
85
|
+
stdout: (text: string) => void;
|
|
86
|
+
stderr: (line: string) => void;
|
|
87
|
+
engineVersion: string;
|
|
88
|
+
},
|
|
89
|
+
deps: LocalDeps = {},
|
|
90
|
+
): number {
|
|
91
|
+
// The account, the provider and the settings are checked before the change is read, as `local` does.
|
|
92
|
+
const { config, provider, state } = openLocalSession({
|
|
93
|
+
profile: args.profile,
|
|
94
|
+
verify: false,
|
|
95
|
+
repoDir,
|
|
96
|
+
env,
|
|
97
|
+
stderr: io.stderr,
|
|
98
|
+
deps,
|
|
99
|
+
});
|
|
100
|
+
const onSigint = () => {
|
|
101
|
+
state.interrupted = true;
|
|
102
|
+
};
|
|
103
|
+
process.on("SIGINT", onSigint);
|
|
104
|
+
let release: (() => void) | undefined;
|
|
105
|
+
let material: string | undefined;
|
|
106
|
+
try {
|
|
107
|
+
const scope = localScopeInput({
|
|
108
|
+
repoDir,
|
|
109
|
+
workingTree: args.workingTree,
|
|
110
|
+
base: args.base,
|
|
111
|
+
commit: args.commit,
|
|
112
|
+
from: args.from,
|
|
113
|
+
maxDepth: args.maxDepth,
|
|
114
|
+
paths: args.paths,
|
|
115
|
+
log: io.stderr,
|
|
116
|
+
warn: io.stderr,
|
|
117
|
+
});
|
|
118
|
+
release = scope.release;
|
|
119
|
+
const { input } = scope;
|
|
120
|
+
// The same files the review would send (its excludes and its scope), so both read one change.
|
|
121
|
+
const { kept, dropped } = filterFiles(input.files, [...DEFAULT_EXCLUDE, ...config.exclude], input.scope);
|
|
122
|
+
if (kept.length === 0) {
|
|
123
|
+
throw new UsageError(`No file in this scope is kept for review (${dropped.length} excluded): there is nothing to ask about.`);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
material = mkdtempSync(join(tmpdir(), "wachiman-ask-"));
|
|
127
|
+
writeFileSync(join(material, "ask.diff"), annotateDiff(kept));
|
|
128
|
+
writeFileSync(
|
|
129
|
+
join(material, "ask.json"),
|
|
130
|
+
`${JSON.stringify(
|
|
131
|
+
{
|
|
132
|
+
change: input.change.describe,
|
|
133
|
+
kind: input.change.kind,
|
|
134
|
+
scope: input.scope,
|
|
135
|
+
files: kept.map((f) => ({ path: f.filename, additions: f.additions, deletions: f.deletions })),
|
|
136
|
+
excludedFiles: dropped.length,
|
|
137
|
+
},
|
|
138
|
+
null,
|
|
139
|
+
2,
|
|
140
|
+
)}\n`,
|
|
141
|
+
);
|
|
142
|
+
const stored = storedReviewOf(historyRoot(wachimanHome(env)), repoDir, input, kept.map((f) => f.filename), io.stderr);
|
|
143
|
+
if (stored) {
|
|
144
|
+
writeFileSync(join(material, "review.json"), renderJson(stored, 2));
|
|
145
|
+
writeFileSync(join(material, "review.md"), renderMarkdown(stored));
|
|
146
|
+
} else io.stderr(NO_REVIEW_NOTICE);
|
|
147
|
+
|
|
148
|
+
const prompt = buildAskPrompt({
|
|
149
|
+
changeDescription: `the local change in repository ${input.change.repository.name}: ${input.change.describe}`,
|
|
150
|
+
materialPaths: {
|
|
151
|
+
meta: join(material, "ask.json"),
|
|
152
|
+
diff: join(material, "ask.diff"),
|
|
153
|
+
review: stored ? join(material, "review.md") : undefined,
|
|
154
|
+
},
|
|
155
|
+
instructions: renderInstructions(input.instructions),
|
|
156
|
+
question: args.question,
|
|
157
|
+
hasReview: stored !== undefined,
|
|
158
|
+
local: true,
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
// One call, read-only, in the snapshot of the head: the same place the review reads from.
|
|
162
|
+
let result: ReturnType<typeof runProvider> | undefined;
|
|
163
|
+
let failure = "";
|
|
164
|
+
try {
|
|
165
|
+
result = runProvider(
|
|
166
|
+
{ provider, log: io.stderr, warn: io.stderr },
|
|
167
|
+
config,
|
|
168
|
+
input.headDir,
|
|
169
|
+
{ operation: "on-demand", label: args.question ? "question" : "walkthrough" },
|
|
170
|
+
prompt,
|
|
171
|
+
material,
|
|
172
|
+
config.answerBudgetUsd,
|
|
173
|
+
ASK_SCHEMA,
|
|
174
|
+
);
|
|
175
|
+
} catch (error) {
|
|
176
|
+
failure = error instanceof Error ? error.message : String(error);
|
|
177
|
+
}
|
|
178
|
+
if (state.interrupted) {
|
|
179
|
+
io.stderr("Interrupted: the answer was not produced.");
|
|
180
|
+
return 130;
|
|
181
|
+
}
|
|
182
|
+
const parsed = result && !result.isError ? result.structuredOutput : undefined;
|
|
183
|
+
if (!result || !isAskAnswer(parsed)) {
|
|
184
|
+
const reason = result ? (result.isError ? result.terminalReason || "the call failed" : "its output was not an answer") : failure;
|
|
185
|
+
io.stderr(`Wachiman could not answer (${reason}).`);
|
|
186
|
+
return 1;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// A reference is kept only if its file exists in the head snapshot and the line is in the file.
|
|
190
|
+
const lineCount = repoLineCounter(input.headDir);
|
|
191
|
+
const checked = checkRefs(parsed, (path, line) => {
|
|
192
|
+
const count = lineCount(path);
|
|
193
|
+
return count !== null && line <= count;
|
|
194
|
+
});
|
|
195
|
+
const cost = { costUsdEstimate: result.costUsd, calls: 1, turns: result.turns, durationMs: result.durationMs };
|
|
196
|
+
const text =
|
|
197
|
+
args.format === "json"
|
|
198
|
+
? `${JSON.stringify(
|
|
199
|
+
{
|
|
200
|
+
format: ASK_FORMAT,
|
|
201
|
+
question: args.question,
|
|
202
|
+
walkthrough: args.question === "",
|
|
203
|
+
hasReview: stored !== undefined,
|
|
204
|
+
sections: checked.answer.sections.map((s) => ({
|
|
205
|
+
title: s.title,
|
|
206
|
+
body: s.body,
|
|
207
|
+
refs: s.refs.map((r) => ({ path: r.path, line: r.line })),
|
|
208
|
+
})),
|
|
209
|
+
notAnswered: checked.answer.not_answered,
|
|
210
|
+
removedRefs: checked.removed,
|
|
211
|
+
provider: { label: provider.modelLabel(), model: config.model, costUsd: result.costUsd },
|
|
212
|
+
},
|
|
213
|
+
null,
|
|
214
|
+
2,
|
|
215
|
+
)}\n`
|
|
216
|
+
: `${renderAnswer(checked.answer, {
|
|
217
|
+
removed: checked.removed,
|
|
218
|
+
style: args.format === "markdown" ? "markdown" : "plain",
|
|
219
|
+
})}\n\n${costSentence(cost)}\n`;
|
|
220
|
+
if (args.output !== undefined) {
|
|
221
|
+
const path = resolve(args.output);
|
|
222
|
+
writeFileSync(path, text);
|
|
223
|
+
io.stderr(`report: ${path}`);
|
|
224
|
+
} else io.stdout(text);
|
|
225
|
+
return 0;
|
|
226
|
+
} finally {
|
|
227
|
+
process.off("SIGINT", onSigint);
|
|
228
|
+
release?.();
|
|
229
|
+
if (material !== undefined) rmSync(material, { recursive: true, force: true });
|
|
230
|
+
}
|
|
231
|
+
}
|