@hifullmoon/aicommit 2.4.1 → 2.6.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.
@@ -16,11 +16,16 @@
16
16
  "warnings",
17
17
  "exitReason",
18
18
  "committed",
19
+ "commitState",
20
+ "commitSha",
21
+ "planFile",
22
+ "scope",
23
+ "changeCount",
19
24
  "error"
20
25
  ],
21
26
  "properties": {
22
27
  "schemaVersion": {
23
- "const": "1.0"
28
+ "const": "1.1"
24
29
  },
25
30
  "ok": {
26
31
  "type": "boolean"
@@ -107,10 +112,26 @@
107
112
  "committed": {
108
113
  "type": "boolean"
109
114
  },
115
+ "commitState": {
116
+ "enum": ["none", "partial", "complete", "unknown"]
117
+ },
118
+ "commitSha": {
119
+ "type": ["string", "null"]
120
+ },
121
+ "planFile": {
122
+ "type": ["string", "null"]
123
+ },
124
+ "scope": {
125
+ "type": ["string", "null"]
126
+ },
127
+ "changeCount": {
128
+ "type": ["integer", "null"],
129
+ "minimum": 0
130
+ },
110
131
  "error": {
111
132
  "type": ["object", "null"],
112
133
  "additionalProperties": false,
113
- "required": ["category", "message"],
134
+ "required": ["category", "code", "message", "retryable", "nextAction"],
114
135
  "properties": {
115
136
  "category": {
116
137
  "enum": [
@@ -126,6 +147,16 @@
126
147
  },
127
148
  "message": {
128
149
  "type": "string"
150
+ },
151
+ "code": {
152
+ "type": "string",
153
+ "minLength": 1
154
+ },
155
+ "retryable": {
156
+ "type": "boolean"
157
+ },
158
+ "nextAction": {
159
+ "type": ["string", "null"]
129
160
  }
130
161
  }
131
162
  },
@@ -150,7 +181,7 @@
150
181
  "description": "Files represented by partial excerpts; not fully analyzed files."
151
182
  },
152
183
  "strategy": {
153
- "enum": ["auto", "deep"]
184
+ "enum": ["auto", "deep", "fallback"]
154
185
  },
155
186
  "metadataOnlyFiles": {
156
187
  "type": "number",
@@ -181,6 +212,33 @@
181
212
  "minimum": 0
182
213
  }
183
214
  }
215
+ },
216
+ "split": {
217
+ "type": "object",
218
+ "additionalProperties": false,
219
+ "required": ["state"],
220
+ "properties": {
221
+ "state": { "enum": ["idle", "pending"] },
222
+ "transactionId": { "type": "string" },
223
+ "checkpointPath": { "type": "string" },
224
+ "scope": { "enum": ["staged", "all"] },
225
+ "totalGroups": { "type": "integer", "minimum": 0 },
226
+ "completedGroups": { "type": "integer", "minimum": 0 },
227
+ "pendingGroups": { "type": "integer", "minimum": 0 },
228
+ "completedCommits": {
229
+ "type": "array",
230
+ "items": { "type": "string", "pattern": "^[0-9a-f]{40}([0-9a-f]{24})?$" }
231
+ },
232
+ "inFlight": {
233
+ "type": ["object", "null"],
234
+ "additionalProperties": false,
235
+ "properties": {
236
+ "group": { "type": "integer", "minimum": 1 },
237
+ "state": { "enum": ["pending", "committed", "unknown"] }
238
+ }
239
+ },
240
+ "nextAction": { "type": "string" }
241
+ }
184
242
  }
185
243
  }
186
244
  }
@@ -6,6 +6,12 @@ export const DEFAULT_LARGE_CHANGE = Object.freeze({
6
6
  maxTotalTokens: 200000,
7
7
  concurrency: 2,
8
8
  timeoutMs: 180000,
9
+ cache: Object.freeze({
10
+ enabled: true,
11
+ ttlMs: 24 * 60 * 60 * 1000,
12
+ maxBytes: 32 * 1024 * 1024,
13
+ allowUnprotected: false,
14
+ }),
9
15
  });
10
16
 
11
17
  export function estimateTokens(text) {
@@ -40,21 +46,25 @@ export function createAnalysisBudget(settings = {}) {
40
46
  };
41
47
  },
42
48
  reserve(input, output) {
43
- if (
44
- !this.remainingMs() ||
45
- charged + input + output + reserveFinal > limits.maxTotalTokens ||
46
- requests >= 256
47
- ) {
49
+ const exhausted = !this.remainingMs()
50
+ ? 'time'
51
+ : requests >= 256
52
+ ? 'requests'
53
+ : charged + input + output + reserveFinal > limits.maxTotalTokens
54
+ ? 'tokens'
55
+ : null;
56
+ if (exhausted) {
48
57
  throw fail(
49
58
  ERROR_CATEGORIES.PROVIDER,
50
- 'Large-change analysis reached its token, request, or time budget. No incomplete plan will be committed. Increase the personal largeChange budget or stage a smaller change.',
51
- { data: { analysis: this.snapshot() } },
59
+ `Large-change analysis reached its ${exhausted} budget.`,
60
+ { data: { analysis: { ...this.snapshot(), exhausted } } },
52
61
  );
53
62
  }
54
63
  if (input > limits.chunkInputTokens) {
55
64
  throw fail(
56
65
  ERROR_CATEGORIES.PROVIDER,
57
66
  'Analysis request exceeds largeChange.chunkInputTokens; shorten repository context or increase the personal input budget.',
67
+ { data: { analysis: { ...this.snapshot(), exhausted: 'input' } } },
58
68
  );
59
69
  }
60
70
  charged += input + output;
@@ -0,0 +1,246 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { execFileSync } from 'node:child_process';
3
+ import {
4
+ existsSync,
5
+ lstatSync,
6
+ mkdirSync,
7
+ readFileSync,
8
+ readdirSync,
9
+ renameSync,
10
+ rmSync,
11
+ statSync,
12
+ utimesSync,
13
+ writeFileSync,
14
+ } from 'node:fs';
15
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
16
+
17
+ export const ANALYSIS_CACHE_KIND = 'aicommit-analysis-cache-entry';
18
+ export const ANALYSIS_CACHE_VERSION = 1;
19
+ // Bump whenever the fragment-analysis prompt or summary contract changes.
20
+ export const ANALYSIS_CONTRACT_VERSION = 1;
21
+ const MAX_ENTRY_BYTES = 128 * 1024;
22
+ const SHA256_RE = /^[0-9a-f]{64}$/;
23
+
24
+ function object(value) {
25
+ return value && typeof value === 'object' && !Array.isArray(value);
26
+ }
27
+
28
+ function canonical(value) {
29
+ if (Array.isArray(value)) return value.map(canonical);
30
+ if (!object(value)) return value;
31
+ return Object.fromEntries(
32
+ Object.keys(value)
33
+ .sort()
34
+ .filter((key) => value[key] !== undefined)
35
+ .map((key) => [key, canonical(value[key])]),
36
+ );
37
+ }
38
+
39
+ function digest(value) {
40
+ return createHash('sha256')
41
+ .update(JSON.stringify(canonical(value)))
42
+ .digest('hex');
43
+ }
44
+
45
+ function cacheRoot(projectRoot) {
46
+ const raw = execFileSync(
47
+ 'git',
48
+ ['rev-parse', '--git-path', `aicommit/analysis-cache/v${ANALYSIS_CACHE_VERSION}`],
49
+ {
50
+ cwd: projectRoot,
51
+ encoding: 'utf8',
52
+ stdio: ['pipe', 'pipe', 'pipe'],
53
+ },
54
+ ).trim();
55
+ return isAbsolute(raw) ? raw : resolve(projectRoot, raw);
56
+ }
57
+
58
+ function namespaceSignature(config, protect) {
59
+ return digest({
60
+ contractVersion: ANALYSIS_CONTRACT_VERSION,
61
+ providerType: config.providerType || '',
62
+ apiUrl: config.apiUrl,
63
+ modelId: config.modelId,
64
+ reasoning: config.reasoning,
65
+ extraBody: config.extraBody,
66
+ protect,
67
+ });
68
+ }
69
+
70
+ function normalizeGroups(groups) {
71
+ if (!Array.isArray(groups) || !groups.length || groups.length > 16) {
72
+ throw new Error('Analysis cache groups must be a non-empty bounded array.');
73
+ }
74
+ return groups.map((group) => {
75
+ if (
76
+ !object(group) ||
77
+ !Array.isArray(group.ids) ||
78
+ !group.ids.length ||
79
+ group.ids.some((id) => typeof id !== 'string' || !id || id.length > 128) ||
80
+ typeof group.summary !== 'string' ||
81
+ !group.summary.trim() ||
82
+ group.summary.length > 2000
83
+ ) {
84
+ throw new Error('Analysis cache contains an invalid group.');
85
+ }
86
+ return { ids: [...group.ids], summary: group.summary };
87
+ });
88
+ }
89
+
90
+ function validateEntry(input, expectedIds) {
91
+ if (
92
+ !object(input) ||
93
+ Object.keys(input).some(
94
+ (key) => !['kind', 'version', 'createdAt', 'ids', 'groups'].includes(key),
95
+ ) ||
96
+ input.kind !== ANALYSIS_CACHE_KIND ||
97
+ input.version !== ANALYSIS_CACHE_VERSION ||
98
+ typeof input.createdAt !== 'string' ||
99
+ !Number.isFinite(Date.parse(input.createdAt)) ||
100
+ !Array.isArray(input.ids) ||
101
+ input.ids.length !== expectedIds.length ||
102
+ input.ids.some((id, index) => id !== expectedIds[index])
103
+ ) {
104
+ throw new Error('Analysis cache entry is invalid or belongs to another chunk.');
105
+ }
106
+ return normalizeGroups(input.groups);
107
+ }
108
+
109
+ function namespaceRecords(root) {
110
+ if (!existsSync(root)) return [];
111
+ const records = [];
112
+ for (const entry of readdirSync(root, { withFileTypes: true })) {
113
+ if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
114
+ const path = join(root, entry.name);
115
+ let bytes = 0;
116
+ let modified = lstatSync(path).mtimeMs;
117
+ for (const child of readdirSync(path, { withFileTypes: true })) {
118
+ if (!child.isFile() || child.isSymbolicLink()) continue;
119
+ const stat = statSync(join(path, child.name));
120
+ bytes += stat.size;
121
+ modified = Math.max(modified, stat.mtimeMs);
122
+ }
123
+ records.push({ path, bytes, modified });
124
+ }
125
+ return records;
126
+ }
127
+
128
+ function prune(root, settings, keep = null, now = Date.now()) {
129
+ try {
130
+ let records = namespaceRecords(root);
131
+ for (const record of records) {
132
+ if (record.path !== keep && now - record.modified > settings.ttlMs) {
133
+ rmSync(record.path, { recursive: true, force: true });
134
+ }
135
+ }
136
+ records = namespaceRecords(root).sort((left, right) => left.modified - right.modified);
137
+ let total = records.reduce((sum, record) => sum + record.bytes, 0);
138
+ for (const record of records) {
139
+ if (total <= settings.maxBytes) break;
140
+ if (record.path === keep) continue;
141
+ rmSync(record.path, { recursive: true, force: true });
142
+ total -= record.bytes;
143
+ }
144
+ } catch {
145
+ // A cache maintenance failure must never block commit generation.
146
+ }
147
+ }
148
+
149
+ export function createAnalysisCache({ projectRoot, snapshotFingerprint, config, protect = true }) {
150
+ const settings = config.largeChange?.cache;
151
+ if (
152
+ !settings?.enabled ||
153
+ config.largeChange?.strategy !== 'deep' ||
154
+ !SHA256_RE.test(snapshotFingerprint || '') ||
155
+ (!protect && !settings.allowUnprotected)
156
+ ) {
157
+ return null;
158
+ }
159
+
160
+ try {
161
+ const root = cacheRoot(projectRoot);
162
+ const signature = namespaceSignature(config, protect);
163
+ const namespace = join(root, `${snapshotFingerprint}.${signature}`);
164
+ prune(root, settings);
165
+ mkdirSync(namespace, { recursive: true, mode: 0o700 });
166
+
167
+ return {
168
+ keyFor(task, input) {
169
+ return digest({
170
+ contractVersion: ANALYSIS_CONTRACT_VERSION,
171
+ signature,
172
+ task,
173
+ input,
174
+ });
175
+ },
176
+ read(key, expectedIds, validate) {
177
+ if (!SHA256_RE.test(key)) return null;
178
+ const path = join(namespace, `${key}.json`);
179
+ try {
180
+ const stat = lstatSync(path);
181
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_ENTRY_BYTES) return null;
182
+ const groups = validateEntry(JSON.parse(readFileSync(path, 'utf8')), expectedIds);
183
+ validate?.(groups);
184
+ const now = new Date();
185
+ utimesSync(namespace, now, now);
186
+ return groups;
187
+ } catch {
188
+ return null;
189
+ }
190
+ },
191
+ write(key, ids, groups) {
192
+ if (!SHA256_RE.test(key)) return false;
193
+ let entry;
194
+ try {
195
+ entry = {
196
+ kind: ANALYSIS_CACHE_KIND,
197
+ version: ANALYSIS_CACHE_VERSION,
198
+ createdAt: new Date().toISOString(),
199
+ ids: [...ids],
200
+ groups: normalizeGroups(groups),
201
+ };
202
+ } catch {
203
+ return false;
204
+ }
205
+ const path = join(namespace, `${key}.json`);
206
+ const temporary = `${path}.${process.pid}.${Date.now()}.tmp`;
207
+ try {
208
+ const contents = JSON.stringify(entry) + '\n';
209
+ const bytes = Buffer.byteLength(contents);
210
+ const current = namespaceRecords(root).find((record) => record.path === namespace);
211
+ let existingBytes = 0;
212
+ try {
213
+ existingBytes = lstatSync(path).size;
214
+ } catch (error) {
215
+ if (error.code !== 'ENOENT') return false;
216
+ }
217
+ if (
218
+ bytes > MAX_ENTRY_BYTES ||
219
+ (current?.bytes || 0) - existingBytes + bytes > settings.maxBytes
220
+ ) {
221
+ return false;
222
+ }
223
+ writeFileSync(temporary, contents, { encoding: 'utf8', mode: 0o600 });
224
+ renameSync(temporary, path);
225
+ prune(root, settings, namespace);
226
+ return true;
227
+ } catch {
228
+ rmSync(temporary, { force: true });
229
+ return false;
230
+ }
231
+ },
232
+ clear() {
233
+ try {
234
+ rmSync(namespace, { recursive: true, force: true });
235
+ const parent = dirname(namespace);
236
+ if (existsSync(parent) && readdirSync(parent).length === 0) rmSync(parent);
237
+ } catch {
238
+ // Cache cleanup is best-effort and does not affect the completed result.
239
+ }
240
+ },
241
+ path: namespace,
242
+ };
243
+ } catch {
244
+ return null;
245
+ }
246
+ }