diffpact 0.0.0-stage → 0.4.3

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 (51) hide show
  1. package/CHANGELOG.md +142 -0
  2. package/LICENSE +21 -0
  3. package/README.md +223 -2
  4. package/bin/diffpact.mjs +15 -0
  5. package/dist/adapters/claude-code.d.ts +21 -0
  6. package/dist/adapters/claude-code.js +191 -0
  7. package/dist/adapters/codex.d.ts +31 -0
  8. package/dist/adapters/codex.js +348 -0
  9. package/dist/adapters/gemini-agy.d.ts +26 -0
  10. package/dist/adapters/gemini-agy.js +429 -0
  11. package/dist/adapters/vercel-board.d.ts +30 -0
  12. package/dist/adapters/vercel-board.js +138 -0
  13. package/dist/amend.d.ts +46 -0
  14. package/dist/amend.js +476 -0
  15. package/dist/boundaries.d.ts +43 -0
  16. package/dist/boundaries.js +309 -0
  17. package/dist/canonical-json.d.ts +6 -0
  18. package/dist/canonical-json.js +63 -0
  19. package/dist/cli.d.ts +1 -0
  20. package/dist/cli.js +1704 -0
  21. package/dist/delegate.d.ts +22 -0
  22. package/dist/delegate.js +140 -0
  23. package/dist/doctor.d.ts +36 -0
  24. package/dist/doctor.js +293 -0
  25. package/dist/git.d.ts +27 -0
  26. package/dist/git.js +234 -0
  27. package/dist/index.d.ts +19 -0
  28. package/dist/index.js +19 -0
  29. package/dist/merge-verify.d.ts +31 -0
  30. package/dist/merge-verify.js +721 -0
  31. package/dist/report.d.ts +25 -0
  32. package/dist/report.js +220 -0
  33. package/dist/review.d.ts +46 -0
  34. package/dist/review.js +527 -0
  35. package/dist/runner.d.ts +45 -0
  36. package/dist/runner.js +213 -0
  37. package/dist/schema.d.ts +6 -0
  38. package/dist/schema.js +424 -0
  39. package/dist/types.d.ts +190 -0
  40. package/dist/types.js +220 -0
  41. package/dist/verify.d.ts +45 -0
  42. package/dist/verify.js +952 -0
  43. package/dist/worktree.d.ts +82 -0
  44. package/dist/worktree.js +717 -0
  45. package/examples/harnesses/README.md +63 -0
  46. package/examples/quickstart/README.md +17 -0
  47. package/examples/quickstart/run.mjs +247 -0
  48. package/package.json +62 -4
  49. package/schemas/contract.schema.json +148 -0
  50. package/schemas/receipt.schema.json +49 -0
  51. package/schemas/review.schema.json +48 -0
@@ -0,0 +1,22 @@
1
+ import { type ExitCode, type SessionIdentity, type TaskContractV01 } from './types.ts';
2
+ export interface DelegateOptions {
3
+ parentContractPath: string;
4
+ cwd?: string;
5
+ subtaskId: string;
6
+ mission: string;
7
+ allowedPaths: string[];
8
+ reservedBudgetUsd?: number;
9
+ implementer: SessionIdentity;
10
+ branch?: string;
11
+ worktreePath?: string;
12
+ }
13
+ /**
14
+ * Creates a monotonically narrowed child subcontract under `.diffpact/subcontracts/<subtaskId>.json`,
15
+ * enforcing path subset containment, depth bounds, and shared root budget conservation.
16
+ */
17
+ export declare function createDelegatedSubcontract(options: DelegateOptions): {
18
+ exitCode: ExitCode;
19
+ subcontractPath?: string;
20
+ subcontract?: TaskContractV01;
21
+ error?: string;
22
+ };
@@ -0,0 +1,140 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { canonicalSha256 } from './canonical-json.js';
4
+ import { evaluatePathBoundary } from './boundaries.js';
5
+ import { resolveRepoRoot } from './git.js';
6
+ import { validateContract } from './schema.js';
7
+ import {
8
+ EXIT_INCOMPLETE,
9
+ EXIT_PASS,
10
+ EXIT_VIOLATION,
11
+
12
+
13
+
14
+ } from './types.js';
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+ /**
29
+ * Creates a monotonically narrowed child subcontract under `.diffpact/subcontracts/<subtaskId>.json`,
30
+ * enforcing path subset containment, depth bounds, and shared root budget conservation.
31
+ */
32
+ export function createDelegatedSubcontract(options )
33
+
34
+
35
+
36
+
37
+ {
38
+ const baseDir = options.cwd ?? process.cwd();
39
+ const parentAbs = path.resolve(baseDir, options.parentContractPath);
40
+ if (!fs.existsSync(parentAbs)) {
41
+ return { exitCode: EXIT_INCOMPLETE, error: `Parent contract not found: "${parentAbs}"` };
42
+ }
43
+
44
+ if (!/^[a-zA-Z0-9._-]+$/.test(options.subtaskId)) {
45
+ return {
46
+ exitCode: EXIT_VIOLATION,
47
+ error: `Invalid subtaskId "${options.subtaskId}": must contain only alphanumeric, dot, underscore, or dash characters`
48
+ };
49
+ }
50
+
51
+ let parent ;
52
+ try {
53
+ parent = validateContract(JSON.parse(fs.readFileSync(parentAbs, 'utf8')));
54
+ } catch (err) {
55
+ return { exitCode: EXIT_INCOMPLETE, error: (err ).message };
56
+ }
57
+
58
+ const parentSha = canonicalSha256('diffpact/contract/v0.1', parent);
59
+ const repoRoot = resolveRepoRoot(path.dirname(path.dirname(parentAbs)));
60
+
61
+ const parentDepth = parent.budget?.delegation_depth ?? 0;
62
+ const maxDepth = parent.budget?.max_delegation_depth ?? 1;
63
+ const nextDepth = parentDepth + 1;
64
+ if (nextDepth > maxDepth) {
65
+ return {
66
+ exitCode: EXIT_VIOLATION,
67
+ error: `Delegation depth ${nextDepth} exceeds parent max_delegation_depth ${maxDepth}`
68
+ };
69
+ }
70
+
71
+ // Verify every child allowed_path fits strictly within parent boundaries
72
+ for (const glob of options.allowedPaths) {
73
+ const sample = glob.replace(/\*\*/g, 'sample_dir').replace(/\*/g, 'sample_item').replace(/\?/g, 'x');
74
+ const v = evaluatePathBoundary(sample, repoRoot, parent);
75
+ if (v) {
76
+ return {
77
+ exitCode: EXIT_VIOLATION,
78
+ error: `Child allowed_path "${glob}" escapes parent boundary (${v.code}: ${v.message})`
79
+ };
80
+ }
81
+ }
82
+
83
+ const subDir = path.join(path.dirname(parentAbs), 'subcontracts');
84
+ fs.mkdirSync(subDir, { recursive: true });
85
+
86
+ // Sum existing sibling reservations
87
+ let existingReserved = 0;
88
+ for (const file of fs.readdirSync(subDir).filter((f) => f.endsWith('.json'))) {
89
+ if (file === `${options.subtaskId}.json`) continue;
90
+ const sib = validateContract(JSON.parse(fs.readFileSync(path.join(subDir, file), 'utf8')));
91
+ existingReserved += sib.budget?.reserved_budget_usd ?? sib.budget?.max_budget_usd ?? 0;
92
+ }
93
+
94
+ const requestedBudget = options.reservedBudgetUsd ?? 0;
95
+ if (
96
+ typeof parent.budget?.max_budget_usd === 'number' &&
97
+ existingReserved + requestedBudget > parent.budget.max_budget_usd + 1e-9
98
+ ) {
99
+ return {
100
+ exitCode: EXIT_VIOLATION,
101
+ error: `Budget conservation violated: existing $${existingReserved.toFixed(2)} + requested $${requestedBudget.toFixed(2)} exceeds parent max_budget_usd $${parent.budget.max_budget_usd.toFixed(2)}`
102
+ };
103
+ }
104
+
105
+ const childContract = validateContract({
106
+ schema_version: 'diffpact-contract-v0.1',
107
+ task_id: options.subtaskId,
108
+ task_type: parent.task_type,
109
+ mission: options.mission,
110
+ starting_sha: parent.starting_sha,
111
+ worktree: {
112
+ ...(options.branch ? { branch: options.branch } : {}),
113
+ ...(options.worktreePath ? { path: options.worktreePath } : {}),
114
+ require_clean_start: parent.worktree.require_clean_start ?? true,
115
+ require_clean_end: parent.worktree.require_clean_end ?? true
116
+ },
117
+ allowed_paths: options.allowedPaths,
118
+ read_only_paths: parent.read_only_paths ?? [],
119
+ forbidden_paths: parent.forbidden_paths,
120
+ ...(parent.version_assertions ? { version_assertions: parent.version_assertions } : {}),
121
+ ...(parent.interfacedelta_lockfile !== undefined
122
+ ? { interfacedelta_lockfile: parent.interfacedelta_lockfile }
123
+ : {}),
124
+ budget: {
125
+ max_budget_usd: requestedBudget,
126
+ reserved_budget_usd: requestedBudget,
127
+ delegation_depth: nextDepth,
128
+ max_delegation_depth: maxDepth,
129
+ parent_contract_sha256: parentSha
130
+ },
131
+ required_checks: parent.required_checks,
132
+ ...(parent.allow_no_checks !== undefined ? { allow_no_checks: parent.allow_no_checks } : {}),
133
+ implementer_session: options.implementer,
134
+ ...(parent.review_policy ? { review_policy: parent.review_policy } : {})
135
+ });
136
+
137
+ const outPath = path.join(subDir, `${options.subtaskId}.json`);
138
+ fs.writeFileSync(outPath, JSON.stringify(childContract, null, 2) + '\n');
139
+ return { exitCode: EXIT_PASS, subcontractPath: outPath, subcontract: childContract };
140
+ }
@@ -0,0 +1,36 @@
1
+ export type ProbedHarnessId = 'claude-code' | 'codex' | 'crush' | 'agy' | 'agy-worker' | 'gemini-cli' | 'vercel-board' | 'vercel-cli';
2
+ export interface HarnessProbeResult {
3
+ id: ProbedHarnessId;
4
+ binary: string;
5
+ installed: boolean;
6
+ resolvedPath?: string;
7
+ version?: string;
8
+ }
9
+ export interface DoctorReport {
10
+ ok: boolean;
11
+ nodeVersion: string;
12
+ gitAvailable: boolean;
13
+ insideGitRepo: boolean;
14
+ repoRoot?: string;
15
+ workingTreeClean?: boolean;
16
+ diffpactExcludedInGit?: boolean;
17
+ runningAsRoot: boolean;
18
+ harnesses: HarnessProbeResult[];
19
+ warnings: string[];
20
+ }
21
+ export interface InstallHooksOptions {
22
+ target: 'claude-code' | 'codex' | 'gemini' | 'agy';
23
+ contractPath?: string;
24
+ cwd?: string;
25
+ excludeInGitInfo?: boolean;
26
+ }
27
+ export declare function runDoctor(options?: {
28
+ cwd?: string;
29
+ env?: NodeJS.ProcessEnv;
30
+ isRoot?: boolean;
31
+ }): DoctorReport;
32
+ export declare function installHarnessHooks(options: InstallHooksOptions): {
33
+ configPath: string;
34
+ created: boolean;
35
+ merged: boolean;
36
+ };
package/dist/doctor.js ADDED
@@ -0,0 +1,293 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { collectRepoChanges, ensureGitInfoExclude, resolveHeadSha, resolveRepoRoot } from './git.js';
5
+ import { generateClaudeCodeConfig } from './adapters/claude-code.js';
6
+ import { generateCodexConfig } from './adapters/codex.js';
7
+ import { generateAgyConfig, generateGeminiCliConfig } from './adapters/gemini-agy.js';
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+
41
+
42
+
43
+
44
+
45
+
46
+
47
+ function findExecutableOnPath(binary , pathEnv ) {
48
+ for (const dir of pathEnv.split(path.delimiter).filter(Boolean)) {
49
+ const candidate = path.join(dir, binary);
50
+ try {
51
+ fs.accessSync(candidate, fs.constants.X_OK);
52
+ const st = fs.statSync(candidate);
53
+ if (st.isFile()) return candidate;
54
+ } catch {
55
+ // continue
56
+ }
57
+ }
58
+ return undefined;
59
+ }
60
+
61
+ function readBinaryVersion(binPath , env ) {
62
+ try {
63
+ const out = execFileSync(binPath, ['--version'], {
64
+ env,
65
+ encoding: 'utf8',
66
+ timeout: 5000,
67
+ stdio: ['ignore', 'pipe', 'pipe']
68
+ });
69
+ const lines = out
70
+ .split(/\r?\n/)
71
+ .map((l) => l.trim())
72
+ .filter(Boolean);
73
+ const versionLine = lines.find((l) => /(?:version|\bv?\d+\.\d+)/i.test(l));
74
+ return versionLine ?? lines[0] ?? undefined;
75
+ } catch {
76
+ return undefined;
77
+ }
78
+ }
79
+
80
+ export function runDoctor(options
81
+
82
+
83
+
84
+ ) {
85
+ const cwd = options?.cwd ?? process.cwd();
86
+ const env = options?.env ?? process.env;
87
+ const pathEnv = env.PATH ?? '';
88
+
89
+ let gitAvailable = false;
90
+ try {
91
+ execFileSync('git', ['--version'], { env, stdio: 'ignore' });
92
+ gitAvailable = true;
93
+ } catch {
94
+ gitAvailable = false;
95
+ }
96
+
97
+ let insideGitRepo = false;
98
+ let repoRoot ;
99
+ let workingTreeClean ;
100
+ let diffpactExcludedInGit ;
101
+
102
+ if (gitAvailable) {
103
+ try {
104
+ repoRoot = resolveRepoRoot(cwd);
105
+ insideGitRepo = true;
106
+ try {
107
+ const head = resolveHeadSha(repoRoot);
108
+ workingTreeClean = collectRepoChanges(repoRoot, head, head).workingTreeClean;
109
+ } catch {
110
+ workingTreeClean = undefined;
111
+ }
112
+ try {
113
+ const rawExclude = execFileSync(
114
+ 'git',
115
+ ['--no-optional-locks', '-C', repoRoot, 'rev-parse', '--git-path', 'info/exclude'],
116
+ { env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }
117
+ ).trim();
118
+ const excludeAbs = path.resolve(repoRoot, rawExclude);
119
+ if (fs.existsSync(excludeAbs)) {
120
+ const lines = fs
121
+ .readFileSync(excludeAbs, 'utf8')
122
+ .split(/\r?\n/)
123
+ .map((l) => l.trim());
124
+ diffpactExcludedInGit = lines.includes('.diffpact/') || lines.includes('.diffpact');
125
+ } else {
126
+ diffpactExcludedInGit = false;
127
+ }
128
+ } catch {
129
+ diffpactExcludedInGit = false;
130
+ }
131
+ } catch {
132
+ insideGitRepo = false;
133
+ }
134
+ }
135
+
136
+ const probes = [
137
+ { id: 'claude-code', candidates: ['claude'] },
138
+ { id: 'codex', candidates: ['codex'] },
139
+ { id: 'crush', candidates: ['crush'] },
140
+ { id: 'agy', candidates: ['agy'] },
141
+ { id: 'agy-worker', candidates: ['agy-worker'], skipVersionFlag: true },
142
+ { id: 'gemini-cli', candidates: ['gemini'] },
143
+ { id: 'vercel-board', candidates: ['vb', 'board'] },
144
+ { id: 'vercel-cli', candidates: ['vercel'] }
145
+ ];
146
+
147
+ const harnesses = probes.map((p) => {
148
+ for (const binName of p.candidates) {
149
+ const resolvedPath = findExecutableOnPath(binName, pathEnv);
150
+ if (resolvedPath) {
151
+ const version = p.skipVersionFlag ? 'executable' : readBinaryVersion(resolvedPath, env);
152
+ return {
153
+ id: p.id,
154
+ binary: binName,
155
+ installed: true,
156
+ resolvedPath,
157
+ ...(version ? { version } : {})
158
+ };
159
+ }
160
+ }
161
+ return {
162
+ id: p.id,
163
+ binary: p.candidates[0] ,
164
+ installed: false
165
+ };
166
+ });
167
+
168
+ const runningAsRoot =
169
+ options?.isRoot ?? (typeof process.geteuid === 'function' ? process.geteuid() === 0 : false);
170
+ const warnings = [];
171
+
172
+ const claudeInstalled = harnesses.some((h) => h.id === 'claude-code' && h.installed);
173
+ if (runningAsRoot && claudeInstalled) {
174
+ warnings.push(
175
+ 'Running as root with Claude Code installed: `--dangerously-skip-permissions` is rejected under root/sudo. Use `diffpact run --harness claude` (which passes `--permission-mode acceptEdits --allowedTools ... --`).'
176
+ );
177
+ }
178
+
179
+ const codexInstalled = harnesses.some((h) => h.id === 'codex' && h.installed);
180
+ if (codexInstalled) {
181
+ warnings.push(
182
+ 'Codex CLI detected: nested `diffpact verify` subprocesses inside Codex `workspace-write` sandboxes may hit spawn restrictions (EPERM/EACCES). Run `diffpact verify` from the host orchestrator or `diffpact exec` / `diffpact run` wrapper.'
183
+ );
184
+ }
185
+
186
+ const crushInstalled = harnesses.some((h) => h.id === 'crush' && h.installed);
187
+ if (crushInstalled) {
188
+ warnings.push(
189
+ 'Crush CLI detected: `crush` creates a local `.crush/` directory inside the working tree unless `--data-dir <tempdir>` is passed. Use `diffpact run --harness crush` so `.crush/` stays outside the worktree.'
190
+ );
191
+ }
192
+
193
+ return {
194
+ ok: gitAvailable,
195
+ nodeVersion: process.version,
196
+ gitAvailable,
197
+ insideGitRepo,
198
+ ...(repoRoot ? { repoRoot } : {}),
199
+ ...(workingTreeClean !== undefined ? { workingTreeClean } : {}),
200
+ ...(diffpactExcludedInGit !== undefined ? { diffpactExcludedInGit } : {}),
201
+ runningAsRoot,
202
+ harnesses,
203
+ warnings
204
+ };
205
+ }
206
+
207
+ function mergeHookArraysIdempotently(existingArr , incomingArr ) {
208
+ const base = Array.isArray(existingArr) ? [...existingArr] : [];
209
+ const nonDiffpact = base.filter((item) => {
210
+ const serialized = JSON.stringify(item);
211
+ return !serialized.includes('diffpact ');
212
+ });
213
+ return [...nonDiffpact, ...incomingArr];
214
+ }
215
+
216
+ export function installHarnessHooks(options )
217
+
218
+
219
+
220
+ {
221
+ const cwd = options.cwd ?? process.cwd();
222
+ const contractPath = options.contractPath ?? '.diffpact/contract.json';
223
+
224
+ const relTargetMap = {
225
+ 'claude-code': '.claude/settings.json',
226
+ codex: '.codex/hooks.json',
227
+ gemini: '.gemini/settings.json',
228
+ agy: '.agents/hooks.json'
229
+ };
230
+
231
+ const generatedMap = {
232
+ 'claude-code': generateClaudeCodeConfig(contractPath),
233
+ codex: generateCodexConfig(contractPath),
234
+ gemini: generateGeminiCliConfig(contractPath),
235
+ agy: generateAgyConfig(contractPath)
236
+ };
237
+
238
+ const relConfigPath = relTargetMap[options.target];
239
+ const configAbs = path.resolve(cwd, relConfigPath);
240
+ const generatedObj = JSON.parse(generatedMap[options.target]) ;
241
+
242
+ fs.mkdirSync(path.dirname(configAbs), { recursive: true });
243
+
244
+ let created = false;
245
+ let merged = false;
246
+ let finalObj ;
247
+
248
+ if (!fs.existsSync(configAbs)) {
249
+ created = true;
250
+ finalObj = generatedObj;
251
+ } else {
252
+ merged = true;
253
+ const existingObj = JSON.parse(fs.readFileSync(configAbs, 'utf8')) ;
254
+ if (options.target === 'agy') {
255
+ finalObj = {
256
+ ...existingObj,
257
+ 'diffpact-guard': generatedObj['diffpact-guard']
258
+ };
259
+ } else {
260
+ const existingHooks =
261
+ typeof existingObj.hooks === 'object' && existingObj.hooks !== null && !Array.isArray(existingObj.hooks)
262
+ ? (existingObj.hooks )
263
+ : {};
264
+ const incomingHooks = generatedObj.hooks ;
265
+ const mergedHooks = { ...existingHooks };
266
+ for (const [eventKey, incomingList] of Object.entries(incomingHooks)) {
267
+ mergedHooks[eventKey] = mergeHookArraysIdempotently(existingHooks[eventKey], incomingList);
268
+ }
269
+ finalObj = {
270
+ ...existingObj,
271
+ hooks: mergedHooks
272
+ };
273
+ }
274
+ }
275
+
276
+ fs.writeFileSync(configAbs, JSON.stringify(finalObj, null, 2) + '\n', 'utf8');
277
+
278
+ if (options.excludeInGitInfo) {
279
+ try {
280
+ const repoRoot = resolveRepoRoot(cwd);
281
+ ensureGitInfoExclude(repoRoot, '.diffpact/');
282
+ ensureGitInfoExclude(repoRoot, relConfigPath);
283
+ } catch {
284
+ // ignore if outside git repo
285
+ }
286
+ }
287
+
288
+ return {
289
+ configPath: configAbs,
290
+ created,
291
+ merged
292
+ };
293
+ }
package/dist/git.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ import type { ChangedFileEntry } from './types.ts';
2
+ export declare function runGitBuffer(cwd: string, args: readonly string[]): Buffer;
3
+ export declare function runGitText(cwd: string, args: readonly string[]): string;
4
+ export declare function resolveRepoRoot(cwd: string): string;
5
+ export declare function resolveHeadSha(cwd: string): string;
6
+ export declare function resolveCurrentBranch(cwd: string): string;
7
+ export declare function ensureGitInfoExclude(cwd: string, entry?: string): void;
8
+ export declare function commitExists(cwd: string, sha: string): boolean;
9
+ /**
10
+ * Resolves a full SHA, abbreviated short SHA (e.g. 7 chars), or Git ref (e.g. HEAD~1, main)
11
+ * to its canonical 40-character lowercase commit SHA-1, or returns null if unresolvable.
12
+ */
13
+ export declare function resolveCommitSha(cwd: string, refOrSha: string): string | null;
14
+ export declare function isAncestor(cwd: string, ancestorSha: string, descendantSha: string): boolean;
15
+ export interface RepoChangeSnapshot {
16
+ changedFiles: ChangedFileEntry[];
17
+ untrackedFiles: string[];
18
+ workingTreeClean: boolean;
19
+ trackedTreeClean: boolean;
20
+ rawDiffSha256: string;
21
+ }
22
+ /**
23
+ * Collects all file changes between `startingSha` and the current repository state
24
+ * (`startingSha..HEAD`, staged changes, unstaged changes, and untracked files),
25
+ * excluding internal `.diffpact/` state files from dirty-worktree accounting.
26
+ */
27
+ export declare function collectRepoChanges(repoRoot: string, startingSha: string, headSha: string): RepoChangeSnapshot;