dotmd-cli 0.69.0 → 0.70.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +144 -964
- package/bin/dotmd.mjs +251 -202
- package/dotmd.config.example.mjs +5 -8
- package/package.json +6 -10
- package/src/agent-context.mjs +132 -0
- package/src/atomic-mutation.mjs +1505 -0
- package/src/baton.mjs +109 -114
- package/src/bulk-tag.mjs +7 -7
- package/src/check-collapse.mjs +2 -2
- package/src/commands.mjs +326 -12
- package/src/completions.mjs +38 -98
- package/src/config.mjs +18 -3
- package/src/diff.mjs +7 -3
- package/src/doctor.mjs +25 -15
- package/src/export.mjs +154 -25
- package/src/fix-refs.mjs +2 -0
- package/src/frontmatter-fix.mjs +9 -7
- package/src/frontmatter.mjs +3 -2
- package/src/git.mjs +722 -14
- package/src/graph.mjs +53 -25
- package/src/guard.mjs +163 -60
- package/src/hud.mjs +65 -76
- package/src/index-file.mjs +28 -16
- package/src/index.mjs +21 -13
- package/src/init.mjs +1 -1
- package/src/journal.mjs +145 -12
- package/src/lifecycle.mjs +596 -294
- package/src/lint.mjs +117 -56
- package/src/managed-path.mjs +192 -0
- package/src/migrate-prompts.mjs +2 -0
- package/src/migrate-template.mjs +2 -0
- package/src/migrate.mjs +7 -1
- package/src/new.mjs +135 -54
- package/src/output-identity.mjs +106 -0
- package/src/pickup-card.mjs +24 -10
- package/src/pickup.mjs +457 -0
- package/src/prompts.mjs +134 -75
- package/src/query.mjs +22 -10
- package/src/reference-planner.mjs +292 -0
- package/src/rename.mjs +65 -73
- package/src/render.mjs +24 -11
- package/src/runlist.mjs +109 -71
- package/src/section.mjs +2 -1
- package/src/ship.mjs +39 -20
- package/src/stats.mjs +1 -1
- package/src/status-metadata.mjs +87 -0
- package/src/statuses.mjs +11 -26
- package/src/summary.mjs +14 -3
- package/src/update.mjs +38 -10
- package/src/use.mjs +4 -1
- package/src/util.mjs +1 -0
- package/src/validate.mjs +53 -17
- package/src/watch.mjs +6 -1
- package/src/notion.mjs +0 -528
package/src/git.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { spawnSync } from 'node:child_process';
|
|
2
|
-
import { renameSync } from 'node:fs';
|
|
2
|
+
import { chmodSync, closeSync, existsSync, fsyncSync, linkSync, lstatSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
3
3
|
import path from 'node:path';
|
|
4
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
4
5
|
|
|
5
6
|
// Best-effort `git check-ignore` for a path. Returns true only when git
|
|
6
7
|
// definitively reports the path is ignored; any failure (not a repo, git
|
|
@@ -22,6 +23,13 @@ export function isGitIgnored(absPath, repoRoot) {
|
|
|
22
23
|
}
|
|
23
24
|
|
|
24
25
|
let gitChecked = false;
|
|
26
|
+
function assertSafeGitPaths(paths) {
|
|
27
|
+
for (const filePath of paths) {
|
|
28
|
+
if (!filePath || /[\0\r\n]/.test(filePath) || path.isAbsolute(filePath) || filePath.split(/[\\/]/).includes('..')) {
|
|
29
|
+
throw new Error(`Unsafe repository-relative Git path: ${filePath}`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
25
33
|
function ensureGit() {
|
|
26
34
|
if (gitChecked) return;
|
|
27
35
|
const result = spawnSync('git', ['--version'], { encoding: 'utf8' });
|
|
@@ -31,6 +39,10 @@ function ensureGit() {
|
|
|
31
39
|
gitChecked = true;
|
|
32
40
|
}
|
|
33
41
|
|
|
42
|
+
function literalGitPathspec(filePath) {
|
|
43
|
+
return filePath === '.' ? ':(top,literal)' : `:(top,literal)${filePath}`;
|
|
44
|
+
}
|
|
45
|
+
|
|
34
46
|
export function getGitLastModified(relPath, repoRoot) {
|
|
35
47
|
const result = spawnSync('git', ['log', '-1', '--format=%aI', '--', relPath], {
|
|
36
48
|
cwd: repoRoot,
|
|
@@ -50,22 +62,412 @@ export function getGitFirstAdded(relPath, repoRoot) {
|
|
|
50
62
|
return lines[lines.length - 1] ?? null;
|
|
51
63
|
}
|
|
52
64
|
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
65
|
+
const DEFAULT_GIT_METADATA_MAX_COMMITS = 10_000;
|
|
66
|
+
const DEFAULT_GIT_METADATA_MAX_BUFFER = 10 * 1024 * 1024;
|
|
67
|
+
const DEFAULT_GIT_METADATA_PATH_BATCH = 256;
|
|
68
|
+
const GIT_METADATA_HISTORY_PER_PATH = 16;
|
|
69
|
+
|
|
70
|
+
function boundedPositiveInteger(value, fallback, name) {
|
|
71
|
+
if (value == null) return fallback;
|
|
72
|
+
if (!Number.isSafeInteger(value) || value < 1) {
|
|
73
|
+
throw new TypeError(`${name} must be a positive integer`);
|
|
74
|
+
}
|
|
75
|
+
return value;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function unavailableGitHistory(result) {
|
|
79
|
+
if (result.error?.code === 'ENOENT') return true;
|
|
80
|
+
const detail = `${result.stderr ?? ''}\n${result.error?.message ?? ''}`;
|
|
81
|
+
return /not a git repository|does not have any commits yet|bad revision|unknown revision|ambiguous argument/i.test(detail);
|
|
82
|
+
}
|
|
58
83
|
|
|
59
|
-
|
|
84
|
+
function parseGitMetadataOutput(stdout, dates, commits, history, expectedPaths) {
|
|
85
|
+
const fields = String(stdout ?? '').split('\0');
|
|
60
86
|
let currentDate = null;
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
87
|
+
let currentCommit = null;
|
|
88
|
+
for (let i = 0; i < fields.length; i++) {
|
|
89
|
+
const field = fields[i];
|
|
90
|
+
if (field === 'dotmd:git-metadata:commit'
|
|
91
|
+
&& /^[0-9a-f]{40,64}$/i.test(fields[i + 1] ?? '')
|
|
92
|
+
&& /^\d{4}-\d{2}-\d{2}T/.test(fields[i + 2] ?? '')) {
|
|
93
|
+
currentCommit = fields[++i];
|
|
94
|
+
currentDate = fields[++i];
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
const filePath = field.startsWith('\n') ? field.slice(1) : field;
|
|
98
|
+
if (filePath && currentDate && expectedPaths.has(filePath)) {
|
|
99
|
+
if (!history.has(filePath)) history.set(filePath, []);
|
|
100
|
+
const entries = history.get(filePath);
|
|
101
|
+
if (entries.length < GIT_METADATA_HISTORY_PER_PATH && entries.at(-1)?.commit !== currentCommit) {
|
|
102
|
+
entries.push({ date: currentDate, commit: currentCommit });
|
|
103
|
+
}
|
|
104
|
+
if (!dates.has(filePath)) {
|
|
105
|
+
dates.set(filePath, currentDate);
|
|
106
|
+
commits.set(filePath, currentCommit);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Read latest Git dates only for the current managed paths. Every subprocess
|
|
113
|
+
// has explicit history, output, and path-count bounds. Callers must inspect
|
|
114
|
+
// `complete` before using missing dates as evidence that no history exists.
|
|
115
|
+
export function getGitLastModifiedBatch(repoRoot, relPaths, options = {}) {
|
|
116
|
+
const maxCommits = boundedPositiveInteger(options.maxCommits, DEFAULT_GIT_METADATA_MAX_COMMITS, 'maxCommits');
|
|
117
|
+
const maxBuffer = boundedPositiveInteger(options.maxBuffer, DEFAULT_GIT_METADATA_MAX_BUFFER, 'maxBuffer');
|
|
118
|
+
const maxPathsPerBatch = boundedPositiveInteger(options.maxPathsPerBatch, DEFAULT_GIT_METADATA_PATH_BATCH, 'maxPathsPerBatch');
|
|
119
|
+
const paths = [...new Set(relPaths ?? [])];
|
|
120
|
+
assertSafeGitPaths(paths);
|
|
121
|
+
if (paths.length === 0) return { dates: new Map(), commits: new Map(), history: new Map(), complete: true, reason: null };
|
|
122
|
+
// Full-tree callers can supply a small set of configured root pathspecs for
|
|
123
|
+
// diff extraction. Revision selection still uses the exact requested paths,
|
|
124
|
+
// so excluded or unrelated documents cannot consume the commit bound.
|
|
125
|
+
const scanPaths = options.pathspecs?.length ? [...new Set(options.pathspecs)] : paths;
|
|
126
|
+
assertSafeGitPaths(scanPaths);
|
|
127
|
+
const expectedPaths = new Set(paths);
|
|
128
|
+
const revision = options.revision ?? 'HEAD';
|
|
129
|
+
|
|
130
|
+
const dates = new Map();
|
|
131
|
+
const commitsByPath = new Map();
|
|
132
|
+
const history = new Map();
|
|
133
|
+
let reason = null;
|
|
134
|
+
const revisions = spawnSync('git', ['rev-list', '--stdin', `--max-count=${maxCommits + 1}`, revision], {
|
|
135
|
+
cwd: repoRoot,
|
|
136
|
+
encoding: 'utf8',
|
|
137
|
+
input: `--\n${paths.map(literalGitPathspec).join('\n')}\n`,
|
|
138
|
+
maxBuffer,
|
|
139
|
+
});
|
|
140
|
+
if (revisions.error?.code === 'ENOBUFS') {
|
|
141
|
+
reason = 'output-limit';
|
|
142
|
+
} else if (revisions.error || revisions.status !== 0) {
|
|
143
|
+
if (unavailableGitHistory(revisions)) return { dates, commits: commitsByPath, history, complete: true, reason: null };
|
|
144
|
+
return { dates, commits: commitsByPath, history, complete: false, reason: 'git-error' };
|
|
145
|
+
}
|
|
146
|
+
const revisionList = String(revisions.stdout ?? '')
|
|
147
|
+
.split('\n')
|
|
148
|
+
.filter(line => /^[0-9a-f]{40,64}$/i.test(line))
|
|
149
|
+
.slice(0, maxCommits);
|
|
150
|
+
if (revisionList.length === 0) return { dates, commits: commitsByPath, history, complete: reason === null, reason };
|
|
151
|
+
if (!reason && String(revisions.stdout ?? '').trim().split('\n').length > maxCommits) {
|
|
152
|
+
reason = 'commit-limit';
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
for (let offset = 0; offset < scanPaths.length; offset += maxPathsPerBatch) {
|
|
156
|
+
const batch = scanPaths.slice(offset, offset + maxPathsPerBatch);
|
|
157
|
+
const result = spawnSync('git', [
|
|
158
|
+
'diff-tree', '--stdin', '--root', '-r', '-z', '--format=%x00dotmd:git-metadata:commit%x00%H%x00%aI%x00', '--name-only', '--diff-filter=ACDMR', '--', ...batch.map(literalGitPathspec),
|
|
159
|
+
], { cwd: repoRoot, encoding: 'utf8', input: revisionList.join('\n') + '\n', maxBuffer });
|
|
160
|
+
parseGitMetadataOutput(result.stdout, dates, commitsByPath, history, expectedPaths);
|
|
161
|
+
|
|
162
|
+
if (result.error?.code === 'ENOBUFS') {
|
|
163
|
+
reason = 'output-limit';
|
|
164
|
+
} else if (result.error || result.status !== 0) {
|
|
165
|
+
reason = reason ?? 'git-error';
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// Reaching the history window is harmless when every requested tracked path
|
|
170
|
+
// already received a latest date. Only unresolved tracked paths require
|
|
171
|
+
// older history; untracked files legitimately have no Git date.
|
|
172
|
+
if (reason === 'commit-limit') {
|
|
173
|
+
const missing = paths.filter(filePath => !dates.has(filePath));
|
|
174
|
+
let unresolvedTracked = false;
|
|
175
|
+
let trackingCheckFailed = false;
|
|
176
|
+
for (let offset = 0; offset < missing.length; offset += maxPathsPerBatch) {
|
|
177
|
+
const batch = missing.slice(offset, offset + maxPathsPerBatch);
|
|
178
|
+
const result = spawnSync('git', ['ls-files', '-z', '--', ...batch.map(literalGitPathspec)], {
|
|
179
|
+
cwd: repoRoot, encoding: 'utf8', maxBuffer,
|
|
180
|
+
});
|
|
181
|
+
if (result.error || result.status !== 0) {
|
|
182
|
+
trackingCheckFailed = true;
|
|
183
|
+
break;
|
|
184
|
+
}
|
|
185
|
+
if (String(result.stdout ?? '').split('\0').some(Boolean)) {
|
|
186
|
+
unresolvedTracked = true;
|
|
187
|
+
break;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
if (!trackingCheckFailed && !unresolvedTracked) reason = null;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
return { dates, commits: commitsByPath, history, complete: reason === null, reason };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function parseBatchObjects(stdout, count) {
|
|
197
|
+
const output = Buffer.isBuffer(stdout) ? stdout : Buffer.from(stdout ?? '');
|
|
198
|
+
const objects = [];
|
|
199
|
+
let offset = 0;
|
|
200
|
+
while (objects.length < count && offset < output.length) {
|
|
201
|
+
const newline = output.indexOf(0x0a, offset);
|
|
202
|
+
if (newline < 0) return null;
|
|
203
|
+
const header = output.subarray(offset, newline).toString('utf8');
|
|
204
|
+
offset = newline + 1;
|
|
205
|
+
if (header.endsWith(' missing')) {
|
|
206
|
+
objects.push(null);
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
const size = Number(header.match(/\s(\d+)$/)?.[1]);
|
|
210
|
+
if (!Number.isSafeInteger(size) || size < 0 || offset + size > output.length) return null;
|
|
211
|
+
objects.push(output.subarray(offset, offset + size).toString('utf8'));
|
|
212
|
+
offset += size;
|
|
213
|
+
if (output[offset] === 0x0a) offset++;
|
|
214
|
+
}
|
|
215
|
+
return objects.length === count ? objects : null;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function withoutUpdatedLine(raw) {
|
|
219
|
+
if (raw == null) return null;
|
|
220
|
+
const eol = raw.startsWith('---\r\n') ? '\r\n' : raw.startsWith('---\n') ? '\n' : null;
|
|
221
|
+
if (!eol) return null;
|
|
222
|
+
const marker = `${eol}---${eol}`;
|
|
223
|
+
const end = raw.indexOf(marker, 3 + eol.length);
|
|
224
|
+
if (end < 0) return null;
|
|
225
|
+
const frontmatter = raw.slice(3 + eol.length, end).split(eol);
|
|
226
|
+
const index = frontmatter.findIndex(line => line.startsWith('updated:'));
|
|
227
|
+
if (index < 0) return { line: null, content: raw };
|
|
228
|
+
const [line] = frontmatter.splice(index, 1);
|
|
229
|
+
return { line, content: `---${eol}${frontmatter.join(eol)}${marker}${raw.slice(end + marker.length)}` };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function updatedOnlyPathsByCommit(repoRoot, byCommit, maxBuffer, maxPathsPerBatch) {
|
|
233
|
+
const entries = [...byCommit].flatMap(([commit, commitPaths]) => commitPaths.map(filePath => ({ commit, filePath })));
|
|
234
|
+
const paths = new Set();
|
|
235
|
+
// Blob contents are much larger than path metadata, so keep each bounded
|
|
236
|
+
// cat-file response comfortably below the shared output cap.
|
|
237
|
+
const batchSize = Math.min(maxPathsPerBatch, 32);
|
|
238
|
+
for (let offset = 0; offset < entries.length; offset += batchSize) {
|
|
239
|
+
const batch = entries.slice(offset, offset + batchSize);
|
|
240
|
+
if (batch.some(item => item.filePath.includes('\n'))) return { paths: new Set(), complete: false };
|
|
241
|
+
const specs = batch.flatMap(item => [`${item.commit}:${item.filePath}`, `${item.commit}^:${item.filePath}`]);
|
|
242
|
+
const result = spawnSync('git', ['cat-file', '--batch'], {
|
|
243
|
+
cwd: repoRoot, input: specs.join('\n') + '\n', maxBuffer,
|
|
244
|
+
});
|
|
245
|
+
if (result.error || result.status !== 0) {
|
|
246
|
+
return { paths: new Set(), complete: false };
|
|
247
|
+
}
|
|
248
|
+
const objects = parseBatchObjects(result.stdout, specs.length);
|
|
249
|
+
if (!objects) return { paths: new Set(), complete: false };
|
|
250
|
+
for (let i = 0; i < batch.length; i++) {
|
|
251
|
+
const current = withoutUpdatedLine(objects[i * 2]);
|
|
252
|
+
const parent = withoutUpdatedLine(objects[i * 2 + 1]);
|
|
253
|
+
if (!current || !parent || current.line === parent.line) continue;
|
|
254
|
+
if (current.content === parent.content) paths.add(`${batch[i].commit}\0${batch[i].filePath}`);
|
|
66
255
|
}
|
|
67
256
|
}
|
|
68
|
-
return
|
|
257
|
+
return { paths, complete: true };
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// Resolve the latest substantive date for paths whose latest commit may only
|
|
261
|
+
// have synchronized the top-level `updated:` line. Callers provide their first
|
|
262
|
+
// bounded history scan so normal paths pay no extra Git cost. Metadata-only
|
|
263
|
+
// paths are grouped by commit, then resolved from the retained history window
|
|
264
|
+
// (with a bounded parent fallback); consecutive sync-only commits are skipped.
|
|
265
|
+
export function getGitLastSubstantiveModifiedBatch(repoRoot, relPaths, initialMetadata, options = {}) {
|
|
266
|
+
const maxBuffer = boundedPositiveInteger(options.maxBuffer, DEFAULT_GIT_METADATA_MAX_BUFFER, 'maxBuffer');
|
|
267
|
+
const maxPathsPerBatch = boundedPositiveInteger(options.maxPathsPerBatch, DEFAULT_GIT_METADATA_PATH_BATCH, 'maxPathsPerBatch');
|
|
268
|
+
const paths = [...new Set(relPaths ?? [])];
|
|
269
|
+
assertSafeGitPaths(paths);
|
|
270
|
+
if (paths.length === 0) return { dates: new Map(), commits: new Map(), history: new Map(), complete: true, reason: null };
|
|
271
|
+
|
|
272
|
+
const initial = initialMetadata ?? getGitLastModifiedBatch(repoRoot, paths, options);
|
|
273
|
+
const dates = new Map(initial.dates);
|
|
274
|
+
const commits = new Map(initial.commits ?? []);
|
|
275
|
+
const history = new Map(initial.history ?? []);
|
|
276
|
+
let complete = initial.complete;
|
|
277
|
+
let reason = initial.reason;
|
|
278
|
+
const byCommit = new Map();
|
|
279
|
+
for (const filePath of paths) {
|
|
280
|
+
const commit = commits.get(filePath);
|
|
281
|
+
if (!commit) continue;
|
|
282
|
+
if (!byCommit.has(commit)) byCommit.set(commit, []);
|
|
283
|
+
byCommit.get(commit).push(filePath);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const classification = updatedOnlyPathsByCommit(repoRoot, byCommit, maxBuffer, maxPathsPerBatch);
|
|
287
|
+
if (!classification.complete) {
|
|
288
|
+
complete = false;
|
|
289
|
+
reason = reason ?? 'git-error';
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
for (const [commit, commitPaths] of byCommit) {
|
|
293
|
+
const metadataOnly = commitPaths.filter(filePath => classification.paths.has(`${commit}\0${filePath}`));
|
|
294
|
+
if (metadataOnly.length === 0) continue;
|
|
295
|
+
|
|
296
|
+
const older = {
|
|
297
|
+
dates: new Map(), commits: new Map(), history: new Map(),
|
|
298
|
+
complete: initial.complete, reason: initial.reason,
|
|
299
|
+
};
|
|
300
|
+
const unresolved = [];
|
|
301
|
+
for (const filePath of metadataOnly) {
|
|
302
|
+
const entries = history.get(filePath) ?? [];
|
|
303
|
+
const currentIndex = entries.findIndex(entry => entry.commit === commit);
|
|
304
|
+
const remaining = currentIndex >= 0 ? entries.slice(currentIndex + 1) : [];
|
|
305
|
+
if (remaining.length === 0) {
|
|
306
|
+
unresolved.push(filePath);
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
309
|
+
older.dates.set(filePath, remaining[0].date);
|
|
310
|
+
older.commits.set(filePath, remaining[0].commit);
|
|
311
|
+
older.history.set(filePath, remaining);
|
|
312
|
+
}
|
|
313
|
+
if (unresolved.length > 0) {
|
|
314
|
+
older.complete = false;
|
|
315
|
+
older.reason = older.reason ?? 'commit-limit';
|
|
316
|
+
}
|
|
317
|
+
const substantive = getGitLastSubstantiveModifiedBatch(repoRoot, metadataOnly, older, options);
|
|
318
|
+
complete = complete && substantive.complete;
|
|
319
|
+
reason = reason ?? substantive.reason;
|
|
320
|
+
for (const filePath of metadataOnly) {
|
|
321
|
+
if (substantive.dates.has(filePath)) {
|
|
322
|
+
dates.set(filePath, substantive.dates.get(filePath));
|
|
323
|
+
commits.set(filePath, substantive.commits.get(filePath));
|
|
324
|
+
if (substantive.history.has(filePath)) history.set(filePath, substantive.history.get(filePath));
|
|
325
|
+
} else {
|
|
326
|
+
dates.delete(filePath);
|
|
327
|
+
commits.delete(filePath);
|
|
328
|
+
history.delete(filePath);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
return { dates, commits, history, complete, reason };
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function parseNullPaths(result) {
|
|
337
|
+
if (result.error || result.status !== 0) return [];
|
|
338
|
+
return result.stdout.split('\0').filter(Boolean);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
function parsePorcelainRecords(result) {
|
|
342
|
+
if (result.error || result.status !== 0) return [];
|
|
343
|
+
const fields = result.stdout.split('\0').filter(Boolean);
|
|
344
|
+
const records = [];
|
|
345
|
+
for (let i = 0; i < fields.length; i++) {
|
|
346
|
+
const field = fields[i];
|
|
347
|
+
if (field.length < 4 || field[2] !== ' ') continue;
|
|
348
|
+
const status = field.slice(0, 2);
|
|
349
|
+
records.push({ status, path: field.slice(3) });
|
|
350
|
+
// In porcelain v1 -z, rename/copy records put the destination first and
|
|
351
|
+
// the old source path in the following NUL field. The command includes the
|
|
352
|
+
// destination state, not the now-missing live source.
|
|
353
|
+
if (/[RC]/.test(status)) i += 1;
|
|
354
|
+
}
|
|
355
|
+
return records;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
function parseShortOptions(arg, valueOptions = new Set()) {
|
|
359
|
+
const parsed = { options: new Set(), consumesNext: false };
|
|
360
|
+
if (!/^-[^-]/.test(arg)) return parsed;
|
|
361
|
+
const chars = arg.slice(1);
|
|
362
|
+
for (let i = 0; i < chars.length; i++) {
|
|
363
|
+
const option = chars[i];
|
|
364
|
+
parsed.options.add(option);
|
|
365
|
+
if (valueOptions.has(option)) {
|
|
366
|
+
parsed.consumesNext = i === chars.length - 1;
|
|
367
|
+
break; // remaining characters are this option's attached value
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
return parsed;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
function hasShortOption(args, option, valueOptions = new Set()) {
|
|
374
|
+
return args.some(arg => parseShortOptions(arg, valueOptions).options.has(option));
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function gitPathspecs(args, subcommand) {
|
|
378
|
+
const separator = args.indexOf('--');
|
|
379
|
+
if (separator >= 0) return args.slice(separator + 1);
|
|
380
|
+
const valueFlags = subcommand === 'commit'
|
|
381
|
+
? new Set(['-m', '--message', '-F', '--file', '-C', '-c', '--reuse-message', '--reedit-message', '-t', '--template', '--author', '--date', '--cleanup', '--fixup', '--squash', '--trailer'])
|
|
382
|
+
: new Set(['--chmod', '--pathspec-from-file']);
|
|
383
|
+
const paths = [];
|
|
384
|
+
for (let i = 0; i < args.length; i++) {
|
|
385
|
+
const arg = args[i];
|
|
386
|
+
if (valueFlags.has(arg)) { i += 1; continue; }
|
|
387
|
+
if (subcommand === 'commit' && /^-[^-]/.test(arg)) {
|
|
388
|
+
const short = parseShortOptions(arg, new Set(['m', 'F', 'C', 'c', 't', 'S']));
|
|
389
|
+
if (short.consumesNext) i += 1;
|
|
390
|
+
continue;
|
|
391
|
+
}
|
|
392
|
+
if (arg.startsWith('-')) continue;
|
|
393
|
+
paths.push(arg);
|
|
394
|
+
}
|
|
395
|
+
return paths;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// Paths a broad `git add`/`git commit` would actually include. Read-only and
|
|
399
|
+
// fail-open: any Git error returns an empty list so the PreToolUse guard never
|
|
400
|
+
// blocks on an uncertain repository state.
|
|
401
|
+
export function inspectGitCommandPaths(subcommand, args, repoRoot) {
|
|
402
|
+
try {
|
|
403
|
+
if ((subcommand === 'add' || subcommand === 'stage')
|
|
404
|
+
&& (hasShortOption(args, 'n') || args.includes('--dry-run'))) return [];
|
|
405
|
+
if (subcommand === 'commit' && args.includes('--dry-run')) return [];
|
|
406
|
+
const pathspecs = gitPathspecs(args, subcommand);
|
|
407
|
+
if (subcommand === 'add' || subcommand === 'stage') {
|
|
408
|
+
const cmd = ['status', '--porcelain=v1', '-z', '--untracked-files=all'];
|
|
409
|
+
if (pathspecs.length > 0) cmd.push('--', ...pathspecs);
|
|
410
|
+
const updateOnly = hasShortOption(args, 'u') || args.includes('--update');
|
|
411
|
+
const records = parsePorcelainRecords(spawnSync('git', cmd, { cwd: repoRoot, encoding: 'utf8' }));
|
|
412
|
+
const paths = records
|
|
413
|
+
.filter(record => !updateOnly || record.status !== '??')
|
|
414
|
+
.map(record => record.path)
|
|
415
|
+
.filter(candidate => existsSync(path.resolve(repoRoot, candidate)));
|
|
416
|
+
const forceAll = hasShortOption(args, 'A') || args.includes('--all');
|
|
417
|
+
if ((hasShortOption(args, 'f') || args.includes('--force')) && (pathspecs.length > 0 || forceAll)) {
|
|
418
|
+
const ignoredCmd = ['ls-files', '--others', '--ignored', '--exclude-standard', '-z'];
|
|
419
|
+
if (pathspecs.length > 0) ignoredCmd.push('--', ...pathspecs);
|
|
420
|
+
paths.push(...parseNullPaths(spawnSync('git', ignoredCmd, { cwd: repoRoot, encoding: 'utf8' })));
|
|
421
|
+
}
|
|
422
|
+
return [...new Set(paths)];
|
|
423
|
+
}
|
|
424
|
+
if (subcommand !== 'commit') return [];
|
|
425
|
+
|
|
426
|
+
const commands = [];
|
|
427
|
+
const commitValueOptions = new Set(['m', 'F', 'C', 'c', 't', 'S']);
|
|
428
|
+
const commitAll = args.includes('--all') || hasShortOption(args, 'a', commitValueOptions);
|
|
429
|
+
if (pathspecs.length > 0) {
|
|
430
|
+
const hasHead = spawnSync('git', ['rev-parse', '--verify', 'HEAD'], { cwd: repoRoot, encoding: 'utf8' }).status === 0;
|
|
431
|
+
if (hasHead) commands.push(['diff', 'HEAD', '--name-only', '--diff-filter=ACMR', '-z', '--', ...pathspecs]);
|
|
432
|
+
else commands.push(['diff', '--cached', '--name-only', '--diff-filter=ACMR', '-z', '--', ...pathspecs]);
|
|
433
|
+
if (args.includes('-i') || args.includes('--include')) {
|
|
434
|
+
commands.push(['diff', '--cached', '--name-only', '--diff-filter=ACMR', '-z']);
|
|
435
|
+
}
|
|
436
|
+
} else if (commitAll) {
|
|
437
|
+
// commit -a replaces tracked index entries with worktree state. Comparing
|
|
438
|
+
// HEAD directly to the worktree models that final commit and avoids a
|
|
439
|
+
// false deny when a staged prompt change was subsequently reverted.
|
|
440
|
+
commands.push(['diff', 'HEAD', '--name-only', '--diff-filter=ACMR', '-z']);
|
|
441
|
+
} else {
|
|
442
|
+
commands.push(['diff', '--cached', '--name-only', '--diff-filter=ACMR', '-z']);
|
|
443
|
+
}
|
|
444
|
+
return [...new Set(commands.flatMap(cmd => parseNullPaths(spawnSync('git', cmd, { cwd: repoRoot, encoding: 'utf8' }))))];
|
|
445
|
+
} catch {
|
|
446
|
+
return [];
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
export function listStagedPaths(repoRoot) {
|
|
451
|
+
const result = spawnSync('git', ['diff', '--cached', '--name-only', '--no-renames', '-z'], {
|
|
452
|
+
cwd: repoRoot,
|
|
453
|
+
encoding: 'utf8',
|
|
454
|
+
});
|
|
455
|
+
if (result.error || result.status !== 0) {
|
|
456
|
+
throw new Error(`Cannot inspect staged files: ${result.error?.message || result.stderr.trim() || 'git diff failed'}`);
|
|
457
|
+
}
|
|
458
|
+
return result.stdout.split('\0').filter(Boolean);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
export function assertGitIndex(repoRoot, expectedPaths = []) {
|
|
462
|
+
const actual = [...new Set(listStagedPaths(repoRoot))].sort();
|
|
463
|
+
const expected = [...new Set(expectedPaths)].sort();
|
|
464
|
+
if (actual.length === expected.length && actual.every((item, index) => item === expected[index])) {
|
|
465
|
+
return actual;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
const expectedLabel = expected.length > 0 ? expected.join(', ') : 'empty';
|
|
469
|
+
const actualLabel = actual.length > 0 ? actual.join(', ') : 'empty';
|
|
470
|
+
throw new Error(`Git index mismatch (expected: ${expectedLabel}; staged: ${actualLabel}). Commit or unstage existing work before releasing.`);
|
|
69
471
|
}
|
|
70
472
|
|
|
71
473
|
export function gitMv(source, target, repoRoot) {
|
|
@@ -91,7 +493,7 @@ export function gitMv(source, target, repoRoot) {
|
|
|
91
493
|
return { status: result.status, stderr: result.stderr };
|
|
92
494
|
}
|
|
93
495
|
|
|
94
|
-
function isTracked(source, repoRoot) {
|
|
496
|
+
export function isTracked(source, repoRoot) {
|
|
95
497
|
const relSource = path.isAbsolute(source) ? path.relative(repoRoot, source) : source;
|
|
96
498
|
const result = spawnSync('git', ['ls-files', '--error-unmatch', '--', relSource], {
|
|
97
499
|
cwd: repoRoot,
|
|
@@ -100,6 +502,312 @@ function isTracked(source, repoRoot) {
|
|
|
100
502
|
return result.status === 0;
|
|
101
503
|
}
|
|
102
504
|
|
|
505
|
+
export function gitIndexLocations(repoRoot) {
|
|
506
|
+
const result = spawnSync('git', ['rev-parse', '--git-dir'], { cwd: repoRoot, encoding: 'utf8' });
|
|
507
|
+
if (result.error || result.status !== 0) throw new Error(`Could not locate Git directory: ${result.error?.message || result.stderr.trim()}`);
|
|
508
|
+
const gitDir = path.resolve(repoRoot, result.stdout.trim());
|
|
509
|
+
const indexPath = process.env.GIT_INDEX_FILE ? path.resolve(repoRoot, process.env.GIT_INDEX_FILE) : path.join(gitDir, 'index');
|
|
510
|
+
return { gitDir, indexPath, indexDir: path.dirname(indexPath), lockPath: `${indexPath}.lock` };
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
function generationFromBytes(bytes, indexPath, mode) {
|
|
514
|
+
return { exists: true, hash: createHash('sha256').update(bytes).digest('hex'), size: bytes.length, content: bytes.toString('base64'), mode, indexPath };
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
function captureIndexPath(indexPath) {
|
|
518
|
+
if (!existsSync(indexPath)) return { exists: false, hash: null, size: 0, content: null, mode: null, indexPath };
|
|
519
|
+
const stat = lstatSync(indexPath);
|
|
520
|
+
if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`Selected Git index is not a regular file: ${indexPath}`);
|
|
521
|
+
return generationFromBytes(readFileSync(indexPath), indexPath, stat.mode & 0o7777);
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
export function captureGitIndexGeneration(repoRoot) {
|
|
525
|
+
return captureIndexPath(gitIndexLocations(repoRoot).indexPath);
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
export function sameGitIndexGeneration(left, right) {
|
|
529
|
+
return Boolean(left && right && left.indexPath === right.indexPath && left.exists === right.exists
|
|
530
|
+
&& left.hash === right.hash && left.size === right.size && left.mode === right.mode);
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
function fsyncIndexDirectory(directory, testHooks, reason) {
|
|
534
|
+
testHooks?.beforeGitIndexDirectoryFsync?.({ directory, reason });
|
|
535
|
+
const dirFd = openSync(directory, 'r');
|
|
536
|
+
try { fsyncSync(dirFd); } catch (err) { if (!['EINVAL', 'ENOTSUP', 'EBADF', 'EISDIR', 'EPERM'].includes(err?.code)) throw err; } finally { closeSync(dirFd); }
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
function writeGeneration(filePath, generation, mode = generation.mode ?? (0o666 & ~process.umask())) {
|
|
540
|
+
const bytes = generation.exists ? Buffer.from(generation.content, 'base64') : Buffer.alloc(0);
|
|
541
|
+
if (generation.exists && (bytes.length !== generation.size || createHash('sha256').update(bytes).digest('hex') !== generation.hash)) throw new Error('Invalid captured Git index generation.');
|
|
542
|
+
const fd = openSync(filePath, 'wx', mode);
|
|
543
|
+
try { writeFileSync(fd, bytes); fsyncSync(fd); } finally { closeSync(fd); }
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
function describePrepared(preparedPath, generation) {
|
|
547
|
+
const stat = lstatSync(preparedPath);
|
|
548
|
+
if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`Prepared Git index is unsafe: ${preparedPath}`);
|
|
549
|
+
const bytes = readFileSync(preparedPath);
|
|
550
|
+
return {
|
|
551
|
+
path: preparedPath,
|
|
552
|
+
dev: stat.dev,
|
|
553
|
+
ino: stat.ino,
|
|
554
|
+
mode: stat.mode & 0o7777,
|
|
555
|
+
size: bytes.length,
|
|
556
|
+
hash: createHash('sha256').update(bytes).digest('hex'),
|
|
557
|
+
generation,
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
function preparedMatches(prepared) {
|
|
562
|
+
try {
|
|
563
|
+
const stat = lstatSync(prepared.path);
|
|
564
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.dev !== prepared.dev || stat.ino !== prepared.ino || (stat.mode & 0o7777) !== prepared.mode || stat.size !== prepared.size) return false;
|
|
565
|
+
return createHash('sha256').update(readFileSync(prepared.path)).digest('hex') === prepared.hash;
|
|
566
|
+
} catch { return false; }
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
function unlinkPrepared(prepared, testHooks = null, reason = 'prepared-delete') {
|
|
570
|
+
if (prepared && preparedMatches(prepared)) {
|
|
571
|
+
unlinkSync(prepared.path);
|
|
572
|
+
fsyncIndexDirectory(path.dirname(prepared.path), testHooks, reason);
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
function prepareMoveIndex(source, target, repoRoot, before, options = {}) {
|
|
577
|
+
const testHooks = options.testHooks ?? {};
|
|
578
|
+
const paths = [source, target].map(candidate => path.isAbsolute(candidate) ? path.relative(repoRoot, candidate) : candidate);
|
|
579
|
+
assertSafeGitPaths(paths);
|
|
580
|
+
const { indexDir } = gitIndexLocations(repoRoot);
|
|
581
|
+
const preparedPath = path.join(indexDir, `.dotmd-index-${process.pid}-${randomUUID()}`);
|
|
582
|
+
const artifactPath = options.artifactPath ?? preparedPath;
|
|
583
|
+
writeGeneration(artifactPath, before);
|
|
584
|
+
let seed = { ...describePrepared(artifactPath, before), state: 'preparing', tempPath: preparedPath, work: null };
|
|
585
|
+
testHooks.afterGitIndexArtifact?.({ before, prepared: seed });
|
|
586
|
+
if (artifactPath !== preparedPath && before.exists) {
|
|
587
|
+
try { linkSync(artifactPath, preparedPath); }
|
|
588
|
+
catch (err) {
|
|
589
|
+
if (err?.code !== 'EXDEV') throw err;
|
|
590
|
+
writeGeneration(preparedPath, before);
|
|
591
|
+
seed = { ...seed, work: describePrepared(preparedPath, before) };
|
|
592
|
+
testHooks.afterGitIndexWorkSeed?.({ before, prepared: seed });
|
|
593
|
+
}
|
|
594
|
+
fsyncIndexDirectory(indexDir, testHooks, 'working-index-link');
|
|
595
|
+
}
|
|
596
|
+
testHooks.beforeGitIndexPrepare?.({ preparedPath, before, prepared: seed });
|
|
597
|
+
const env = { ...process.env, GIT_INDEX_FILE: preparedPath };
|
|
598
|
+
const result = spawnSync('git', ['add', '-A', '--', paths[1]], {
|
|
599
|
+
cwd: repoRoot,
|
|
600
|
+
encoding: 'utf8',
|
|
601
|
+
env,
|
|
602
|
+
});
|
|
603
|
+
let preCheckpointError = null;
|
|
604
|
+
try { testHooks.afterGitIndexSubprocessBeforeCheckpoint?.({ preparedPath, before, prepared: seed, step: 'target-added', result }); }
|
|
605
|
+
catch (err) { preCheckpointError = err; }
|
|
606
|
+
fsyncIndexDirectory(indexDir, testHooks, 'working-index-step');
|
|
607
|
+
const prepareStep = existsSync(preparedPath) ? { ...seed, work: describePrepared(preparedPath, captureIndexPath(preparedPath)) } : seed;
|
|
608
|
+
if (prepareStep.work) prepareStep.work.generation.indexPath = before.indexPath;
|
|
609
|
+
testHooks.afterGitIndexPrepareStep?.({ preparedPath, before, prepared: prepareStep, step: 'target-added' });
|
|
610
|
+
if (preCheckpointError) throw preCheckpointError;
|
|
611
|
+
if (result.error || result.status !== 0) {
|
|
612
|
+
throw new Error(`Could not stage moved document: ${result.error?.message || result.stderr.trim() || 'git add failed'}`);
|
|
613
|
+
}
|
|
614
|
+
testHooks.duringGitIndexPrepare?.({ preparedPath, before, prepared: prepareStep, step: 'target-added' });
|
|
615
|
+
const removed = spawnSync('git', ['update-index', '--remove', '--', paths[0]], { cwd: repoRoot, encoding: 'utf8', env });
|
|
616
|
+
preCheckpointError = null;
|
|
617
|
+
try { testHooks.afterGitIndexSubprocessBeforeCheckpoint?.({ preparedPath, before, prepared: prepareStep, step: 'source-removed', result: removed }); }
|
|
618
|
+
catch (err) { preCheckpointError = err; }
|
|
619
|
+
fsyncIndexDirectory(indexDir, testHooks, 'working-index-step');
|
|
620
|
+
const removedStep = existsSync(preparedPath) ? { ...seed, work: describePrepared(preparedPath, captureIndexPath(preparedPath)) } : prepareStep;
|
|
621
|
+
if (removedStep.work) removedStep.work.generation.indexPath = before.indexPath;
|
|
622
|
+
testHooks.afterGitIndexPrepareStep?.({ preparedPath, before, prepared: removedStep, step: 'source-removed' });
|
|
623
|
+
if (preCheckpointError) throw preCheckpointError;
|
|
624
|
+
if (removed.error || removed.status !== 0) {
|
|
625
|
+
throw new Error(`Could not stage moved document source removal: ${removed.error?.message || removed.stderr.trim() || 'git update-index failed'}`);
|
|
626
|
+
}
|
|
627
|
+
if (before.exists && (lstatSync(preparedPath).mode & 0o7777) !== before.mode) {
|
|
628
|
+
chmodSync(preparedPath, before.mode);
|
|
629
|
+
const fd = openSync(preparedPath, 'r+');
|
|
630
|
+
try { fsyncSync(fd); } finally { closeSync(fd); }
|
|
631
|
+
}
|
|
632
|
+
const generation = captureIndexPath(preparedPath);
|
|
633
|
+
generation.indexPath = before.indexPath;
|
|
634
|
+
const work = describePrepared(preparedPath, generation);
|
|
635
|
+
if (artifactPath !== preparedPath) {
|
|
636
|
+
writeFileSync(artifactPath, readFileSync(preparedPath));
|
|
637
|
+
chmodSync(artifactPath, generation.mode);
|
|
638
|
+
const artifactFd = openSync(artifactPath, 'r+');
|
|
639
|
+
try { fsyncSync(artifactFd); } finally { closeSync(artifactFd); }
|
|
640
|
+
}
|
|
641
|
+
const prepared = { ...describePrepared(artifactPath, generation), state: 'prepared', tempPath: preparedPath, work };
|
|
642
|
+
testHooks.afterGitIndexPrepared?.({ preparedPath, before, generation, prepared });
|
|
643
|
+
return prepared;
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
function publishIndexGeneration(repoRoot, expected, desired, prepared, testHooks = {}) {
|
|
647
|
+
const { indexPath, indexDir, lockPath } = gitIndexLocations(repoRoot);
|
|
648
|
+
if (expected.indexPath !== indexPath || desired.indexPath !== indexPath) throw new Error('Selected Git index changed since the transaction snapshot; recovery refused to target a different index.');
|
|
649
|
+
if (!prepared || prepared.state !== 'prepared' || path.dirname(prepared.tempPath) !== indexDir || !path.basename(prepared.tempPath).startsWith('.dotmd-index-') || !preparedMatches(prepared)) throw new Error('Prepared Git index ownership could not be verified.');
|
|
650
|
+
if ((desired.exists && (prepared.hash !== desired.hash || prepared.size !== desired.size || prepared.mode !== desired.mode)) || (!desired.exists && prepared.size !== 0)) throw new Error('Prepared Git index artifact does not match the desired generation.');
|
|
651
|
+
const publication = prepared.work ?? prepared;
|
|
652
|
+
if (!preparedMatches(publication) || (desired.exists && (publication.hash !== desired.hash || publication.size !== desired.size || publication.mode !== desired.mode)) || (!desired.exists && publication.size !== 0)) throw new Error('Selected-directory Git working index does not match the desired generation.');
|
|
653
|
+
let lockOwned = false;
|
|
654
|
+
try {
|
|
655
|
+
linkSync(publication.path, lockPath);
|
|
656
|
+
lockOwned = true;
|
|
657
|
+
fsyncIndexDirectory(indexDir, testHooks, 'lock-acquisition');
|
|
658
|
+
} catch (err) {
|
|
659
|
+
if (lockOwned) {
|
|
660
|
+
try {
|
|
661
|
+
const lock = lstatSync(lockPath);
|
|
662
|
+
if (lock.dev === publication.dev && lock.ino === publication.ino) {
|
|
663
|
+
unlinkSync(lockPath);
|
|
664
|
+
fsyncIndexDirectory(indexDir, null, 'lock-acquisition-rollback');
|
|
665
|
+
}
|
|
666
|
+
} catch { /* retain original durability error */ }
|
|
667
|
+
}
|
|
668
|
+
if (err?.code === 'EEXIST') throw new Error('Git index is locked by another process; transaction index publication was not attempted.');
|
|
669
|
+
throw err;
|
|
670
|
+
}
|
|
671
|
+
let published = false;
|
|
672
|
+
try {
|
|
673
|
+
testHooks.afterGitIndexLock?.({ lockPath, expected, desired });
|
|
674
|
+
const current = captureIndexPath(indexPath);
|
|
675
|
+
if (!sameGitIndexGeneration(current, expected)) throw new Error('Git index changed before transaction publication; current staging was preserved.');
|
|
676
|
+
testHooks.afterGitIndexCompare?.({ lockPath, current, desired });
|
|
677
|
+
if (desired.exists) {
|
|
678
|
+
renameSync(lockPath, indexPath);
|
|
679
|
+
lockOwned = false;
|
|
680
|
+
} else {
|
|
681
|
+
if (existsSync(indexPath)) unlinkSync(indexPath);
|
|
682
|
+
const lock = lstatSync(lockPath);
|
|
683
|
+
if (!lock.isFile() || lock.isSymbolicLink() || lock.dev !== publication.dev || lock.ino !== publication.ino) throw new Error('Transaction-owned Git index lock was replaced before deletion.');
|
|
684
|
+
unlinkSync(lockPath);
|
|
685
|
+
lockOwned = false;
|
|
686
|
+
}
|
|
687
|
+
published = true;
|
|
688
|
+
fsyncIndexDirectory(indexDir, testHooks, 'publication');
|
|
689
|
+
testHooks.afterGitIndexPublication?.({ indexPath, desired });
|
|
690
|
+
return desired;
|
|
691
|
+
} finally {
|
|
692
|
+
if (!published && lockOwned) {
|
|
693
|
+
try {
|
|
694
|
+
const lock = lstatSync(lockPath);
|
|
695
|
+
if (lock.dev === publication.dev && lock.ino === publication.ino) {
|
|
696
|
+
unlinkSync(lockPath);
|
|
697
|
+
fsyncIndexDirectory(indexDir, testHooks, 'failed-lock-delete');
|
|
698
|
+
}
|
|
699
|
+
} catch (err) {
|
|
700
|
+
if (err?.code !== 'ENOENT') throw err;
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
export function stageMovePathsCas(source, target, repoRoot, before, options = {}) {
|
|
707
|
+
const prepared = prepareMoveIndex(source, target, repoRoot, before, options);
|
|
708
|
+
try { return publishIndexGeneration(repoRoot, before, prepared.generation, prepared, options.testHooks); }
|
|
709
|
+
finally {
|
|
710
|
+
if (prepared.work && prepared.work.path !== prepared.path) unlinkPrepared(prepared.work, options.testHooks, 'working-index-delete');
|
|
711
|
+
unlinkPrepared(prepared, options.testHooks);
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
export function restoreGitIndexCas(before, ownedAfter, repoRoot, options = {}) {
|
|
716
|
+
const { indexDir } = gitIndexLocations(repoRoot);
|
|
717
|
+
const preparedPath = options.artifactPath ?? path.join(indexDir, `.dotmd-index-restore-${process.pid}-${randomUUID()}`);
|
|
718
|
+
let artifact = null;
|
|
719
|
+
try {
|
|
720
|
+
writeGeneration(preparedPath, before);
|
|
721
|
+
const prepared = before;
|
|
722
|
+
const tempPath = path.join(indexDir, `.dotmd-index-restore-${process.pid}-${randomUUID()}`);
|
|
723
|
+
artifact = { ...describePrepared(preparedPath, prepared), state: 'preparing', tempPath, work: null };
|
|
724
|
+
options.testHooks?.afterGitRestoreArtifact?.({ before, ownedAfter, prepared: artifact });
|
|
725
|
+
writeGeneration(tempPath, before);
|
|
726
|
+
const work = describePrepared(tempPath, prepared);
|
|
727
|
+
artifact = { ...artifact, state: 'prepared', work };
|
|
728
|
+
options.testHooks?.afterGitRestorePrepared?.({ before, ownedAfter, preparedPath, prepared: artifact });
|
|
729
|
+
return publishIndexGeneration(repoRoot, ownedAfter, prepared, artifact, options.testHooks);
|
|
730
|
+
} finally {
|
|
731
|
+
if (artifact?.work) unlinkPrepared(artifact.work, options.testHooks, 'restore-working-index-delete');
|
|
732
|
+
unlinkPrepared(artifact, options.testHooks, 'restore-prepared-delete');
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
export function reclaimPreparedGitIndex(manifestGitIndex, repoRoot, options = {}) {
|
|
737
|
+
const prepared = manifestGitIndex?.prepared;
|
|
738
|
+
if (!prepared) return { cleaned: false, retainedPaths: [] };
|
|
739
|
+
const retainedPaths = [];
|
|
740
|
+
const { indexPath, indexDir, lockPath } = gitIndexLocations(repoRoot);
|
|
741
|
+
if (manifestGitIndex.before?.indexPath !== indexPath || prepared.generation?.indexPath !== indexPath) throw new Error('Recovery environment selects a different Git index than the abandoned transaction.');
|
|
742
|
+
if (path.dirname(prepared.tempPath) !== indexDir || !path.basename(prepared.tempPath).startsWith('.dotmd-index-')) throw new Error('Abandoned prepared Git index path is unsafe.');
|
|
743
|
+
if (!existsSync(prepared.path)) {
|
|
744
|
+
if (existsSync(lockPath)) throw new Error('Git index lock exists without its recorded prepared inode; it was preserved.');
|
|
745
|
+
if (existsSync(prepared.tempPath)) retainedPaths.push(prepared.tempPath);
|
|
746
|
+
return { cleaned: false, retainedPaths };
|
|
747
|
+
}
|
|
748
|
+
if (!preparedMatches(prepared)) throw new Error('Abandoned prepared Git index ownership could not be verified.');
|
|
749
|
+
if (existsSync(prepared.tempPath)) {
|
|
750
|
+
const expectedWork = prepared.work ?? { ...prepared, path: prepared.tempPath };
|
|
751
|
+
if (!preparedMatches(expectedWork)) {
|
|
752
|
+
if (prepared.state !== 'preparing') throw new Error('Abandoned Git working index is foreign or unverified; it was preserved.');
|
|
753
|
+
retainedPaths.push(prepared.tempPath);
|
|
754
|
+
} else {
|
|
755
|
+
unlinkPrepared(expectedWork, options.testHooks, 'recovery-working-index-delete');
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
if (existsSync(lockPath)) {
|
|
759
|
+
const lock = lstatSync(lockPath);
|
|
760
|
+
const publication = prepared.work ?? prepared;
|
|
761
|
+
if (!lock.isFile() || lock.isSymbolicLink() || lock.dev !== publication.dev || lock.ino !== publication.ino) throw new Error('Git index lock is foreign; it was preserved.');
|
|
762
|
+
unlinkSync(lockPath);
|
|
763
|
+
fsyncIndexDirectory(indexDir, options.testHooks, 'recovery-lock-delete');
|
|
764
|
+
}
|
|
765
|
+
unlinkPrepared(prepared, options.testHooks, 'recovery-prepared-delete');
|
|
766
|
+
return { cleaned: true, retainedPaths };
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
export function stageMovePaths(source, target, repoRoot) {
|
|
770
|
+
const before = captureGitIndexGeneration(repoRoot);
|
|
771
|
+
return stageMovePathsCas(source, target, repoRoot, before);
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
// Legacy selected-path helpers remain read-only compatibility surfaces.
|
|
775
|
+
export function captureGitIndexPaths(paths, repoRoot) {
|
|
776
|
+
const relative = paths.map(candidate => path.isAbsolute(candidate) ? path.relative(repoRoot, candidate) : candidate);
|
|
777
|
+
assertSafeGitPaths(relative);
|
|
778
|
+
const result = spawnSync('git', ['ls-files', '--stage', '-z', '--', ...relative], { cwd: repoRoot, encoding: 'utf8' });
|
|
779
|
+
if (result.error || result.status !== 0) throw new Error(`Could not snapshot Git index: ${result.error?.message || result.stderr.trim()}`);
|
|
780
|
+
const records = result.stdout.split('\0').filter(Boolean);
|
|
781
|
+
return { paths: relative, records, identity: createHash('sha256').update(result.stdout).digest('hex') };
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
export function restoreGitIndexPathsCas(before, ownedAfter, repoRoot) {
|
|
785
|
+
const current = captureGitIndexPaths(before.paths, repoRoot);
|
|
786
|
+
if (!before || !ownedAfter || current.identity !== ownedAfter.identity) {
|
|
787
|
+
throw new Error(`Git index changed after transaction staging for: ${before.paths.join(', ')}; current staging was preserved.`);
|
|
788
|
+
}
|
|
789
|
+
restoreGitIndexPaths(before, repoRoot);
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
export function restoreGitIndexPaths(snapshot, repoRoot) {
|
|
793
|
+
assertSafeGitPaths(snapshot.paths);
|
|
794
|
+
const firstHash = snapshot.records[0]?.match(/^\d+ ([0-9a-f]+) /)?.[1];
|
|
795
|
+
const removals = snapshot.paths.map(filePath => `0 ${'0'.repeat(firstHash?.length ?? 40)}\t${filePath}\n`);
|
|
796
|
+
const records = snapshot.records.map(record => {
|
|
797
|
+
const match = /^(\d+) ([0-9a-f]+) (\d+)\t([\s\S]+)$/.exec(record);
|
|
798
|
+
if (!match) throw new Error(`Unexpected Git index record: ${record}`);
|
|
799
|
+
return `${match[1]} ${match[2]} ${match[3]}\t${match[4]}\n`;
|
|
800
|
+
});
|
|
801
|
+
const restored = spawnSync('git', ['update-index', '--index-info'], {
|
|
802
|
+
cwd: repoRoot,
|
|
803
|
+
encoding: 'utf8',
|
|
804
|
+
input: [...removals, ...records].join(''),
|
|
805
|
+
});
|
|
806
|
+
if (restored.error || restored.status !== 0) {
|
|
807
|
+
throw new Error(`Could not restore Git index: ${restored.error?.message || restored.stderr.trim() || 'git update-index failed'}`);
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
|
|
103
811
|
export function gitDiffSince(relPath, sinceDate, repoRoot, opts = {}) {
|
|
104
812
|
ensureGit();
|
|
105
813
|
// Find the last commit at or before sinceDate
|