@software-dlc/cli 0.192.8 → 0.192.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/dist/local/app-contract-readers.d.ts.map +1 -1
  3. package/dist/local/app-contract-readers.js +12 -0
  4. package/dist/local/app-contract-readers.js.map +1 -1
  5. package/dist/local/app-tasks-read.d.ts +18 -0
  6. package/dist/local/app-tasks-read.d.ts.map +1 -1
  7. package/dist/local/app-tasks-read.js +24 -10
  8. package/dist/local/app-tasks-read.js.map +1 -1
  9. package/dist/local/health-schema.d.ts +3 -3
  10. package/dist/local/projection-stat-pool.d.ts +2 -0
  11. package/dist/local/projection-stat-pool.d.ts.map +1 -0
  12. package/dist/local/projection-stat-pool.js +96 -0
  13. package/dist/local/projection-stat-pool.js.map +1 -0
  14. package/dist/local/projection.d.ts +25 -1
  15. package/dist/local/projection.d.ts.map +1 -1
  16. package/dist/local/projection.js +124 -42
  17. package/dist/local/projection.js.map +1 -1
  18. package/dist/local/source-evidence/schema.d.ts +2 -2
  19. package/dist/local/task-context-observations.d.ts +8 -8
  20. package/dist/local/task-context-schema.d.ts +1 -1
  21. package/dist/local/workspace-change-commit.d.ts +110 -0
  22. package/dist/local/workspace-change-commit.d.ts.map +1 -0
  23. package/dist/local/workspace-change-commit.js +354 -0
  24. package/dist/local/workspace-change-commit.js.map +1 -0
  25. package/dist/local/workspace-commit-generations.d.ts +12 -4
  26. package/dist/local/workspace-commit-generations.d.ts.map +1 -1
  27. package/dist/local/workspace-commit-generations.js +48 -27
  28. package/dist/local/workspace-commit-generations.js.map +1 -1
  29. package/dist/local/workspace-graph-store.d.ts +30 -1
  30. package/dist/local/workspace-graph-store.d.ts.map +1 -1
  31. package/dist/local/workspace-graph-store.js +86 -1
  32. package/dist/local/workspace-graph-store.js.map +1 -1
  33. package/dist/local/workspace-graph-tree.d.ts +42 -0
  34. package/dist/local/workspace-graph-tree.d.ts.map +1 -1
  35. package/dist/local/workspace-graph-tree.js +189 -0
  36. package/dist/local/workspace-graph-tree.js.map +1 -1
  37. package/dist/local/workspace-overlap-allocation.d.ts +5 -3
  38. package/dist/local/workspace-overlap-allocation.d.ts.map +1 -1
  39. package/dist/local/workspace-overlap-allocation.js +3 -7
  40. package/dist/local/workspace-overlap-allocation.js.map +1 -1
  41. package/dist/local/workspace-overlap-impact.d.ts.map +1 -1
  42. package/dist/local/workspace-overlap-impact.js +12 -1
  43. package/dist/local/workspace-overlap-impact.js.map +1 -1
  44. package/dist/local/workspace-overlap-index.d.ts +179 -0
  45. package/dist/local/workspace-overlap-index.d.ts.map +1 -0
  46. package/dist/local/workspace-overlap-index.js +559 -0
  47. package/dist/local/workspace-overlap-index.js.map +1 -0
  48. package/dist/local/workspace-overlap.d.ts +41 -9
  49. package/dist/local/workspace-overlap.d.ts.map +1 -1
  50. package/dist/local/workspace-overlap.js +336 -140
  51. package/dist/local/workspace-overlap.js.map +1 -1
  52. package/dist/local/workspace-runtime.d.ts +71 -1
  53. package/dist/local/workspace-runtime.d.ts.map +1 -1
  54. package/dist/local/workspace-runtime.js +626 -66
  55. package/dist/local/workspace-runtime.js.map +1 -1
  56. package/package.json +2 -2
  57. package/viewer/assets/index-CTZHobW_.js +389 -0
  58. package/viewer/assets/index-Cck9Xf1-.css +1 -0
  59. package/viewer/index.html +2 -2
  60. package/viewer/assets/index-B5o6MLCA.js +0 -389
  61. package/viewer/assets/index-DJmPW-on.css +0 -1
@@ -1,8 +1,11 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
- import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
3
- import { join, resolve } from 'node:path';
2
+ import { readdirSync, statSync } from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import { mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
5
+ import { dirname, join, resolve } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
4
7
  import { getLibraryOriginWarnings } from '@software-dlc/graph/validator';
5
- import { composeGraphProjection, diffProjectionGraphs, extendScopedProjection, graphHasProjectionEntity, hasProjectionManifest, isScopedProjection, materializeGraphProjection, projectionDiffHasChanges, projectionHasManagedContent, projectionScopeOfTaskScope, recordScopedProjectionFiles, assertProjectionNotForeign, removeEmptyGraphProjection, removeProjectionEntity, validateProjectionGraph, writeJsonAtomically } from './projection.js';
8
+ import { composeGraphProjection, diffProjectionGraphs, extendScopedProjection, graphHasProjectionEntity, hasProjectionManifest, isScopedProjection, materializeGraphProjection, PROJECTION_MANIFEST_FILE, projectionDiffHasChanges, projectionHasManagedContent, projectionScopeOfTaskScope, recordScopedProjectionFiles, assertProjectionNotForeign, removeEmptyGraphProjection, removeProjectionEntity, validateProjectionGraph, writeJsonAtomically } from './projection.js';
6
9
  import { heldPackages, packageUseCommitIssues } from './package-uses-check.js';
7
10
  import { introducedBrokenIssues, introducedValidationWarnings } from './workspace-merge.js';
8
11
  import { planEvidenceSign, signedMeta } from './workspace-evidence.js';
@@ -16,8 +19,11 @@ import { findGraphEntities, showGraphEntities } from './graph-read.js';
16
19
  import { readFolderMembers, repositoryTaskScope } from './folder-members.js';
17
20
  import { variantMemberFormIds, variantSyncIds, variantsReport } from './variants.js';
18
21
  import { withWorkspaceOperationLock } from './workspace-lock.js';
19
- import { noteHead } from './operation-costs.js';
22
+ import { noteGraphNodes, noteHead, notePhase } from './operation-costs.js';
23
+ import { changedProjectionFiles, commitCheckKey, graphShapeWarningsOfCounts, neighborhoodGraph, neighborhoodKeys, parseCommitCheck, projectionFileStats, projectionTreeEdits, startingCountsAfter, startingNodeCounts, wholeGraphReason } from './workspace-change-commit.js';
24
+ import { projectionStatRowsMany } from './projection-stat-pool.js';
20
25
  import { allocationUnits, compareLocalWorkspacePlans } from './workspace-overlap.js';
26
+ import { diffCoordinates, entityKey, loadRefIndex, LocalGraphRefIndex } from './workspace-overlap-index.js';
21
27
  import { allocationUnitKey, combineValidationUnits, firstOwnChanges } from './workspace-overlap-allocation.js';
22
28
  import { LocalWorkspaceCommitResolver } from './workspace-commit-resolver.js';
23
29
  import { LocalWorkspaceAuthorityGuard } from './workspace-authority-guard.js';
@@ -43,7 +49,7 @@ import { LocalWorkspaceRemotePullRequestCreator } from './workspace-remote-pull-
43
49
  import { LocalWorkspacePortableAuthoring } from './workspace-portable-authoring.js';
44
50
  import { assertGraphChangesWithinTaskScope, assertNodeTypeRulesOnChangedNodes, assertNoRetiredKeysOnChangedNodes, graphChangeCoordinates, ruleCovers, local_workspace_task_scope_schema } from './workspace-scope.js';
45
51
  import { assertIntroducedVocabularyAdmitted } from './workspace-admission.js';
46
- import { canonicalizePortableGraph, stringifyCanonicalGraph } from './canonical.js';
52
+ import { canonicalizePortableGraph, stringifyCanonicalGraph, stringifyCanonicalJson } from './canonical.js';
47
53
  import { introducedDanglingDocumentEmbeds } from './document-embeds.js';
48
54
  import { readWorkspaceTopology, removeWorkspaceTopology, topologyBindingMatch, writeWorkspaceTopology } from './workspace-topology.js';
49
55
  import { registerWorkspaceRuntimeLease, releaseWorkspaceRuntimeLease, withGraphRepositoryTopologyLock } from './workspace-runtime-lease.js';
@@ -60,18 +66,28 @@ const NAMING_REMOTE_RULE_AT = '2026-10-28T21:14:06.000Z';
60
66
  * link is walked as the compose reads it, each folder once. Null when the folder cannot be listed.
61
67
  */
62
68
  export async function projectionFingerprint(projection_dir) {
69
+ const rows = projectionStatRows(projection_dir);
70
+ return rows ? fingerprintOfRows(rows) : null;
71
+ }
72
+ /**
73
+ * One row per file under a projection folder (path, inode, size, modification and change time),
74
+ * read with synchronous calls, where one awaited call per file takes far longer. A 15,000-file
75
+ * projection takes about 0.3 s on macOS, almost all of it in stat; overlap walks many projections
76
+ * at once with projectionStatRowsMany. Null when the folder cannot be listed.
77
+ */
78
+ export function projectionStatRows(projection_dir) {
63
79
  const rows = [];
64
80
  const folders = [''];
65
81
  const walked = new Set();
66
82
  try {
67
83
  while (folders.length > 0) {
68
84
  const folder = folders.pop();
69
- const at = await stat(join(projection_dir, folder));
85
+ const at = statSync(join(projection_dir, folder));
70
86
  const id = `${at.dev}:${at.ino}`;
71
87
  if (walked.has(id))
72
88
  continue;
73
89
  walked.add(id);
74
- const entries = await readdir(join(projection_dir, folder), { withFileTypes: true });
90
+ const entries = readdirSync(join(projection_dir, folder), { withFileTypes: true });
75
91
  for (const entry of entries) {
76
92
  const path = folder ? `${folder}/${entry.name}` : entry.name;
77
93
  if (entry.isDirectory()) {
@@ -79,7 +95,7 @@ export async function projectionFingerprint(projection_dir) {
79
95
  continue;
80
96
  }
81
97
  // stat follows a symbolic link, as the compose's reads do.
82
- const info = await stat(join(projection_dir, path));
98
+ const info = statSync(join(projection_dir, path));
83
99
  if (info.isDirectory())
84
100
  folders.push(path);
85
101
  else
@@ -90,29 +106,156 @@ export async function projectionFingerprint(projection_dir) {
90
106
  catch {
91
107
  return null;
92
108
  }
93
- return createHash('sha256').update(rows.sort().join('\n')).digest('hex');
109
+ return rows;
110
+ }
111
+ function fingerprintOfRows(rows, omit) {
112
+ const kept = omit ? rows.filter((row) => !row.startsWith(`${omit}\0`)) : rows;
113
+ return createHash('sha256').update([...kept].sort().join('\n')).digest('hex');
114
+ }
115
+ const PROJECTION_FINGERPRINT_FILE = 'projection-fingerprint.json';
116
+ async function readProjectionFingerprint(workspace) {
117
+ try {
118
+ const record = JSON.parse(await readFile(join(controlDirectory(workspace), PROJECTION_FINGERPRINT_FILE), 'utf8'));
119
+ if (record.version !== 1 ||
120
+ typeof record.head_commit_id !== 'string' ||
121
+ typeof record.fingerprint !== 'string' ||
122
+ typeof record.projection_root !== 'string') {
123
+ return null;
124
+ }
125
+ if (record.files !== undefined &&
126
+ (typeof record.files !== 'object' || record.files === null)) {
127
+ delete record.files;
128
+ }
129
+ return record;
130
+ }
131
+ catch {
132
+ return null;
133
+ }
94
134
  }
95
135
  /**
96
- * The node types a graph starts from, outside in (the local-graph-start
97
- * skill): one is missing when no node of it exists. Complete graph validation
98
- * does not ask for them, so a commit only warns.
136
+ * Keeps a projection's fingerprint, with each file's stat from `rows`; a
137
+ * failure to keep it only costs the next run a compose.
99
138
  */
100
- const STARTING_NODE_TYPES = [
101
- ['system', 'the product'],
102
- ['actor', 'the people and outside systems that use it']
103
- ];
104
- /** An outside system, or one nested in another node, is not the product. */
105
- function startsTheGraph(node) {
106
- if (node.type !== 'system')
107
- return true;
108
- const system = node.data?.data
109
- ?.system;
110
- return !node.parentId && system?.external !== true;
139
+ async function writeProjectionFingerprint(workspace, record, rows) {
140
+ await writeJsonAtomically(join(controlDirectory(workspace), PROJECTION_FINGERPRINT_FILE), {
141
+ version: 1,
142
+ ...record,
143
+ fingerprint: fingerprintOfRows([...rows]),
144
+ files: projectionFileStats(rows)
145
+ }).catch(() => undefined);
146
+ }
147
+ /** Diffs with more changes are not kept: they are rare, and large to keep. */
148
+ const KEPT_DIFF_MAX_CHANGES = 5_000;
149
+ function sortEntityChanges(changes) {
150
+ return changes.sort((left, right) => left.entity_kind.localeCompare(right.entity_kind) ||
151
+ left.entity_id.localeCompare(right.entity_id));
111
152
  }
153
+ /**
154
+ * The diff from a graph to a third, given its diffs to a second and from the
155
+ * second to the third, neither changing a graph-level field: each entity
156
+ * keeps its first value and takes its last, and an entity whose two match
157
+ * is unchanged.
158
+ */
159
+ export function composeEntityDiffs(first, second) {
160
+ const key = (change) => `${change.entity_kind}:${change.entity_id}`;
161
+ const changes = new Map(first.changes.map((change) => [key(change), change]));
162
+ for (const change of second.changes) {
163
+ const earlier = changes.get(key(change));
164
+ changes.set(key(change), earlier ? { ...change, before: earlier.before } : change);
165
+ }
166
+ return {
167
+ metadata_changed: false,
168
+ changes: sortEntityChanges([...changes.values()].filter((change) => stringifyCanonicalJson(change.before ?? null) !==
169
+ stringifyCanonicalJson(change.after ?? null)))
170
+ };
171
+ }
172
+ let build_stamp = null;
173
+ /**
174
+ * The entry files of the graph packages whose code decides an overlap outcome. Each is a literal
175
+ * `require.resolve` call so the package assembly renames it to its `@software-dlc/graph` subpath,
176
+ * as it does an import; a list of name strings would keep the retired names (iss-182).
177
+ */
178
+ function overlapCodeEntries(require) {
179
+ return [
180
+ () => require.resolve('@software-dlc/graph/types'),
181
+ () => require.resolve('@software-dlc/graph/schema'),
182
+ () => require.resolve('@software-dlc/graph/validator'),
183
+ () => require.resolve('@software-dlc/graph/computation'),
184
+ () => require.resolve('@software-dlc/graph/client'),
185
+ () => require.resolve('@software-dlc/graph/packages')
186
+ ];
187
+ }
188
+ /** Path, size and modification time of every file under a folder, as rows. */
189
+ function codeRows(root, rows) {
190
+ const walk = (dir) => {
191
+ let entries;
192
+ try {
193
+ entries = readdirSync(dir, { withFileTypes: true });
194
+ }
195
+ catch {
196
+ return;
197
+ }
198
+ for (const entry of entries) {
199
+ if (entry.name === 'node_modules')
200
+ continue;
201
+ const path = join(dir, entry.name);
202
+ if (entry.isDirectory()) {
203
+ walk(path);
204
+ }
205
+ else if (entry.isFile()) {
206
+ try {
207
+ const info = statSync(path);
208
+ rows.push(`${path}\u0000${info.size}\u0000${info.mtimeMs}`);
209
+ }
210
+ catch {
211
+ // A file that vanished mid-walk changes the stamp next time.
212
+ }
213
+ }
214
+ }
215
+ };
216
+ walk(root);
217
+ }
218
+ /**
219
+ * This build's identity, which scopes kept overlap outcomes to the code that
220
+ * computed them: the package version and the files of this folder and of the
221
+ * graph packages it reads, so a rebuild with changed code (the package
222
+ * version is not bumped for every build) reads none of an older build's
223
+ * outcomes, and every worktree's build keeps its own.
224
+ */
225
+ function buildStamp() {
226
+ if (build_stamp === null) {
227
+ const require = createRequire(import.meta.url);
228
+ const rows = [];
229
+ try {
230
+ const metadata = require('../../package.json');
231
+ rows.push(String(metadata.version));
232
+ }
233
+ catch {
234
+ rows.push('unknown');
235
+ }
236
+ codeRows(dirname(fileURLToPath(import.meta.url)), rows);
237
+ overlapCodeEntries(require).forEach((entry, index) => {
238
+ try {
239
+ codeRows(dirname(entry()), rows);
240
+ }
241
+ catch {
242
+ rows.push(`${index}\u0000unresolved`);
243
+ }
244
+ });
245
+ build_stamp = createHash('sha256').update(rows.join('\n')).digest('hex');
246
+ }
247
+ return build_stamp;
248
+ }
249
+ /**
250
+ * The node types a graph starts from, outside in (the local-graph-start
251
+ * skill; STARTING_NODE_TYPES): one is missing when no node of it exists.
252
+ * Complete graph validation does not ask for them, so a commit only warns.
253
+ */
112
254
  function graphShapeWarnings(graph) {
113
- const types = new Set(graph.nodes.filter(startsTheGraph).map((node) => node.type));
114
- return STARTING_NODE_TYPES.filter(([type]) => !types.has(type)).map(([type, what]) => `The graph has no ${type} node for ${what}.`);
255
+ return graphShapeWarningsOfCounts(startingNodeCounts(graph.nodes));
115
256
  }
257
+ /** Changes a commit checks on their neighborhood; more take the whole-graph commit. */
258
+ const NEIGHBORHOOD_CHANGE_LIMIT = 500;
116
259
  function brokenValidationMessages(graph) {
117
260
  return validateProjectionGraph(graph)
118
261
  .issues.filter((issue) => issue.status === 'broken')
@@ -1557,7 +1700,28 @@ export class LocalWorkspaceRuntime {
1557
1700
  }
1558
1701
  return graph;
1559
1702
  };
1560
- const coordinator_graph = await readGraph(coordinator_commit_id);
1703
+ const stamp = buildStamp();
1704
+ // A kept outcome that cannot be read or written is computed again. The
1705
+ // whole-graph reference keeps and reads nothing.
1706
+ const cache = input.replay === 'whole_graph'
1707
+ ? undefined
1708
+ : {
1709
+ read: async (key) => {
1710
+ const text = await this.graphs.readDerivedKey(`${stamp}\u0000${key}`);
1711
+ if (text === null)
1712
+ return null;
1713
+ try {
1714
+ return JSON.parse(text);
1715
+ }
1716
+ catch {
1717
+ return null;
1718
+ }
1719
+ },
1720
+ write: (key, value) => this.graphs
1721
+ .writeDerivedKey(`${stamp}\u0000${key}`, JSON.stringify(value))
1722
+ .catch(() => undefined)
1723
+ };
1724
+ const source = this.planGraphSource(readGraph, coordinator_commit_id, cache);
1561
1725
  const plans = [];
1562
1726
  const projection_dirty = new Map();
1563
1727
  for (const child of children) {
@@ -1577,54 +1741,70 @@ export class LocalWorkspaceRuntime {
1577
1741
  // projection (thousands of files, then a root hash) cost most of a run
1578
1742
  // once they numbered over a hundred (iss-130).
1579
1743
  const held = base_commit_id === child.head_sdlc_commit_id;
1580
- const [base_graph, head_graph] = held
1581
- ? [coordinator_graph, coordinator_graph]
1582
- : await Promise.all([
1583
- readGraph(base_commit_id),
1584
- readGraph(child.head_sdlc_commit_id)
1585
- ]);
1586
1744
  plans.push({
1587
1745
  workspace_id: child.id,
1588
1746
  base_commit_id,
1589
- head_commit_id: child.head_sdlc_commit_id,
1590
- base_graph,
1591
- head_graph
1747
+ head_commit_id: child.head_sdlc_commit_id
1592
1748
  });
1593
- if (held) {
1594
- projection_dirty.set(child.id, null);
1595
- continue;
1596
- }
1597
- try {
1598
- // Root hashes alone say whether the projection moved: no graph is read.
1599
- const { graph } = await composeGraphProjection(projectionDirectory(child), undefined, { base: async () => head_graph });
1600
- const child_root = this.commitRoot(child.head_sdlc_commit_id);
1601
- projection_dirty.set(child.id, child_root !== graphRootFor(graph, child_root));
1602
- }
1603
- catch {
1604
- // A missing or unreadable projection does not change the committed plan.
1605
- projection_dirty.set(child.id, null);
1606
- }
1749
+ projection_dirty.set(child.id, null);
1750
+ }
1751
+ // Every plan's projection files are stat'ed together, on worker threads,
1752
+ // before any compose: a file written during a compose changes the next
1753
+ // run's fingerprint.
1754
+ const changed_plans = children.filter((child) => plans.find((plan) => plan.workspace_id === child.id)?.base_commit_id !==
1755
+ child.head_sdlc_commit_id);
1756
+ const stat_rows = await projectionStatRowsMany(changed_plans.map(projectionDirectory), projectionStatRows);
1757
+ for (const [index, child] of changed_plans.entries()) {
1758
+ projection_dirty.set(child.id, await this.planProjectionDirty(child, readGraph, stat_rows[index] ?? null));
1607
1759
  }
1608
- const comparison = compareLocalWorkspacePlans({
1760
+ const comparison = await compareLocalWorkspacePlans({
1609
1761
  coordinator_commit_id,
1610
- coordinator_graph,
1611
- plans
1762
+ plans,
1763
+ source,
1764
+ replay: input.replay,
1765
+ cache,
1766
+ onReplay: input.onReplay
1612
1767
  });
1613
1768
  const states = new Map(comparison.plans.map((state) => [state.workspace_id, state]));
1614
- let coordinator_ancestors = null;
1615
1769
  for (const pair of comparison.pairs) {
1616
1770
  const units = allocationUnits(pair);
1617
1771
  if (units.length === 0)
1618
1772
  continue;
1619
- coordinator_ancestors ??= this.store.history.ancestorIds(coordinator_commit_id);
1620
- const reachable = coordinator_ancestors;
1773
+ // Allocation reads only the two plans' own commits and the coordinator
1774
+ // head's ancestry, so it is kept under their commit ids too, and under
1775
+ // the workspace ids its times are keyed by (a revived plan has its
1776
+ // closed candidate's commits).
1777
+ const allocation_key = [
1778
+ 'allocation',
1779
+ coordinator_commit_id,
1780
+ ...pair.workspace_ids,
1781
+ ...pair.workspace_ids.flatMap((workspace_id) => {
1782
+ const plan = plans.find((entry) => entry.workspace_id === workspace_id);
1783
+ return [plan?.base_commit_id ?? '', plan?.head_commit_id ?? ''];
1784
+ }),
1785
+ JSON.stringify(units)
1786
+ ].join('\u0000');
1787
+ const kept_allocation = (await cache?.read(allocation_key));
1788
+ if (kept_allocation) {
1789
+ pair.allocation = kept_allocation;
1790
+ continue;
1791
+ }
1621
1792
  const first_changed = await Promise.all(pair.workspace_ids.map((workspace_id) => firstOwnChanges({
1622
1793
  head_commit_id: plans.find((plan) => plan.workspace_id === workspace_id)
1623
1794
  ?.head_commit_id ?? '',
1624
1795
  units,
1625
1796
  getCommit: (commit_id) => this.store.history.getCommit(commit_id),
1626
- reachableFromCoordinator: (commit_id) => reachable.has(commit_id),
1627
- readGraph
1797
+ reachableFromCoordinator: (commit_id) => this.store.history.isAncestor(commit_id, coordinator_commit_id),
1798
+ changes: async (parent_id, commit_id) => {
1799
+ const diff = await source.diff(parent_id, commit_id);
1800
+ if (!diff.metadata_changed)
1801
+ return diffCoordinates(diff);
1802
+ const [base_graph, current_graph] = await Promise.all([
1803
+ readGraph(parent_id),
1804
+ readGraph(commit_id)
1805
+ ]);
1806
+ return graphChangeCoordinates({ base_graph, current_graph });
1807
+ }
1628
1808
  })));
1629
1809
  const timed = units.map((unit) => ({
1630
1810
  ...unit,
@@ -1637,6 +1817,7 @@ export class LocalWorkspaceRuntime {
1637
1817
  // entities fails, so one plan owns it, by its earliest change to any.
1638
1818
  pair.allocation =
1639
1819
  pair.conflicts.length > 0 ? timed : [combineValidationUnits(timed)];
1820
+ await cache?.write(allocation_key, pair.allocation);
1640
1821
  }
1641
1822
  return {
1642
1823
  version: 1,
@@ -1664,6 +1845,138 @@ export class LocalWorkspaceRuntime {
1664
1845
  pairs: comparison.pairs
1665
1846
  };
1666
1847
  }
1848
+ /**
1849
+ * Plan overlap's view of the store: graphs on demand, entity diffs read from
1850
+ * the trees, and each root's reference index, derived from the nearest
1851
+ * first-parent ancestor that has one, or built once from the graph.
1852
+ */
1853
+ planGraphSource(readGraph, coordinator_commit_id, cache) {
1854
+ const value = async (hash) => hash
1855
+ ? (await this.graphs.readTreeEntity(hash))
1856
+ : null;
1857
+ // Plans' roots differ from the coordinator head's in a few entities, so a
1858
+ // legacy root converts against its tree and writes only what differs.
1859
+ let coordinator_tree = null;
1860
+ const diffRoots = async (first, second) => {
1861
+ coordinator_tree ??= this.graphs.treeFor(this.commitRoot(coordinator_commit_id));
1862
+ const left = await this.graphs.treeFor(first, {
1863
+ base: await coordinator_tree
1864
+ });
1865
+ const right = await this.graphs.treeFor(second, { base: left });
1866
+ const { changes, metadata_changed } = await this.graphs.diffRoots(left, right);
1867
+ return {
1868
+ metadata_changed,
1869
+ changes: sortEntityChanges(await Promise.all(changes.map(async (change) => ({
1870
+ entity_kind: change.entity_kind,
1871
+ entity_id: change.entity_id,
1872
+ before: await value(change.before),
1873
+ after: await value(change.after)
1874
+ }))))
1875
+ };
1876
+ };
1877
+ // A diff between two roots never changes, so it is kept. A diff to a
1878
+ // commit whose first parent has a kept diff from the same root is that
1879
+ // diff composed with the parent's own: after a landing, a plan's base is
1880
+ // diffed with the new head without converting or verifying its legacy
1881
+ // root again.
1882
+ const diffKey = (first, second) => `overlap-diff-v1\u0000${first}\u0000${second}`;
1883
+ const keptDiff = async (first, second) => (await cache?.read(diffKey(first, second))) ?? null;
1884
+ const keepDiff = async (first, second, diff) => {
1885
+ if (cache && diff.changes.length <= KEPT_DIFF_MAX_CHANGES) {
1886
+ await cache.write(diffKey(first, second), diff);
1887
+ }
1888
+ };
1889
+ const diff = async (from, to) => {
1890
+ const [first, second] = [this.commitRoot(from), this.commitRoot(to)];
1891
+ if (first === second)
1892
+ return { changes: [], metadata_changed: false };
1893
+ const kept = await keptDiff(first, second);
1894
+ if (kept)
1895
+ return kept;
1896
+ const parent_id = this.store.history.getCommit(to)?.parent_ids[0];
1897
+ const parent = parent_id ? this.commitRoot(parent_id) : null;
1898
+ const to_parent = parent && parent !== second ? await keptDiff(first, parent) : null;
1899
+ let found = null;
1900
+ if (parent && to_parent && !to_parent.metadata_changed) {
1901
+ const step = (await keptDiff(parent, second)) ?? (await diffRoots(parent, second));
1902
+ await keepDiff(parent, second, step);
1903
+ if (!step.metadata_changed)
1904
+ found = composeEntityDiffs(to_parent, step);
1905
+ }
1906
+ found ??= await diffRoots(first, second);
1907
+ await keepDiff(first, second, found);
1908
+ return found;
1909
+ };
1910
+ return {
1911
+ readGraph,
1912
+ diff,
1913
+ refs: async (commit_id) => loadRefIndex({
1914
+ root: await this.graphs.treeFor(this.commitRoot(commit_id)),
1915
+ ancestor_roots: () => this.firstParentTreeRoots(commit_id),
1916
+ readDerived: (root) => this.graphs.readDerived(root),
1917
+ writeDerived: (root, text) => this.graphs.writeDerived(root, text),
1918
+ diffRoots,
1919
+ readGraph: (root) => this.graphs.readGraph(root)
1920
+ })
1921
+ };
1922
+ }
1923
+ /**
1924
+ * The tree roots of a commit's first-parent ancestors, nearest first, at
1925
+ * most `limit` of them; a legacy root counts through its alias.
1926
+ */
1927
+ async *firstParentTreeRoots(commit_id, limit = 64) {
1928
+ let commit = this.store.history.getCommit(commit_id);
1929
+ for (let walked = 0; commit && walked < limit; walked += 1) {
1930
+ const parent_id = commit.parent_ids[0];
1931
+ if (!parent_id)
1932
+ return;
1933
+ const root = this.commitRoot(parent_id);
1934
+ const tree = isTreeRoot(root) ? root : await this.graphs.readAlias(root);
1935
+ if (tree)
1936
+ yield tree;
1937
+ commit = this.store.history.getCommit(parent_id);
1938
+ }
1939
+ }
1940
+ /**
1941
+ * Whether a plan's projection differs from its committed head, for
1942
+ * sdlc workspace overlap. While the projection's files have the fingerprint
1943
+ * kept at its last commit (or at overlap's last compose of it), the kept
1944
+ * root answers and nothing is composed. While the head keeps per-file
1945
+ * stats, only the files whose stat differs are read and the head's tree is
1946
+ * edited along them (projectionChange). Otherwise the projection is
1947
+ * composed, and its fingerprint and root are kept for the next run. Null
1948
+ * when the projection is missing or unreadable.
1949
+ */
1950
+ async planProjectionDirty(child, readGraph,
1951
+ /** The projection's stat rows, taken before any compose. */
1952
+ rows) {
1953
+ const projection_dir = projectionDirectory(child);
1954
+ const head_commit_id = child.head_sdlc_commit_id;
1955
+ const head_root = this.commitRoot(head_commit_id);
1956
+ const fingerprint = rows ? fingerprintOfRows(rows) : null;
1957
+ const kept = fingerprint ? await readProjectionFingerprint(child) : null;
1958
+ if (kept &&
1959
+ kept.head_commit_id === head_commit_id &&
1960
+ kept.fingerprint === fingerprint) {
1961
+ return kept.projection_root !== head_root;
1962
+ }
1963
+ // The files whose stat changed, against the head's tree, when the head's stats are kept.
1964
+ const change = await this.projectionChange(child, rows, kept).catch(() => null);
1965
+ if (change)
1966
+ return (change.edit?.root ?? head_root) !== head_root;
1967
+ try {
1968
+ const { graph } = await composeGraphProjection(projection_dir, undefined, { base: () => readGraph(head_commit_id) });
1969
+ const projection_root = graphRootFor(graph, head_root);
1970
+ if (rows) {
1971
+ await writeProjectionFingerprint(child, { head_commit_id, projection_root }, rows);
1972
+ }
1973
+ return projection_root !== head_root;
1974
+ }
1975
+ catch {
1976
+ // A missing or unreadable projection does not change the committed plan.
1977
+ return null;
1978
+ }
1979
+ }
1667
1980
  inspectAuthority() {
1668
1981
  return inspectLocalWorkspaceAuthority({
1669
1982
  workspace: this.currentActiveWorkspace(),
@@ -1764,15 +2077,26 @@ export class LocalWorkspaceRuntime {
1764
2077
  const hashes = options.projection_hashes;
1765
2078
  // Taken before the compose: a file written during it changes the next fingerprint, so the
1766
2079
  // next read composes again rather than keep a hash of files as they were.
1767
- const fingerprint = hashes ? await projectionFingerprint(projection_dir) : null;
2080
+ const rows = projectionStatRows(projection_dir);
2081
+ const fingerprint = hashes && rows ? fingerprintOfRows(rows) : null;
1768
2082
  const kept = hashes?.get(projection_dir);
1769
2083
  let projection_root_hash;
2084
+ // The files whose stat changed, against the head's tree, when the head's stats are kept.
2085
+ const change = kept &&
2086
+ fingerprint !== null &&
2087
+ kept.fingerprint === fingerprint &&
2088
+ kept.head_commit_id === workspace.head_sdlc_commit_id
2089
+ ? null
2090
+ : await this.projectionChange(workspace, rows).catch(() => null);
1770
2091
  if (kept &&
1771
2092
  fingerprint !== null &&
1772
2093
  kept.fingerprint === fingerprint &&
1773
2094
  kept.head_commit_id === workspace.head_sdlc_commit_id) {
1774
2095
  projection_root_hash = kept.projection_root_hash;
1775
2096
  }
2097
+ else if (change) {
2098
+ projection_root_hash = change.edit?.root ?? head_root_hash;
2099
+ }
1776
2100
  else {
1777
2101
  hashes?.delete(projection_dir);
1778
2102
  const { graph } = await composeGraphProjection(projection_dir, undefined, {
@@ -1811,6 +2135,158 @@ export class LocalWorkspaceRuntime {
1811
2135
  : {})
1812
2136
  };
1813
2137
  }
2138
+ /**
2139
+ * The projection as an edit of its head's tree, from the files whose stat
2140
+ * differs from those kept when the projection last matched the head: `edit`
2141
+ * is null when none differs. Null when the head's stats are not kept, the
2142
+ * head is not a tree, or a file the edit cannot take changed (tags, package
2143
+ * uses, a scope manifest, a file that does not parse): the caller composes.
2144
+ */
2145
+ async projectionChange(workspace, rows, kept_record) {
2146
+ if (!rows)
2147
+ return null;
2148
+ const head_root = this.commitRoot(workspace.head_sdlc_commit_id);
2149
+ if (!isTreeRoot(head_root))
2150
+ return null;
2151
+ const kept = kept_record === undefined ? await readProjectionFingerprint(workspace) : kept_record;
2152
+ if (!kept?.files ||
2153
+ kept.head_commit_id !== workspace.head_sdlc_commit_id ||
2154
+ kept.projection_root !== head_root) {
2155
+ return null;
2156
+ }
2157
+ // The cost line's graph size: the projection's node files, from the kept stats.
2158
+ let node_files = 0;
2159
+ for (const path of Object.keys(kept.files))
2160
+ if (path.startsWith('nodes/'))
2161
+ node_files += 1;
2162
+ noteGraphNodes(node_files);
2163
+ const changes = changedProjectionFiles(kept.files, rows);
2164
+ if (!changes)
2165
+ return null;
2166
+ if (changes.present.length === 0 && changes.removed.length === 0) {
2167
+ return { head_root, edit: null };
2168
+ }
2169
+ const projection_dir = projectionDirectory(workspace);
2170
+ for (let index = 0; index < changes.present.length; index += 1) {
2171
+ notePhase('projection_file_read', 0);
2172
+ }
2173
+ const edits = await projectionTreeEdits({
2174
+ projection_dir,
2175
+ changes,
2176
+ scoped: await hasProjectionManifest(projection_dir)
2177
+ });
2178
+ if (!edits)
2179
+ return null;
2180
+ return { head_root, edit: await this.graphs.editTree(head_root, edits) };
2181
+ }
2182
+ /** The entities that differ between two stored tree roots, with their values. */
2183
+ async treeEntityDiff(first, second) {
2184
+ const { changes, metadata_changed } = await this.graphs.diffRoots(first, second);
2185
+ const value = async (hash) => hash
2186
+ ? (await this.graphs.readTreeEntity(hash))
2187
+ : null;
2188
+ return {
2189
+ metadata_changed,
2190
+ changes: sortEntityChanges(await Promise.all(changes.map(async (change) => ({
2191
+ entity_kind: change.entity_kind,
2192
+ entity_id: change.entity_id,
2193
+ before: await value(change.before),
2194
+ after: await value(change.after)
2195
+ }))))
2196
+ };
2197
+ }
2198
+ /**
2199
+ * A commit's change checked on its neighborhood (lst-change-commit): the
2200
+ * head's and the projection's graphs over the entities the change's checks
2201
+ * read, with the tree edit that commits it. `unchanged` when no file
2202
+ * differs from the head. Null when the commit must compose and check the
2203
+ * whole graph: the head's stats or check record are not kept, a file the
2204
+ * edit cannot take changed, the change is too large, deletes an entity
2205
+ * without its recorded deletion, or reaches what only the whole graph shows
2206
+ * (wholeGraphReason).
2207
+ */
2208
+ async changeNeighborhood(workspace, rows) {
2209
+ const change = await this.projectionChange(workspace, rows);
2210
+ if (!change)
2211
+ return null;
2212
+ const { head_root, edit } = change;
2213
+ if (!edit || edit.root === head_root)
2214
+ return { unchanged: true, head_root };
2215
+ const changed = [...edit.after].filter(([key, hash]) => edit.before.get(key) !== hash);
2216
+ if (changed.length > NEIGHBORHOOD_CHANGE_LIMIT)
2217
+ return null;
2218
+ const check = parseCommitCheck(await this.graphs.readDerivedKey(commitCheckKey(head_root, buildStamp())), head_root);
2219
+ if (!check)
2220
+ return null;
2221
+ const keyOf = (key) => ({
2222
+ entity_kind: key.slice(0, key.indexOf(':')),
2223
+ entity_id: key.slice(key.indexOf(':') + 1)
2224
+ });
2225
+ const before = await this.graphs.readTreeEntities(head_root, changed.map(([key]) => keyOf(key)));
2226
+ const intents = new Set(this.store
2227
+ .listWorkspaceDeletions(workspace.id)
2228
+ .map((intent) => entityKey(intent.entity_kind, intent.entity_id)));
2229
+ const values = this.projectionEditValues(edit, changed.map(([key]) => key));
2230
+ const changes = [];
2231
+ for (const [key] of changed) {
2232
+ const after = values.get(key) ?? null;
2233
+ const was = before.get(key) ?? null;
2234
+ // An unrecorded deletion is reported by the whole-graph commit.
2235
+ if (!after && was && !intents.has(key))
2236
+ return null;
2237
+ changes.push({
2238
+ ...keyOf(key),
2239
+ before: was,
2240
+ after: after
2241
+ });
2242
+ }
2243
+ const index = await loadRefIndex({
2244
+ root: head_root,
2245
+ ancestor_roots: () => this.firstParentTreeRoots(workspace.head_sdlc_commit_id),
2246
+ readDerived: (root) => this.graphs.readDerived(root),
2247
+ writeDerived: (root, text) => this.graphs.writeDerived(root, text),
2248
+ diffRoots: (first, second) => this.treeEntityDiff(first, second),
2249
+ readGraph: (root) => this.graphs.readGraph(root)
2250
+ });
2251
+ if (wholeGraphReason({ changes, index }) !== null)
2252
+ return null;
2253
+ const changed_keys = new Set(changed.map(([key]) => key));
2254
+ const around = [...neighborhoodKeys({ changes, index })].filter((key) => !changed_keys.has(key));
2255
+ const held = await this.graphs.readTreeEntities(head_root, around.map(keyOf));
2256
+ const metadata = await this.graphs.readTreeMetadata(head_root);
2257
+ const unchanged = [...held].filter((entry) => entry[1] !== null);
2258
+ const sides = (side) => neighborhoodGraph([
2259
+ ...unchanged,
2260
+ ...changes.flatMap((each) => each[side]
2261
+ ? [[entityKey(each.entity_kind, each.entity_id), each[side]]]
2262
+ : [])
2263
+ ], metadata);
2264
+ return {
2265
+ unchanged: false,
2266
+ head_root,
2267
+ edit,
2268
+ changes,
2269
+ index,
2270
+ check,
2271
+ base_graph: sides('before'),
2272
+ graph: sides('after')
2273
+ };
2274
+ }
2275
+ /** The values an edit sets, by entity key; a removed entity is absent. */
2276
+ projectionEditValues(edit, keys) {
2277
+ const values = new Map();
2278
+ const wanted = new Set(keys);
2279
+ // The edit's new entity objects hold the values it sets.
2280
+ for (const [, json] of edit.objects) {
2281
+ const object = JSON.parse(json);
2282
+ if (object.type !== 'entity' || !object.kind || !object.value)
2283
+ continue;
2284
+ const key = entityKey(object.kind, object.value.id);
2285
+ if (wanted.has(key) && edit.after.get(key))
2286
+ values.set(key, object.value);
2287
+ }
2288
+ return values;
2289
+ }
1814
2290
  async commitCurrentProjection(input) {
1815
2291
  const { workspace, git } = await this.authority.requireCurrent(input.actor_workspace_id);
1816
2292
  // Before the commit reads the binding for its source context; a move that
@@ -1821,13 +2297,55 @@ export class LocalWorkspaceRuntime {
1821
2297
  operation: 'commit',
1822
2298
  run: async () => {
1823
2299
  const current_workspace = this.requireWorkspace(workspace.id);
1824
- const base_graph = await this.readCommitGraph(current_workspace.head_sdlc_commit_id);
1825
- const { graph } = await composeGraphProjection(projectionDirectory(current_workspace), undefined, { base: async () => base_graph });
1826
- // A node parent the head already had is not this commit's to fix.
2300
+ // Taken before the compose, so an edit made while the commit runs is
2301
+ // never kept as the committed projection's fingerprint.
2302
+ const rows_before = projectionStatRows(projectionDirectory(current_workspace));
2303
+ const head_root = this.commitRoot(current_workspace.head_sdlc_commit_id);
2304
+ const neighborhood = input.whole_graph
2305
+ ? null
2306
+ : await this.changeNeighborhood(current_workspace, rows_before).catch(() => null);
2307
+ if (neighborhood?.unchanged) {
2308
+ // No file differs from the head the stats were kept at.
2309
+ this.store.clearWorkspaceDeletions(current_workspace.id);
2310
+ if (rows_before) {
2311
+ await writeProjectionFingerprint(current_workspace, {
2312
+ head_commit_id: current_workspace.head_sdlc_commit_id,
2313
+ projection_root: head_root
2314
+ }, rows_before);
2315
+ }
2316
+ return {
2317
+ version: 1,
2318
+ status: 'unchanged',
2319
+ workspace: current_workspace,
2320
+ root_hash: head_root
2321
+ };
2322
+ }
2323
+ notePhase(neighborhood ? 'commit_neighborhood' : 'commit_whole_graph', 0);
2324
+ // On the neighborhood path, both graphs hold only the entities the
2325
+ // change's checks read (lst-change-commit); otherwise they are whole.
2326
+ const base_graph = neighborhood?.base_graph ??
2327
+ (await this.readCommitGraph(current_workspace.head_sdlc_commit_id));
2328
+ const graph = neighborhood?.graph ??
2329
+ (await composeGraphProjection(projectionDirectory(current_workspace), undefined, { base: async () => base_graph })).graph;
1827
2330
  const graph_issues = validateProjectionGraph(graph, {
1828
2331
  node_parents: true
1829
2332
  }).issues;
1830
- const issues = introducedBrokenIssues(graph, [base_graph], graph_issues).map((issue) => `${issue.code}: ${issue.message}`);
2333
+ // A node parent the head already had is not this commit's to fix. On
2334
+ // the neighborhood path the head held no other broken issue (its check
2335
+ // record says so), and an issue the head's neighborhood also has comes
2336
+ // from an entity outside it.
2337
+ let broken;
2338
+ if (neighborhood) {
2339
+ const known = new Set(validateProjectionGraph(base_graph, { node_parents: true })
2340
+ .issues.filter((issue) => issue.status === 'broken')
2341
+ .map((issue) => `${issue.code}\u0000${issue.message}`));
2342
+ broken = graph_issues.filter((issue) => issue.status === 'broken' &&
2343
+ !known.has(`${issue.code}\u0000${issue.message}`));
2344
+ }
2345
+ else {
2346
+ broken = introducedBrokenIssues(graph, [base_graph], graph_issues);
2347
+ }
2348
+ const issues = broken.map((issue) => `${issue.code}: ${issue.message}`);
1831
2349
  if (issues.length > 0) {
1832
2350
  throw new Error(`Cannot commit invalid projection: ${issues.join('; ')}`);
1833
2351
  }
@@ -1844,6 +2362,12 @@ export class LocalWorkspaceRuntime {
1844
2362
  if (!projectionDiffHasChanges(diff)) {
1845
2363
  // Intents for entities that are still present no longer apply.
1846
2364
  this.store.clearWorkspaceDeletions(current_workspace.id);
2365
+ if (rows_before) {
2366
+ await writeProjectionFingerprint(current_workspace, {
2367
+ head_commit_id: current_workspace.head_sdlc_commit_id,
2368
+ projection_root: neighborhood?.edit.root ?? graphRootFor(graph, head_root)
2369
+ }, rows_before);
2370
+ }
1847
2371
  return {
1848
2372
  version: 1,
1849
2373
  status: 'unchanged',
@@ -1885,9 +2409,9 @@ export class LocalWorkspaceRuntime {
1885
2409
  const validation_warnings = introducedValidationWarnings(graph, base_graph, graph_issues);
1886
2410
  // Against the head, so only the changed entities and the path above
1887
2411
  // them are written.
1888
- const root_hash = await this.graphs.writeGraph(graph, {
1889
- base: this.commitRoot(current_workspace.head_sdlc_commit_id)
1890
- });
2412
+ const root_hash = neighborhood
2413
+ ? await this.graphs.writeTreeEdit(neighborhood.edit)
2414
+ : await this.graphs.writeGraph(graph, { base: head_root });
1891
2415
  const binding = this.store.getSourceRepositoryBinding(git.git_common_dir);
1892
2416
  const commit = this.store.history.commitWorkspace({
1893
2417
  actor_workspace_id: current_workspace.id,
@@ -1922,12 +2446,48 @@ export class LocalWorkspaceRuntime {
1922
2446
  });
1923
2447
  this.store.clearWorkspaceDeletions(current_workspace.id);
1924
2448
  await recordScopedProjectionFiles(projectionDirectory(current_workspace));
2449
+ // Kept only when no file but the scope manifest, which the line above
2450
+ // rewrites, changed while the commit ran.
2451
+ const rows_after = projectionStatRows(projectionDirectory(current_workspace));
2452
+ if (rows_before &&
2453
+ rows_after &&
2454
+ fingerprintOfRows(rows_before, PROJECTION_MANIFEST_FILE) ===
2455
+ fingerprintOfRows(rows_after, PROJECTION_MANIFEST_FILE)) {
2456
+ await writeProjectionFingerprint(current_workspace, { head_commit_id: commit.id, projection_root: root_hash }, rows_after);
2457
+ }
2458
+ // What the next commit's neighborhood check reads of this root: its
2459
+ // reference index and its check record. Derived data: a failure to
2460
+ // keep it only sends the next commit down the whole-graph path.
2461
+ const starting = neighborhood
2462
+ ? startingCountsAfter(neighborhood.check.starting, neighborhood.changes)
2463
+ : startingNodeCounts(graph.nodes);
2464
+ if (isTreeRoot(root_hash)) {
2465
+ const index = neighborhood
2466
+ ? neighborhood.index.apply({
2467
+ changes: neighborhood.changes,
2468
+ metadata_changed: false
2469
+ })
2470
+ : LocalGraphRefIndex.ofGraph(graph);
2471
+ await this.graphs
2472
+ .writeDerived(root_hash, index.serialize(root_hash))
2473
+ .catch(() => undefined);
2474
+ await this.graphs
2475
+ .writeDerivedKey(commitCheckKey(root_hash, buildStamp()), JSON.stringify({
2476
+ format: 1,
2477
+ type: 'commit-check',
2478
+ root: root_hash,
2479
+ starting
2480
+ }))
2481
+ .catch(() => undefined);
2482
+ }
1925
2483
  const source_context = binding
1926
2484
  ? this.store.getWorkspaceCommitSourceContext(commit.id)
1927
2485
  : null;
1928
2486
  const warnings = [
1929
2487
  ...commit.validation_evidence.slice(1),
1930
- ...graphShapeWarnings(graph)
2488
+ ...(neighborhood
2489
+ ? graphShapeWarningsOfCounts(starting)
2490
+ : graphShapeWarnings(graph))
1931
2491
  ];
1932
2492
  return {
1933
2493
  version: 1,