@quolu/lattice 0.52.3 → 0.52.4
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/package.json +1 -1
- package/src/artifact-contracts-v2.mjs +325 -325
- package/src/artifact-contracts.mjs +895 -895
- package/src/boundary-compiler.mjs +712 -712
- package/src/boundary-observation-compiler-v2.mjs +344 -344
- package/src/bounded-seam.mjs +230 -230
- package/src/bridge-address.mjs +107 -107
- package/src/bridge-cli.mjs +297 -297
- package/src/bridge-config.mjs +346 -346
- package/src/bridge-daemon.mjs +378 -378
- package/src/bridge-hub-protocol.mjs +198 -0
- package/src/bridge-launch-agent.mjs +323 -323
- package/src/bridge-registrar.mjs +102 -102
- package/src/bridge-server.mjs +376 -376
- package/src/cli-help.mjs +308 -308
- package/src/cli-stdio.mjs +40 -40
- package/src/control-compiler.mjs +532 -532
- package/src/dag-chain.mjs +261 -261
- package/src/factory-diagnostics.mjs +188 -188
- package/src/git-process.mjs +72 -0
- package/src/hash-chain.mjs +76 -76
- package/src/hooks-cli.mjs +1057 -1057
- package/src/isolation-runner.mjs +409 -409
- package/src/node-version-guard.mjs +44 -44
- package/src/project-cli.mjs +3 -3
- package/src/project-identity.mjs +130 -130
- package/src/rc1-black-box-oracle.mjs +906 -906
- package/src/rc1-comparison.mjs +154 -154
- package/src/rc1-evidence-bundle.mjs +456 -456
- package/src/rc1-v4-campaign.mjs +708 -708
- package/src/rc1-v4-transform.mjs +467 -467
- package/src/rc1-v5-artifact-set.mjs +855 -855
- package/src/rc1-v5-behavior-evidence.mjs +594 -594
- package/src/rc1-v5-campaign.mjs +797 -797
- package/src/rc1-v5-transform.mjs +421 -421
- package/src/rc1-v6-artifact-set.mjs +807 -807
- package/src/rc1-v6-behavior-evidence.mjs +273 -273
- package/src/rc1-v6-campaign.mjs +623 -623
- package/src/rc1-v6-causal-binding.mjs +473 -473
- package/src/rc1-v6-measurement.mjs +313 -313
- package/src/rc2-artifact-set.mjs +1584 -1584
- package/src/rc2-campaign.mjs +1506 -1506
- package/src/rc2-delivery-policy-front-end.mjs +1079 -1079
- package/src/rc2-delivery-policy-oracle.mjs +134 -134
- package/src/rc2-delivery-policy-transform.mjs +1127 -1127
- package/src/rc2-rc1-transfer-front-end.mjs +511 -511
- package/src/rc3-actual-dogfood.mjs +652 -652
- package/src/rc3-dogfood-scaffold.mjs +315 -315
- package/src/rc3-scripted-campaign.mjs +1383 -1383
- package/src/rc4-stage1-dogfood.mjs +673 -673
- package/src/runtime-adapter-registry.mjs +524 -524
- package/src/runtime-cli.mjs +4588 -4588
- package/src/runtime-contracts.mjs +824 -824
- package/src/runtime-control-store.mjs +604 -604
- package/src/runtime-controller-protocol.mjs +587 -587
- package/src/runtime-decision-verifier.mjs +701 -701
- package/src/runtime-diff-observer.mjs +361 -361
- package/src/runtime-direct-os-observer.mjs +301 -301
- package/src/runtime-driver-state.mjs +166 -166
- package/src/runtime-engine.mjs +779 -779
- package/src/runtime-errors.mjs +356 -356
- package/src/runtime-event-store.mjs +189 -189
- package/src/runtime-front-end.mjs +925 -925
- package/src/runtime-gate-store.mjs +481 -481
- package/src/runtime-hold-recompile.mjs +916 -916
- package/src/runtime-io-sentinel.mjs +391 -391
- package/src/runtime-lifecycle-lock.mjs +294 -294
- package/src/runtime-managed-supervisor.mjs +1490 -1490
- package/src/runtime-multi-epoch-store.mjs +838 -838
- package/src/runtime-projection.mjs +269 -269
- package/src/runtime-pull-intake.mjs +1192 -1192
- package/src/runtime-scripted-adapter-controller.mjs +1160 -1160
- package/src/runtime-scripted-executor.mjs +163 -163
- package/src/runtime-scripted-worktree.mjs +104 -104
- package/src/runtime-seam-resolve.mjs +428 -428
- package/src/runtime-seam-treatment.mjs +173 -173
- package/src/runtime-socket-owner.mjs +125 -125
- package/src/runtime-work-order-contracts.mjs +91 -91
- package/src/runtime-work-order-controller.mjs +1171 -1171
- package/src/runtime-worktree-executor.mjs +199 -199
- package/src/schedulability-compiler-v2.mjs +303 -303
- package/src/schedulability-verifier-v2.mjs +317 -317
- package/src/seam-apply.mjs +549 -549
- package/src/seam-commit-shared.mjs +22 -22
- package/src/seam-commit-transform.mjs +81 -81
- package/src/seam-commit.mjs +18 -18
- package/src/seam-cost.mjs +322 -322
- package/src/seam-derivation.mjs +188 -188
- package/src/seam-gate.mjs +146 -146
- package/src/seam-proposal-contracts.mjs +446 -446
- package/src/seam-proposal-queries.mjs +521 -521
- package/src/seam-proposal.mjs +2011 -2011
- package/src/seam-ref.mjs +33 -33
- package/src/seam-rewrite.mjs +286 -286
- package/src/seam-transform.mjs +554 -554
- package/src/seam-verification.mjs +260 -260
- package/src/sensor-adapter.mjs +432 -432
- package/src/sensor-cli.mjs +139 -139
- package/src/sensor-diff.mjs +661 -661
- package/src/sensor-node-runtime.mjs +53 -53
- package/src/sensor-runtime.mjs +52 -52
- package/src/timestamp-contract.mjs +8 -8
- package/src/todo-audit-pending.mjs +91 -91
- package/src/todo-chain.mjs +178 -178
- package/src/todo-cli.mjs +8 -8
- package/src/todo-contracts.mjs +728 -728
- package/src/todo-dashboard-registry.mjs +573 -573
- package/src/todo-dispatch-shape.mjs +190 -190
- package/src/todo-gantt-html-independence.mjs +239 -239
- package/src/todo-gantt-html-shared.mjs +226 -226
- package/src/todo-gantt-html-style.mjs +131 -131
- package/src/todo-gantt-html.mjs +248 -248
- package/src/todo-gantt-layout.mjs +974 -974
- package/src/todo-gantt-live.mjs +361 -361
- package/src/todo-gantt-nested.mjs +263 -263
- package/src/todo-gantt-presentation.mjs +217 -217
- package/src/todo-gantt-scope.mjs +123 -123
- package/src/todo-gantt-svg.mjs +353 -353
- package/src/todo-independence-contracts.mjs +595 -595
- package/src/todo-independence-guidance.mjs +322 -322
- package/src/todo-independence.mjs +640 -640
- package/src/todo-markdown-renderer.mjs +260 -260
- package/src/todo-migration.mjs +448 -448
- package/src/todo-narrative-anchor.mjs +130 -130
- package/src/todo-note-store.mjs +629 -629
- package/src/todo-parallel-candidates.mjs +114 -114
- package/src/todo-revision.mjs +995 -995
- package/src/todo-split.mjs +472 -472
- package/src/todo-status.mjs +690 -690
- package/src/todo-store-git-transaction.mjs +418 -418
- package/src/todo-store.mjs +42 -21
- package/src/treatment-compiler.mjs +728 -728
- package/src/treatment-runner.mjs +656 -656
- package/src/witness-scaffold.mjs +180 -180
|
@@ -1,418 +1,418 @@
|
|
|
1
|
-
import { execFile } from 'node:child_process';
|
|
2
|
-
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
-
import { constants as fsConstants } from 'node:fs';
|
|
4
|
-
import {
|
|
5
|
-
cp, mkdir, mkdtemp, open, readFile, rename, rm, writeFile,
|
|
6
|
-
} from 'node:fs/promises';
|
|
7
|
-
import path from 'node:path';
|
|
8
|
-
import { promisify } from 'node:util';
|
|
9
|
-
|
|
10
|
-
import { selfDigest } from './runtime-contracts.mjs';
|
|
11
|
-
import {
|
|
12
|
-
RuntimeLifecycleLockError,
|
|
13
|
-
acquireRuntimeLifecycleLock,
|
|
14
|
-
} from './runtime-lifecycle-lock.mjs';
|
|
15
|
-
|
|
16
|
-
const execFileAsync = promisify(execFile);
|
|
17
|
-
const STORE_REF = '.lattice/todo';
|
|
18
|
-
const LOCK_NAME = 'lattice-todo-store-commit.lock';
|
|
19
|
-
|
|
20
|
-
export class TodoStoreGitTransactionError extends Error {
|
|
21
|
-
constructor(code, message, detail = {}) {
|
|
22
|
-
super(message);
|
|
23
|
-
this.name = 'TodoStoreGitTransactionError';
|
|
24
|
-
this.code = code;
|
|
25
|
-
this.detail = detail;
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
function fail(code, message, detail = {}) {
|
|
30
|
-
throw new TodoStoreGitTransactionError(code, message, detail);
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
async function git(repoRoot, args, { env = process.env, allowExitCodes = [0] } = {}) {
|
|
34
|
-
try {
|
|
35
|
-
const result = await execFileAsync('git', args, {
|
|
36
|
-
cwd: repoRoot,
|
|
37
|
-
env,
|
|
38
|
-
encoding: 'buffer',
|
|
39
|
-
maxBuffer: 16 * 1024 * 1024,
|
|
40
|
-
});
|
|
41
|
-
return { stdout: result.stdout, stderr: result.stderr, exitCode: 0 };
|
|
42
|
-
} catch (error) {
|
|
43
|
-
const exitCode = Number.isInteger(error?.code) ? error.code : null;
|
|
44
|
-
if (exitCode !== null && allowExitCodes.includes(exitCode)) {
|
|
45
|
-
return {
|
|
46
|
-
stdout: Buffer.isBuffer(error.stdout) ? error.stdout : Buffer.from(error.stdout ?? ''),
|
|
47
|
-
stderr: Buffer.isBuffer(error.stderr) ? error.stderr : Buffer.from(error.stderr ?? ''),
|
|
48
|
-
exitCode,
|
|
49
|
-
};
|
|
50
|
-
}
|
|
51
|
-
throw error;
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
function text(buffer) { return buffer.toString('utf8').trim(); }
|
|
56
|
-
function fields(buffer) {
|
|
57
|
-
return buffer.toString('utf8').split('\0').filter((value) => value.length > 0);
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
function failureSummary(error) {
|
|
61
|
-
return {
|
|
62
|
-
code: typeof error?.code === 'string' ? error.code : null,
|
|
63
|
-
type: error?.constructor?.name ?? 'Error',
|
|
64
|
-
message: typeof error?.message === 'string' ? error.message.slice(0, 1_024) : null,
|
|
65
|
-
};
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
function repositoryGitEnvironment(env) {
|
|
69
|
-
const result = { ...env };
|
|
70
|
-
for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE']) {
|
|
71
|
-
delete result[key];
|
|
72
|
-
}
|
|
73
|
-
return result;
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
async function commonGitDir(repoRoot, env) {
|
|
77
|
-
const result = await git(repoRoot,
|
|
78
|
-
['rev-parse', '--path-format=absolute', '--git-common-dir'], { env });
|
|
79
|
-
const resolved = text(result.stdout);
|
|
80
|
-
if (!path.isAbsolute(resolved)) fail('STORE_COMMIT_GIT_INVALID', 'git_common_dir_not_absolute');
|
|
81
|
-
return resolved;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
export async function resolveTodoStoreCommitLockPath({ repoRoot, env = process.env }) {
|
|
85
|
-
return path.join(await commonGitDir(repoRoot, env), LOCK_NAME);
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
async function head(repoRoot, env) {
|
|
89
|
-
const result = await git(repoRoot, ['rev-parse', '--verify', 'HEAD'], {
|
|
90
|
-
env, allowExitCodes: [0, 128],
|
|
91
|
-
});
|
|
92
|
-
if (result.exitCode !== 0) {
|
|
93
|
-
fail('STORE_COMMIT_HEAD_UNBORN', 'todo_store_commit_requires_head');
|
|
94
|
-
}
|
|
95
|
-
return text(result.stdout);
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
async function headTarget(repoRoot, env) {
|
|
99
|
-
const symbolic = await git(repoRoot, ['symbolic-ref', '-q', 'HEAD'], {
|
|
100
|
-
env, allowExitCodes: [0, 1],
|
|
101
|
-
});
|
|
102
|
-
return symbolic.exitCode === 0 ? text(symbolic.stdout) : 'HEAD';
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
async function storeStatus(repoRoot, env) {
|
|
106
|
-
const result = await git(repoRoot,
|
|
107
|
-
['status', '--porcelain=v1', '-z', '--untracked-files=all', '--', STORE_REF], { env });
|
|
108
|
-
return fields(result.stdout);
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
async function actualIndexPath(repoRoot, env) {
|
|
112
|
-
const result = await git(repoRoot,
|
|
113
|
-
['rev-parse', '--path-format=absolute', '--git-path', 'index'], { env });
|
|
114
|
-
const resolved = text(result.stdout);
|
|
115
|
-
if (!path.isAbsolute(resolved)) fail('STORE_COMMIT_GIT_INVALID', 'git_index_path_not_absolute');
|
|
116
|
-
return resolved;
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
async function syncPath(target) {
|
|
120
|
-
const handle = await open(target, fsConstants.O_RDONLY);
|
|
121
|
-
try { await handle.sync(); } finally { await handle.close(); }
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
async function prepareSharedIndex({ repoRoot, commitSha, env }) {
|
|
125
|
-
const indexPath = await actualIndexPath(repoRoot, env);
|
|
126
|
-
const lockPath = `${indexPath}.lock`;
|
|
127
|
-
let lockHandle;
|
|
128
|
-
try {
|
|
129
|
-
// 元indexを開いてからlockを作ると、その隙に別processがindexを置換し得る。
|
|
130
|
-
// wxでlock所有を先に確定し、その後に安定した元index bytesを複製する。
|
|
131
|
-
lockHandle = await open(lockPath,
|
|
132
|
-
fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY, 0o600);
|
|
133
|
-
} catch (error) {
|
|
134
|
-
if (error?.code === 'EEXIST') {
|
|
135
|
-
fail('STORE_COMMIT_INDEX_BUSY', 'git_index_lock_already_exists', { lock_path: lockPath });
|
|
136
|
-
}
|
|
137
|
-
throw error;
|
|
138
|
-
}
|
|
139
|
-
try {
|
|
140
|
-
await lockHandle.writeFile(await readFile(indexPath));
|
|
141
|
-
await lockHandle.sync();
|
|
142
|
-
await lockHandle.close();
|
|
143
|
-
lockHandle = null;
|
|
144
|
-
const isolatedEnv = { ...env, GIT_INDEX_FILE: lockPath };
|
|
145
|
-
await git(repoRoot, ['reset', '--quiet', commitSha, '--', STORE_REF], { env: isolatedEnv });
|
|
146
|
-
const indexCompared = await git(repoRoot,
|
|
147
|
-
['diff', '--quiet', '--cached', commitSha, '--', STORE_REF], {
|
|
148
|
-
env: isolatedEnv, allowExitCodes: [0, 1],
|
|
149
|
-
});
|
|
150
|
-
const worktreeCompared = await git(repoRoot,
|
|
151
|
-
['diff', '--quiet', commitSha, '--', STORE_REF], {
|
|
152
|
-
env: isolatedEnv, allowExitCodes: [0, 1],
|
|
153
|
-
});
|
|
154
|
-
if (indexCompared.exitCode !== 0 || worktreeCompared.exitCode !== 0) {
|
|
155
|
-
fail('STORE_COMMIT_INDEX_DIRTY', 'prepared_todo_store_index_not_clean', {
|
|
156
|
-
index_matches_commit: indexCompared.exitCode === 0,
|
|
157
|
-
worktree_matches_commit: worktreeCompared.exitCode === 0,
|
|
158
|
-
});
|
|
159
|
-
}
|
|
160
|
-
await syncPath(lockPath);
|
|
161
|
-
return {
|
|
162
|
-
indexPath,
|
|
163
|
-
lockPath,
|
|
164
|
-
async commit() {
|
|
165
|
-
await rename(lockPath, indexPath);
|
|
166
|
-
},
|
|
167
|
-
async rollback() {
|
|
168
|
-
await rm(lockPath, { force: true });
|
|
169
|
-
},
|
|
170
|
-
};
|
|
171
|
-
} catch (error) {
|
|
172
|
-
if (lockHandle !== null) await lockHandle.close().catch(() => {});
|
|
173
|
-
await rm(lockPath, { force: true });
|
|
174
|
-
throw error;
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
async function restoreStore({ repoRoot, backupStore, env }) {
|
|
179
|
-
const storeRoot = path.join(repoRoot, STORE_REF);
|
|
180
|
-
await rm(storeRoot, { recursive: true, force: true });
|
|
181
|
-
await mkdir(path.dirname(storeRoot), { recursive: true });
|
|
182
|
-
await cp(backupStore, storeRoot, { recursive: true, force: false, errorOnExist: true });
|
|
183
|
-
const dirty = await storeStatus(repoRoot, env);
|
|
184
|
-
if (dirty.length > 0) {
|
|
185
|
-
fail('STORE_COMMIT_ROLLBACK_FAILED', 'todo_store_rollback_not_clean', { paths: dirty });
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
function commitIdentity(argv) {
|
|
190
|
-
const firstFlag = argv.findIndex((value) => typeof value === 'string' && value.startsWith('--'));
|
|
191
|
-
const operation = argv.slice(0, firstFlag < 0 ? argv.length : firstFlag).join('-');
|
|
192
|
-
const valueAfter = (flag) => {
|
|
193
|
-
const index = argv.indexOf(flag);
|
|
194
|
-
return index >= 0 && typeof argv[index + 1] === 'string' ? argv[index + 1] : null;
|
|
195
|
-
};
|
|
196
|
-
const plan = valueAfter('--plan');
|
|
197
|
-
const task = valueAfter('--task');
|
|
198
|
-
const phase = valueAfter('--phase');
|
|
199
|
-
const labels = [operation, plan === null ? null : `plan=${plan}`,
|
|
200
|
-
task === null ? null : `task=${task}`, phase === null ? null : `phase=${phase}`]
|
|
201
|
-
.filter(Boolean);
|
|
202
|
-
return {
|
|
203
|
-
operation: operation || 'write',
|
|
204
|
-
message: `Lattice ToDo状態更新: ${labels.join(' ')}`,
|
|
205
|
-
};
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
async function buildDetachedCommit({ repoRoot, commonDir, headBefore, message, env }) {
|
|
209
|
-
const adminDir = await mkdtemp(path.join(commonDir, 'lattice-todo-commit-'));
|
|
210
|
-
const indexPath = path.join(adminDir, 'index');
|
|
211
|
-
const messagePath = path.join(adminDir, 'message');
|
|
212
|
-
try {
|
|
213
|
-
await mkdir(path.join(adminDir, 'logs'), { recursive: true });
|
|
214
|
-
await writeFile(path.join(adminDir, 'commondir'), '..\n', { flag: 'wx' });
|
|
215
|
-
await writeFile(path.join(adminDir, 'HEAD'), `${headBefore}\n`, { flag: 'wx' });
|
|
216
|
-
await writeFile(messagePath, `${message}\n`, { flag: 'wx' });
|
|
217
|
-
const isolatedEnv = {
|
|
218
|
-
...env,
|
|
219
|
-
GIT_DIR: adminDir,
|
|
220
|
-
GIT_WORK_TREE: repoRoot,
|
|
221
|
-
GIT_INDEX_FILE: indexPath,
|
|
222
|
-
};
|
|
223
|
-
await git(repoRoot, ['read-tree', headBefore], { env: isolatedEnv });
|
|
224
|
-
await git(repoRoot, ['add', '-A', '--', STORE_REF], { env: isolatedEnv });
|
|
225
|
-
const changed = fields((await git(repoRoot,
|
|
226
|
-
['diff', '--cached', '--name-only', '-z', '--', STORE_REF], { env: isolatedEnv })).stdout);
|
|
227
|
-
if (changed.length === 0) fail('STORE_COMMIT_NO_CHANGES', 'todo_store_mutation_changed_no_paths');
|
|
228
|
-
if (changed.some((ref) => ref !== STORE_REF && !ref.startsWith(`${STORE_REF}/`))) {
|
|
229
|
-
fail('STORE_COMMIT_SCOPE_VIOLATION', 'todo_store_commit_contains_outside_path', {
|
|
230
|
-
paths: changed,
|
|
231
|
-
});
|
|
232
|
-
}
|
|
233
|
-
await git(repoRoot, ['commit', '--quiet', '--no-status', '--file', messagePath], {
|
|
234
|
-
env: isolatedEnv,
|
|
235
|
-
});
|
|
236
|
-
const commitSha = text((await git(repoRoot, ['rev-parse', 'HEAD'], { env: isolatedEnv })).stdout);
|
|
237
|
-
return { commitSha, changed };
|
|
238
|
-
} finally {
|
|
239
|
-
await rm(adminDir, { recursive: true, force: true });
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
async function updateHead({ repoRoot, target, commitSha, headBefore, env }) {
|
|
244
|
-
try {
|
|
245
|
-
await git(repoRoot, ['update-ref', target, commitSha, headBefore], { env });
|
|
246
|
-
} catch (error) {
|
|
247
|
-
const current = await head(repoRoot, env).catch(() => null);
|
|
248
|
-
if (current !== headBefore) {
|
|
249
|
-
fail('STORE_COMMIT_HEAD_CONFLICT', 'head_changed_before_store_commit', {
|
|
250
|
-
expected_head: headBefore,
|
|
251
|
-
actual_head: current,
|
|
252
|
-
});
|
|
253
|
-
}
|
|
254
|
-
throw error;
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
function receipt({ operationResult, commitSha, headBefore, changed, message }) {
|
|
259
|
-
const result = {
|
|
260
|
-
schema: 'lattice.todo_store_atomic_commit_result.v1',
|
|
261
|
-
operation_result: operationResult,
|
|
262
|
-
commit: {
|
|
263
|
-
schema: 'lattice.todo_store_commit_receipt.v1',
|
|
264
|
-
commit_sha: commitSha,
|
|
265
|
-
parent_sha: headBefore,
|
|
266
|
-
paths: changed,
|
|
267
|
-
message,
|
|
268
|
-
},
|
|
269
|
-
result_digest: '',
|
|
270
|
-
};
|
|
271
|
-
result.result_digest = selfDigest(result, 'result_digest');
|
|
272
|
-
return result;
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
/**
|
|
276
|
-
* Todo store mutationをcommon Git-dir lockの内側で実行し、store pathだけをcommitする。
|
|
277
|
-
* sourceのworking treeと、store以外の共有index entryには触れない。
|
|
278
|
-
*/
|
|
279
|
-
export async function commitTodoStoreMutation({
|
|
280
|
-
repoRoot,
|
|
281
|
-
argv,
|
|
282
|
-
action,
|
|
283
|
-
env = process.env,
|
|
284
|
-
lockTimeoutMs = 0,
|
|
285
|
-
} = {}) {
|
|
286
|
-
if (typeof repoRoot !== 'string' || !path.isAbsolute(repoRoot)
|
|
287
|
-
|| !Array.isArray(argv) || typeof action !== 'function'
|
|
288
|
-
|| env === null || typeof env !== 'object' || Array.isArray(env)
|
|
289
|
-
|| !Number.isSafeInteger(lockTimeoutMs) || lockTimeoutMs < 0) {
|
|
290
|
-
throw new TypeError('commitTodoStoreMutation optionsが不正');
|
|
291
|
-
}
|
|
292
|
-
const gitEnv = repositoryGitEnvironment(env);
|
|
293
|
-
const commonDir = await commonGitDir(repoRoot, gitEnv);
|
|
294
|
-
const { operation, message } = commitIdentity(argv);
|
|
295
|
-
const nonce = randomUUID();
|
|
296
|
-
const lockPath = path.join(commonDir, LOCK_NAME);
|
|
297
|
-
let lock;
|
|
298
|
-
try {
|
|
299
|
-
lock = await acquireRuntimeLifecycleLock({
|
|
300
|
-
lockPath,
|
|
301
|
-
sessionNonceDigest: createHash('sha256').update(nonce).digest('hex'),
|
|
302
|
-
operation: `todo-${operation}`.slice(0, 128),
|
|
303
|
-
requestId: `todo-${process.pid}-${nonce.replaceAll('-', '').slice(0, 16)}`,
|
|
304
|
-
timeoutMs: lockTimeoutMs,
|
|
305
|
-
});
|
|
306
|
-
} catch (error) {
|
|
307
|
-
if (error instanceof RuntimeLifecycleLockError) {
|
|
308
|
-
fail(error.code, 'todo_store_commit_lock_failed', {
|
|
309
|
-
lock_path: lockPath,
|
|
310
|
-
reason: error.detail,
|
|
311
|
-
});
|
|
312
|
-
}
|
|
313
|
-
throw error;
|
|
314
|
-
}
|
|
315
|
-
let transactionDir = null;
|
|
316
|
-
let backupStore = null;
|
|
317
|
-
let refUpdated = false;
|
|
318
|
-
let commitSha = null;
|
|
319
|
-
let backupReady = false;
|
|
320
|
-
let preparedIndex = null;
|
|
321
|
-
let primaryFailure = null;
|
|
322
|
-
try {
|
|
323
|
-
try {
|
|
324
|
-
transactionDir = await mkdtemp(path.join(commonDir, 'lattice-todo-rollback-'));
|
|
325
|
-
backupStore = path.join(transactionDir, 'todo');
|
|
326
|
-
const dirty = await storeStatus(repoRoot, gitEnv);
|
|
327
|
-
if (dirty.length > 0) {
|
|
328
|
-
fail('STORE_COMMIT_DIRTY', 'todo_store_dirty_at_atomic_entry', { paths: dirty });
|
|
329
|
-
}
|
|
330
|
-
const storeRoot = path.join(repoRoot, STORE_REF);
|
|
331
|
-
await cp(storeRoot, backupStore, { recursive: true, force: false, errorOnExist: true });
|
|
332
|
-
backupReady = true;
|
|
333
|
-
const headBefore = await head(repoRoot, gitEnv);
|
|
334
|
-
const target = await headTarget(repoRoot, gitEnv);
|
|
335
|
-
const operationResult = await action(repoRoot);
|
|
336
|
-
const built = await buildDetachedCommit({
|
|
337
|
-
repoRoot, commonDir, headBefore, message, env: gitEnv,
|
|
338
|
-
});
|
|
339
|
-
commitSha = built.commitSha;
|
|
340
|
-
preparedIndex = await prepareSharedIndex({ repoRoot, commitSha, env: gitEnv });
|
|
341
|
-
await updateHead({ repoRoot, target, commitSha, headBefore, env: gitEnv });
|
|
342
|
-
refUpdated = true;
|
|
343
|
-
try {
|
|
344
|
-
// 共有index lockを保持したまま、store entryだけ整合済みのindexへatomic renameする。
|
|
345
|
-
await preparedIndex.commit();
|
|
346
|
-
preparedIndex = null;
|
|
347
|
-
} catch (error) {
|
|
348
|
-
try {
|
|
349
|
-
await updateHead({
|
|
350
|
-
repoRoot, target, commitSha: headBefore, headBefore: commitSha, env: gitEnv,
|
|
351
|
-
});
|
|
352
|
-
refUpdated = false;
|
|
353
|
-
} catch (recoveryError) {
|
|
354
|
-
fail('STORE_COMMIT_RECOVERY_REQUIRED', 'todo_store_index_finalize_and_ref_rollback_failed', {
|
|
355
|
-
commit_sha: commitSha,
|
|
356
|
-
index_lock_path: preparedIndex?.lockPath ?? null,
|
|
357
|
-
cause: recoveryError?.code ?? recoveryError?.constructor?.name ?? 'Error',
|
|
358
|
-
});
|
|
359
|
-
}
|
|
360
|
-
if (error instanceof TodoStoreGitTransactionError) throw error;
|
|
361
|
-
fail('STORE_COMMIT_FINALIZE_FAILED', 'todo_store_index_finalize_failed', {
|
|
362
|
-
commit_sha: commitSha,
|
|
363
|
-
});
|
|
364
|
-
}
|
|
365
|
-
return receipt({
|
|
366
|
-
operationResult, commitSha, headBefore, changed: built.changed, message,
|
|
367
|
-
});
|
|
368
|
-
} catch (error) {
|
|
369
|
-
if (!refUpdated) {
|
|
370
|
-
try {
|
|
371
|
-
if (backupReady) await restoreStore({ repoRoot, backupStore, env: gitEnv });
|
|
372
|
-
} catch (rollbackError) {
|
|
373
|
-
if (rollbackError instanceof TodoStoreGitTransactionError) throw rollbackError;
|
|
374
|
-
fail('STORE_COMMIT_ROLLBACK_FAILED', 'todo_store_rollback_failed', {
|
|
375
|
-
cause: rollbackError?.constructor?.name ?? 'Error',
|
|
376
|
-
});
|
|
377
|
-
}
|
|
378
|
-
}
|
|
379
|
-
if (error instanceof TypeError || error instanceof TodoStoreGitTransactionError
|
|
380
|
-
|| (typeof error?.code === 'string' && error.detail !== null
|
|
381
|
-
&& typeof error.detail === 'object')) throw error;
|
|
382
|
-
fail('STORE_COMMIT_FAILED', 'todo_store_git_commit_failed', {
|
|
383
|
-
cause: error?.constructor?.name ?? 'Error',
|
|
384
|
-
commit_sha: commitSha,
|
|
385
|
-
});
|
|
386
|
-
}
|
|
387
|
-
} catch (error) {
|
|
388
|
-
primaryFailure = error;
|
|
389
|
-
throw error;
|
|
390
|
-
} finally {
|
|
391
|
-
const cleanupFailures = [];
|
|
392
|
-
const indexLockPath = preparedIndex?.lockPath ?? null;
|
|
393
|
-
if (preparedIndex !== null) {
|
|
394
|
-
try { await preparedIndex.rollback(); }
|
|
395
|
-
catch (error) { cleanupFailures.push(error); }
|
|
396
|
-
}
|
|
397
|
-
if (transactionDir !== null) {
|
|
398
|
-
try { await rm(transactionDir, { recursive: true, force: true }); }
|
|
399
|
-
catch (error) { cleanupFailures.push(error); }
|
|
400
|
-
}
|
|
401
|
-
try { await lock.release(); }
|
|
402
|
-
catch (error) { cleanupFailures.push(error); }
|
|
403
|
-
if (cleanupFailures.length > 0) {
|
|
404
|
-
throw new TodoStoreGitTransactionError(
|
|
405
|
-
refUpdated ? 'STORE_COMMIT_POST_COMMIT_CLEANUP_FAILED' : 'STORE_COMMIT_CLEANUP_FAILED',
|
|
406
|
-
refUpdated ? 'todo_store_commit_succeeded_but_cleanup_failed' : 'todo_store_cleanup_failed',
|
|
407
|
-
{
|
|
408
|
-
commit_sha: refUpdated ? commitSha : null,
|
|
409
|
-
index_lock_path: indexLockPath,
|
|
410
|
-
primary: primaryFailure === null ? null : failureSummary(primaryFailure),
|
|
411
|
-
failures: cleanupFailures.map((error) => (
|
|
412
|
-
typeof error?.code === 'string' ? error.code : error?.constructor?.name ?? 'Error'
|
|
413
|
-
)),
|
|
414
|
-
},
|
|
415
|
-
);
|
|
416
|
-
}
|
|
417
|
-
}
|
|
418
|
-
}
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { constants as fsConstants } from 'node:fs';
|
|
4
|
+
import {
|
|
5
|
+
cp, mkdir, mkdtemp, open, readFile, rename, rm, writeFile,
|
|
6
|
+
} from 'node:fs/promises';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { promisify } from 'node:util';
|
|
9
|
+
|
|
10
|
+
import { selfDigest } from './runtime-contracts.mjs';
|
|
11
|
+
import {
|
|
12
|
+
RuntimeLifecycleLockError,
|
|
13
|
+
acquireRuntimeLifecycleLock,
|
|
14
|
+
} from './runtime-lifecycle-lock.mjs';
|
|
15
|
+
|
|
16
|
+
const execFileAsync = promisify(execFile);
|
|
17
|
+
const STORE_REF = '.lattice/todo';
|
|
18
|
+
const LOCK_NAME = 'lattice-todo-store-commit.lock';
|
|
19
|
+
|
|
20
|
+
export class TodoStoreGitTransactionError extends Error {
|
|
21
|
+
constructor(code, message, detail = {}) {
|
|
22
|
+
super(message);
|
|
23
|
+
this.name = 'TodoStoreGitTransactionError';
|
|
24
|
+
this.code = code;
|
|
25
|
+
this.detail = detail;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function fail(code, message, detail = {}) {
|
|
30
|
+
throw new TodoStoreGitTransactionError(code, message, detail);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function git(repoRoot, args, { env = process.env, allowExitCodes = [0] } = {}) {
|
|
34
|
+
try {
|
|
35
|
+
const result = await execFileAsync('git', args, {
|
|
36
|
+
cwd: repoRoot,
|
|
37
|
+
env,
|
|
38
|
+
encoding: 'buffer',
|
|
39
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
40
|
+
});
|
|
41
|
+
return { stdout: result.stdout, stderr: result.stderr, exitCode: 0 };
|
|
42
|
+
} catch (error) {
|
|
43
|
+
const exitCode = Number.isInteger(error?.code) ? error.code : null;
|
|
44
|
+
if (exitCode !== null && allowExitCodes.includes(exitCode)) {
|
|
45
|
+
return {
|
|
46
|
+
stdout: Buffer.isBuffer(error.stdout) ? error.stdout : Buffer.from(error.stdout ?? ''),
|
|
47
|
+
stderr: Buffer.isBuffer(error.stderr) ? error.stderr : Buffer.from(error.stderr ?? ''),
|
|
48
|
+
exitCode,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
throw error;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function text(buffer) { return buffer.toString('utf8').trim(); }
|
|
56
|
+
function fields(buffer) {
|
|
57
|
+
return buffer.toString('utf8').split('\0').filter((value) => value.length > 0);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function failureSummary(error) {
|
|
61
|
+
return {
|
|
62
|
+
code: typeof error?.code === 'string' ? error.code : null,
|
|
63
|
+
type: error?.constructor?.name ?? 'Error',
|
|
64
|
+
message: typeof error?.message === 'string' ? error.message.slice(0, 1_024) : null,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function repositoryGitEnvironment(env) {
|
|
69
|
+
const result = { ...env };
|
|
70
|
+
for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE']) {
|
|
71
|
+
delete result[key];
|
|
72
|
+
}
|
|
73
|
+
return result;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function commonGitDir(repoRoot, env) {
|
|
77
|
+
const result = await git(repoRoot,
|
|
78
|
+
['rev-parse', '--path-format=absolute', '--git-common-dir'], { env });
|
|
79
|
+
const resolved = text(result.stdout);
|
|
80
|
+
if (!path.isAbsolute(resolved)) fail('STORE_COMMIT_GIT_INVALID', 'git_common_dir_not_absolute');
|
|
81
|
+
return resolved;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export async function resolveTodoStoreCommitLockPath({ repoRoot, env = process.env }) {
|
|
85
|
+
return path.join(await commonGitDir(repoRoot, env), LOCK_NAME);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function head(repoRoot, env) {
|
|
89
|
+
const result = await git(repoRoot, ['rev-parse', '--verify', 'HEAD'], {
|
|
90
|
+
env, allowExitCodes: [0, 128],
|
|
91
|
+
});
|
|
92
|
+
if (result.exitCode !== 0) {
|
|
93
|
+
fail('STORE_COMMIT_HEAD_UNBORN', 'todo_store_commit_requires_head');
|
|
94
|
+
}
|
|
95
|
+
return text(result.stdout);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function headTarget(repoRoot, env) {
|
|
99
|
+
const symbolic = await git(repoRoot, ['symbolic-ref', '-q', 'HEAD'], {
|
|
100
|
+
env, allowExitCodes: [0, 1],
|
|
101
|
+
});
|
|
102
|
+
return symbolic.exitCode === 0 ? text(symbolic.stdout) : 'HEAD';
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function storeStatus(repoRoot, env) {
|
|
106
|
+
const result = await git(repoRoot,
|
|
107
|
+
['status', '--porcelain=v1', '-z', '--untracked-files=all', '--', STORE_REF], { env });
|
|
108
|
+
return fields(result.stdout);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function actualIndexPath(repoRoot, env) {
|
|
112
|
+
const result = await git(repoRoot,
|
|
113
|
+
['rev-parse', '--path-format=absolute', '--git-path', 'index'], { env });
|
|
114
|
+
const resolved = text(result.stdout);
|
|
115
|
+
if (!path.isAbsolute(resolved)) fail('STORE_COMMIT_GIT_INVALID', 'git_index_path_not_absolute');
|
|
116
|
+
return resolved;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function syncPath(target) {
|
|
120
|
+
const handle = await open(target, fsConstants.O_RDONLY);
|
|
121
|
+
try { await handle.sync(); } finally { await handle.close(); }
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function prepareSharedIndex({ repoRoot, commitSha, env }) {
|
|
125
|
+
const indexPath = await actualIndexPath(repoRoot, env);
|
|
126
|
+
const lockPath = `${indexPath}.lock`;
|
|
127
|
+
let lockHandle;
|
|
128
|
+
try {
|
|
129
|
+
// 元indexを開いてからlockを作ると、その隙に別processがindexを置換し得る。
|
|
130
|
+
// wxでlock所有を先に確定し、その後に安定した元index bytesを複製する。
|
|
131
|
+
lockHandle = await open(lockPath,
|
|
132
|
+
fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY, 0o600);
|
|
133
|
+
} catch (error) {
|
|
134
|
+
if (error?.code === 'EEXIST') {
|
|
135
|
+
fail('STORE_COMMIT_INDEX_BUSY', 'git_index_lock_already_exists', { lock_path: lockPath });
|
|
136
|
+
}
|
|
137
|
+
throw error;
|
|
138
|
+
}
|
|
139
|
+
try {
|
|
140
|
+
await lockHandle.writeFile(await readFile(indexPath));
|
|
141
|
+
await lockHandle.sync();
|
|
142
|
+
await lockHandle.close();
|
|
143
|
+
lockHandle = null;
|
|
144
|
+
const isolatedEnv = { ...env, GIT_INDEX_FILE: lockPath };
|
|
145
|
+
await git(repoRoot, ['reset', '--quiet', commitSha, '--', STORE_REF], { env: isolatedEnv });
|
|
146
|
+
const indexCompared = await git(repoRoot,
|
|
147
|
+
['diff', '--quiet', '--cached', commitSha, '--', STORE_REF], {
|
|
148
|
+
env: isolatedEnv, allowExitCodes: [0, 1],
|
|
149
|
+
});
|
|
150
|
+
const worktreeCompared = await git(repoRoot,
|
|
151
|
+
['diff', '--quiet', commitSha, '--', STORE_REF], {
|
|
152
|
+
env: isolatedEnv, allowExitCodes: [0, 1],
|
|
153
|
+
});
|
|
154
|
+
if (indexCompared.exitCode !== 0 || worktreeCompared.exitCode !== 0) {
|
|
155
|
+
fail('STORE_COMMIT_INDEX_DIRTY', 'prepared_todo_store_index_not_clean', {
|
|
156
|
+
index_matches_commit: indexCompared.exitCode === 0,
|
|
157
|
+
worktree_matches_commit: worktreeCompared.exitCode === 0,
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
await syncPath(lockPath);
|
|
161
|
+
return {
|
|
162
|
+
indexPath,
|
|
163
|
+
lockPath,
|
|
164
|
+
async commit() {
|
|
165
|
+
await rename(lockPath, indexPath);
|
|
166
|
+
},
|
|
167
|
+
async rollback() {
|
|
168
|
+
await rm(lockPath, { force: true });
|
|
169
|
+
},
|
|
170
|
+
};
|
|
171
|
+
} catch (error) {
|
|
172
|
+
if (lockHandle !== null) await lockHandle.close().catch(() => {});
|
|
173
|
+
await rm(lockPath, { force: true });
|
|
174
|
+
throw error;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
async function restoreStore({ repoRoot, backupStore, env }) {
|
|
179
|
+
const storeRoot = path.join(repoRoot, STORE_REF);
|
|
180
|
+
await rm(storeRoot, { recursive: true, force: true });
|
|
181
|
+
await mkdir(path.dirname(storeRoot), { recursive: true });
|
|
182
|
+
await cp(backupStore, storeRoot, { recursive: true, force: false, errorOnExist: true });
|
|
183
|
+
const dirty = await storeStatus(repoRoot, env);
|
|
184
|
+
if (dirty.length > 0) {
|
|
185
|
+
fail('STORE_COMMIT_ROLLBACK_FAILED', 'todo_store_rollback_not_clean', { paths: dirty });
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function commitIdentity(argv) {
|
|
190
|
+
const firstFlag = argv.findIndex((value) => typeof value === 'string' && value.startsWith('--'));
|
|
191
|
+
const operation = argv.slice(0, firstFlag < 0 ? argv.length : firstFlag).join('-');
|
|
192
|
+
const valueAfter = (flag) => {
|
|
193
|
+
const index = argv.indexOf(flag);
|
|
194
|
+
return index >= 0 && typeof argv[index + 1] === 'string' ? argv[index + 1] : null;
|
|
195
|
+
};
|
|
196
|
+
const plan = valueAfter('--plan');
|
|
197
|
+
const task = valueAfter('--task');
|
|
198
|
+
const phase = valueAfter('--phase');
|
|
199
|
+
const labels = [operation, plan === null ? null : `plan=${plan}`,
|
|
200
|
+
task === null ? null : `task=${task}`, phase === null ? null : `phase=${phase}`]
|
|
201
|
+
.filter(Boolean);
|
|
202
|
+
return {
|
|
203
|
+
operation: operation || 'write',
|
|
204
|
+
message: `Lattice ToDo状態更新: ${labels.join(' ')}`,
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async function buildDetachedCommit({ repoRoot, commonDir, headBefore, message, env }) {
|
|
209
|
+
const adminDir = await mkdtemp(path.join(commonDir, 'lattice-todo-commit-'));
|
|
210
|
+
const indexPath = path.join(adminDir, 'index');
|
|
211
|
+
const messagePath = path.join(adminDir, 'message');
|
|
212
|
+
try {
|
|
213
|
+
await mkdir(path.join(adminDir, 'logs'), { recursive: true });
|
|
214
|
+
await writeFile(path.join(adminDir, 'commondir'), '..\n', { flag: 'wx' });
|
|
215
|
+
await writeFile(path.join(adminDir, 'HEAD'), `${headBefore}\n`, { flag: 'wx' });
|
|
216
|
+
await writeFile(messagePath, `${message}\n`, { flag: 'wx' });
|
|
217
|
+
const isolatedEnv = {
|
|
218
|
+
...env,
|
|
219
|
+
GIT_DIR: adminDir,
|
|
220
|
+
GIT_WORK_TREE: repoRoot,
|
|
221
|
+
GIT_INDEX_FILE: indexPath,
|
|
222
|
+
};
|
|
223
|
+
await git(repoRoot, ['read-tree', headBefore], { env: isolatedEnv });
|
|
224
|
+
await git(repoRoot, ['add', '-A', '--', STORE_REF], { env: isolatedEnv });
|
|
225
|
+
const changed = fields((await git(repoRoot,
|
|
226
|
+
['diff', '--cached', '--name-only', '-z', '--', STORE_REF], { env: isolatedEnv })).stdout);
|
|
227
|
+
if (changed.length === 0) fail('STORE_COMMIT_NO_CHANGES', 'todo_store_mutation_changed_no_paths');
|
|
228
|
+
if (changed.some((ref) => ref !== STORE_REF && !ref.startsWith(`${STORE_REF}/`))) {
|
|
229
|
+
fail('STORE_COMMIT_SCOPE_VIOLATION', 'todo_store_commit_contains_outside_path', {
|
|
230
|
+
paths: changed,
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
await git(repoRoot, ['commit', '--quiet', '--no-status', '--file', messagePath], {
|
|
234
|
+
env: isolatedEnv,
|
|
235
|
+
});
|
|
236
|
+
const commitSha = text((await git(repoRoot, ['rev-parse', 'HEAD'], { env: isolatedEnv })).stdout);
|
|
237
|
+
return { commitSha, changed };
|
|
238
|
+
} finally {
|
|
239
|
+
await rm(adminDir, { recursive: true, force: true });
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
async function updateHead({ repoRoot, target, commitSha, headBefore, env }) {
|
|
244
|
+
try {
|
|
245
|
+
await git(repoRoot, ['update-ref', target, commitSha, headBefore], { env });
|
|
246
|
+
} catch (error) {
|
|
247
|
+
const current = await head(repoRoot, env).catch(() => null);
|
|
248
|
+
if (current !== headBefore) {
|
|
249
|
+
fail('STORE_COMMIT_HEAD_CONFLICT', 'head_changed_before_store_commit', {
|
|
250
|
+
expected_head: headBefore,
|
|
251
|
+
actual_head: current,
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
throw error;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function receipt({ operationResult, commitSha, headBefore, changed, message }) {
|
|
259
|
+
const result = {
|
|
260
|
+
schema: 'lattice.todo_store_atomic_commit_result.v1',
|
|
261
|
+
operation_result: operationResult,
|
|
262
|
+
commit: {
|
|
263
|
+
schema: 'lattice.todo_store_commit_receipt.v1',
|
|
264
|
+
commit_sha: commitSha,
|
|
265
|
+
parent_sha: headBefore,
|
|
266
|
+
paths: changed,
|
|
267
|
+
message,
|
|
268
|
+
},
|
|
269
|
+
result_digest: '',
|
|
270
|
+
};
|
|
271
|
+
result.result_digest = selfDigest(result, 'result_digest');
|
|
272
|
+
return result;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Todo store mutationをcommon Git-dir lockの内側で実行し、store pathだけをcommitする。
|
|
277
|
+
* sourceのworking treeと、store以外の共有index entryには触れない。
|
|
278
|
+
*/
|
|
279
|
+
export async function commitTodoStoreMutation({
|
|
280
|
+
repoRoot,
|
|
281
|
+
argv,
|
|
282
|
+
action,
|
|
283
|
+
env = process.env,
|
|
284
|
+
lockTimeoutMs = 0,
|
|
285
|
+
} = {}) {
|
|
286
|
+
if (typeof repoRoot !== 'string' || !path.isAbsolute(repoRoot)
|
|
287
|
+
|| !Array.isArray(argv) || typeof action !== 'function'
|
|
288
|
+
|| env === null || typeof env !== 'object' || Array.isArray(env)
|
|
289
|
+
|| !Number.isSafeInteger(lockTimeoutMs) || lockTimeoutMs < 0) {
|
|
290
|
+
throw new TypeError('commitTodoStoreMutation optionsが不正');
|
|
291
|
+
}
|
|
292
|
+
const gitEnv = repositoryGitEnvironment(env);
|
|
293
|
+
const commonDir = await commonGitDir(repoRoot, gitEnv);
|
|
294
|
+
const { operation, message } = commitIdentity(argv);
|
|
295
|
+
const nonce = randomUUID();
|
|
296
|
+
const lockPath = path.join(commonDir, LOCK_NAME);
|
|
297
|
+
let lock;
|
|
298
|
+
try {
|
|
299
|
+
lock = await acquireRuntimeLifecycleLock({
|
|
300
|
+
lockPath,
|
|
301
|
+
sessionNonceDigest: createHash('sha256').update(nonce).digest('hex'),
|
|
302
|
+
operation: `todo-${operation}`.slice(0, 128),
|
|
303
|
+
requestId: `todo-${process.pid}-${nonce.replaceAll('-', '').slice(0, 16)}`,
|
|
304
|
+
timeoutMs: lockTimeoutMs,
|
|
305
|
+
});
|
|
306
|
+
} catch (error) {
|
|
307
|
+
if (error instanceof RuntimeLifecycleLockError) {
|
|
308
|
+
fail(error.code, 'todo_store_commit_lock_failed', {
|
|
309
|
+
lock_path: lockPath,
|
|
310
|
+
reason: error.detail,
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
throw error;
|
|
314
|
+
}
|
|
315
|
+
let transactionDir = null;
|
|
316
|
+
let backupStore = null;
|
|
317
|
+
let refUpdated = false;
|
|
318
|
+
let commitSha = null;
|
|
319
|
+
let backupReady = false;
|
|
320
|
+
let preparedIndex = null;
|
|
321
|
+
let primaryFailure = null;
|
|
322
|
+
try {
|
|
323
|
+
try {
|
|
324
|
+
transactionDir = await mkdtemp(path.join(commonDir, 'lattice-todo-rollback-'));
|
|
325
|
+
backupStore = path.join(transactionDir, 'todo');
|
|
326
|
+
const dirty = await storeStatus(repoRoot, gitEnv);
|
|
327
|
+
if (dirty.length > 0) {
|
|
328
|
+
fail('STORE_COMMIT_DIRTY', 'todo_store_dirty_at_atomic_entry', { paths: dirty });
|
|
329
|
+
}
|
|
330
|
+
const storeRoot = path.join(repoRoot, STORE_REF);
|
|
331
|
+
await cp(storeRoot, backupStore, { recursive: true, force: false, errorOnExist: true });
|
|
332
|
+
backupReady = true;
|
|
333
|
+
const headBefore = await head(repoRoot, gitEnv);
|
|
334
|
+
const target = await headTarget(repoRoot, gitEnv);
|
|
335
|
+
const operationResult = await action(repoRoot);
|
|
336
|
+
const built = await buildDetachedCommit({
|
|
337
|
+
repoRoot, commonDir, headBefore, message, env: gitEnv,
|
|
338
|
+
});
|
|
339
|
+
commitSha = built.commitSha;
|
|
340
|
+
preparedIndex = await prepareSharedIndex({ repoRoot, commitSha, env: gitEnv });
|
|
341
|
+
await updateHead({ repoRoot, target, commitSha, headBefore, env: gitEnv });
|
|
342
|
+
refUpdated = true;
|
|
343
|
+
try {
|
|
344
|
+
// 共有index lockを保持したまま、store entryだけ整合済みのindexへatomic renameする。
|
|
345
|
+
await preparedIndex.commit();
|
|
346
|
+
preparedIndex = null;
|
|
347
|
+
} catch (error) {
|
|
348
|
+
try {
|
|
349
|
+
await updateHead({
|
|
350
|
+
repoRoot, target, commitSha: headBefore, headBefore: commitSha, env: gitEnv,
|
|
351
|
+
});
|
|
352
|
+
refUpdated = false;
|
|
353
|
+
} catch (recoveryError) {
|
|
354
|
+
fail('STORE_COMMIT_RECOVERY_REQUIRED', 'todo_store_index_finalize_and_ref_rollback_failed', {
|
|
355
|
+
commit_sha: commitSha,
|
|
356
|
+
index_lock_path: preparedIndex?.lockPath ?? null,
|
|
357
|
+
cause: recoveryError?.code ?? recoveryError?.constructor?.name ?? 'Error',
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
if (error instanceof TodoStoreGitTransactionError) throw error;
|
|
361
|
+
fail('STORE_COMMIT_FINALIZE_FAILED', 'todo_store_index_finalize_failed', {
|
|
362
|
+
commit_sha: commitSha,
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
return receipt({
|
|
366
|
+
operationResult, commitSha, headBefore, changed: built.changed, message,
|
|
367
|
+
});
|
|
368
|
+
} catch (error) {
|
|
369
|
+
if (!refUpdated) {
|
|
370
|
+
try {
|
|
371
|
+
if (backupReady) await restoreStore({ repoRoot, backupStore, env: gitEnv });
|
|
372
|
+
} catch (rollbackError) {
|
|
373
|
+
if (rollbackError instanceof TodoStoreGitTransactionError) throw rollbackError;
|
|
374
|
+
fail('STORE_COMMIT_ROLLBACK_FAILED', 'todo_store_rollback_failed', {
|
|
375
|
+
cause: rollbackError?.constructor?.name ?? 'Error',
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
if (error instanceof TypeError || error instanceof TodoStoreGitTransactionError
|
|
380
|
+
|| (typeof error?.code === 'string' && error.detail !== null
|
|
381
|
+
&& typeof error.detail === 'object')) throw error;
|
|
382
|
+
fail('STORE_COMMIT_FAILED', 'todo_store_git_commit_failed', {
|
|
383
|
+
cause: error?.constructor?.name ?? 'Error',
|
|
384
|
+
commit_sha: commitSha,
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
} catch (error) {
|
|
388
|
+
primaryFailure = error;
|
|
389
|
+
throw error;
|
|
390
|
+
} finally {
|
|
391
|
+
const cleanupFailures = [];
|
|
392
|
+
const indexLockPath = preparedIndex?.lockPath ?? null;
|
|
393
|
+
if (preparedIndex !== null) {
|
|
394
|
+
try { await preparedIndex.rollback(); }
|
|
395
|
+
catch (error) { cleanupFailures.push(error); }
|
|
396
|
+
}
|
|
397
|
+
if (transactionDir !== null) {
|
|
398
|
+
try { await rm(transactionDir, { recursive: true, force: true }); }
|
|
399
|
+
catch (error) { cleanupFailures.push(error); }
|
|
400
|
+
}
|
|
401
|
+
try { await lock.release(); }
|
|
402
|
+
catch (error) { cleanupFailures.push(error); }
|
|
403
|
+
if (cleanupFailures.length > 0) {
|
|
404
|
+
throw new TodoStoreGitTransactionError(
|
|
405
|
+
refUpdated ? 'STORE_COMMIT_POST_COMMIT_CLEANUP_FAILED' : 'STORE_COMMIT_CLEANUP_FAILED',
|
|
406
|
+
refUpdated ? 'todo_store_commit_succeeded_but_cleanup_failed' : 'todo_store_cleanup_failed',
|
|
407
|
+
{
|
|
408
|
+
commit_sha: refUpdated ? commitSha : null,
|
|
409
|
+
index_lock_path: indexLockPath,
|
|
410
|
+
primary: primaryFailure === null ? null : failureSummary(primaryFailure),
|
|
411
|
+
failures: cleanupFailures.map((error) => (
|
|
412
|
+
typeof error?.code === 'string' ? error.code : error?.constructor?.name ?? 'Error'
|
|
413
|
+
)),
|
|
414
|
+
},
|
|
415
|
+
);
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
}
|