@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
package/src/todo-cli.mjs
CHANGED
|
@@ -201,6 +201,9 @@ import {
|
|
|
201
201
|
readTodoPlanNotesForStatus,
|
|
202
202
|
} from './todo-note-store.mjs';
|
|
203
203
|
import { dependencyNoteBody, todoAddNoteBody } from './todo-revision-note.mjs';
|
|
204
|
+
import { buildDeclarationRow, declaredPaths, proposeFromText, resolveDeclaredRanges } from './todo-declaration.mjs';
|
|
205
|
+
import { anchorsOf, claimsOf, judgeTask, neededAnchors, rangeIndex, relationView } from './todo-judgment.mjs';
|
|
206
|
+
import { readTodoRelationSummary, readTodoTaskRelations, transactTodoRelations } from './todo-relation-store.mjs';
|
|
204
207
|
import { readTodoParallelCandidatesForStatus } from './todo-parallel-candidates.mjs';
|
|
205
208
|
import { commitTodoStoreMutation } from './todo-store-git-transaction.mjs';
|
|
206
209
|
import { repairTodoStoreWorktreeEol } from './todo-store-worktree-eol.mjs';
|
|
@@ -343,7 +346,7 @@ const TODO_FLAG_SPECS = Object.freeze({
|
|
|
343
346
|
reopen: Object.freeze({ known: ['plan', 'task', 'reason', 'override-reason'], required: ['plan', 'task', 'reason'] }),
|
|
344
347
|
'dependency connect': DEPENDENCY_FLAG_SPEC,
|
|
345
348
|
add: Object.freeze({
|
|
346
|
-
known: ['plan', 'task', 'title', 'phase', 'lane', 'done-condition', 'design-memo', 'after', 'before', 'reason'],
|
|
349
|
+
known: ['plan', 'task', 'title', 'phase', 'lane', 'done-condition', 'design-memo', 'after', 'before', 'reason', 'owns', 'reads'],
|
|
347
350
|
required: ['plan', 'task', 'title'],
|
|
348
351
|
}),
|
|
349
352
|
'dependency disconnect': DEPENDENCY_FLAG_SPEC,
|
|
@@ -1345,9 +1348,11 @@ async function startTask({
|
|
|
1345
1348
|
};
|
|
1346
1349
|
}
|
|
1347
1350
|
// 助言はjournalへ書く前に確定させる。助言はstartを止めない(u03 B1–B6)。
|
|
1348
|
-
const
|
|
1351
|
+
const startAdvice = await startAdvisory({
|
|
1349
1352
|
repoRoot, store, projection, planKey, taskId: resolvedTaskId,
|
|
1350
1353
|
});
|
|
1354
|
+
const relations = await taskRelations({ repoRoot, planKey, taskId: resolvedTaskId });
|
|
1355
|
+
const advisory = relations === null ? startAdvice : { ...startAdvice, relations };
|
|
1351
1356
|
if (member.coordination?.mode === 'enforced' && !(await noCodeTask({ repoRoot, member, taskId: resolvedTaskId }))) {
|
|
1352
1357
|
enforcedStartGate({ advisory, planKey, taskId: resolvedTaskId, overrideReason });
|
|
1353
1358
|
}
|
|
@@ -1370,6 +1375,23 @@ async function startTask({
|
|
|
1370
1375
|
structureContext, featureContext, externalTasks: store.external_tasks ?? [] });
|
|
1371
1376
|
}
|
|
1372
1377
|
|
|
1378
|
+
/**
|
|
1379
|
+
* a5c/a5d: the open function-level relations of one task, for `todo start` and `todo show` (ADR 0204 §5). One call reads the
|
|
1380
|
+
* plan's summary and this task's own small file, never the history (ADR 0203, a4c).
|
|
1381
|
+
* → null when the plan has none (the field is then left out), else `{open: [relationView], plan_relation_count, unresolved_count,
|
|
1382
|
+
* head_sha}`; an unreadable record is named, never refused: an unknown state is not dangerous.
|
|
1383
|
+
*/
|
|
1384
|
+
async function taskRelations({ repoRoot, planKey, taskId }) {
|
|
1385
|
+
try {
|
|
1386
|
+
const read = await readTodoTaskRelations({ repoRoot, planKey, taskId });
|
|
1387
|
+
if (read === null) return null;
|
|
1388
|
+
return { open: read.open.map((relation) => relationView(taskId, relation)),
|
|
1389
|
+
plan_relation_count: read.relation_count, unresolved_count: read.unresolved_count, head_sha: read.head_sha };
|
|
1390
|
+
} catch (error) {
|
|
1391
|
+
return { unreadable: error?.detail?.reason ?? error?.code ?? 'relations_unreadable' };
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1373
1395
|
/** declare-without-git: HEAD does not resolve (no commit) and the plan's witness set records this task's row. */
|
|
1374
1396
|
async function declaredWithoutHead({ repoRoot, planKey, taskId }) {
|
|
1375
1397
|
if (headResolves(repoRoot)) return false;
|
|
@@ -1691,9 +1713,10 @@ async function addTask({ repoRoot, env, planKey, flags }) {
|
|
|
1691
1713
|
repoRoot, env, input: { schema: 'lattice.plan_revise_input.v1', desired },
|
|
1692
1714
|
notes: [{ task_id: taskId, body: todoAddNoteBody(taskId, reason) }],
|
|
1693
1715
|
});
|
|
1716
|
+
const declaration = await declareOnAdd({ repoRoot, planKey, taskId, flags });
|
|
1694
1717
|
const result = {
|
|
1695
|
-
schema: 'lattice.todo_task_add_result.
|
|
1696
|
-
task_id: taskId, after, before, reason, actor: desired.actor,
|
|
1718
|
+
schema: 'lattice.todo_task_add_result.v2', project_id: store.project_id, plan_key: planKey,
|
|
1719
|
+
task_id: taskId, after, before, reason, actor: desired.actor, declaration,
|
|
1697
1720
|
plan_version: applied.plan_version, revision_digest: applied.revision?.revision_digest ?? null,
|
|
1698
1721
|
rebound_task_ids: applied.rebound_task_ids, result_digest: '',
|
|
1699
1722
|
};
|
|
@@ -1701,6 +1724,41 @@ async function addTask({ repoRoot, env, planKey, flags }) {
|
|
|
1701
1724
|
return result;
|
|
1702
1725
|
}
|
|
1703
1726
|
|
|
1727
|
+
/**
|
|
1728
|
+
* ADR 0204: the functions the new task changes, written once now. The task is already added; nothing here can refuse the add,
|
|
1729
|
+
* so a failure comes back as `declaration` (`written: false`) and the same flags are given again to `witness declare`.
|
|
1730
|
+
* Without seeds the title and design memo are searched for names that exist in the code graph; those are proposed, never recorded.
|
|
1731
|
+
*/
|
|
1732
|
+
async function declareOnAdd({ repoRoot, planKey, taskId, flags }) {
|
|
1733
|
+
const seeded = (value) => typeof value === 'string' || Array.isArray(value);
|
|
1734
|
+
if (!seeded(flags.owns) && !seeded(flags.reads)) {
|
|
1735
|
+
const proposed = await proposeFromText({ root: repoRoot, observable: headResolves(repoRoot), title: flags.title, memo: flags['design-memo'] });
|
|
1736
|
+
return { written: false, resolved: [], unresolved: [], malformed: [], proposed };
|
|
1737
|
+
}
|
|
1738
|
+
try {
|
|
1739
|
+
const declared = await declareTaskRow({ repoRoot, planKey, taskId, flags, observable: headResolves(repoRoot) });
|
|
1740
|
+
return declared.declaration;
|
|
1741
|
+
} catch (error) {
|
|
1742
|
+
if (!(error instanceof TodoStoreError)) throw error;
|
|
1743
|
+
return { written: false, resolved: [], unresolved: [], malformed: [],
|
|
1744
|
+
refused: { code: error.code, ...error.detail } };
|
|
1745
|
+
}
|
|
1746
|
+
}
|
|
1747
|
+
|
|
1748
|
+
/**
|
|
1749
|
+
* Plan create/revise input `tasks[].touches` (ADR 0204 §6): declared after the plan is written, one row per task through the same
|
|
1750
|
+
* path as `todo add`. A task's failure comes back under its id and never undoes the plan. → `{task_id: declaration}`, or null.
|
|
1751
|
+
* shortcut: one Resolve and one witness write per task; batch them when a plan routinely declares dozens of tasks.
|
|
1752
|
+
*/
|
|
1753
|
+
export async function declareTouches({ repoRoot, planKey, touches }) {
|
|
1754
|
+
if (touches.length === 0) return null;
|
|
1755
|
+
const declarations = {};
|
|
1756
|
+
for (const { task_id: taskId, owns, reads } of touches) {
|
|
1757
|
+
declarations[taskId] = await declareOnAdd({ repoRoot, planKey, taskId, flags: { owns, reads } });
|
|
1758
|
+
}
|
|
1759
|
+
return declarations;
|
|
1760
|
+
}
|
|
1761
|
+
|
|
1704
1762
|
const samePlanEdge = (member, fromTaskId, toTaskId) => member.plan.hard_dependencies.some((edge) => (
|
|
1705
1763
|
edge.from.task_id === fromTaskId && edge.to.task_id === toTaskId));
|
|
1706
1764
|
|
|
@@ -2691,6 +2749,7 @@ async function todoDetail({ repoRoot, env, planKey, taskId }) {
|
|
|
2691
2749
|
const featureContext = await readTaskBackchainContext({
|
|
2692
2750
|
repoRoot, plan: member.plan, taskId: task.task_id,
|
|
2693
2751
|
});
|
|
2752
|
+
const relations = await taskRelations({ repoRoot, planKey, taskId: task.task_id });
|
|
2694
2753
|
const result = {
|
|
2695
2754
|
schema: featureContext === null ? 'lattice.todo_detail_result.v3' : 'lattice.todo_detail_result.v4',
|
|
2696
2755
|
project_id: store.project_id,
|
|
@@ -2702,6 +2761,7 @@ async function todoDetail({ repoRoot, env, planKey, taskId }) {
|
|
|
2702
2761
|
state,
|
|
2703
2762
|
prerequisites: taskPrerequisites(store, member, task.task_id),
|
|
2704
2763
|
note_context: context,
|
|
2764
|
+
...(relations === null ? {} : { relations }),
|
|
2705
2765
|
...(featureContext === null ? {} : { feature_context: featureContext }),
|
|
2706
2766
|
result_digest: '',
|
|
2707
2767
|
};
|
|
@@ -3482,25 +3542,7 @@ async function independenceCompile({ repoRoot, planKey, inputRef }) {
|
|
|
3482
3542
|
{ task_ids: absentFromPlan },
|
|
3483
3543
|
);
|
|
3484
3544
|
}
|
|
3485
|
-
|
|
3486
|
-
.filter((task) => task.plan_key === planKey)
|
|
3487
|
-
.map((task) => task.task_id);
|
|
3488
|
-
const declared = new Set(declaredIds);
|
|
3489
|
-
const missingReady = readyIds.filter((taskId) => !declared.has(taskId)).sort();
|
|
3490
|
-
if (missingReady.length > 0) {
|
|
3491
|
-
throw new TodoStoreError(
|
|
3492
|
-
'INDEPENDENCE_READY_UNDECLARED',
|
|
3493
|
-
'ready_tasks_missing_from_witness',
|
|
3494
|
-
undefined,
|
|
3495
|
-
{
|
|
3496
|
-
plan_key: planKey,
|
|
3497
|
-
missing_task_ids: missingReady,
|
|
3498
|
-
// a35: compiling the same set again cannot add them; the template keeps what is declared.
|
|
3499
|
-
next_action: `Declare ${missingReady.join(', ')} in the witness set. ${witnessRoute(planKey)}`
|
|
3500
|
-
+ ' The template keeps the declarations already recorded, so only the new tasks need filling.',
|
|
3501
|
-
},
|
|
3502
|
-
);
|
|
3503
|
-
}
|
|
3545
|
+
// g4: a ready task nobody declared is `witness_missing` for itself only (projectIndependenceFrontier), so it no longer stops the compile.
|
|
3504
3546
|
const observation = await collectTodoIndependenceAuthoritativeObservation({ repoRoot, witnessSet });
|
|
3505
3547
|
const baseSha = observation.head_sha;
|
|
3506
3548
|
const store = storeForReady;
|
|
@@ -3512,6 +3554,10 @@ async function independenceCompile({ repoRoot, planKey, inputRef }) {
|
|
|
3512
3554
|
// INDEPENDENCE_ARTIFACT_INVALIDでtyped fail」を既に区別している。ここでcatchすると
|
|
3513
3555
|
// **corrupt/permission/I-Oまで「初回」へ化けて履歴が黙って切れる**(suzune の監査で実測・room [1148])。
|
|
3514
3556
|
const previousArtifact = await readTodoIndependenceArtifact({ repoRoot, store, planKey });
|
|
3557
|
+
// a5b: resolve the declared functions once so the compile judges a path declared with functions by those functions only.
|
|
3558
|
+
const anchors = Object.values(witnessSet.manual_witness).flatMap((row) => anchorsOf(claimsOf(row)));
|
|
3559
|
+
const functionRanges = anchors.length === 0 ? null
|
|
3560
|
+
: rangeIndex(await resolveDeclaredRanges({ root: repoRoot, anchors }));
|
|
3515
3561
|
const artifact = compileTodoIndependence({
|
|
3516
3562
|
witnessSet,
|
|
3517
3563
|
plan: member.plan,
|
|
@@ -3519,6 +3565,7 @@ async function independenceCompile({ repoRoot, planKey, inputRef }) {
|
|
|
3519
3565
|
compiledAt: new Date().toISOString(),
|
|
3520
3566
|
sensorEvidence: observation.sensor_evidence,
|
|
3521
3567
|
previousArtifact,
|
|
3568
|
+
functionRanges,
|
|
3522
3569
|
});
|
|
3523
3570
|
const { ref } = await writeTodoIndependenceArtifact({ repoRoot, artifact });
|
|
3524
3571
|
// compile成功後にだけ、受理した宣言をruntime readerが要求するcanonical bytesで固定する。
|
|
@@ -3592,6 +3639,33 @@ async function independenceWitnessMigrate({ repoRoot, planKey }) {
|
|
|
3592
3639
|
return result;
|
|
3593
3640
|
}
|
|
3594
3641
|
|
|
3642
|
+
/**
|
|
3643
|
+
* g4: the independence artifact is keyed to the plan version, so a revision (todo add, predecessor, plan revise ...) leaves the
|
|
3644
|
+
* new version without a record and an enforced plan refuses every start. After a revision, move the recorded declarations to the
|
|
3645
|
+
* new version and recompile over them: unchanged tasks keep their verdicts, a new undeclared task is `witness_missing` for itself
|
|
3646
|
+
* only. Best effort: the revision is already recorded, so a failure is one warning with the way out, never an error.
|
|
3647
|
+
*/
|
|
3648
|
+
export async function carryIndependenceAfterRevision({ cwd }) {
|
|
3649
|
+
let planKey = null;
|
|
3650
|
+
try {
|
|
3651
|
+
const repoRoot = resolveRepoRoot(cwd);
|
|
3652
|
+
const store = await readTodoStore({ repoRoot });
|
|
3653
|
+
for (const member of store.members) {
|
|
3654
|
+
planKey = member.plan.plan_key;
|
|
3655
|
+
if (!['witness', 'enforced'].includes(member.coordination?.mode) || !headResolves(repoRoot)) continue;
|
|
3656
|
+
const artifact = await readTodoIndependenceArtifact({ repoRoot, store, planKey });
|
|
3657
|
+
if (artifact !== null && !isTodoIndependenceLegacyMarker(artifact)) continue;
|
|
3658
|
+
if (await readTodoWitnessSet({ repoRoot, planKey }) === null) continue;
|
|
3659
|
+
if (Array.isArray(member.revision?.task_migration)) await independenceWitnessMigrate({ repoRoot, planKey });
|
|
3660
|
+
await independenceCompile({ repoRoot, planKey, inputRef: todoWitnessRef(planKey) });
|
|
3661
|
+
}
|
|
3662
|
+
} catch (error) {
|
|
3663
|
+
process.emitWarning(`independence record not carried to the new plan version${planKey === null ? '' : ` of ${planKey}`}`
|
|
3664
|
+
+ ` (${error?.detail?.reason ?? error?.message ?? error}): declare a task again, or run \`lattice todo independence witness migrate --plan <key>\``
|
|
3665
|
+
+ ' and then compile', { code: 'LATTICE_INDEPENDENCE_NOT_CARRIED' });
|
|
3666
|
+
}
|
|
3667
|
+
}
|
|
3668
|
+
|
|
3595
3669
|
async function independence({ repoRoot, requestedPlanKey }) {
|
|
3596
3670
|
const store = await readTodoStore({ repoRoot });
|
|
3597
3671
|
if (requestedPlanKey !== null
|
|
@@ -3856,8 +3930,8 @@ async function witnessScaffold({ repoRoot, planKey, inputRef }) {
|
|
|
3856
3930
|
return scaffoldWitnessDraft({ repoRoot, planKey, draft });
|
|
3857
3931
|
}
|
|
3858
3932
|
|
|
3859
|
-
/** The
|
|
3860
|
-
async function
|
|
3933
|
+
/** The fresh observation a witness set carries: the affected tests of every owned path. → `{paths, observationByPath}`. */
|
|
3934
|
+
async function observeWitnessDraft({ repoRoot, draft }) {
|
|
3861
3935
|
const { queries, paths } = buildWitnessObservationQuerySet(draft);
|
|
3862
3936
|
const collected = await collectSensorEvidence({ cwd: repoRoot, querySet: { queries } });
|
|
3863
3937
|
const observationByPath = {};
|
|
@@ -3874,6 +3948,12 @@ async function scaffoldWitnessDraft({ repoRoot, planKey, draft }) {
|
|
|
3874
3948
|
changedFiles: [...entry.data.changedFiles],
|
|
3875
3949
|
};
|
|
3876
3950
|
});
|
|
3951
|
+
return { paths, observationByPath };
|
|
3952
|
+
}
|
|
3953
|
+
|
|
3954
|
+
/** The scaffold itself: fresh observation, wiring and digest for a checked draft, then the write. */
|
|
3955
|
+
async function scaffoldWitnessDraft({ repoRoot, planKey, draft }) {
|
|
3956
|
+
const { paths, observationByPath } = await observeWitnessDraft({ repoRoot, draft });
|
|
3877
3957
|
const { witnessSet, reasons } = buildWitnessSet({ draft, observationByPath });
|
|
3878
3958
|
if (witnessSet === null) {
|
|
3879
3959
|
// 理由コードは具体的なのに次の一手が汎用だと、何をどう直すのかが伝わらない。
|
|
@@ -3920,7 +4000,7 @@ function declaredStartHint(store, member, state) {
|
|
|
3920
4000
|
|
|
3921
4001
|
/**
|
|
3922
4002
|
* a40: one task's witness row, declared by its member. Rows nobody declared stay out (an empty row
|
|
3923
|
-
* would claim "touches nothing"); compile runs
|
|
4003
|
+
* would claim "touches nothing"); compile runs on the declared rows (g4), `waiting_for` names the ready tasks still undeclared.
|
|
3924
4004
|
*/
|
|
3925
4005
|
async function witnessDeclare({ repoRoot, env, planKey, flags }) {
|
|
3926
4006
|
const store = await readTodoStoreForReadiness({ repoRoot, env });
|
|
@@ -3937,29 +4017,28 @@ async function witnessDeclare({ repoRoot, env, planKey, flags }) {
|
|
|
3937
4017
|
next_action: `${planKey}/${taskId} is ${state.status}; only unfinished tasks are declared (see \`lattice todo status --json\`).`,
|
|
3938
4018
|
});
|
|
3939
4019
|
}
|
|
3940
|
-
const
|
|
3941
|
-
const
|
|
3942
|
-
const
|
|
3943
|
-
|
|
3944
|
-
|
|
3945
|
-
|
|
3946
|
-
|
|
3947
|
-
|
|
3948
|
-
const {
|
|
3949
|
-
|
|
3950
|
-
|
|
3951
|
-
|
|
3952
|
-
|
|
4020
|
+
const observable = headResolves(repoRoot);
|
|
4021
|
+
const declared = await declareTaskRow({ repoRoot, planKey, taskId, flags, observable });
|
|
4022
|
+
const base = {
|
|
4023
|
+
schema: 'lattice.todo_witness_declare_result.v2', project_id: member.plan.project_id, plan_key: planKey,
|
|
4024
|
+
task_id: taskId, declaration: declared.declaration,
|
|
4025
|
+
};
|
|
4026
|
+
if (declared.scaffolded === null) {
|
|
4027
|
+
// Names that do not resolve never fail the command (ADR 0204 §6): the row stays unwritten and the same declare retries.
|
|
4028
|
+
const result = { ...base, witness_ref: null, witness_set_digest: null, compiled: false, waiting_for: [], compile: null,
|
|
4029
|
+
next_action: declarationNextAction(planKey, taskId, declared.declaration), result_digest: '' };
|
|
4030
|
+
result.result_digest = todoSelfDigest(result, 'result_digest');
|
|
4031
|
+
return result;
|
|
4032
|
+
}
|
|
4033
|
+
const { row, scaffolded, keep } = declared;
|
|
3953
4034
|
const waitingFor = projectTodoStatus(await readTodoStoreForReadiness({ repoRoot, env }), TODO_STATUS_DISPATCH_ONLY).next_ready
|
|
3954
4035
|
.filter((task) => task.plan_key === planKey && !keep.has(task.task_id))
|
|
3955
4036
|
.map(({ task_id: id }) => id).sort();
|
|
3956
4037
|
// declare-without-git: a Store root with no commit cannot be observed, so the row is recorded and not compiled.
|
|
3957
|
-
const
|
|
3958
|
-
const compile = waitingFor.length === 0 && observable
|
|
4038
|
+
const compile = observable
|
|
3959
4039
|
? await independenceCompile({ repoRoot, planKey, inputRef: scaffolded.witness_ref }) : null;
|
|
3960
4040
|
const result = {
|
|
3961
|
-
|
|
3962
|
-
task_id: taskId, ...row, witness_ref: scaffolded.witness_ref,
|
|
4041
|
+
...base, owns: row.owns, reads: row.reads, writes: row.writes, witness_ref: scaffolded.witness_ref,
|
|
3963
4042
|
witness_set_digest: scaffolded.witness_set_digest, compiled: compile !== null, waiting_for: waitingFor,
|
|
3964
4043
|
compile,
|
|
3965
4044
|
...(observable ? {} : {
|
|
@@ -3973,6 +4052,94 @@ async function witnessDeclare({ repoRoot, env, planKey, flags }) {
|
|
|
3973
4052
|
return result;
|
|
3974
4053
|
}
|
|
3975
4054
|
|
|
4055
|
+
/** What to do when a declaration was not written: the names that failed, with the nearest ones. */
|
|
4056
|
+
function declarationNextAction(planKey, taskId, declaration) {
|
|
4057
|
+
const parts = [];
|
|
4058
|
+
for (const { text, reason } of declaration.malformed) parts.push(`${text} (${reason}; write path#function, e.g. src/a.mjs#foo or src/a.mjs#Klass.method)`);
|
|
4059
|
+
for (const entry of declaration.unresolved) {
|
|
4060
|
+
const near = entry.nearest.length > 0 ? ` nearest: ${entry.nearest.join(', ')}` : '';
|
|
4061
|
+
const where = entry.elsewhere.length > 0 ? ` found elsewhere: ${entry.elsewhere.join(', ')}` : '';
|
|
4062
|
+
parts.push(`${entry.path}#${entry.symbol} (${entry.reason});${near}${where}`.replace(/;$/u, ''));
|
|
4063
|
+
}
|
|
4064
|
+
return `${planKey}/${taskId}'s functions were not recorded: ${parts.join('; ')}. Correct the names and run the same declaration again;`
|
|
4065
|
+
+ ' the task itself is unchanged.';
|
|
4066
|
+
}
|
|
4067
|
+
|
|
4068
|
+
/**
|
|
4069
|
+
* One task's witness row from `--owns/--reads/--writes` (paths, or path#function): resolves the functions through the
|
|
4070
|
+
* code graph and, when every name resolves, writes the plan's witness set with the row and the task's conflict relations
|
|
4071
|
+
* in one `transactTodoRelations` call (ADR 0204 §3, a5). `scaffolded: null` = not written. Never refused for a conflict:
|
|
4072
|
+
* `conflicts` lists the tasks this one overlaps, `[]` when none.
|
|
4073
|
+
* Resolve and the fresh observation run before the Store lock; if another declaration changed the set meanwhile (a row or
|
|
4074
|
+
* path this attempt did not resolve or observe), the call writes nothing and the attempt runs again (three at most).
|
|
4075
|
+
*/
|
|
4076
|
+
async function declareTaskRow({ repoRoot, planKey, taskId, flags, observable }) {
|
|
4077
|
+
const store = await readTodoStore({ repoRoot });
|
|
4078
|
+
const member = store.members.find(({ descriptor }) => descriptor.plan_key === planKey);
|
|
4079
|
+
if (member === undefined) throw new TodoStoreError('STORE_INCONSISTENT', 'plan_not_active', undefined, { plan_key: planKey });
|
|
4080
|
+
const writer = createTodoStoreWriter({ caller: 'todo-relations' });
|
|
4081
|
+
const mine = declaredPaths(flags);
|
|
4082
|
+
const headSha = observable ? currentHeadSha(repoRoot) : null;
|
|
4083
|
+
const peek = await readTodoWitnessSet({ repoRoot, planKey }).catch(() => null);
|
|
4084
|
+
let alsoResolve = neededAnchors(peek?.plan_key === planKey ? peek.manual_witness : {}, taskId, mine);
|
|
4085
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
4086
|
+
const { row, declaration, ranges } = await buildDeclarationRow({
|
|
4087
|
+
root: repoRoot, observable, owns: flags.owns, reads: flags.reads, writes: flags.writes, alsoResolve });
|
|
4088
|
+
if (row === null) return { declaration, scaffolded: null };
|
|
4089
|
+
const resolved = new Set([...alsoResolve, ...declaration.resolved].map(({ path: where, symbol }) => `${where}\0${symbol}`));
|
|
4090
|
+
const draftFor = (witnessSet, unfinishedTaskIds) => {
|
|
4091
|
+
const template = witnessDraftTemplate({ projectId: member.plan.project_id, planKey,
|
|
4092
|
+
witnessSet: witnessSet?.plan_key === planKey ? witnessSet : null, taskIds: unfinishedTaskIds });
|
|
4093
|
+
const keep = new Set([...Object.keys(witnessSet?.plan_key === planKey ? witnessSet.manual_witness : {}), taskId]);
|
|
4094
|
+
const draft = { ...template, tasks: Object.fromEntries(Object.entries(template.tasks)
|
|
4095
|
+
.filter(([id]) => keep.has(id)).map(([id, task]) => [id, id === taskId ? row : task])) };
|
|
4096
|
+
if (!validateWitnessDraft(draft)) {
|
|
4097
|
+
const { valid: _valid, reason, path: at, ...keys } = explainWitnessDraft(draft);
|
|
4098
|
+
throw new TodoStoreError('WITNESS_DRAFT_INVALID', reason, undefined, {
|
|
4099
|
+
pointer: at, ...keys, next_action: witnessRoute(planKey) });
|
|
4100
|
+
}
|
|
4101
|
+
return { draft, keep };
|
|
4102
|
+
};
|
|
4103
|
+
const unfinishedNow = member.tasks.filter(({ status }) => !['done', 'retired'].includes(status)).map(({ task_id: id }) => id);
|
|
4104
|
+
const first = draftFor(peek, unfinishedNow);
|
|
4105
|
+
const observed = await observeWitnessDraft({ repoRoot, draft: first.draft });
|
|
4106
|
+
const known = new Set(observed.paths);
|
|
4107
|
+
let outcome = null;
|
|
4108
|
+
let stale = null;
|
|
4109
|
+
await transactTodoRelations({ repoRoot, planKey, writer, update: ({ witnessSet, openRelations, unfinishedTaskIds }) => {
|
|
4110
|
+
const { draft, keep } = draftFor(witnessSet, unfinishedTaskIds);
|
|
4111
|
+
const missingPaths = buildWitnessObservationQuerySet(draft).paths.filter((target) => !known.has(target));
|
|
4112
|
+
const needed = neededAnchors(witnessSet?.plan_key === planKey ? witnessSet.manual_witness : {}, taskId, mine);
|
|
4113
|
+
if (missingPaths.length > 0 || needed.some(({ path: where, symbol }) => !resolved.has(`${where}\0${symbol}`))) {
|
|
4114
|
+
stale = needed;
|
|
4115
|
+
return {};
|
|
4116
|
+
}
|
|
4117
|
+
const built = buildWitnessSet({ draft, observationByPath: observed.observationByPath });
|
|
4118
|
+
if (built.witnessSet === null) {
|
|
4119
|
+
const guidance = selectWitnessScaffoldGuidance(built.reasons);
|
|
4120
|
+
throw new TodoStoreError('WITNESS_SCAFFOLD_INCOMPLETE', 'witness_scaffold_incomplete', undefined, {
|
|
4121
|
+
reasons: built.reasons, guidance, next_action: guidance.next_action });
|
|
4122
|
+
}
|
|
4123
|
+
const judged = judgeTask({ taskId, rows: built.witnessSet.manual_witness, ranges: rangeIndex(ranges), openRelations });
|
|
4124
|
+
outcome = { witnessSet: built.witnessSet, judged, keep, paths: observed.paths };
|
|
4125
|
+
return { witnessSet: built.witnessSet, relations: judged.relations, gone: judged.gone, headSha,
|
|
4126
|
+
unresolvedCount: judged.unresolved };
|
|
4127
|
+
} });
|
|
4128
|
+
if (outcome !== null) {
|
|
4129
|
+
const { witnessSet, judged, keep, paths } = outcome;
|
|
4130
|
+
declaration.conflicts = judged.relations.map((relation) => relationView(taskId, relation));
|
|
4131
|
+
const ref = todoWitnessRef(planKey);
|
|
4132
|
+
return { row, declaration, keep, scaffolded: {
|
|
4133
|
+
schema: 'lattice.todo_witness_scaffold_result.v1', project_id: member.plan.project_id, plan_key: planKey, witness_ref: ref,
|
|
4134
|
+
observed_paths: paths, task_count: Object.keys(witnessSet.manual_witness).length,
|
|
4135
|
+
witness_set_digest: witnessSet.witness_set_digest, next_action: independenceCompileCommand(planKey, ref) } };
|
|
4136
|
+
}
|
|
4137
|
+
alsoResolve = stale;
|
|
4138
|
+
}
|
|
4139
|
+
throw new TodoStoreError('STORE_WRITE_CONFLICT', 'witness_set_changing', undefined, {
|
|
4140
|
+
next_action: `Other declarations on ${planKey} kept changing the witness set; run the same declaration again.` });
|
|
4141
|
+
}
|
|
4142
|
+
|
|
3976
4143
|
/**
|
|
3977
4144
|
* 着地時に使うsurface名。提案が出すhash由来の仮名を、人が読む名前へ置き換える。
|
|
3978
4145
|
*
|
|
@@ -4693,6 +4860,25 @@ function writesTodoStore(argv) {
|
|
|
4693
4860
|
}
|
|
4694
4861
|
}
|
|
4695
4862
|
|
|
4863
|
+
/**
|
|
4864
|
+
* a5: `todo done` / `todo retire` do not take the relations lock, so a finished task can leave an open relation. One empty
|
|
4865
|
+
* transaction closes it, and only when the plan has relations at all (one small read otherwise). Never fails the command:
|
|
4866
|
+
* the next write of the plan closes it the same way.
|
|
4867
|
+
*/
|
|
4868
|
+
async function settleRelations({ repoRoot, planKey }) {
|
|
4869
|
+
try {
|
|
4870
|
+
if (((await readTodoRelationSummary({ repoRoot, planKey }))?.relation_count ?? 0) === 0) return;
|
|
4871
|
+
await transactTodoRelations({ repoRoot, planKey, writer: createTodoStoreWriter({ caller: 'todo-relations' }), update: () => ({}) });
|
|
4872
|
+
} catch { /* shortcut: relations left open until the plan's next write; no relation is ever worth failing a done */ }
|
|
4873
|
+
}
|
|
4874
|
+
|
|
4875
|
+
/** g4: the todo commands that write a new plan version (the plan revise command carries on its own in bin/lattice.mjs). */
|
|
4876
|
+
function revisesPlan(argv) {
|
|
4877
|
+
return ['add', 'revise', 'revise-phase', 'revise-set', 'split', 'dependency', 'predecessor'].includes(argv[0])
|
|
4878
|
+
&& !(argv[0] === 'dependency' && !['connect', 'disconnect'].includes(argv[1]))
|
|
4879
|
+
&& !(argv[0] === 'predecessor' && !['add', 'remove'].includes(argv[1]));
|
|
4880
|
+
}
|
|
4881
|
+
|
|
4696
4882
|
/** notice-impl: the writes that can make a task startable carry `notices` ([startable notices](dfd-done-notice.md)). */
|
|
4697
4883
|
function releasesTasks(argv) {
|
|
4698
4884
|
const [command, second] = argv;
|
|
@@ -5619,6 +5805,10 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
|
|
|
5619
5805
|
: await action(repoRoot);
|
|
5620
5806
|
const result = releasesTasks(argv) ? await withNotices(repoRoot, written, before, env) : written;
|
|
5621
5807
|
if (result !== null) stdout.write(`${plainVerify ? verifyVerdictLine(result) : JSON.stringify(result)}\n`);
|
|
5808
|
+
if (!atomicCommit && revisesPlan(argv)) await carryIndependenceAfterRevision({ cwd });
|
|
5809
|
+
if (!atomicCommit && ['done', 'retire'].includes(argv[0]) && typeof result?.plan_key === 'string') {
|
|
5810
|
+
await settleRelations({ repoRoot, planKey: result.plan_key });
|
|
5811
|
+
}
|
|
5622
5812
|
return 0;
|
|
5623
5813
|
} catch (error) {
|
|
5624
5814
|
if (error instanceof TodoStoreError || (typeof error?.code === 'string'
|
package/src/todo-contracts.mjs
CHANGED
|
@@ -53,6 +53,10 @@ export const TODO_NOTICE_ACKS_SCHEMA = 'lattice.todo_notice_acks.v2';
|
|
|
53
53
|
export const TODO_NOTICE_WAITS_SCHEMA = 'lattice.todo_notice_waits.v1';
|
|
54
54
|
/** a101 K4: chart identity `.lattice/chart.json` (dfd-charts-read). */
|
|
55
55
|
export const TODO_CHART_META_SCHEMA = 'lattice.chart_meta.v1';
|
|
56
|
+
/** ADR 0204 a4: function-level conflict relations, one open relation per (task_a, task_b, path); dfd-store-relations. */
|
|
57
|
+
export const TODO_RELATION_EVENT_SCHEMA = 'lattice.todo_relation_event.v1';
|
|
58
|
+
export const TODO_RELATION_SUMMARY_SCHEMA = 'lattice.todo_relation_summary.v1';
|
|
59
|
+
export const TODO_RELATION_SUMMARY_OPEN = 20;
|
|
56
60
|
/**
|
|
57
61
|
* v2でnoteの`scope`とplan noteを載せる。v1のままでは`task_id`が identifier 必須・
|
|
58
62
|
* `full_history_command`が`--task <id>`込みの文字列と完全一致で、どちらもplan noteを表せない。
|
|
@@ -906,3 +910,61 @@ export function validateTodoChartMeta(value) {
|
|
|
906
910
|
&& (repo === null || (exactRecord(repo, ['url', 'branch', 'accepted_tip'])
|
|
907
911
|
&& word(repo.url) && word(repo.branch) && text(repo.accepted_tip)));
|
|
908
912
|
}
|
|
913
|
+
|
|
914
|
+
// ---- ADR 0204 a4 relations ------------------------------------------------------------------------------------
|
|
915
|
+
const relationText = (field) => typeof field === 'string' && field.length > 0 && field.length <= 1024;
|
|
916
|
+
const relationSha = (field) => field === null || relationText(field);
|
|
917
|
+
const lineNumber = (field) => Number.isSafeInteger(field) && field >= 1;
|
|
918
|
+
|
|
919
|
+
/** One side of an overlap. A whole-file claim has no symbol and no range (both null). */
|
|
920
|
+
function relationEntry(entry) {
|
|
921
|
+
return exactRecord(entry, ['symbol', 'start_line', 'end_line', 'access'])
|
|
922
|
+
&& ['read', 'write'].includes(entry.access)
|
|
923
|
+
&& ((entry.symbol === null && entry.start_line === null && entry.end_line === null)
|
|
924
|
+
|| (relationText(entry.symbol) && lineNumber(entry.start_line) && lineNumber(entry.end_line)
|
|
925
|
+
&& entry.end_line >= entry.start_line));
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
/** The pair identity: task_a sorts before task_b, so a pair has one spelling. */
|
|
929
|
+
const relationKey = (value) => isTodoIdentifier(value.task_a) && isTodoIdentifier(value.task_b)
|
|
930
|
+
&& value.task_a < value.task_b && relationText(value.path);
|
|
931
|
+
|
|
932
|
+
export const todoRelationOverlapsValid = (overlaps) => Array.isArray(overlaps) && overlaps.length > 0
|
|
933
|
+
&& overlaps.every((overlap) => exactRecord(overlap, ['a', 'b']) && relationEntry(overlap.a) && relationEntry(overlap.b));
|
|
934
|
+
|
|
935
|
+
/** Content identity of a relation (head and time excluded): the same overlap re-found is not a new relation. */
|
|
936
|
+
export function todoRelationId(relation) {
|
|
937
|
+
return digestTodoArtifact({ task_a: relation.task_a, task_b: relation.task_b, path: relation.path,
|
|
938
|
+
overlaps: relation.overlaps });
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
export function validateTodoRelationEvent(value) {
|
|
942
|
+
try {
|
|
943
|
+
const common = value !== null && typeof value === 'object' && value.schema === TODO_RELATION_EVENT_SCHEMA
|
|
944
|
+
&& Number.isSafeInteger(value.sequence) && value.sequence >= 1 && isTodoDigest(value.relation_id)
|
|
945
|
+
&& relationKey(value) && relationSha(value.head_sha) && isStrictTodoTimestamp(value.computed_at);
|
|
946
|
+
if (!common) return false;
|
|
947
|
+
if (value.kind === 'gone') {
|
|
948
|
+
return exactRecord(value, ['schema', 'kind', 'sequence', 'relation_id', 'task_a', 'task_b', 'path', 'head_sha', 'computed_at']);
|
|
949
|
+
}
|
|
950
|
+
return value.kind === 'relation'
|
|
951
|
+
&& exactRecord(value, ['schema', 'kind', 'sequence', 'relation_id', 'task_a', 'task_b', 'path', 'overlaps', 'head_sha', 'computed_at'])
|
|
952
|
+
&& todoRelationOverlapsValid(value.overlaps) && value.relation_id === todoRelationId(value);
|
|
953
|
+
} catch { return false; }
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
const summaryRelation = (entry) => exactRecord(entry, ['relation_id', 'task_a', 'task_b', 'path', 'overlaps'])
|
|
957
|
+
&& isTodoDigest(entry.relation_id) && relationKey(entry) && todoRelationOverlapsValid(entry.overlaps);
|
|
958
|
+
|
|
959
|
+
export function validateTodoRelationSummary(value) {
|
|
960
|
+
try {
|
|
961
|
+
return exactRecord(value, ['schema', 'plan_key', 'relation_count', 'open_relations', 'open_truncated',
|
|
962
|
+
'unresolved_count', 'head_sha', 'log_sequence', 'computed_at'])
|
|
963
|
+
&& value.schema === TODO_RELATION_SUMMARY_SCHEMA && isTodoIdentifier(value.plan_key)
|
|
964
|
+
&& isNonNegativeSafeInteger(value.relation_count) && isNonNegativeSafeInteger(value.unresolved_count)
|
|
965
|
+
&& isNonNegativeSafeInteger(value.log_sequence) && Array.isArray(value.open_relations)
|
|
966
|
+
&& value.open_relations.length <= TODO_RELATION_SUMMARY_OPEN && value.open_relations.every(summaryRelation)
|
|
967
|
+
&& value.open_truncated === (value.relation_count > value.open_relations.length)
|
|
968
|
+
&& relationSha(value.head_sha) && isStrictTodoTimestamp(value.computed_at);
|
|
969
|
+
} catch { return false; }
|
|
970
|
+
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
// Plan/lifecycle: the functions a task changes or reads, declared once when the task is added (ADR 0204 §1, §6).
|
|
2
|
+
// `--owns src/a.mjs#foo,src/b.mjs` / `--reads src/c.mjs#bar` → one witness-draft row. Resolution goes through the code graph's
|
|
3
|
+
// public Resolve interface only; nothing here reads the sensor index.
|
|
4
|
+
import { existsSync } from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
|
|
7
|
+
import { runSensorCli } from './sensor-cli.mjs';
|
|
8
|
+
import { parseAnchor, proposeSymbols, resolveAnchors, SensorResolveError } from './sensor-resolve.mjs';
|
|
9
|
+
import { isTodoIdentifier } from './todo-contracts.mjs';
|
|
10
|
+
import { TodoStoreError } from './todo-store.mjs';
|
|
11
|
+
|
|
12
|
+
// A flag is a comma list; plan input (`touches`) already gives an array.
|
|
13
|
+
const items = (value) => (Array.isArray(value) ? value : typeof value === 'string' ? value.split(',') : [])
|
|
14
|
+
.map((item) => item.trim()).filter(Boolean);
|
|
15
|
+
const sortedUnique = (values) => [...new Set(values)].sort();
|
|
16
|
+
|
|
17
|
+
/** Every path a declaration names, anchored or not (`owns`, `reads`, `writes` flags): a Set. */
|
|
18
|
+
export function declaredPaths({ owns, reads, writes }) {
|
|
19
|
+
const { paths: ownPaths, anchors: ownAnchors } = parseDeclarationList(owns);
|
|
20
|
+
const { paths: readPaths, anchors: readAnchors } = parseDeclarationList(reads);
|
|
21
|
+
return new Set([...ownPaths, ...readPaths, ...items(writes), ...[...ownAnchors, ...readAnchors].map(({ path: where }) => where)]);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** `a.mjs,b.mjs#foo` → bare paths, anchors, and entries that cannot be stored (with why). */
|
|
25
|
+
export function parseDeclarationList(value) {
|
|
26
|
+
const paths = [];
|
|
27
|
+
const anchors = [];
|
|
28
|
+
const malformed = [];
|
|
29
|
+
for (const text of items(value)) {
|
|
30
|
+
if (!text.includes('#')) { paths.push(text); continue; }
|
|
31
|
+
const anchor = parseAnchor(text);
|
|
32
|
+
if (anchor === null) malformed.push({ text, reason: 'expected_path_hash_symbol' });
|
|
33
|
+
// The witness row stores the symbol as a dotted identifier chain (Ruby `Foo#bar` cannot be stored).
|
|
34
|
+
else if (!isTodoIdentifier(anchor.symbol)) malformed.push({ text, reason: 'symbol_not_a_dotted_identifier' });
|
|
35
|
+
else anchors.push(anchor);
|
|
36
|
+
}
|
|
37
|
+
return { paths, anchors, malformed };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const byWithin = (anchors) => {
|
|
41
|
+
const grouped = new Map();
|
|
42
|
+
for (const { path: within, symbol } of anchors) grouped.set(within, [...(grouped.get(within) ?? []), symbol]);
|
|
43
|
+
return [...grouped].map(([within, symbols]) => ({ within, symbols: sortedUnique(symbols) }));
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
async function resolveOnce(root, anchors) {
|
|
47
|
+
try { return await resolveAnchors({ root, anchors }); } catch (error) {
|
|
48
|
+
if (!(error instanceof SensorResolveError) || error.code !== 'RESOLVE_INDEX_MISSING') throw error;
|
|
49
|
+
}
|
|
50
|
+
// First use only: the maintained index does not exist yet (Observe builds it; later calls reuse it).
|
|
51
|
+
const sink = { write() {} };
|
|
52
|
+
await runSensorCli({ argv: ['init', root, '--json'], stdout: sink, stderr: sink });
|
|
53
|
+
return resolveAnchors({ root, anchors });
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const unresolvedEntry = (anchor, reason, nearest = [], elsewhere = []) => ({
|
|
57
|
+
path: anchor.path, symbol: anchor.symbol, reason, nearest, elsewhere,
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Resolve a task's declared functions and build its witness-draft row.
|
|
62
|
+
* → `{row, declaration: {written, resolved[], unresolved[], malformed[]}}`; `row` is null when `written` is false
|
|
63
|
+
* (a task's row is not written until every name resolves, so the next declare retries from scratch).
|
|
64
|
+
* `observable` false = the Store root has no code tree: functions cannot be checked, never recorded as a guess.
|
|
65
|
+
*/
|
|
66
|
+
export async function buildDeclarationRow({ root, observable, owns, reads, writes, alsoResolve = [] }) {
|
|
67
|
+
const own = parseDeclarationList(owns);
|
|
68
|
+
const read = parseDeclarationList(reads);
|
|
69
|
+
const malformed = [...own.malformed, ...read.malformed];
|
|
70
|
+
const keyOf = (anchor) => `${anchor.path}\0${anchor.symbol}`;
|
|
71
|
+
const wanted = [...new Map([...own.anchors, ...read.anchors].map((anchor) => [keyOf(anchor), anchor])).values()];
|
|
72
|
+
const declaration = { written: false, resolved: [], unresolved: [], malformed };
|
|
73
|
+
if (malformed.length > 0) return { row: null, declaration };
|
|
74
|
+
// `alsoResolve`: other tasks' anchors, answered by the same Resolve call (a5 compares ranges); a miss there is not this task's refusal.
|
|
75
|
+
const wantedKeys = new Set(wanted.map(keyOf));
|
|
76
|
+
const extra = [...new Map(alsoResolve.filter((anchor) => !wantedKeys.has(keyOf(anchor))).map((anchor) => [keyOf(anchor), anchor])).values()];
|
|
77
|
+
let ranges = [];
|
|
78
|
+
if (wanted.length > 0 && !observable) {
|
|
79
|
+
declaration.unresolved = wanted.map((anchor) => unresolvedEntry(anchor, 'no_code_tree'));
|
|
80
|
+
return { row: null, declaration };
|
|
81
|
+
}
|
|
82
|
+
if (wanted.length + extra.length > 0 && observable) {
|
|
83
|
+
let answer;
|
|
84
|
+
try { answer = await resolveOnce(root, [...wanted, ...extra]); } catch (error) {
|
|
85
|
+
if (wanted.length === 0) return buildRow({ own, read, writes, declaration, ranges });
|
|
86
|
+
declaration.unresolved = wanted.map((anchor) => unresolvedEntry(anchor, 'resolve_unavailable'));
|
|
87
|
+
declaration.resolve_error = error?.code ?? error?.message ?? 'resolve_failed';
|
|
88
|
+
return { row: null, declaration };
|
|
89
|
+
}
|
|
90
|
+
const mine = answer.unresolved.filter((anchor) => wantedKeys.has(keyOf(anchor)));
|
|
91
|
+
declaration.unresolved = mine.map((anchor) => unresolvedEntry(
|
|
92
|
+
anchor, anchor.reason,
|
|
93
|
+
anchor.nearest.map(({ qualified }) => qualified),
|
|
94
|
+
anchor.elsewhere.map(({ path: where, qualified }) => `${where}#${qualified}`),
|
|
95
|
+
));
|
|
96
|
+
ranges = answer.resolved;
|
|
97
|
+
declaration.resolved = answer.resolved.filter(({ path: where, symbol }) => wantedKeys.has(`${where}\0${symbol}`))
|
|
98
|
+
.map(({ path: where, symbol, kind, start_line: start, end_line: end }) => ({
|
|
99
|
+
path: where, symbol, kind, start_line: start, end_line: end,
|
|
100
|
+
}));
|
|
101
|
+
if (declaration.unresolved.length > 0) return { row: null, declaration };
|
|
102
|
+
}
|
|
103
|
+
return buildRow({ own, read, writes, declaration, ranges });
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function buildRow({ own, read, writes, declaration, ranges }) {
|
|
107
|
+
const concern = byWithin(own.anchors);
|
|
108
|
+
const readAnchors = byWithin(read.anchors);
|
|
109
|
+
const row = {
|
|
110
|
+
owns: sortedUnique([...own.paths, ...concern.map(({ within }) => within)]),
|
|
111
|
+
reads: sortedUnique([...read.paths, ...readAnchors.map(({ within }) => within)]),
|
|
112
|
+
writes: items(writes),
|
|
113
|
+
...(concern.length > 0 ? { concern_anchors: concern } : {}),
|
|
114
|
+
...(readAnchors.length > 0 ? { read_anchors: readAnchors } : {}),
|
|
115
|
+
};
|
|
116
|
+
declaration.written = true;
|
|
117
|
+
return { row, declaration, ranges };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Fallback without seeds (ADR 0204 §1): identifiers in the title and design memo that name graph symbols are proposed in the
|
|
122
|
+
* result and never recorded; the AI that adds the task decides. Needs an existing index and a code tree; any failure = no proposal.
|
|
123
|
+
*/
|
|
124
|
+
export async function proposeFromText({ root, observable, title, memo }) {
|
|
125
|
+
if (!observable || !existsSync(path.join(root, '.lattice/sensor/sensor.db'))) return null;
|
|
126
|
+
// Resolve's `snake` leaves `qualified: undefined` on a definition; a result is canonical JSON, so drop undefined here.
|
|
127
|
+
try { return JSON.parse(JSON.stringify(await proposeSymbols({ root, title, memo }))); } catch { return null; }
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
131
|
+
const isPathList = (list) => list === undefined || (Array.isArray(list) && list.every((entry) => typeof entry === 'string' && entry.trim() !== ''));
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Plan input v6 (ADR 0204 §6): `tasks[].touches {owns, reads}` is read here and goes to the witness set only.
|
|
135
|
+
* Returns the input as v5 without `touches`, so the stored plan and its digest are the v5 ones, plus the claims to declare
|
|
136
|
+
* (`{task_id, owns[], reads[]}`; a task whose lists are both empty claims nothing and is left out). `pointer` prefixes a refusal.
|
|
137
|
+
*/
|
|
138
|
+
export function splitTouches(input, pointer = '') {
|
|
139
|
+
if (input?.schema !== 'lattice.plan_create_input.v6' || !Array.isArray(input.tasks)) return { input, touches: [] };
|
|
140
|
+
const touches = [];
|
|
141
|
+
const tasks = input.tasks.map((task, index) => {
|
|
142
|
+
if (!isRecord(task) || !('touches' in task)) return task;
|
|
143
|
+
const { touches: claim, ...rest } = task;
|
|
144
|
+
if (!isRecord(claim) || Object.keys(claim).some((key) => key !== 'owns' && key !== 'reads')
|
|
145
|
+
|| !isPathList(claim.owns) || !isPathList(claim.reads)) {
|
|
146
|
+
throw new TodoStoreError('INPUT_INVALID', 'plan_create_touches_invalid', undefined, {
|
|
147
|
+
pointer: `${pointer}/tasks/${index}/touches`, expected: { owns: 'string[] of path or path#function', reads: 'string[] of path or path#function' },
|
|
148
|
+
actual: claim, next_action: 'Write touches as {"owns": ["src/a.mjs#foo"], "reads": ["src/b.mjs"]}; both lists are optional.',
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
const { owns = [], reads = [] } = claim;
|
|
152
|
+
if (owns.length + reads.length > 0) touches.push({ task_id: rest.task_id, owns, reads });
|
|
153
|
+
return rest;
|
|
154
|
+
});
|
|
155
|
+
return { input: { ...input, schema: 'lattice.plan_create_input.v5', tasks }, touches };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* The line ranges of every function the witness rows declare (`resolved` of one Resolve call), for the compile (a5b).
|
|
160
|
+
* No anchors → no call. Any failure → `[]`: the compile then reads every declared function as a whole-file claim, as before.
|
|
161
|
+
*/
|
|
162
|
+
export async function resolveDeclaredRanges({ root, anchors }) {
|
|
163
|
+
if (anchors.length === 0) return [];
|
|
164
|
+
try { return (await resolveOnce(root, anchors)).resolved; } catch { return []; }
|
|
165
|
+
}
|