@quolu/lattice 0.107.0 → 0.109.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +1 -1
- package/README.md +2 -2
- package/bin/lattice.mjs +5 -2
- package/docs/schemas/lattice.plan_create_input.v6.schema.json +384 -0
- package/docs/schemas/lattice.plan_revise_input.v1.schema.json +3 -0
- package/docs/schemas/lattice.todo_witness_draft.v2.schema.json +14 -2
- package/docs/schemas/lattice.todo_witness_set.v6.schema.json +482 -0
- package/package.json +3 -1
- package/sensor/dist/bin/lattice-sensor.js +76 -0
- package/sensor/dist/graph/anchor-resolve.d.ts +90 -0
- package/sensor/dist/graph/anchor-resolve.d.ts.map +1 -0
- package/sensor/dist/graph/anchor-resolve.js +132 -0
- package/sensor/dist/graph/anchor-resolve.js.map +1 -0
- package/sensor/dist/graph/touched-symbols.d.ts +42 -0
- package/sensor/dist/graph/touched-symbols.d.ts.map +1 -0
- package/sensor/dist/graph/touched-symbols.js +80 -0
- package/sensor/dist/graph/touched-symbols.js.map +1 -0
- package/src/cli-help.mjs +21 -7
- package/src/plan-revise.mjs +12 -1
- package/src/plan-scope-review.mjs +1 -1
- package/src/project-cli.mjs +20 -3
- package/src/runtime-front-end.mjs +26 -9
- package/src/schedulability-compiler-v2.mjs +10 -4
- package/src/sensor-cli.mjs +82 -1
- package/src/sensor-resolve.mjs +116 -0
- package/src/sensor-touched.mjs +76 -0
- package/src/todo-authoring-input.mjs +1 -0
- package/src/todo-cli.mjs +233 -43
- package/src/todo-contracts.mjs +62 -0
- package/src/todo-declaration.mjs +165 -0
- package/src/todo-independence-authoritative-observation.mjs +45 -15
- package/src/todo-independence-contracts.mjs +18 -4
- package/src/todo-independence.mjs +8 -2
- package/src/todo-judgment.mjs +141 -0
- package/src/todo-relation-store.mjs +294 -0
- package/src/todo-store.mjs +8 -4
- package/src/witness-scaffold.mjs +23 -15
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
1
2
|
import { mkdtemp, rm } from 'node:fs/promises';
|
|
2
3
|
import { tmpdir } from 'node:os';
|
|
3
4
|
import path from 'node:path';
|
|
@@ -40,31 +41,45 @@ function memoryStream() {
|
|
|
40
41
|
};
|
|
41
42
|
}
|
|
42
43
|
|
|
43
|
-
async function
|
|
44
|
+
async function runSensor(command, observationRoot) {
|
|
44
45
|
const stdout = memoryStream();
|
|
45
46
|
const stderr = memoryStream();
|
|
46
47
|
const status = await runSensorCli({
|
|
47
|
-
argv: [
|
|
48
|
+
argv: [command, observationRoot, '--json'],
|
|
48
49
|
stdout: stdout.stream,
|
|
49
50
|
stderr: stderr.stream,
|
|
50
51
|
});
|
|
51
52
|
if (status !== 0) {
|
|
52
53
|
fail('INDEPENDENCE_OBSERVATION_SENSOR_INIT_FAILED', 'observation_sensor_init_failed', {
|
|
53
|
-
sensor_error: stderr.read(),
|
|
54
|
+
sensor_command: command, sensor_error: stderr.read(),
|
|
54
55
|
});
|
|
55
56
|
}
|
|
56
57
|
}
|
|
57
58
|
|
|
58
|
-
/**
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
}
|
|
59
|
+
/**
|
|
60
|
+
* a2 (ADR 0204 Observe): 作業木がHEADと同じ内容か。`.lattice/`はsensor索引とstoreが書く場所で、
|
|
61
|
+
* 索引の対象外なので数えない(storeがtrackedな製品repoでは書込みのたびにdirtyになるため)。
|
|
62
|
+
*/
|
|
63
|
+
function isCleanAtHead(repoRoot, headSha) {
|
|
64
|
+
return git({ cwd: repoRoot, args: ['rev-parse', '--verify', 'HEAD^{commit}'], operation: 'resolve_head' }) === headSha
|
|
65
|
+
&& git({
|
|
66
|
+
cwd: repoRoot, operation: 'status_clean_check',
|
|
67
|
+
args: ['status', '--porcelain', '--untracked-files=all', '--', '.', ':(exclude).lattice'],
|
|
68
|
+
}) === '';
|
|
69
|
+
}
|
|
64
70
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
71
|
+
/**
|
|
72
|
+
* Observe (ADR 0204): `work(root)` を、`sha` の内容を持つ索引つきの木の上で実行する。
|
|
73
|
+
* HEADと同じ内容の作業木なら、維持されている索引を増分syncして使う(無ければ最初の1回だけinit)。同期の前後で
|
|
74
|
+
* cleanとHEADを確かめ、崩れていたら隔離worktreeへ落とす。`sha` がHEADでない、または作業木がdirtyなら、
|
|
75
|
+
* `sha` の使い捨てworktreeで新しく索引する。保護するもの: 未commitの状態を観測しないこと。落とす先が出口で、拒否はしない。
|
|
76
|
+
*/
|
|
77
|
+
export async function withObservedTree({ repoRoot, sha }, work) {
|
|
78
|
+
if (isCleanAtHead(repoRoot, sha)) {
|
|
79
|
+
await runSensor(existsSync(path.join(repoRoot, '.lattice/sensor/sensor.db')) ? 'sync' : 'init', repoRoot);
|
|
80
|
+
if (isCleanAtHead(repoRoot, sha)) return work(repoRoot);
|
|
81
|
+
}
|
|
82
|
+
const headSha = sha;
|
|
68
83
|
const temporaryRoot = await mkdtemp(path.join(tmpdir(), 'lattice-independence-observation-'));
|
|
69
84
|
const observationRoot = path.join(temporaryRoot, 'worktree');
|
|
70
85
|
let registered = false;
|
|
@@ -86,8 +101,8 @@ export async function collectTodoIndependenceAuthoritativeObservation({ repoRoot
|
|
|
86
101
|
expected_head_sha: headSha, actual_head_sha: observedHead,
|
|
87
102
|
});
|
|
88
103
|
}
|
|
89
|
-
await
|
|
90
|
-
result = await
|
|
104
|
+
await runSensor('init', observationRoot);
|
|
105
|
+
result = await work(observationRoot);
|
|
91
106
|
} catch (error) {
|
|
92
107
|
operationError = error;
|
|
93
108
|
}
|
|
@@ -112,5 +127,20 @@ export async function collectTodoIndependenceAuthoritativeObservation({ repoRoot
|
|
|
112
127
|
});
|
|
113
128
|
}
|
|
114
129
|
if (operationError !== null) throw operationError;
|
|
115
|
-
return
|
|
130
|
+
return result;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** 共有repoのdirtyな状態を観測せず、current HEADの索引(維持されたもの、無ければclean worktree)でsensorを実行する。 */
|
|
134
|
+
export async function collectTodoIndependenceAuthoritativeObservation({ repoRoot, witnessSet } = {}) {
|
|
135
|
+
if (typeof repoRoot !== 'string' || repoRoot.length === 0
|
|
136
|
+
|| witnessSet === null || typeof witnessSet !== 'object') {
|
|
137
|
+
fail('INDEPENDENCE_OBSERVATION_INPUT_INVALID', 'observation_input_invalid');
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const headSha = git({
|
|
141
|
+
cwd: repoRoot, args: ['rev-parse', '--verify', 'HEAD^{commit}'], operation: 'resolve_head',
|
|
142
|
+
});
|
|
143
|
+
const sensorEvidence = await withObservedTree({ repoRoot, sha: headSha },
|
|
144
|
+
(root) => collectWitnessSensorEvidence({ cwd: root, witnessSet }));
|
|
145
|
+
return { head_sha: headSha, sensor_evidence: sensorEvidence };
|
|
116
146
|
}
|
|
@@ -17,6 +17,8 @@ import {
|
|
|
17
17
|
import { TODO_INDEPENDENCE_GUIDANCE_CODES } from './todo-independence-guidance.mjs';
|
|
18
18
|
|
|
19
19
|
export const TODO_WITNESS_SET_SCHEMA = 'lattice.todo_witness_set.v5';
|
|
20
|
+
/** v5 plus `read_anchors` (ADR 0204 §6): written only when a task declares functions it reads, so v5 charts stay v5. */
|
|
21
|
+
export const TODO_WITNESS_SET_READ_ANCHORS_SCHEMA = 'lattice.todo_witness_set.v6';
|
|
20
22
|
/**
|
|
21
23
|
* まだ受理する旧witness set契約。v3以前の厳密なcompile意味を変えず、
|
|
22
24
|
* 既存宣言を書き換えさせないために読み口を残す。
|
|
@@ -28,18 +30,20 @@ export const TODO_WITNESS_SET_LEGACY_SCHEMAS = Object.freeze([
|
|
|
28
30
|
'lattice.todo_witness_set.v1',
|
|
29
31
|
]);
|
|
30
32
|
export const TODO_WITNESS_SET_SCHEMAS = Object.freeze([
|
|
33
|
+
TODO_WITNESS_SET_READ_ANCHORS_SCHEMA,
|
|
31
34
|
TODO_WITNESS_SET_SCHEMA,
|
|
32
35
|
...TODO_WITNESS_SET_LEGACY_SCHEMAS,
|
|
33
36
|
]);
|
|
34
37
|
/** 宣言できる欄はversionごとに違う。どの版から使えるかを1箇所で持つ。 */
|
|
35
38
|
const CONCERN_ANCHOR_SCHEMAS = Object.freeze([
|
|
39
|
+
TODO_WITNESS_SET_READ_ANCHORS_SCHEMA,
|
|
36
40
|
TODO_WITNESS_SET_SCHEMA,
|
|
37
41
|
'lattice.todo_witness_set.v4',
|
|
38
42
|
'lattice.todo_witness_set.v3',
|
|
39
43
|
'lattice.todo_witness_set.v2',
|
|
40
44
|
]);
|
|
41
45
|
const CREATES_SCHEMAS = Object.freeze([
|
|
42
|
-
TODO_WITNESS_SET_SCHEMA, 'lattice.todo_witness_set.v4', 'lattice.todo_witness_set.v3',
|
|
46
|
+
TODO_WITNESS_SET_READ_ANCHORS_SCHEMA, TODO_WITNESS_SET_SCHEMA, 'lattice.todo_witness_set.v4', 'lattice.todo_witness_set.v3',
|
|
43
47
|
]);
|
|
44
48
|
|
|
45
49
|
/** 1 taskが宣言できるconcern anchorの資源数と、資源あたりのsymbol数の上限。 */
|
|
@@ -178,7 +182,7 @@ function boundedText(value, maximumBytes = 4_096) {
|
|
|
178
182
|
export function synthesizeWitnessRunRequest(witnessSet, { baseSha, requestId }) {
|
|
179
183
|
const taskIds = Object.keys(witnessSet.manual_witness).sort(compareText);
|
|
180
184
|
const request = {
|
|
181
|
-
schema: witnessSet.schema === TODO_WITNESS_SET_SCHEMA
|
|
185
|
+
schema: witnessSet.schema === TODO_WITNESS_SET_SCHEMA || witnessSet.schema === TODO_WITNESS_SET_READ_ANCHORS_SCHEMA
|
|
182
186
|
? RUN_REQUEST_SCHEMA
|
|
183
187
|
: witnessSet.schema === 'lattice.todo_witness_set.v4'
|
|
184
188
|
? RUN_REQUEST_PREDICTION_SCHEMA
|
|
@@ -188,7 +192,7 @@ export function synthesizeWitnessRunRequest(witnessSet, { baseSha, requestId })
|
|
|
188
192
|
capacity: witnessSet.capacity,
|
|
189
193
|
todos: taskIds.map((taskId) => ({ todo_id: taskId })),
|
|
190
194
|
manual_witness: Object.fromEntries(taskIds.map((taskId) => {
|
|
191
|
-
const { concern_anchors: _concernAnchors, ...boundary } = witnessSet.manual_witness[taskId];
|
|
195
|
+
const { concern_anchors: _concernAnchors, read_anchors: _readAnchors, ...boundary } = witnessSet.manual_witness[taskId];
|
|
192
196
|
return [taskId, boundary];
|
|
193
197
|
})),
|
|
194
198
|
sensor_query_set: witnessSet.sensor_query_set,
|
|
@@ -280,7 +284,7 @@ export function explainTodoWitnessSet(value) {
|
|
|
280
284
|
for (const taskId of taskIds) {
|
|
281
285
|
const witness = value.manual_witness[taskId];
|
|
282
286
|
if (plain(witness) && Object.hasOwn(witness, 'lines')
|
|
283
|
-
&& value.schema !== TODO_WITNESS_SET_SCHEMA) {
|
|
287
|
+
&& value.schema !== TODO_WITNESS_SET_SCHEMA && value.schema !== TODO_WITNESS_SET_READ_ANCHORS_SCHEMA) {
|
|
284
288
|
return reject('lines_require_witness_set_v5', `/manual_witness/${taskId}/lines`);
|
|
285
289
|
}
|
|
286
290
|
}
|
|
@@ -297,6 +301,15 @@ export function explainTodoWitnessSet(value) {
|
|
|
297
301
|
&& witness.owns.some((own) => Object.hasOwn(own, 'creates'))) {
|
|
298
302
|
return reject('creates_require_witness_set_v3', `/manual_witness/${taskId}/owns`);
|
|
299
303
|
}
|
|
304
|
+
const readAt = `/manual_witness/${taskId}/read_anchors`;
|
|
305
|
+
if (Object.hasOwn(witness, 'read_anchors')) {
|
|
306
|
+
if (value.schema !== TODO_WITNESS_SET_READ_ANCHORS_SCHEMA) {
|
|
307
|
+
return reject('read_anchors_require_witness_set_v6', readAt);
|
|
308
|
+
}
|
|
309
|
+
// A read anchor sits inside a path the task reads (its own `reads` list), the way a write anchor sits inside an owned path.
|
|
310
|
+
const readAnchors = explainConcernAnchors(witness.read_anchors, [], witness.reads, readAt);
|
|
311
|
+
if (!readAnchors.valid) return reject(readAnchors.reason, readAnchors.path);
|
|
312
|
+
}
|
|
300
313
|
const at = `/manual_witness/${taskId}/concern_anchors`;
|
|
301
314
|
if (!Object.hasOwn(witness, 'concern_anchors')) continue;
|
|
302
315
|
if (!CONCERN_ANCHOR_SCHEMAS.includes(value.schema)) {
|
|
@@ -400,6 +413,7 @@ function wavePlan(value, taskIds) {
|
|
|
400
413
|
* conflictは`conflict_resources`のresource idを参照し、kindとnormalized targetを一度だけ保持する。
|
|
401
414
|
* `task_boundaries`はtask別の宣言境界で、鮮度のdiff交差判定をartifactだけで閉じるために持つ。
|
|
402
415
|
* `wave_plan`はschedulability compileが`compiled`を返した時だけ持ち、unknownが残る間はnullになる。
|
|
416
|
+
* `outcome: compiled`で`wave_plan: null`は、exact探索の上限(MAX_TODOS)を超えたため波の計画だけを省いた記録で、verdictは全て揃う(g5)。
|
|
403
417
|
* verdictに現れないペアをverified独立と読めるのは、両taskにunknownが無いときだけである。
|
|
404
418
|
*/
|
|
405
419
|
export function validateTodoIndependence(value) {
|
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
} from './todo-independence-contracts.mjs';
|
|
11
11
|
import { compileRuntimePlanV1, evidenceFromCollectedOutcomes } from './runtime-front-end.mjs';
|
|
12
12
|
import { collectSensorEvidence } from './sensor-adapter.mjs';
|
|
13
|
+
import { refineResourcesByFunction } from './todo-judgment.mjs';
|
|
13
14
|
|
|
14
15
|
export class TodoIndependenceError extends Error {
|
|
15
16
|
constructor(code, reason, detail = {}) {
|
|
@@ -257,7 +258,7 @@ function scopeExpansionFrom({ taskIds, boundaries, previousArtifact, plan }) {
|
|
|
257
258
|
}
|
|
258
259
|
|
|
259
260
|
export function compileTodoIndependence(options = {}) {
|
|
260
|
-
const { witnessSet, plan, baseSha, compiledAt, sensorEvidence, previousArtifact = null } = options;
|
|
261
|
+
const { witnessSet, plan, baseSha, compiledAt, sensorEvidence, previousArtifact = null, functionRanges = null } = options;
|
|
261
262
|
if (!validateTodoWitnessSet(witnessSet)) {
|
|
262
263
|
fail('INDEPENDENCE_WITNESS_INVALID', 'witness_set_invalid');
|
|
263
264
|
}
|
|
@@ -284,6 +285,9 @@ export function compileTodoIndependence(options = {}) {
|
|
|
284
285
|
planRef: witnessRequestId(witnessSet, plan.plan_version),
|
|
285
286
|
planEpoch: 0,
|
|
286
287
|
predecessorRefs: [],
|
|
288
|
+
omitWavesOverLimit: true,
|
|
289
|
+
// a5b: with resolved function ranges, a path declared with functions claims only those functions (ADR 0204 §6 container ruling).
|
|
290
|
+
...(functionRanges === null ? {} : { refineResources: refineResourcesByFunction({ rows: witnessSet.manual_witness, ranges: functionRanges }) }),
|
|
287
291
|
});
|
|
288
292
|
|
|
289
293
|
if (compiled.outcome !== 'dispatchable'
|
|
@@ -316,7 +320,9 @@ export function compileTodoIndependence(options = {}) {
|
|
|
316
320
|
conflicts: conflictProjection.conflicts,
|
|
317
321
|
precedences: dispatchable ? precedencesFrom(compiled.pairwise_verdicts) : [],
|
|
318
322
|
unknowns: dispatchable ? [] : unknownsFrom(compiled.detail),
|
|
319
|
-
wave_plan:
|
|
323
|
+
// g5: `outcome: compiled` with `wave_plan: null` = the exact wave search was omitted (more tasks than MAX_TODOS in the
|
|
324
|
+
// schedulability compiler); every verdict above is still complete. `unknown` is the other reason for null.
|
|
325
|
+
wave_plan: dispatchable && compiled.schedule !== null
|
|
320
326
|
? {
|
|
321
327
|
waves: compiled.schedule.waves.map((wave) => ({
|
|
322
328
|
task_ids: [...wave.todo_ids].sort(compareText),
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// Plan/lifecycle: the add-time conflict judgment (ADR 0204 §3). Pure: it compares one task's declared claims with every other
|
|
2
|
+
// unfinished task's, on resolved ranges the caller passes in. Resolve, sensor and git run outside (transactTodoRelations
|
|
3
|
+
// forbids them inside its lock); nothing here refuses anything.
|
|
4
|
+
|
|
5
|
+
import { digestTodoArtifact } from './todo-contracts.mjs';
|
|
6
|
+
|
|
7
|
+
const compareText = (left, right) => (left < right ? -1 : left > right ? 1 : 0);
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* A task's claims per path, from its witness row: `Map<path, [{symbol, access}]>`. A path declared with anchors is a
|
|
11
|
+
* container: it claims only those functions. A path without anchors claims the whole file (`symbol: null`).
|
|
12
|
+
*/
|
|
13
|
+
export function claimsOf(row) {
|
|
14
|
+
const claims = new Map();
|
|
15
|
+
const add = (target, claim) => claims.set(target, [...(claims.get(target) ?? []), claim]);
|
|
16
|
+
const anchored = (list) => new Map((list ?? []).map(({ within, symbols }) => [within.target, symbols]));
|
|
17
|
+
const concern = anchored(row.concern_anchors);
|
|
18
|
+
const readAnchor = anchored(row.read_anchors);
|
|
19
|
+
const written = new Set([...row.owns.filter(({ kind }) => kind === 'path').map(({ target }) => target), ...row.writes]);
|
|
20
|
+
for (const target of written) for (const symbol of concern.get(target) ?? [null]) add(target, { symbol, access: 'write' });
|
|
21
|
+
for (const target of row.reads) for (const symbol of readAnchor.get(target) ?? [null]) add(target, { symbol, access: 'read' });
|
|
22
|
+
return claims;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** `[{path, symbol}]` of every anchored claim in `claims`, for one batched Resolve. */
|
|
26
|
+
export const anchorsOf = (claims) => [...claims].flatMap(([target, list]) => list
|
|
27
|
+
.filter(({ symbol }) => symbol !== null).map(({ symbol }) => ({ path: target, symbol })));
|
|
28
|
+
|
|
29
|
+
const rangeKey = (target, symbol) => `${target}\0${symbol}`;
|
|
30
|
+
|
|
31
|
+
/** `Map<path\0symbol, {start_line, end_line}>` from Resolve's `resolved` list. */
|
|
32
|
+
export const rangeIndex = (resolved) => new Map(resolved.map(({ path: target, symbol, start_line: start, end_line: end }) => [
|
|
33
|
+
rangeKey(target, symbol), { start_line: start, end_line: end }]));
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Judge `taskId` against every other task in `rows` (`{taskId: witnessRow}`, already limited to unfinished tasks).
|
|
37
|
+
* `ranges` is a `rangeIndex`; an anchored claim with no range (the name no longer resolves) is read as a whole-file claim
|
|
38
|
+
* and counted in `unresolved` (distinct names). Overlap needs at least one write; two reads never conflict (ADR 0204, claim 4).
|
|
39
|
+
* → `{relations: [{task_a, task_b, path, overlaps}], gone: [{task_a, task_b, path}], unresolved}`: `gone` names the pairs of
|
|
40
|
+
* this task that no longer overlap on a path they once shared (the caller closes only those that are open).
|
|
41
|
+
*/
|
|
42
|
+
export function judgeTask({ taskId, rows, ranges, openRelations = [], only = null }) {
|
|
43
|
+
const mine = claimsOf(rows[taskId]);
|
|
44
|
+
const relations = [];
|
|
45
|
+
const missing = new Set();
|
|
46
|
+
const side = (target, claim) => {
|
|
47
|
+
const range = claim.symbol === null ? undefined : ranges.get(rangeKey(target, claim.symbol));
|
|
48
|
+
if (claim.symbol !== null && range === undefined) missing.add(rangeKey(target, claim.symbol));
|
|
49
|
+
return range === undefined
|
|
50
|
+
? { symbol: null, start_line: null, end_line: null, access: claim.access }
|
|
51
|
+
: { symbol: claim.symbol, start_line: range.start_line, end_line: range.end_line, access: claim.access };
|
|
52
|
+
};
|
|
53
|
+
const overlap = (left, right) => left.symbol === null || right.symbol === null
|
|
54
|
+
|| !(left.end_line < right.start_line || right.end_line < left.start_line);
|
|
55
|
+
for (const otherId of Object.keys(rows).sort(compareText)) {
|
|
56
|
+
if (otherId === taskId) continue;
|
|
57
|
+
const [taskA, taskB] = taskId < otherId ? [taskId, otherId] : [otherId, taskId];
|
|
58
|
+
const theirs = claimsOf(rows[otherId]);
|
|
59
|
+
for (const [target, claims] of [...mine].sort(([left], [right]) => compareText(left, right))) {
|
|
60
|
+
const others = theirs.get(target);
|
|
61
|
+
if (others === undefined) continue;
|
|
62
|
+
const found = new Map();
|
|
63
|
+
for (const claim of claims) {
|
|
64
|
+
for (const other of others) {
|
|
65
|
+
if (claim.access === 'read' && other.access === 'read') continue;
|
|
66
|
+
// `only` narrows to one resource's meaning (a5b): 'ww' = both write, 'rw' = one writes and the other reads.
|
|
67
|
+
if ((only === 'ww' && (claim.access !== 'write' || other.access !== 'write')) || (only === 'rw' && claim.access === other.access)) continue;
|
|
68
|
+
const [first, second] = taskA === taskId ? [side(target, claim), side(target, other)] : [side(target, other), side(target, claim)];
|
|
69
|
+
if (!overlap(first, second)) continue;
|
|
70
|
+
found.set(JSON.stringify([first, second]), { a: first, b: second });
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (found.size > 0) {
|
|
74
|
+
relations.push({ task_a: taskA, task_b: taskB, path: target,
|
|
75
|
+
overlaps: [...found.entries()].sort(([left], [right]) => compareText(left, right)).map(([, entry]) => entry) });
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const keep = new Set(relations.map(({ task_a: a, task_b: b, path: target }) => `${a}\0${b}\0${target}`));
|
|
80
|
+
const gone = openRelations
|
|
81
|
+
.filter(({ task_a: a, task_b: b, path: target }) => (a === taskId || b === taskId) && !keep.has(`${a}\0${b}\0${target}`))
|
|
82
|
+
.map(({ task_a: a, task_b: b, path: target }) => ({ task_a: a, task_b: b, path: target }));
|
|
83
|
+
return { relations, gone, unresolved: missing.size };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The other tasks' anchored claims on the paths `paths` (a Set) touches: what the same Resolve call must also answer so
|
|
88
|
+
* `judgeTask` can compare ranges. Rows are witness rows (`manual_witness`); `taskId`'s own row is skipped.
|
|
89
|
+
*/
|
|
90
|
+
export function neededAnchors(rows, taskId, paths) {
|
|
91
|
+
const found = new Map();
|
|
92
|
+
for (const [otherId, row] of Object.entries(rows)) {
|
|
93
|
+
if (otherId === taskId) continue;
|
|
94
|
+
for (const anchor of anchorsOf(claimsOf(row))) if (paths.has(anchor.path)) found.set(`${anchor.path}\0${anchor.symbol}`, anchor);
|
|
95
|
+
}
|
|
96
|
+
return [...found.values()];
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* ADR 0204 a5b: narrow the compile's shared path resources to the task pairs that really overlap. A resource on path P
|
|
101
|
+
* (an owned path `own-…`, or a read x write `rw-…` state on P) is shared by `todo_ids`; when both tasks of a pair claim
|
|
102
|
+
* P and at least one of them declared functions in it, the pair stays only if `judgeTask` finds an overlap (same function,
|
|
103
|
+
* overlapping lines, a write on either side). A pair with no claim on exactly P, or with only whole-file claims, stays
|
|
104
|
+
* as the compile made it. → a function for `compileRuntimePlanV1`'s `refineResources`.
|
|
105
|
+
*/
|
|
106
|
+
export function refineResourcesByFunction({ rows, ranges }) {
|
|
107
|
+
const comparable = (target, first, second) => {
|
|
108
|
+
const left = claimsOf(rows[first] ?? {owns: [], reads: [], writes: []}).get(target);
|
|
109
|
+
const right = claimsOf(rows[second] ?? {owns: [], reads: [], writes: []}).get(target);
|
|
110
|
+
return left !== undefined && right !== undefined && [...left, ...right].some(({ symbol }) => symbol !== null);
|
|
111
|
+
};
|
|
112
|
+
const overlaps = (target, first, second, only) => judgeTask({ taskId: first, rows: { [first]: rows[first], [second]: rows[second] }, ranges, only })
|
|
113
|
+
.relations.some(({ path: where }) => where === target);
|
|
114
|
+
// The path a shared resource stands for, or null when it is not one this can narrow: an owned path (`own-…`), a read x write
|
|
115
|
+
// state on one path (`rw-…`), or a predicted write overlap of one path with itself (`predicted-ww-…`, target `P ↔ P`).
|
|
116
|
+
const pathOf = (resource) => {
|
|
117
|
+
if (resource.kind === 'path' && resource.resource_id.startsWith('own-')) return resource.target;
|
|
118
|
+
if (resource.kind !== 'state') return null;
|
|
119
|
+
if (resource.resource_id.startsWith('rw-')) return resource.target;
|
|
120
|
+
const [left, right, ...rest] = resource.target.split(' ↔ ');
|
|
121
|
+
return resource.resource_id.startsWith('predicted-ww-') && rest.length === 0 && left === right ? left : null;
|
|
122
|
+
};
|
|
123
|
+
return (resources) => resources.flatMap((resource) => {
|
|
124
|
+
const target = pathOf(resource);
|
|
125
|
+
if (target === null || resource.todo_ids.length < 2) return [resource];
|
|
126
|
+
const pairs = [];
|
|
127
|
+
for (let left = 0; left < resource.todo_ids.length; left += 1) {
|
|
128
|
+
for (let right = left + 1; right < resource.todo_ids.length; right += 1) pairs.push([resource.todo_ids[left], resource.todo_ids[right]]);
|
|
129
|
+
}
|
|
130
|
+
const kept = pairs.filter(([first, second]) => !comparable(target, first, second) || overlaps(target, first, second, resource.resource_id.startsWith('rw-') ? 'rw' : 'ww'));
|
|
131
|
+
if (kept.length === pairs.length) return [resource];
|
|
132
|
+
return kept.map(([first, second]) => ({ ...resource,
|
|
133
|
+
resource_id: `${resource.resource_id}-fn-${digestTodoArtifact({ first, second }).slice(0, 12)}`, todo_ids: [first, second] }));
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** One relation as seen from `taskId`: `{with, path, overlaps: [{self, other}]}` (`self` is this task's side). */
|
|
138
|
+
export function relationView(taskId, { task_a: a, task_b: b, path: where, overlaps }) {
|
|
139
|
+
return { with: a === taskId ? b : a, path: where,
|
|
140
|
+
overlaps: overlaps.map(({ a: first, b: second }) => (a === taskId ? { self: first, other: second } : { self: second, other: first })) };
|
|
141
|
+
}
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
// ADR 0204 a4: per-plan function-level conflict relations. docs/architecture/dfd-store-relations.md
|
|
2
|
+
import { appendFile, lstat, mkdir, readFile, readdir, rename, rm } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { LOCK_WAIT_MS, StoreLockError, withStoreLock } from './store-lock.mjs';
|
|
5
|
+
import {
|
|
6
|
+
TODO_RELATION_EVENT_SCHEMA, TODO_RELATION_SUMMARY_OPEN, TODO_RELATION_SUMMARY_SCHEMA,
|
|
7
|
+
canonicalizeTodoArtifact, exactRecord, isStrictTodoTimestamp, isTodoIdentifier, todoRelationId,
|
|
8
|
+
todoRelationOverlapsValid, validateTodoRelationEvent, validateTodoRelationSummary,
|
|
9
|
+
} from './todo-contracts.mjs';
|
|
10
|
+
import {
|
|
11
|
+
TodoStoreError, atomicWrite, readTodoStore, readTodoWitnessSet, rejectNewerTodoSchema, requireTodoStoreWriter,
|
|
12
|
+
writeTodoWitnessSet,
|
|
13
|
+
} from './todo-store.mjs';
|
|
14
|
+
|
|
15
|
+
const ROOT_REF = '.lattice/todo/relations';
|
|
16
|
+
const TASK_FILE_MAX_BYTES = 4_194_304;
|
|
17
|
+
const LOG_SEGMENT_BYTES = 4_194_304;
|
|
18
|
+
const SUMMARY_MAX_BYTES = 65_536;
|
|
19
|
+
const FINISHED = new Set(['done', 'retired']);
|
|
20
|
+
|
|
21
|
+
const fail = (code, reason, detail) => { throw new TodoStoreError(code, reason, reason, detail); };
|
|
22
|
+
const line = (value) => Buffer.from(`${canonicalizeTodoArtifact(value)}\n`, 'utf8');
|
|
23
|
+
const keyOf = ({ task_a: a, task_b: b, path: p }) => `${a}\0${b}\0${p}`;
|
|
24
|
+
const refs = (planKey) => ({ dir: `${ROOT_REF}/${planKey}`, open: `${ROOT_REF}/${planKey}/open`,
|
|
25
|
+
log: `${ROOT_REF}/${planKey}/log.jsonl`, summary: `${ROOT_REF}/${planKey}/summary.json`,
|
|
26
|
+
task: (taskId) => `${ROOT_REF}/${planKey}/open/${taskId}.json` });
|
|
27
|
+
|
|
28
|
+
function planKeyOf(planKey) {
|
|
29
|
+
if (!isTodoIdentifier(planKey)) throw new TypeError('planKey must be a todo identifier');
|
|
30
|
+
return planKey;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** A file under the relation directory: missing = null; a symlink, non-file or oversize file is invalid. */
|
|
34
|
+
async function readBounded(repoRoot, ref, maxBytes) {
|
|
35
|
+
const absolute = path.resolve(repoRoot, ref);
|
|
36
|
+
try {
|
|
37
|
+
const state = await lstat(absolute);
|
|
38
|
+
if (state.isSymbolicLink() || !state.isFile() || state.size > maxBytes) {
|
|
39
|
+
fail('STORE_INCONSISTENT', 'relation_file_invalid', { ref });
|
|
40
|
+
}
|
|
41
|
+
return await readFile(absolute, 'utf8');
|
|
42
|
+
} catch (error) {
|
|
43
|
+
if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') return null;
|
|
44
|
+
throw error;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function parseLines(text, ref, validate, family) {
|
|
49
|
+
if (text === null || text === '') return [];
|
|
50
|
+
if (!text.endsWith('\n')) fail('STORE_INCONSISTENT', 'relation_log_invalid', { ref });
|
|
51
|
+
return text.slice(0, -1).split('\n').map((entry) => {
|
|
52
|
+
let value;
|
|
53
|
+
try { value = JSON.parse(entry); } catch { fail('STORE_INCONSISTENT', 'relation_log_invalid', { ref }); }
|
|
54
|
+
if (!validate(value)) {
|
|
55
|
+
rejectNewerTodoSchema(value, family, ref);
|
|
56
|
+
fail('STORE_INCONSISTENT', 'relation_log_invalid', { ref });
|
|
57
|
+
}
|
|
58
|
+
return value;
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The open relations of one task: its file, one `relation` event per line (missing file = none). */
|
|
63
|
+
async function readTaskFile(repoRoot, planKey, taskId) {
|
|
64
|
+
const ref = refs(planKey).task(taskId);
|
|
65
|
+
const about = (event) => validateTodoRelationEvent(event) && event.kind === 'relation'
|
|
66
|
+
&& (event.task_a === taskId || event.task_b === taskId);
|
|
67
|
+
return parseLines(await readBounded(repoRoot, ref, TASK_FILE_MAX_BYTES), ref, about, 'todo_relation_event');
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The plan's relation summary, or null when it has none (a missing file is "no records", not an error).
|
|
72
|
+
* Reads exactly this one small file and never verifies it (ADR 0203).
|
|
73
|
+
*/
|
|
74
|
+
export async function readTodoRelationSummary({ repoRoot = process.cwd(), planKey } = {}) {
|
|
75
|
+
const ref = refs(planKeyOf(planKey)).summary;
|
|
76
|
+
const text = await readBounded(path.resolve(repoRoot), ref, SUMMARY_MAX_BYTES);
|
|
77
|
+
if (text === null) return null;
|
|
78
|
+
let value;
|
|
79
|
+
try { value = JSON.parse(text); } catch { fail('STORE_INCONSISTENT', 'relation_summary_invalid', { ref }); }
|
|
80
|
+
rejectNewerTodoSchema(value, 'todo_relation_summary', ref);
|
|
81
|
+
if (!validateTodoRelationSummary(value) || value.plan_key !== planKey) {
|
|
82
|
+
fail('STORE_INCONSISTENT', 'relation_summary_invalid', { ref });
|
|
83
|
+
}
|
|
84
|
+
return value;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* a4c: one task's open relations and the plan's counts, from two small bounded files (the summary and `open/<task>.json`);
|
|
89
|
+
* never the history. → null when the plan has no open relation, else
|
|
90
|
+
* `{relation_count, unresolved_count, head_sha, open: [{task_a, task_b, path, overlaps}]}` (this task's, by pair and path).
|
|
91
|
+
* Unreadable or damaged: STORE_INCONSISTENT, as the summary read.
|
|
92
|
+
*/
|
|
93
|
+
export async function readTodoTaskRelations({ repoRoot = process.cwd(), planKey, taskId } = {}) {
|
|
94
|
+
if (!isTodoIdentifier(taskId)) throw new TypeError('taskId must be a todo identifier');
|
|
95
|
+
const root = path.resolve(repoRoot);
|
|
96
|
+
const summary = await readTodoRelationSummary({ repoRoot: root, planKey });
|
|
97
|
+
if (summary === null || summary.relation_count === 0) return null;
|
|
98
|
+
const open = (await readTaskFile(root, planKey, taskId)).map(({ task_a: a, task_b: b, path: where, overlaps }) => ({
|
|
99
|
+
task_a: a, task_b: b, path: where, overlaps })).sort((left, right) => (keyOf(left) < keyOf(right) ? -1 : 1));
|
|
100
|
+
return { relation_count: summary.relation_count, unresolved_count: summary.unresolved_count, head_sha: summary.head_sha, open };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Every task file of the plan: `Map<taskId, Map<key, event>>` (the open set; names that are not task ids are ignored). */
|
|
104
|
+
async function readOpenFiles(repoRoot, planKey) {
|
|
105
|
+
const names = await readdir(path.resolve(repoRoot, refs(planKey).open)).catch((error) => {
|
|
106
|
+
if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') return [];
|
|
107
|
+
throw error;
|
|
108
|
+
});
|
|
109
|
+
const files = new Map();
|
|
110
|
+
for (const name of names) {
|
|
111
|
+
const taskId = name.endsWith('.json') ? name.slice(0, -5) : null;
|
|
112
|
+
if (!isTodoIdentifier(taskId)) continue;
|
|
113
|
+
files.set(taskId, new Map((await readTaskFile(repoRoot, planKey, taskId)).map((event) => [keyOf(event), event])));
|
|
114
|
+
}
|
|
115
|
+
return files;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function ensureRelationDirectory(repoRoot, planKey) {
|
|
119
|
+
const stale = () => fail('STORE_WRITE_CONFLICT', 'store_locked', {
|
|
120
|
+
next_action: 'Initialize a published Todo Store before writing relations, then retry.',
|
|
121
|
+
});
|
|
122
|
+
for (const ref of ['.lattice', '.lattice/todo', '.lattice/todo/manifest.json']) {
|
|
123
|
+
const state = await lstat(path.resolve(repoRoot, ref)).catch((error) => {
|
|
124
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
125
|
+
return null;
|
|
126
|
+
});
|
|
127
|
+
if (state === null || state.isSymbolicLink() || (ref.endsWith('.json') ? !state.isFile() : !state.isDirectory())) stale();
|
|
128
|
+
}
|
|
129
|
+
for (const ref of [ROOT_REF, refs(planKey).dir, refs(planKey).open]) {
|
|
130
|
+
const absolute = path.resolve(repoRoot, ref);
|
|
131
|
+
await mkdir(absolute).catch((error) => { if (error?.code !== 'EEXIST') throw error; });
|
|
132
|
+
const state = await lstat(absolute);
|
|
133
|
+
if (state.isSymbolicLink() || !state.isDirectory()) fail('STORE_INCONSISTENT', 'relation_file_invalid', { ref });
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const sameOverlaps = (left, right) => canonicalizeTodoArtifact(left) === canonicalizeTodoArtifact(right);
|
|
138
|
+
|
|
139
|
+
function checkInput(result) {
|
|
140
|
+
if (result === null || typeof result !== 'object' || Array.isArray(result)
|
|
141
|
+
|| Object.keys(result).some((key) => !['witnessSet', 'relations', 'gone', 'headSha', 'unresolvedCount', 'computedAt']
|
|
142
|
+
.includes(key))) throw new TypeError('relation update result invalid');
|
|
143
|
+
const relations = result.relations ?? [];
|
|
144
|
+
const gone = result.gone ?? [];
|
|
145
|
+
const pair = (value, keys) => exactRecord(value, keys) && isTodoIdentifier(value.task_a)
|
|
146
|
+
&& isTodoIdentifier(value.task_b) && value.task_a < value.task_b
|
|
147
|
+
&& typeof value.path === 'string' && value.path.length > 0 && value.path.length <= 1024;
|
|
148
|
+
if (!Array.isArray(relations) || !Array.isArray(gone)
|
|
149
|
+
|| !relations.every((entry) => pair(entry, ['task_a', 'task_b', 'path', 'overlaps'])
|
|
150
|
+
&& todoRelationOverlapsValid(entry.overlaps))
|
|
151
|
+
|| !gone.every((entry) => pair(entry, ['task_a', 'task_b', 'path']))
|
|
152
|
+
|| new Set(relations.map(keyOf)).size !== relations.length
|
|
153
|
+
|| (result.headSha !== undefined && result.headSha !== null
|
|
154
|
+
&& (typeof result.headSha !== 'string' || result.headSha.length === 0 || result.headSha.length > 1024))
|
|
155
|
+
|| (result.unresolvedCount !== undefined
|
|
156
|
+
&& !(Number.isSafeInteger(result.unresolvedCount) && result.unresolvedCount >= 0))
|
|
157
|
+
|| (result.computedAt !== undefined && !isStrictTodoTimestamp(result.computedAt))) {
|
|
158
|
+
throw new TypeError('relation update result invalid');
|
|
159
|
+
}
|
|
160
|
+
return { relations, gone };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** The history log: appended, never read. At LOG_SEGMENT_BYTES the file is sealed under its last sequence and a new one starts. */
|
|
164
|
+
async function appendHistory(repoRoot, logRef, lastSequence, events) {
|
|
165
|
+
const absolute = path.resolve(repoRoot, logRef);
|
|
166
|
+
const state = await lstat(absolute).catch((error) => {
|
|
167
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
168
|
+
return null;
|
|
169
|
+
});
|
|
170
|
+
if (state !== null && (state.isSymbolicLink() || !state.isFile())) fail('STORE_INCONSISTENT', 'relation_file_invalid', { ref: logRef });
|
|
171
|
+
if (state !== null && state.size >= LOG_SEGMENT_BYTES) {
|
|
172
|
+
await rename(absolute, path.resolve(path.dirname(absolute), `log-${lastSequence}.jsonl`));
|
|
173
|
+
}
|
|
174
|
+
await appendFile(absolute, Buffer.concat(events.map(line)), { mode: 0o644 });
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* ADR 0204: one transaction over a plan's witness set and relation record, so two adds at once never miss each other.
|
|
179
|
+
* Under `relations/<planKey>/.write.lock` Store reads the witness set, the open relations and the plan's unfinished task
|
|
180
|
+
* ids, calls `update({witnessSet, openRelations, logSequence, unfinishedTaskIds})` (no Resolve, sensor or git inside:
|
|
181
|
+
* it only compares resolved ranges), then writes witness set, log, summary in that order. A crash between them leaves the
|
|
182
|
+
* row without its relations; the next write of that task recomputes its pairs (ids are content digests).
|
|
183
|
+
* Open relations are one per {task_a, task_b, path}: a changed one replaces the old, an identical one is a no-op, `gone`
|
|
184
|
+
* closes by key, and a relation of a task that is no longer unfinished is closed without being asked.
|
|
185
|
+
* Never call this while holding the Todo Store lock: this takes the relations lock first, then reads the Store.
|
|
186
|
+
*/
|
|
187
|
+
export async function transactTodoRelations({ repoRoot = process.cwd(), planKey, writer, update } = {}) {
|
|
188
|
+
requireTodoStoreWriter(writer, 'todo-relations');
|
|
189
|
+
planKeyOf(planKey);
|
|
190
|
+
if (typeof update !== 'function') throw new TypeError('update must be a function');
|
|
191
|
+
const root = path.resolve(repoRoot);
|
|
192
|
+
const { dir, log: logRef, summary: summaryRef } = refs(planKey);
|
|
193
|
+
await ensureRelationDirectory(root, planKey);
|
|
194
|
+
try {
|
|
195
|
+
return await withStoreLock({ lockPath: path.join(root, dir, '.write.lock'), createParent: false,
|
|
196
|
+
waitMs: LOCK_WAIT_MS }, async (assertHeld) => {
|
|
197
|
+
const store = await readTodoStore({ repoRoot: root });
|
|
198
|
+
const member = store.members.find(({ descriptor }) => descriptor.plan_key === planKey);
|
|
199
|
+
if (member === undefined) throw new TypeError('planKey is not an active plan of this Store');
|
|
200
|
+
const unfinished = new Set(member.tasks.filter(({ status }) => !FINISHED.has(status)).map(({ task_id: id }) => id));
|
|
201
|
+
const files = await readOpenFiles(root, planKey);
|
|
202
|
+
const dirty = new Set();
|
|
203
|
+
const open = new Map();
|
|
204
|
+
for (const entries of files.values()) {
|
|
205
|
+
for (const [key, event] of entries) if ((open.get(key)?.sequence ?? 0) < event.sequence) open.set(key, event);
|
|
206
|
+
}
|
|
207
|
+
// A relation lives in both its tasks' files; a crash between the two writes leaves one side: complete it.
|
|
208
|
+
const place = (event) => {
|
|
209
|
+
for (const id of [event.task_a, event.task_b]) {
|
|
210
|
+
if (!files.has(id)) files.set(id, new Map());
|
|
211
|
+
const held = files.get(id).get(keyOf(event));
|
|
212
|
+
if (held?.sequence !== event.sequence || held.relation_id !== event.relation_id) {
|
|
213
|
+
files.get(id).set(keyOf(event), event);
|
|
214
|
+
dirty.add(id);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
};
|
|
218
|
+
const unplace = (event) => {
|
|
219
|
+
for (const id of [event.task_a, event.task_b]) if (files.get(id)?.delete(keyOf(event))) dirty.add(id);
|
|
220
|
+
};
|
|
221
|
+
for (const event of open.values()) place(event);
|
|
222
|
+
const previous = await readTodoRelationSummary({ repoRoot: root, planKey });
|
|
223
|
+
const witnessSet = await readTodoWitnessSet({ repoRoot: root, planKey });
|
|
224
|
+
const lastSequence = Math.max(previous?.log_sequence ?? 0, ...[...open.values()].map(({ sequence }) => sequence));
|
|
225
|
+
|
|
226
|
+
const result = await update({ witnessSet, openRelations: [...open.values()].map((event) => structuredClone(event)),
|
|
227
|
+
logSequence: lastSequence, unfinishedTaskIds: [...unfinished].sort() });
|
|
228
|
+
const { relations, gone } = checkInput(result ?? {});
|
|
229
|
+
const computedAt = result?.computedAt ?? new Date().toISOString();
|
|
230
|
+
const headSha = result?.headSha === undefined ? previous?.head_sha ?? null : result.headSha;
|
|
231
|
+
const unresolvedCount = result?.unresolvedCount ?? previous?.unresolved_count ?? 0;
|
|
232
|
+
|
|
233
|
+
const appended = [];
|
|
234
|
+
let sequence = lastSequence;
|
|
235
|
+
const close = (event) => {
|
|
236
|
+
open.delete(keyOf(event));
|
|
237
|
+
unplace(event);
|
|
238
|
+
appended.push({ schema: TODO_RELATION_EVENT_SCHEMA, kind: 'gone', sequence: ++sequence,
|
|
239
|
+
relation_id: event.relation_id, task_a: event.task_a, task_b: event.task_b, path: event.path,
|
|
240
|
+
head_sha: headSha, computed_at: computedAt });
|
|
241
|
+
};
|
|
242
|
+
for (const event of [...open.values()]) {
|
|
243
|
+
if (!unfinished.has(event.task_a) || !unfinished.has(event.task_b)) close(event);
|
|
244
|
+
}
|
|
245
|
+
for (const entry of gone) if (open.has(keyOf(entry))) close(open.get(keyOf(entry)));
|
|
246
|
+
let added = 0;
|
|
247
|
+
for (const entry of relations) {
|
|
248
|
+
if (!unfinished.has(entry.task_a) || !unfinished.has(entry.task_b)) continue;
|
|
249
|
+
const id = todoRelationId(entry);
|
|
250
|
+
const current = open.get(keyOf(entry));
|
|
251
|
+
if (current !== undefined && current.relation_id === id && sameOverlaps(current.overlaps, entry.overlaps)) continue;
|
|
252
|
+
if (current !== undefined) close(current);
|
|
253
|
+
const event = { schema: TODO_RELATION_EVENT_SCHEMA, kind: 'relation', sequence: ++sequence, relation_id: id,
|
|
254
|
+
task_a: entry.task_a, task_b: entry.task_b, path: entry.path, overlaps: entry.overlaps,
|
|
255
|
+
head_sha: headSha, computed_at: computedAt };
|
|
256
|
+
if (!validateTodoRelationEvent(event)) throw new TypeError('relation update result invalid');
|
|
257
|
+
open.set(keyOf(entry), event);
|
|
258
|
+
place(event);
|
|
259
|
+
appended.push(event);
|
|
260
|
+
added += 1;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const openList = [...open.values()].sort((left, right) => right.sequence - left.sequence);
|
|
264
|
+
const summary = { schema: TODO_RELATION_SUMMARY_SCHEMA, plan_key: planKey, relation_count: openList.length,
|
|
265
|
+
open_relations: openList.slice(0, TODO_RELATION_SUMMARY_OPEN).map(({ relation_id: id, task_a: a, task_b: b,
|
|
266
|
+
path: p, overlaps }) => ({ relation_id: id, task_a: a, task_b: b, path: p, overlaps })),
|
|
267
|
+
open_truncated: openList.length > TODO_RELATION_SUMMARY_OPEN, unresolved_count: unresolvedCount,
|
|
268
|
+
head_sha: headSha, log_sequence: sequence, computed_at: computedAt };
|
|
269
|
+
const stable = ({ computed_at: _at, ...rest }) => canonicalizeTodoArtifact(rest);
|
|
270
|
+
// The summary is recounted from the task files, so a crash that left it behind is healed by any later write.
|
|
271
|
+
const summaryChanged = previous === null
|
|
272
|
+
? appended.length > 0 || openList.length > 0 || result?.headSha !== undefined || result?.unresolvedCount !== undefined
|
|
273
|
+
: stable(summary) !== stable(previous);
|
|
274
|
+
|
|
275
|
+
await assertHeld();
|
|
276
|
+
let writtenWitness = witnessSet;
|
|
277
|
+
if (result?.witnessSet !== undefined && result.witnessSet !== null) {
|
|
278
|
+
writtenWitness = (await writeTodoWitnessSet({ repoRoot: root, witnessSet: result.witnessSet })).witnessSet;
|
|
279
|
+
}
|
|
280
|
+
for (const id of [...dirty].sort()) {
|
|
281
|
+
const target = path.resolve(root, refs(planKey).task(id));
|
|
282
|
+
if (files.get(id).size === 0) await rm(target, { force: true });
|
|
283
|
+
else await atomicWrite(target, Buffer.concat([...files.get(id).values()].sort((l, r) => l.sequence - r.sequence).map(line)));
|
|
284
|
+
}
|
|
285
|
+
if (summaryChanged) await atomicWrite(path.resolve(root, summaryRef), line(summary));
|
|
286
|
+
if (appended.length > 0) await appendHistory(root, logRef, lastSequence, appended);
|
|
287
|
+
return { witnessSet: writtenWitness, summary: summaryChanged ? summary : previous, appended: added,
|
|
288
|
+
gone: appended.length - added };
|
|
289
|
+
});
|
|
290
|
+
} catch (error) {
|
|
291
|
+
if (error instanceof StoreLockError) fail('STORE_WRITE_CONFLICT', error.reason, error.detail);
|
|
292
|
+
throw error;
|
|
293
|
+
}
|
|
294
|
+
}
|