@quolu/lattice 0.116.0 → 0.118.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/bin/lattice.mjs +15 -6
- package/docs/schemas/lattice.plan_backchain.v1.schema.json +2 -2
- package/package.json +1 -1
- package/src/cli-help.mjs +5 -1
- package/src/plan-backchain.mjs +106 -46
- package/src/plan-draft.mjs +452 -0
- package/src/plan-edit-advice.mjs +144 -0
- package/src/plan-revise.mjs +4 -0
- package/src/project-cli.mjs +3 -1
- package/src/todo-cli.mjs +34 -6
package/bin/lattice.mjs
CHANGED
|
@@ -195,7 +195,12 @@ if (help !== null) {
|
|
|
195
195
|
}
|
|
196
196
|
} else if (args[0] === 'plan' && args[1] === 'backchain') {
|
|
197
197
|
const { matchFlagCommand } = await import('../src/todo-authoring-input.mjs');
|
|
198
|
-
|
|
198
|
+
// One entry, three inputs: a finished chain (--input), a goal-side draft (--draft), or the draft skeleton (--template).
|
|
199
|
+
const spec = args.includes('--template') ? {
|
|
200
|
+
known: ['template', 'plan', 'json'], required: [], booleans: ['template', 'json'],
|
|
201
|
+
} : args.includes('--draft') ? {
|
|
202
|
+
known: ['draft', 'dry-run', 'json'], required: ['draft'], booleans: ['dry-run', 'json'],
|
|
203
|
+
} : {
|
|
199
204
|
known: ['input', 'dry-run', 'json'], required: ['input'],
|
|
200
205
|
booleans: ['dry-run', 'json'],
|
|
201
206
|
};
|
|
@@ -207,10 +212,13 @@ if (help !== null) {
|
|
|
207
212
|
const { runPlanBackchain } = await import('../src/plan-backchain.mjs');
|
|
208
213
|
const { projectCliFailure } = await import('../src/project-cli.mjs');
|
|
209
214
|
try {
|
|
210
|
-
process.exitCode =
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
215
|
+
process.exitCode = flags.template === true
|
|
216
|
+
? await (await import('../src/plan-backchain.mjs')).runPlanBackchainTemplate({
|
|
217
|
+
cwd: process.cwd(), planKey: flags.plan ?? null, stdout: process.stdout })
|
|
218
|
+
: await runPlanBackchain({
|
|
219
|
+
cwd: process.cwd(), inputRef: flags.input ?? null, draftRef: flags.draft ?? null,
|
|
220
|
+
dryRun: flags['dry-run'] === true, stdout: process.stdout, env: process.env,
|
|
221
|
+
});
|
|
214
222
|
} catch (error) {
|
|
215
223
|
process.exitCode = projectCliFailure(process.stderr, error, { command: 'backchain', flags });
|
|
216
224
|
}
|
|
@@ -325,11 +333,12 @@ function withImpliedJson(argv) {
|
|
|
325
333
|
if (argv.includes('--json') || argv.includes('--help') || argv.includes('-h')) return argv;
|
|
326
334
|
const [command, sub] = argv;
|
|
327
335
|
const bare = !argv.some((word) => word.startsWith('-'));
|
|
328
|
-
const input = argv.indexOf('--input');
|
|
336
|
+
const input = Math.max(argv.indexOf('--input'), argv.indexOf('--draft'));
|
|
329
337
|
const implied = (bare && argv.length === 1 && (command === 'status' || command === 'session-context'))
|
|
330
338
|
|| (bare && argv.length === 3 && command === 'plan' && sub === 'show')
|
|
331
339
|
|| (bare && command === 'sensor' && (sub === 'init' || sub === 'sync') && argv.length <= 3)
|
|
332
340
|
|| (command === 'sensor' && (sub === 'diff' || sub === 'resolve' || sub === 'touched'))
|
|
341
|
+
|| (command === 'plan' && sub === 'backchain' && argv.includes('--template'))
|
|
333
342
|
|| (command === 'plan' && (sub === 'revise' || sub === 'backchain')
|
|
334
343
|
&& input > 1 && typeof argv[input + 1] === 'string' && !argv[input + 1].startsWith('-'));
|
|
335
344
|
return implied ? [...argv, '--json'] : argv;
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
}
|
|
24
24
|
},
|
|
25
25
|
"features": {
|
|
26
|
-
"type": "array", "minItems": 1,
|
|
26
|
+
"type": "array", "minItems": 1,
|
|
27
27
|
"items": { "$ref": "#/$defs/feature" }
|
|
28
28
|
},
|
|
29
29
|
"tasks": {
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
"type": "string", "minLength": 1, "maxLength": 1024,
|
|
46
46
|
"pattern": "^(?!/)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*\\\\)(?!.*[\\u0000-\\u001f\\u007f])[^/]+(?:/[^/]+)*$"
|
|
47
47
|
},
|
|
48
|
-
"ids": { "type": "array", "
|
|
48
|
+
"ids": { "type": "array", "uniqueItems": true, "items": { "$ref": "#/$defs/identifier" } },
|
|
49
49
|
"nonemptyIds": { "allOf": [{ "$ref": "#/$defs/ids" }, { "minItems": 1 }] },
|
|
50
50
|
"provider": {
|
|
51
51
|
"oneOf": [
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@quolu/lattice",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.118.0",
|
|
4
4
|
"description": "Schedulability compiler for multi-agent development: observe real code boundaries, refactor the conflicting seam, recompile the plan for parallel execution",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Quo / クオ at kitepon.dev",
|
package/src/cli-help.mjs
CHANGED
|
@@ -44,6 +44,10 @@ Commands:
|
|
|
44
44
|
revise --schema --json
|
|
45
45
|
backchain --input <file> [--dry-run] [--json]
|
|
46
46
|
# 各工程の必要・提供機能を照合し、初回又は既存storeへのplan登録まで行う
|
|
47
|
+
backchain --template [--plan <key>] --json
|
|
48
|
+
# ゴール側から書く下書きの雛形。--planを付けると今のplanのtaskと版が入る
|
|
49
|
+
backchain --draft <file> [--dry-run] [--json]
|
|
50
|
+
# 下書きを下流から上流の順に書く(新規は final、既存は steps[].before が起点)。--dry-runで差分・継続・指摘を確認でき、指摘があっても登録できる
|
|
47
51
|
show <plan_key> --json # task・依存辺・phase・状態をplan本体から1コマンドで投影する
|
|
48
52
|
scope-review --plan-input <file> --review <scope-review.json> --json
|
|
49
53
|
# 書き終えたplanの全taskが持ち主の作業仕様の内にあるかを、登録前に検査する
|
|
@@ -304,7 +308,7 @@ const SUBCOMMAND_USAGE = Object.freeze({
|
|
|
304
308
|
'plan create': 'plan create --input <file> [--serialization-reviewed] | --schema --json | --schema-version <1|2|3|4|5|6> --json | --template --json',
|
|
305
309
|
'plan show': 'plan show <plan_key> --json',
|
|
306
310
|
'plan scope-review': 'plan scope-review --plan-input <plan-create-or-extraction.json> --review <scope-review.json> --json | --schema --json',
|
|
307
|
-
'plan backchain': 'plan backchain --input <file> [--dry-run] [--json] | --schema --json',
|
|
311
|
+
'plan backchain': 'plan backchain --input <file> [--dry-run] [--json] | --draft <file> [--dry-run] [--json] | --template [--plan <key>] --json | --schema --json',
|
|
308
312
|
'plan revise': 'plan revise [--plan <key>] --input <file> [--dry-run] [--json] | --schema --json\n\n'
|
|
309
313
|
+ '--input: the whole desired plan in the same shape as `plan create` (start from `plan create --template --json`),\n'
|
|
310
314
|
+ 'or {"schema":"lattice.plan_revise_input.v1","desired":<that plan>,"continuity":[{task_id, policy: carry|reset|retire, reason}]}.\n'
|
package/src/plan-backchain.mjs
CHANGED
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
readTodoStore, TodoStoreError,
|
|
12
12
|
} from './todo-store.mjs';
|
|
13
13
|
import { gitSync } from './git-process.mjs';
|
|
14
|
+
import { findingHandoff, planEditAdvice } from './plan-edit-advice.mjs';
|
|
14
15
|
import { completeCreateInput, readAuthoringJsonFile } from './todo-authoring-input.mjs';
|
|
15
16
|
import {
|
|
16
17
|
explainPhaseTodoRevision, phaseTodoRevisionPlanVersion, validatePhaseTodoRevision,
|
|
@@ -18,7 +19,6 @@ import {
|
|
|
18
19
|
|
|
19
20
|
export const BACKCHAIN_SCHEMA = 'lattice.plan_backchain.v1';
|
|
20
21
|
const CREATE_SCHEMA = 'lattice.plan_create_input.v4';
|
|
21
|
-
const MAX_FEATURES = 2_048;
|
|
22
22
|
const MAX_TEXT_BYTES = 16_384;
|
|
23
23
|
const MAX_BINDING_BYTES = 8_388_608;
|
|
24
24
|
const BINDING_SCHEMA = 'lattice.plan_backchain_binding.v1';
|
|
@@ -36,7 +36,7 @@ function text(value) {
|
|
|
36
36
|
|
|
37
37
|
function identifiers(value, { nonempty = false } = {}) {
|
|
38
38
|
return Array.isArray(value) && (!nonempty || value.length > 0)
|
|
39
|
-
&& value.
|
|
39
|
+
&& value.every(isTodoIdentifier)
|
|
40
40
|
&& new Set(value).size === value.length;
|
|
41
41
|
}
|
|
42
42
|
|
|
@@ -128,8 +128,7 @@ export function validatePlanBackchain(chain, authoring) {
|
|
|
128
128
|
|| !identifiers(chain.goal.required_feature_ids, { nonempty: true })) {
|
|
129
129
|
fail('goal_invalid', '/goal');
|
|
130
130
|
}
|
|
131
|
-
if (!Array.isArray(chain.features) || chain.features.length === 0
|
|
132
|
-
|| chain.features.length > MAX_FEATURES) fail('features_invalid', '/features');
|
|
131
|
+
if (!Array.isArray(chain.features) || chain.features.length === 0) fail('features_invalid', '/features'); // no count cap (ADR 0201); bytes bound it
|
|
133
132
|
const features = new Map();
|
|
134
133
|
for (const [index, feature] of chain.features.entries()) {
|
|
135
134
|
if (!exactRecord(feature, [
|
|
@@ -257,7 +256,7 @@ export function validatePlanBackchain(chain, authoring) {
|
|
|
257
256
|
}
|
|
258
257
|
|
|
259
258
|
/** 決定的な順序(pointer, reason, 正準JSON)で並べ、同一の指摘は1件にする。 */
|
|
260
|
-
function sortFindings(list) {
|
|
259
|
+
export function sortFindings(list) {
|
|
261
260
|
const keyed = new Map(list.map((entry) => [canonicalizeTodoArtifact(entry), entry]));
|
|
262
261
|
return [...keyed.entries()].sort(([left, a], [right, b]) =>
|
|
263
262
|
a.pointer.localeCompare(b.pointer) || a.reason.localeCompare(b.reason)
|
|
@@ -386,34 +385,35 @@ function gitRoot(cwd) {
|
|
|
386
385
|
} catch { fail('repository_unresolved', '/'); }
|
|
387
386
|
}
|
|
388
387
|
|
|
389
|
-
|
|
388
|
+
/** null when the repo-relative ref is a readable regular file inside the repo, else unsafe | missing | unreadable. */
|
|
389
|
+
export async function existingReferenceProblem(canonicalRoot, ref) {
|
|
390
|
+
const absolute = path.resolve(canonicalRoot, ref);
|
|
391
|
+
if (!absolute.startsWith(`${canonicalRoot}${path.sep}`)) return 'unsafe';
|
|
392
|
+
let state;
|
|
393
|
+
try { state = await lstat(absolute); } catch { return 'missing'; }
|
|
394
|
+
let resolved;
|
|
395
|
+
try { resolved = await realpath(absolute); } catch { return 'unreadable'; }
|
|
396
|
+
return !state.isFile() || state.isSymbolicLink() || !resolved.startsWith(`${canonicalRoot}${path.sep}`)
|
|
397
|
+
? 'unsafe' : null;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/** advisory (a draft): a receipt carried from an earlier version that is gone is reported, never invented or refused. */
|
|
401
|
+
async function verifyExistingFeatureReferences(repoRoot, chain, { advisory = false } = {}) {
|
|
390
402
|
const canonicalRoot = await realpath(repoRoot);
|
|
403
|
+
const unresolved = [];
|
|
391
404
|
for (const feature of chain.features) {
|
|
392
405
|
if (feature.provider.kind !== 'existing') continue;
|
|
393
|
-
const
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
let state;
|
|
401
|
-
try { state = await lstat(absolute); }
|
|
402
|
-
catch { fail('existing_feature_reference_missing', `/features/${feature.feature_id}/provider`, {
|
|
403
|
-
evidence_ref: ref,
|
|
404
|
-
}); }
|
|
405
|
-
let resolved;
|
|
406
|
-
try { resolved = await realpath(absolute); }
|
|
407
|
-
catch { fail('existing_feature_reference_unreadable', `/features/${feature.feature_id}/provider`, {
|
|
408
|
-
evidence_ref: ref,
|
|
409
|
-
}); }
|
|
410
|
-
if (!state.isFile() || state.isSymbolicLink()
|
|
411
|
-
|| !resolved.startsWith(`${canonicalRoot}${path.sep}`)) {
|
|
412
|
-
fail('existing_feature_reference_unsafe', `/features/${feature.feature_id}/provider`, {
|
|
413
|
-
evidence_ref: ref,
|
|
406
|
+
const problem = await existingReferenceProblem(canonicalRoot, feature.provider.evidence_ref);
|
|
407
|
+
if (problem !== null && advisory) {
|
|
408
|
+
unresolved.push({ reason: 'observation_unresolved', pointer: `/features/${feature.feature_id}/provider`,
|
|
409
|
+
feature_id: feature.feature_id, evidence_ref: feature.provider.evidence_ref, cause: problem, carried: true });
|
|
410
|
+
} else if (problem !== null) {
|
|
411
|
+
fail(`existing_feature_reference_${problem}`, `/features/${feature.feature_id}/provider`, {
|
|
412
|
+
evidence_ref: feature.provider.evidence_ref,
|
|
414
413
|
});
|
|
415
414
|
}
|
|
416
415
|
}
|
|
416
|
+
return unresolved;
|
|
417
417
|
}
|
|
418
418
|
|
|
419
419
|
const DONE_CONDITION_PLAN_SCHEMA = 'lattice.todo_plan.v8';
|
|
@@ -457,7 +457,7 @@ function featureGraphDigest(chain) {
|
|
|
457
457
|
return digestTodoArtifact({ goal: chain.goal, features: chain.features, tasks: chain.tasks });
|
|
458
458
|
}
|
|
459
459
|
|
|
460
|
-
function taskSignature(chain, taskId) {
|
|
460
|
+
export function taskSignature(chain, taskId) {
|
|
461
461
|
const task = chain?.tasks?.find(({ task_id: id }) => id === taskId);
|
|
462
462
|
if (task === undefined) return null;
|
|
463
463
|
const byId = new Map(chain.features.map((feature) => [feature.feature_id, feature]));
|
|
@@ -493,7 +493,8 @@ function compileTaskMigration(previousPlan, oldChain, desiredSeed, newChain) {
|
|
|
493
493
|
return { from_task_id: id, to_task_id: 'removed', state_policy: 'removed' };
|
|
494
494
|
}
|
|
495
495
|
if (decision?.policy === 'retire') fail('continuity_live_task_mismatch', '/continuity', { task_id: id });
|
|
496
|
-
|
|
496
|
+
// No earlier chain = no earlier contract to compare: absence is not a change (it would reset every task's history).
|
|
497
|
+
const sameContract = oldChain === null || taskSignature(oldChain, id) === taskSignature(newChain, id);
|
|
497
498
|
const sameTask = oldTask.title === nextTask.title && oldTask.lane === nextTask.lane
|
|
498
499
|
&& oldTask.phase_id === nextTask.phase_id
|
|
499
500
|
&& oldTask.parent_task_id === nextTask.parent_task_id
|
|
@@ -506,7 +507,8 @@ function compileTaskMigration(previousPlan, oldChain, desiredSeed, newChain) {
|
|
|
506
507
|
|| (decision === undefined && sameContract && sameTask);
|
|
507
508
|
return { from_task_id: id, to_task_id: id,
|
|
508
509
|
state_policy: carry ? 'carry_reconciled_metadata' : 'reset_pending' };
|
|
509
|
-
|
|
510
|
+
// Code-unit order, as validTaskMigration requires (localeCompare misorders mixed-case ids such as T and split-…).
|
|
511
|
+
}).sort((left, right) => (left.from_task_id < right.from_task_id ? -1 : left.from_task_id > right.from_task_id ? 1 : 0));
|
|
510
512
|
}
|
|
511
513
|
|
|
512
514
|
export function compilePhaseMigration(previousPlan, desiredSeed, taskMigration) {
|
|
@@ -535,7 +537,7 @@ export function compilePhaseMigration(previousPlan, desiredSeed, taskMigration)
|
|
|
535
537
|
}
|
|
536
538
|
|
|
537
539
|
export async function compileBackchainRevision({ repoRoot, member, chain, authoring }) {
|
|
538
|
-
if (!['lattice.todo_plan.v7', DONE_CONDITION_PLAN_SCHEMA].includes(member.plan.schema)) {
|
|
540
|
+
if (!['lattice.todo_plan.v7', DONE_CONDITION_PLAN_SCHEMA, SPLIT_PLAN_SCHEMA].includes(member.plan.schema)) {
|
|
539
541
|
fail('predecessor_plan_schema_unsupported', '/plan_key', {
|
|
540
542
|
actual: member.plan.schema, next_action: 'author_a_new_backchain_plan',
|
|
541
543
|
});
|
|
@@ -578,7 +580,7 @@ export async function compileBackchainRevision({ repoRoot, member, chain, author
|
|
|
578
580
|
}
|
|
579
581
|
|
|
580
582
|
async function activeIntentUnchanged({ repoRoot, member, chain, authoring }) {
|
|
581
|
-
if (!['lattice.todo_plan.v7', DONE_CONDITION_PLAN_SCHEMA].includes(member.plan.schema)) return false;
|
|
583
|
+
if (!['lattice.todo_plan.v7', DONE_CONDITION_PLAN_SCHEMA, SPLIT_PLAN_SCHEMA].includes(member.plan.schema)) return false;
|
|
582
584
|
const binding = await readPlanBackchainBinding({ repoRoot, plan: member.plan });
|
|
583
585
|
if (binding === null || featureGraphDigest(binding.chain) !== featureGraphDigest(chain)) return false;
|
|
584
586
|
const amended = attachBackchainMemos(chain, authoring, { previousChain: binding.chain });
|
|
@@ -634,24 +636,56 @@ export async function rebindCarriedWork({ repoRoot, planKey, env,
|
|
|
634
636
|
return rebound;
|
|
635
637
|
}
|
|
636
638
|
|
|
637
|
-
|
|
639
|
+
const draftOutput = async (report, repoRoot) => (report === null ? {} : { draft: report.summary, draft_findings: report.findings,
|
|
640
|
+
finding_handoff: await findingHandoff({ repoRoot, planKey: report.summary.plan_key, findings: report.findings }) });
|
|
641
|
+
|
|
642
|
+
export async function runPlanBackchain({ cwd, inputRef = null, draftRef = null, stdout, dryRun = false, env = process.env }) {
|
|
638
643
|
const repoRoot = gitRoot(cwd);
|
|
639
|
-
const
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
644
|
+
const loadStore = async () => {
|
|
645
|
+
try {
|
|
646
|
+
await lstat(path.join(repoRoot, '.lattice', 'todo', 'manifest.json'));
|
|
647
|
+
return await readTodoStore({ repoRoot });
|
|
648
|
+
} catch (error) {
|
|
649
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
650
|
+
return null;
|
|
651
|
+
}
|
|
652
|
+
};
|
|
653
|
+
let chain;
|
|
654
|
+
let authoring;
|
|
655
|
+
let store;
|
|
656
|
+
let draftReport = null;
|
|
657
|
+
// The seat's structured-input route passes JSON through --input: a draft is recognized by its schema.
|
|
658
|
+
let given = draftRef !== null ? await readAuthoringJsonFile(repoRoot, draftRef, { invalidCode: 'PLAN_BACKCHAIN_INVALID' }) : null;
|
|
659
|
+
if (given === null) {
|
|
660
|
+
given = await readAuthoringJsonFile(repoRoot, inputRef, { invalidCode: 'PLAN_BACKCHAIN_INVALID' });
|
|
661
|
+
if (given?.schema === 'lattice.plan_draft.v1') draftRef = inputRef; else draftRef = null;
|
|
662
|
+
}
|
|
663
|
+
if (draftRef !== null) {
|
|
664
|
+
const draft = given;
|
|
665
|
+
store = await loadStore();
|
|
666
|
+
const { compilePlanDraft } = await import('./plan-draft.mjs');
|
|
667
|
+
({ chain, authoring, report: draftReport } = await compilePlanDraft({
|
|
668
|
+
repoRoot, draft, draftRef, store, env,
|
|
669
|
+
member: store?.members.find(({ plan }) => plan.plan_key === draft?.plan_key) ?? null,
|
|
670
|
+
}));
|
|
671
|
+
} else {
|
|
672
|
+
chain = given;
|
|
673
|
+
failOnShape(chain);
|
|
674
|
+
authoring = completeCreateInput(await readAuthoringJsonFile(repoRoot, chain.authoring_ref, {
|
|
675
|
+
invalidCode: 'PLAN_BACKCHAIN_INVALID',
|
|
676
|
+
}), { env, now: new Date() });
|
|
677
|
+
store = await loadStore();
|
|
678
|
+
}
|
|
679
|
+
const { findings: allFindings } = validatePlanBackchain(chain, authoring);
|
|
680
|
+
// A draft over a legacy plan declares only the branch it touches; tasks elsewhere are unassessed, not missing.
|
|
681
|
+
const featureChainFindings = draftReport === null ? allFindings
|
|
682
|
+
: allFindings.filter(({ reason }) => reason !== 'task_coverage_missing');
|
|
683
|
+
const carriedGaps = await verifyExistingFeatureReferences(repoRoot, chain, { advisory: draftReport !== null });
|
|
684
|
+
if (carriedGaps.length > 0) draftReport.findings = sortFindings([...draftReport.findings, ...carriedGaps]);
|
|
646
685
|
let member = null;
|
|
647
|
-
|
|
648
|
-
try {
|
|
649
|
-
await lstat(path.join(repoRoot, '.lattice', 'todo', 'manifest.json'));
|
|
650
|
-
store = await readTodoStore({ repoRoot });
|
|
686
|
+
if (store !== null) {
|
|
651
687
|
if (store.project_id !== chain.project_id) fail('project_id_mismatch', '/project_id');
|
|
652
688
|
member = store.members.find(({ plan }) => plan.plan_key === chain.plan_key) ?? null;
|
|
653
|
-
} catch (error) {
|
|
654
|
-
if (error?.code !== 'ENOENT') throw error;
|
|
655
689
|
}
|
|
656
690
|
if (member === null && (chain.continuity?.length ?? 0) > 0) {
|
|
657
691
|
fail('continuity_without_predecessor', '/continuity');
|
|
@@ -666,6 +700,9 @@ export async function runPlanBackchain({ cwd, inputRef, stdout, dryRun = false,
|
|
|
666
700
|
try { buildTodoPlan({ ...planSeed(amended, null), plan_version: chain.plan_version }); }
|
|
667
701
|
catch { fail('authoring_plan_invalid', '/authoring_ref'); }
|
|
668
702
|
}
|
|
703
|
+
// A finished chain revised through --input gets the same cut-off advisory; a draft already carries draft_findings + handoff.
|
|
704
|
+
const editAdvice = draftReport === null && revision !== null
|
|
705
|
+
? Object.fromEntries([['advice', await planEditAdvice({ repoRoot, before: member.plan, after: revision.desired_plan, states: member.tasks })]].filter(([, v]) => v !== null)) : {};
|
|
669
706
|
const unknownFeatureIds = chain.features.filter(({ provider: source }) => source.kind === 'unknown')
|
|
670
707
|
.map(({ feature_id: id }) => id).sort();
|
|
671
708
|
if (dryRun) {
|
|
@@ -679,6 +716,8 @@ export async function runPlanBackchain({ cwd, inputRef, stdout, dryRun = false,
|
|
|
679
716
|
: store === null ? 'create' : 'add',
|
|
680
717
|
task_migration: revision?.task_migration ?? null,
|
|
681
718
|
feature_chain_findings: featureChainFindings,
|
|
719
|
+
...await draftOutput(draftReport, repoRoot),
|
|
720
|
+
...editAdvice,
|
|
682
721
|
result_digest: '',
|
|
683
722
|
};
|
|
684
723
|
checked.result_digest = todoSelfDigest(checked, 'result_digest');
|
|
@@ -736,6 +775,8 @@ export async function runPlanBackchain({ cwd, inputRef, stdout, dryRun = false,
|
|
|
736
775
|
chain_digest: effectiveChain.chain_digest, authoring_result: created,
|
|
737
776
|
rebound_task_ids: reboundTaskIds,
|
|
738
777
|
feature_chain_findings: featureChainFindings,
|
|
778
|
+
...await draftOutput(draftReport, repoRoot),
|
|
779
|
+
...editAdvice,
|
|
739
780
|
operation: unchanged ? 'unchanged' : revision !== null ? 'revise'
|
|
740
781
|
: store === null ? 'create' : 'add',
|
|
741
782
|
journal_head_digest: finalMember.journal.events.at(-1).event_digest,
|
|
@@ -746,6 +787,25 @@ export async function runPlanBackchain({ cwd, inputRef, stdout, dryRun = false,
|
|
|
746
787
|
return 0;
|
|
747
788
|
}
|
|
748
789
|
|
|
790
|
+
/** `plan backchain --template [--plan K]`: the draft skeleton, seeded from the active plan when one is named. */
|
|
791
|
+
export async function runPlanBackchainTemplate({ cwd, planKey = null, stdout }) {
|
|
792
|
+
const repoRoot = gitRoot(cwd);
|
|
793
|
+
let store = null;
|
|
794
|
+
try {
|
|
795
|
+
await lstat(path.join(repoRoot, '.lattice', 'todo', 'manifest.json'));
|
|
796
|
+
store = await readTodoStore({ repoRoot });
|
|
797
|
+
} catch (error) {
|
|
798
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
799
|
+
}
|
|
800
|
+
const member = planKey === null ? null : store?.members.find(({ plan }) => plan.plan_key === planKey) ?? null;
|
|
801
|
+
if (planKey !== null && member === null) {
|
|
802
|
+
fail('plan_not_active', '/plan', { plan_key: planKey, next_action: 'Run lattice todo status --json to list the active plan keys.' });
|
|
803
|
+
}
|
|
804
|
+
const { draftTemplate } = await import('./plan-draft.mjs');
|
|
805
|
+
stdout.write(`${JSON.stringify(await draftTemplate({ repoRoot, member, store }))}\n`);
|
|
806
|
+
return 0;
|
|
807
|
+
}
|
|
808
|
+
|
|
749
809
|
export async function backchainSchema() {
|
|
750
810
|
return JSON.parse(await readFile(new URL('../docs/schemas/lattice.plan_backchain.v1.schema.json', import.meta.url), 'utf8'));
|
|
751
811
|
}
|
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
import { realpath } from 'node:fs/promises';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
isTodoIdentifier, isTodoRef, todoSelfDigest,
|
|
5
|
+
} from './todo-contracts.mjs';
|
|
6
|
+
import { TodoStoreError } from './todo-store.mjs';
|
|
7
|
+
import { completeCreateInput } from './todo-authoring-input.mjs';
|
|
8
|
+
import {
|
|
9
|
+
BACKCHAIN_SCHEMA, existingReferenceProblem, readPlanBackchainBinding, sortFindings, taskSignature,
|
|
10
|
+
} from './plan-backchain.mjs';
|
|
11
|
+
|
|
12
|
+
// Goal-side authoring draft (docs/architecture/dfd-plan-draft.md). The AI writes steps downstream-first;
|
|
13
|
+
// this module only normalizes them into the existing backchain chain + create-shaped authoring. It reads
|
|
14
|
+
// the Store through the caller's member and writes nothing; publication stays in runPlanBackchain.
|
|
15
|
+
export const DRAFT_SCHEMA = 'lattice.plan_draft.v1';
|
|
16
|
+
const CREATE_SCHEMA = 'lattice.plan_create_input.v4';
|
|
17
|
+
const KEYS = ['schema', 'project_id', 'plan_key', 'plan_version', 'base_plan_version', 'actor', 'recorded_at',
|
|
18
|
+
'goal', 'phases', 'final', 'steps', 'observations', 'retire', 'continuity', 'context'];
|
|
19
|
+
const MAX_TEXT_BYTES = 16_384;
|
|
20
|
+
const DONE_PLANS = ['lattice.todo_plan.v8', 'lattice.todo_plan.v9'];
|
|
21
|
+
|
|
22
|
+
function fail(reason, pointer, detail = {}) {
|
|
23
|
+
throw new TodoStoreError('PLAN_BACKCHAIN_INVALID', reason, undefined, { pointer, ...detail });
|
|
24
|
+
}
|
|
25
|
+
const rec = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
26
|
+
const text = (value) => typeof value === 'string' && value.trim().length > 0
|
|
27
|
+
&& Buffer.byteLength(value, 'utf8') <= MAX_TEXT_BYTES;
|
|
28
|
+
const push = (list, value) => { if (!list.includes(value)) list.push(value); };
|
|
29
|
+
|
|
30
|
+
function only(value, allowed, pointer, required = []) {
|
|
31
|
+
if (!rec(value)) fail('draft_shape_invalid', pointer, { expected: { type: 'object' } });
|
|
32
|
+
const unexpected = Object.keys(value).filter((key) => !allowed.includes(key));
|
|
33
|
+
const missing = required.filter((key) => value[key] === undefined);
|
|
34
|
+
if (unexpected.length > 0 || missing.length > 0) {
|
|
35
|
+
fail('draft_keys_invalid', pointer, { unexpected_keys: unexpected, missing_keys: missing, allowed_keys: allowed });
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function result(value, pointer, withId) {
|
|
40
|
+
only(value, ['capability', 'acceptance', 'feature_id'], pointer, ['capability', 'acceptance']);
|
|
41
|
+
if (!text(value.capability) || !text(value.acceptance)) fail('draft_result_invalid', pointer);
|
|
42
|
+
if (value.feature_id !== undefined && !isTodoIdentifier(value.feature_id)) fail('draft_result_invalid', `${pointer}/feature_id`);
|
|
43
|
+
if (withId && value.feature_id === undefined) {
|
|
44
|
+
fail('draft_result_feature_id_required', `${pointer}/feature_id`, { cause: 'step has no task to name the result' });
|
|
45
|
+
}
|
|
46
|
+
return value;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function newTask(task, pointer) {
|
|
50
|
+
only(task, ['task_id', 'title', 'lane', 'design_memo', 'phase_id', 'done'], pointer, ['task_id', 'title', 'design_memo']);
|
|
51
|
+
if (!isTodoIdentifier(task.task_id) || !text(task.title) || !text(task.design_memo)
|
|
52
|
+
|| (task.done !== undefined && !text(task.done))) fail('draft_task_invalid', pointer);
|
|
53
|
+
return task;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Normalizes the draft into { chain, authoring, report }. member is the active plan member or null. */
|
|
57
|
+
export async function compilePlanDraft({ repoRoot, draft, draftRef, member, store, env, now = new Date() }) {
|
|
58
|
+
only(draft, KEYS, '/', ['schema', 'plan_key']);
|
|
59
|
+
if (draft.schema !== DRAFT_SCHEMA) fail('schema_invalid', '/schema', { expected: DRAFT_SCHEMA, actual: draft.schema });
|
|
60
|
+
if (!isTodoIdentifier(draft.plan_key)) fail('identifier_invalid', '/plan_key');
|
|
61
|
+
const plan = member?.plan ?? null;
|
|
62
|
+
const planKey = draft.plan_key;
|
|
63
|
+
const projectId = draft.project_id ?? store?.project_id
|
|
64
|
+
?? (await import('./project-cli.mjs')).identifierFromRepoRoot(repoRoot, 'project');
|
|
65
|
+
if (!isTodoIdentifier(projectId)) fail('identifier_invalid', '/project_id');
|
|
66
|
+
const steps = draft.steps ?? [];
|
|
67
|
+
if (!Array.isArray(steps)) fail('draft_shape_invalid', '/steps', { expected: { type: 'array' } });
|
|
68
|
+
if (plan !== null) {
|
|
69
|
+
if (draft.final !== undefined) {
|
|
70
|
+
fail('final_on_existing_plan', '/final', { next_action: 'Name the goal-side task in steps[].before instead.' });
|
|
71
|
+
}
|
|
72
|
+
if (draft.base_plan_version !== undefined && draft.base_plan_version !== plan.plan_version) {
|
|
73
|
+
fail('draft_base_stale', '/base_plan_version', {
|
|
74
|
+
current_plan_version: plan.plan_version,
|
|
75
|
+
next_action: 'Run lattice plan backchain --template --plan ' + planKey + ' --json, keep your steps, set base_plan_version to the current value, then rerun.',
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
} else {
|
|
79
|
+
only(draft.final, ['task', 'result'], '/final', ['task', 'result']);
|
|
80
|
+
if (!rec(draft.goal)) fail('goal_missing', '/goal', { expected: ['purpose', 'outcome', 'acceptance'] });
|
|
81
|
+
}
|
|
82
|
+
if (draft.goal !== undefined) {
|
|
83
|
+
only(draft.goal, ['purpose', 'outcome', 'acceptance'], '/goal', ['purpose', 'outcome', 'acceptance']);
|
|
84
|
+
if (!Object.values(draft.goal).every(text)) fail('goal_invalid', '/goal');
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const ref = (id) => ({ project_id: projectId, plan_key: planKey, task_id: id });
|
|
88
|
+
const edgeKey = ({ from, to }) => `${from.plan_key}/${from.task_id}->${to.plan_key}/${to.task_id}`;
|
|
89
|
+
const tasks = new Map((plan?.tasks ?? []).map((task) => [task.task_id, { ...task }]));
|
|
90
|
+
const baseIds = new Set(tasks.keys());
|
|
91
|
+
const edges = [...(plan?.hard_dependencies ?? [])];
|
|
92
|
+
const initialEdges = new Set(edges.map(edgeKey));
|
|
93
|
+
const oldChain = plan === null ? null : (await readPlanBackchainBinding({ repoRoot, plan }))?.chain ?? null;
|
|
94
|
+
const features = new Map((oldChain?.features ?? []).map((f) =>
|
|
95
|
+
[f.feature_id, { ...f, requires_feature_ids: [...f.requires_feature_ids] }]));
|
|
96
|
+
const ctasks = new Map((oldChain?.tasks ?? []).map((t) => [t.task_id, {
|
|
97
|
+
task_id: t.task_id, requires_feature_ids: [...t.requires_feature_ids],
|
|
98
|
+
provides_feature_ids: [...t.provides_feature_ids] }]));
|
|
99
|
+
const placeFindings = [];
|
|
100
|
+
const canonicalRoot = await realpath(repoRoot);
|
|
101
|
+
const doneField = plan !== null && DONE_PLANS.includes(plan.schema);
|
|
102
|
+
const defaultPhase = draft.phases?.[0]?.phase_id ?? 'main';
|
|
103
|
+
|
|
104
|
+
// A join (task waits for several) is a consumption too: its `after` tasks serve the task that waits.
|
|
105
|
+
const joinAfter = new Map();
|
|
106
|
+
for (const join of plan?.joins ?? []) {
|
|
107
|
+
if (join.before.plan_key !== planKey) continue;
|
|
108
|
+
joinAfter.set(join.before.task_id, [...(joinAfter.get(join.before.task_id) ?? []),
|
|
109
|
+
...join.after.filter((r) => r.plan_key === planKey).map((r) => r.task_id)]);
|
|
110
|
+
}
|
|
111
|
+
const joinNeeded = new Set();
|
|
112
|
+
const introduced = new Map();
|
|
113
|
+
steps.forEach((step, index) => { if (rec(step?.task)) introduced.set(step.task.task_id, index); });
|
|
114
|
+
|
|
115
|
+
// A task in the plan that the feature chain does not describe yet is described by its own title, so a legacy
|
|
116
|
+
// plan can be edited from the task the author names (the draft declares only the branch it touches).
|
|
117
|
+
const ensure = (id, pointer) => {
|
|
118
|
+
if (!tasks.has(id)) fail('task_unknown', pointer, { task_id: id, available_task_ids: [...tasks.keys()].sort() });
|
|
119
|
+
if (!ctasks.has(id)) {
|
|
120
|
+
const task = tasks.get(id);
|
|
121
|
+
let featureId = id;
|
|
122
|
+
if (features.has(featureId)) featureId = `${id}-result`;
|
|
123
|
+
if (features.has(featureId)) fail('feature_id_taken', pointer, { feature_id: featureId });
|
|
124
|
+
features.set(featureId, { feature_id: featureId, capability: task.title,
|
|
125
|
+
acceptance: task.done_condition ?? task.title, requires_feature_ids: [],
|
|
126
|
+
provider: { kind: 'task', task_id: id } });
|
|
127
|
+
ctasks.set(id, { task_id: id, requires_feature_ids: [], provides_feature_ids: [featureId] });
|
|
128
|
+
}
|
|
129
|
+
return ctasks.get(id);
|
|
130
|
+
};
|
|
131
|
+
const soleFeature = (ctask, wanted, pointer) => {
|
|
132
|
+
if (wanted !== undefined) {
|
|
133
|
+
if (!ctask.provides_feature_ids.includes(wanted)) {
|
|
134
|
+
fail('feature_not_provided', pointer, { task_id: ctask.task_id, provides_feature_ids: ctask.provides_feature_ids });
|
|
135
|
+
}
|
|
136
|
+
return wanted;
|
|
137
|
+
}
|
|
138
|
+
if (ctask.provides_feature_ids.length !== 1) {
|
|
139
|
+
fail('feature_ambiguous', pointer, { task_id: ctask.task_id, provides_feature_ids: ctask.provides_feature_ids });
|
|
140
|
+
}
|
|
141
|
+
return ctask.provides_feature_ids[0];
|
|
142
|
+
};
|
|
143
|
+
// A plan with no chain is described whole (the Store revision needs every task covered): each task by its own
|
|
144
|
+
// title, wired by its existing edges. Only the branch the draft touches is assessed afterwards.
|
|
145
|
+
const touched = new Set();
|
|
146
|
+
if (plan !== null && oldChain === null) {
|
|
147
|
+
for (const id of tasks.keys()) ensure(id, '/');
|
|
148
|
+
for (const { from, to } of edges) {
|
|
149
|
+
if (from.plan_key !== planKey || to.plan_key !== planKey) continue;
|
|
150
|
+
const feature = ctasks.get(from.task_id).provides_feature_ids[0];
|
|
151
|
+
push(ctasks.get(to.task_id).requires_feature_ids, feature);
|
|
152
|
+
push(features.get(ctasks.get(to.task_id).provides_feature_ids[0]).requires_feature_ids, feature);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
const addEdge = (from, to) => {
|
|
156
|
+
const edge = { from: ref(from), to: ref(to) };
|
|
157
|
+
if (!edges.some((e) => edgeKey(e) === edgeKey(edge))) edges.push(edge);
|
|
158
|
+
};
|
|
159
|
+
const place = async (step, pointer, phase) => {
|
|
160
|
+
const result0 = result(step.result, `${pointer}/result`, step.task === undefined);
|
|
161
|
+
const provided = [step.task, step.existing, step.unknown].filter((x) => x !== undefined).length;
|
|
162
|
+
if (provided !== 1) fail('draft_provider_invalid', pointer, { expected: 'exactly one of task, existing, unknown' });
|
|
163
|
+
let provider;
|
|
164
|
+
let featureId = result0.feature_id;
|
|
165
|
+
if (step.task !== undefined) {
|
|
166
|
+
const task = newTask(step.task, `${pointer}/task`);
|
|
167
|
+
featureId ??= task.task_id;
|
|
168
|
+
if (tasks.has(task.task_id)) {
|
|
169
|
+
fail('step_task_exists', `${pointer}/task/task_id`, { task_id: task.task_id,
|
|
170
|
+
next_action: 'The plan already has this task: re-read it with lattice plan show and rebase the draft.' });
|
|
171
|
+
}
|
|
172
|
+
provider = { kind: 'task', task_id: task.task_id };
|
|
173
|
+
const phaseId = task.phase_id ?? phase;
|
|
174
|
+
const memo = doneField || task.done === undefined ? task.design_memo : `${task.design_memo}\n完了条件: ${task.done}`;
|
|
175
|
+
tasks.set(task.task_id, { task_id: task.task_id, title: task.title, lane: task.lane ?? 'main',
|
|
176
|
+
design_memo: memo, narrative_ref: null, narrative_anchor: null, compile_binding: null,
|
|
177
|
+
parent_task_id: null, phase_id: phaseId,
|
|
178
|
+
...(doneField ? { done_condition: task.done ?? null } : {}) });
|
|
179
|
+
} else if (step.existing !== undefined) {
|
|
180
|
+
only(step.existing, ['evidence_ref'], `${pointer}/existing`, ['evidence_ref']);
|
|
181
|
+
const given = step.existing.evidence_ref;
|
|
182
|
+
// An observation that cannot be read is a finding, not a refusal: the result stays unresolved and the plan usable.
|
|
183
|
+
const cause = typeof given === 'string' && isTodoRef(given)
|
|
184
|
+
? await existingReferenceProblem(canonicalRoot, given) : 'not_a_repo_file';
|
|
185
|
+
if (cause === null) provider = { kind: 'existing', evidence_ref: given };
|
|
186
|
+
else {
|
|
187
|
+
provider = { kind: 'unknown', reason: `observation ${typeof given === 'string' ? given : '(invalid)'} is not readable (${cause})`,
|
|
188
|
+
question: 'Which readable repo file records this result, or is it still unobserved?' };
|
|
189
|
+
placeFindings.push({ reason: 'observation_unresolved', pointer: `${pointer}/existing`, evidence_ref: given, cause });
|
|
190
|
+
}
|
|
191
|
+
} else {
|
|
192
|
+
only(step.unknown, ['reason', 'question'], `${pointer}/unknown`, ['reason', 'question']);
|
|
193
|
+
if (!text(step.unknown.reason) || !text(step.unknown.question)) fail('draft_provider_invalid', `${pointer}/unknown`);
|
|
194
|
+
provider = { kind: 'unknown', reason: step.unknown.reason, question: step.unknown.question };
|
|
195
|
+
}
|
|
196
|
+
if (features.has(featureId)) fail('feature_id_taken', `${pointer}/result/feature_id`, { feature_id: featureId });
|
|
197
|
+
features.set(featureId, { feature_id: featureId, capability: result0.capability,
|
|
198
|
+
acceptance: result0.acceptance, requires_feature_ids: [], provider });
|
|
199
|
+
if (provider.kind === 'task') {
|
|
200
|
+
ctasks.set(provider.task_id, { task_id: provider.task_id, requires_feature_ids: [], provides_feature_ids: [featureId] });
|
|
201
|
+
}
|
|
202
|
+
return { featureId, provider };
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
for (const afters of joinAfter.values()) for (const id of afters) for (const f of ctasks.get(id)?.provides_feature_ids ?? []) joinNeeded.add(f);
|
|
206
|
+
// Goals of a plan with no chain are its own sinks as they stand before the draft: an edit that cuts a branch off a goal
|
|
207
|
+
// must not turn that branch into a new goal (it is reported as unused instead), and unrelated goals are not rewritten.
|
|
208
|
+
let goalIds = oldChain?.goal.required_feature_ids ?? (plan === null ? null
|
|
209
|
+
: [...features.keys()].filter((id) => ![...features.values()].some((f) => f.requires_feature_ids.includes(id))
|
|
210
|
+
&& !joinNeeded.has(id)));
|
|
211
|
+
if (plan === null) {
|
|
212
|
+
const { featureId } = await place(draft.final, '/final', defaultPhase);
|
|
213
|
+
goalIds = [featureId];
|
|
214
|
+
}
|
|
215
|
+
for (const [index, step] of steps.entries()) {
|
|
216
|
+
const pointer = `/steps/${index}`;
|
|
217
|
+
only(step, ['before', 'task', 'existing', 'unknown', 'result', 'for', 'after', 'unlink'], pointer, ['before', 'result']);
|
|
218
|
+
const before = step.before;
|
|
219
|
+
if (!tasks.has(before)) {
|
|
220
|
+
if (introduced.has(before) && introduced.get(before) > index) {
|
|
221
|
+
fail('step_out_of_order', `${pointer}/before`, { task_id: before, introduced_at_step: introduced.get(before),
|
|
222
|
+
next_action: 'Write the step that adds this task first, or name a task already in the plan.' });
|
|
223
|
+
}
|
|
224
|
+
fail('before_unknown', `${pointer}/before`, { task_id: before, available_task_ids: [...tasks.keys()].sort() });
|
|
225
|
+
}
|
|
226
|
+
touched.add(before);
|
|
227
|
+
const consumer = ensure(before, `${pointer}/before`);
|
|
228
|
+
const consumerFeature = soleFeature(consumer, step.for, `${pointer}/for`);
|
|
229
|
+
const { featureId, provider } = await place(step, pointer, tasks.get(before).phase_id);
|
|
230
|
+
if (provider.kind === 'task') touched.add(provider.task_id);
|
|
231
|
+
push(consumer.requires_feature_ids, featureId);
|
|
232
|
+
push(features.get(consumerFeature).requires_feature_ids, featureId);
|
|
233
|
+
if (provider.kind === 'task') addEdge(provider.task_id, before);
|
|
234
|
+
const after = step.after ?? [];
|
|
235
|
+
if (!Array.isArray(after) || (after.length > 0 && provider.kind !== 'task')) {
|
|
236
|
+
fail('draft_after_invalid', `${pointer}/after`, { expected: 'a list of task ids, only on a step that adds a task' });
|
|
237
|
+
}
|
|
238
|
+
after.forEach((upstream, i) => {
|
|
239
|
+
const at = `${pointer}/after/${i}`;
|
|
240
|
+
const id = typeof upstream === 'string' ? upstream : upstream?.task_id;
|
|
241
|
+
touched.add(id);
|
|
242
|
+
if (!tasks.has(id) || id === provider.task_id) fail('task_unknown', at, { task_id: id, available_task_ids: [...tasks.keys()].sort() });
|
|
243
|
+
const feature = soleFeature(ensure(id, at), typeof upstream === 'string' ? undefined : upstream.feature_id, at);
|
|
244
|
+
push(ctasks.get(provider.task_id).requires_feature_ids, feature);
|
|
245
|
+
push(features.get(featureId).requires_feature_ids, feature);
|
|
246
|
+
addEdge(id, provider.task_id);
|
|
247
|
+
});
|
|
248
|
+
(step.unlink ?? []).forEach((edge, i) => {
|
|
249
|
+
const at = `${pointer}/unlink/${i}`;
|
|
250
|
+
only(edge, ['from', 'to'], at, ['from', 'to']);
|
|
251
|
+
const index2 = edges.findIndex((e) => e.from.plan_key === planKey && e.to.plan_key === planKey
|
|
252
|
+
&& e.from.task_id === edge.from && e.to.task_id === edge.to);
|
|
253
|
+
if (index2 < 0) fail('unlink_edge_missing', at, { from: edge.from, to: edge.to });
|
|
254
|
+
edges.splice(index2, 1);
|
|
255
|
+
touched.add(edge.from); touched.add(edge.to);
|
|
256
|
+
const gone = ctasks.get(edge.from)?.provides_feature_ids ?? [];
|
|
257
|
+
const to = ctasks.get(edge.to);
|
|
258
|
+
if (to !== undefined) {
|
|
259
|
+
to.requires_feature_ids = to.requires_feature_ids.filter((id) => !gone.includes(id));
|
|
260
|
+
for (const id of to.provides_feature_ids) {
|
|
261
|
+
const f = features.get(id);
|
|
262
|
+
f.requires_feature_ids = f.requires_feature_ids.filter((r) => !gone.includes(r));
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
const continuity = [];
|
|
269
|
+
const retired = new Set();
|
|
270
|
+
(draft.retire ?? []).forEach((entry, i) => {
|
|
271
|
+
const at = `/retire/${i}`;
|
|
272
|
+
only(entry, ['task_id', 'reason'], at, ['task_id', 'reason']);
|
|
273
|
+
if (!baseIds.has(entry.task_id) || retired.has(entry.task_id) || !text(entry.reason)) {
|
|
274
|
+
fail('retire_invalid', at, { task_id: entry.task_id, cause: 'must name a task of the active plan once, with a reason' });
|
|
275
|
+
}
|
|
276
|
+
const dependent = [...(plan.joins ?? []), ...(plan.phase_accept_dependencies ?? [])].some((e) =>
|
|
277
|
+
JSON.stringify(e).includes(`"task_id":"${entry.task_id}"`));
|
|
278
|
+
if (dependent) fail('retire_task_referenced', at, { task_id: entry.task_id, cause: 'a join or phase accept names it' });
|
|
279
|
+
retired.add(entry.task_id);
|
|
280
|
+
for (const e of edges) { if (e.from.task_id === entry.task_id) touched.add(e.to.task_id); }
|
|
281
|
+
tasks.delete(entry.task_id);
|
|
282
|
+
for (let k = edges.length - 1; k >= 0; k -= 1) {
|
|
283
|
+
if (edges[k].from.task_id === entry.task_id || edges[k].to.task_id === entry.task_id) {
|
|
284
|
+
if (edges[k].from.plan_key === planKey && edges[k].to.plan_key === planKey) edges.splice(k, 1);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
for (const id of ctasks.get(entry.task_id)?.provides_feature_ids ?? []) {
|
|
288
|
+
if (goalIds?.includes(id)) fail('retire_goal_feature', at, { task_id: entry.task_id, feature_id: id });
|
|
289
|
+
features.delete(id);
|
|
290
|
+
for (const f of features.values()) f.requires_feature_ids = f.requires_feature_ids.filter((r) => r !== id);
|
|
291
|
+
for (const t of ctasks.values()) t.requires_feature_ids = t.requires_feature_ids.filter((r) => r !== id);
|
|
292
|
+
}
|
|
293
|
+
ctasks.delete(entry.task_id);
|
|
294
|
+
continuity.push({ task_id: entry.task_id, policy: 'retire', reason: entry.reason });
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
goalIds = goalIds.filter((id) => features.has(id));
|
|
298
|
+
const goal = {
|
|
299
|
+
purpose: draft.goal?.purpose ?? oldChain?.goal.purpose ?? `${planKey}`,
|
|
300
|
+
outcome: draft.goal?.outcome ?? oldChain?.goal.outcome ?? '(plan goal not recorded)',
|
|
301
|
+
acceptance: draft.goal?.acceptance ?? oldChain?.goal.acceptance ?? '(plan goal not recorded)',
|
|
302
|
+
required_feature_ids: goalIds,
|
|
303
|
+
};
|
|
304
|
+
const chain = {
|
|
305
|
+
schema: BACKCHAIN_SCHEMA, authoring_ref: isTodoRef(draftRef) ? draftRef : 'plan-draft.json',
|
|
306
|
+
project_id: projectId, plan_key: planKey, plan_version: plan?.plan_version ?? draft.plan_version ?? 'v1',
|
|
307
|
+
goal, features: [...features.values()], tasks: [...ctasks.values()], chain_digest: '',
|
|
308
|
+
};
|
|
309
|
+
// Existing work keeps its state unless the author says otherwise; a first draft over a plan with no chain
|
|
310
|
+
// must not read "no record" as "everything changed" (it would reset the history).
|
|
311
|
+
const explicit = new Map((draft.continuity ?? []).map((entry, i) => {
|
|
312
|
+
only(entry, ['task_id', 'policy', 'reason'], `/continuity/${i}`, ['task_id', 'policy', 'reason']);
|
|
313
|
+
if (!baseIds.has(entry.task_id) || retired.has(entry.task_id) || !['carry', 'reset'].includes(entry.policy) || !text(entry.reason)) {
|
|
314
|
+
fail('continuity_invalid', `/continuity/${i}`, { task_id: entry.task_id });
|
|
315
|
+
}
|
|
316
|
+
return [entry.task_id, entry];
|
|
317
|
+
}));
|
|
318
|
+
continuity.push(...explicit.values());
|
|
319
|
+
for (const id of baseIds) {
|
|
320
|
+
if (retired.has(id) || explicit.has(id) || !ctasks.has(id)) continue;
|
|
321
|
+
const incomingOf = (list) => list.filter((e) => e.to.task_id === id).map(edgeKey).sort().join();
|
|
322
|
+
if ((oldChain !== null && taskSignature(oldChain, id) !== taskSignature(chain, id))
|
|
323
|
+
|| incomingOf(plan.hard_dependencies) !== incomingOf(edges)) {
|
|
324
|
+
continuity.push({ task_id: id, policy: 'carry', reason: 'draft changed its inputs or outputs; recorded state is kept' });
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
if (continuity.length > 0) chain.continuity = continuity.sort((a, b) => a.task_id.localeCompare(b.task_id));
|
|
328
|
+
chain.chain_digest = todoSelfDigest(chain, 'chain_digest');
|
|
329
|
+
|
|
330
|
+
const authoring = completeCreateInput({
|
|
331
|
+
schema: CREATE_SCHEMA, project_id: projectId, plan_key: planKey, plan_version: chain.plan_version,
|
|
332
|
+
...(draft.actor !== undefined ? { actor: draft.actor } : {}),
|
|
333
|
+
...(draft.recorded_at !== undefined ? { recorded_at: draft.recorded_at } : {}),
|
|
334
|
+
tasks: [...tasks.values()],
|
|
335
|
+
phases: plan?.phases ?? draft.phases ?? [{ phase_id: defaultPhase, title: planKey }],
|
|
336
|
+
hard_dependencies: edges, joins: plan?.joins ?? [],
|
|
337
|
+
phase_accept_dependencies: plan?.phase_accept_dependencies ?? [],
|
|
338
|
+
}, { env, now });
|
|
339
|
+
|
|
340
|
+
const { findings, unreachedTaskIds } = await draftFindings({ repoRoot, draft, chain, member, baseIds, extra: placeFindings,
|
|
341
|
+
scope: oldChain === null && plan !== null ? touched : null, joinAfter });
|
|
342
|
+
const finalEdges = new Set(edges.map(edgeKey));
|
|
343
|
+
const pairs = (keys) => keys.map((key) => { const [from, to] = key.split('->'); return { from: from.split('/')[1], to: to.split('/')[1] }; });
|
|
344
|
+
return { chain, authoring, report: {
|
|
345
|
+
summary: {
|
|
346
|
+
mode: plan === null ? (store === null ? 'create' : 'add') : 'revise', plan_key: planKey,
|
|
347
|
+
added_task_ids: [...tasks.keys()].filter((id) => !baseIds.has(id)),
|
|
348
|
+
retired_task_ids: [...retired].sort(),
|
|
349
|
+
edge_changes: {
|
|
350
|
+
added: pairs([...finalEdges].filter((k) => !initialEdges.has(k))),
|
|
351
|
+
removed: pairs([...initialEdges].filter((k) => !finalEdges.has(k))),
|
|
352
|
+
},
|
|
353
|
+
unassessed_task_count: oldChain === null && plan !== null ? [...tasks.keys()].filter((id) => !touched.has(id) && baseIds.has(id) && !unreachedTaskIds.includes(id)).length : 0,
|
|
354
|
+
},
|
|
355
|
+
findings,
|
|
356
|
+
} };
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* Advisory only (never blocks publish or readiness). Mechanical facts over the declared scope:
|
|
361
|
+
* an output nobody consumes, one capability string claimed by two providers, and a planned provider whose result
|
|
362
|
+
* the author matched to an observation file. A matched file is a candidate for comparison, not equivalence.
|
|
363
|
+
*/
|
|
364
|
+
async function draftFindings({ repoRoot, draft, chain, member, baseIds, scope, extra, joinAfter }) {
|
|
365
|
+
const found = [];
|
|
366
|
+
const state = new Map((member?.tasks ?? []).map((task) => [task.task_id, task.status]));
|
|
367
|
+
const features = new Map(chain.features.map((f) => [f.feature_id, f]));
|
|
368
|
+
// Reachable from a goal result through requirements. A task result outside it serves no goal: the branch an edit cut off
|
|
369
|
+
// (with everything only it needed) is the retirement candidate, found from the edit and not from the whole plan.
|
|
370
|
+
const reached = new Set();
|
|
371
|
+
const byTask = new Map(chain.tasks.map((t) => [t.task_id, t]));
|
|
372
|
+
const walk = (id) => {
|
|
373
|
+
if (reached.has(id) || !features.has(id)) return;
|
|
374
|
+
reached.add(id);
|
|
375
|
+
const feature = features.get(id);
|
|
376
|
+
feature.requires_feature_ids.forEach(walk);
|
|
377
|
+
if (feature.provider.kind === 'task') {
|
|
378
|
+
(byTask.get(feature.provider.task_id)?.requires_feature_ids ?? []).forEach(walk);
|
|
379
|
+
for (const after of joinAfter.get(feature.provider.task_id) ?? []) (byTask.get(after)?.provides_feature_ids ?? []).forEach(walk);
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
chain.goal.required_feature_ids.forEach(walk);
|
|
383
|
+
const stateOf = (id) => (baseIds.has(id) ? state.get(id) ?? null : 'new');
|
|
384
|
+
const inScope = (feature) => scope === null || (feature.provider.kind === 'task' && scope.has(feature.provider.task_id));
|
|
385
|
+
for (const [index, feature] of chain.features.entries()) {
|
|
386
|
+
if (feature.provider.kind === 'task' && !reached.has(feature.feature_id)) {
|
|
387
|
+
found.push({ reason: 'unused_output', pointer: `/features/${index}`, feature_id: feature.feature_id,
|
|
388
|
+
task_id: feature.provider.task_id, task_state: stateOf(feature.provider.task_id),
|
|
389
|
+
candidate: 'retirement' });
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
const byCapability = new Map();
|
|
393
|
+
for (const feature of chain.features.filter(inScope)) {
|
|
394
|
+
const key = `${feature.capability.trim()}\u0000${feature.acceptance.trim()}`; // same capability with another acceptance/scope is a different result
|
|
395
|
+
byCapability.set(key, [...(byCapability.get(key) ?? []), feature]);
|
|
396
|
+
}
|
|
397
|
+
for (const [capability, group] of byCapability) {
|
|
398
|
+
if (group.length > 1) {
|
|
399
|
+
found.push({ reason: 'duplicate_result', pointer: '/features', capability: capability.split('\u0000')[0],
|
|
400
|
+
feature_ids: group.map((f) => f.feature_id).sort(),
|
|
401
|
+
task_ids: group.filter((f) => f.provider.kind === 'task').map((f) => f.provider.task_id).sort() });
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
const canonicalRoot = await realpath(repoRoot);
|
|
405
|
+
for (const [index, entry] of (draft.observations ?? []).entries()) {
|
|
406
|
+
const at = `/observations/${index}`;
|
|
407
|
+
only(entry, ['feature_id', 'evidence_ref'], at, ['feature_id', 'evidence_ref']);
|
|
408
|
+
const feature = features.get(entry.feature_id);
|
|
409
|
+
const cause = typeof entry.evidence_ref === 'string' && isTodoRef(entry.evidence_ref)
|
|
410
|
+
? await existingReferenceProblem(canonicalRoot, entry.evidence_ref) : 'not_a_repo_file';
|
|
411
|
+
if (feature === undefined) {
|
|
412
|
+
found.push({ reason: 'observation_unresolved', pointer: at, feature_id: entry.feature_id, evidence_ref: entry.evidence_ref,
|
|
413
|
+
cause: 'feature_unknown' });
|
|
414
|
+
} else if (cause !== null) {
|
|
415
|
+
found.push({ reason: 'observation_unresolved', pointer: at, feature_id: feature.feature_id, evidence_ref: entry.evidence_ref, cause });
|
|
416
|
+
} else if (feature.provider.kind === 'task') {
|
|
417
|
+
found.push({ reason: 'planned_provider_has_observation', pointer: at, feature_id: feature.feature_id,
|
|
418
|
+
task_id: feature.provider.task_id, task_state: stateOf(feature.provider.task_id), evidence_ref: entry.evidence_ref });
|
|
419
|
+
} else {
|
|
420
|
+
// A result that has no planned task (an existing observation or an open question): the file is noted, never a refusal.
|
|
421
|
+
found.push({ reason: 'observation_noted', pointer: at, feature_id: feature.feature_id, provider_kind: feature.provider.kind,
|
|
422
|
+
evidence_ref: entry.evidence_ref });
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
return { findings: sortFindings([...found, ...extra]),
|
|
426
|
+
unreachedTaskIds: chain.features.filter((f) => f.provider.kind === 'task' && !reached.has(f.feature_id)).map((f) => f.provider.task_id) };
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/** The authoring entry: a skeleton to fill in, seeded from the active plan on revision. */
|
|
430
|
+
export async function draftTemplate({ repoRoot, member, store }) {
|
|
431
|
+
const projectId = store?.project_id ?? (await import('./project-cli.mjs')).identifierFromRepoRoot(repoRoot, 'project');
|
|
432
|
+
const step = { before: '<downstream task id already in the plan or an earlier step>',
|
|
433
|
+
task: { task_id: '<new task id>', title: '<title>', design_memo: '<what to do>', done: '<completion condition>' },
|
|
434
|
+
result: { capability: '<what the downstream task needs from this one>', acceptance: '<how to tell it is there>' },
|
|
435
|
+
after: ['<existing upstream task id to link, optional>'], unlink: [] };
|
|
436
|
+
if (member === null || member === undefined) {
|
|
437
|
+
return { schema: DRAFT_SCHEMA, project_id: projectId, plan_key: '<plan key>',
|
|
438
|
+
goal: { purpose: '<why>', outcome: '<final result>', acceptance: '<how the goal is judged>' },
|
|
439
|
+
final: { task: { task_id: '<goal task id>', title: '<title>', design_memo: '<what to do>', done: '<completion condition>' },
|
|
440
|
+
result: { capability: '<the observable result>', acceptance: '<how to tell it is there>' } },
|
|
441
|
+
steps: [step], observations: [] };
|
|
442
|
+
}
|
|
443
|
+
const binding = await readPlanBackchainBinding({ repoRoot, plan: member.plan });
|
|
444
|
+
const states = new Map(member.tasks.map((task) => [task.task_id, task.status]));
|
|
445
|
+
return { schema: DRAFT_SCHEMA, project_id: projectId, plan_key: member.plan.plan_key,
|
|
446
|
+
base_plan_version: member.plan.plan_version,
|
|
447
|
+
...(binding === null ? {} : { goal: {
|
|
448
|
+
purpose: binding.chain.goal.purpose, outcome: binding.chain.goal.outcome,
|
|
449
|
+
acceptance: binding.chain.goal.acceptance } }),
|
|
450
|
+
steps: [step], observations: [],
|
|
451
|
+
context: { tasks: member.plan.tasks.map(({ task_id: id, title }) => ({ task_id: id, title, state: states.get(id) })) } };
|
|
452
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { readTodoChartMeta } from './todo-store.mjs';
|
|
2
|
+
|
|
3
|
+
// Advisory only (never a gate, never a message sent): what an edit cut off from its goals, and who to tell.
|
|
4
|
+
// Contract: docs/architecture/dfd-finding-handoff.md.
|
|
5
|
+
export const ADVICE_SCHEMA = 'lattice.plan_edit_advice.v1';
|
|
6
|
+
export const HANDOFF_SCHEMA = 'lattice.finding_handoff.v1';
|
|
7
|
+
// Missing or unreadable evidence alone is never a retirement candidate, so it is not handed off.
|
|
8
|
+
const HANDOFF_REASONS = new Set(['unused_output', 'duplicate_result', 'planned_provider_has_observation', 'completed_result_matches_planned']);
|
|
9
|
+
|
|
10
|
+
/** Prerequisite lists inside one plan: hard edges, joins (before waits for each after) and phase accepts. */
|
|
11
|
+
function prerequisites(plan) {
|
|
12
|
+
const into = new Map(plan.tasks.map(({ task_id: id }) => [id, new Set()]));
|
|
13
|
+
const wait = (to, from) => { if (into.has(to) && into.has(from)) into.get(to).add(from); };
|
|
14
|
+
const mine = (ref) => ref?.plan_key === plan.plan_key;
|
|
15
|
+
for (const { from, to } of plan.hard_dependencies ?? []) if (mine(from) && mine(to)) wait(to.task_id, from.task_id);
|
|
16
|
+
for (const { before, after } of plan.joins ?? []) {
|
|
17
|
+
if (mine(before)) for (const ref of after) if (mine(ref)) wait(before.task_id, ref.task_id);
|
|
18
|
+
}
|
|
19
|
+
for (const { from, to } of plan.phase_accept_dependencies ?? []) if (mine(from) && mine(to)) wait(to.task_id, from.task_id);
|
|
20
|
+
return into;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function served(into, goals) {
|
|
24
|
+
const seen = new Set();
|
|
25
|
+
const stack = goals.filter((id) => into.has(id));
|
|
26
|
+
while (stack.length > 0) {
|
|
27
|
+
const id = stack.pop();
|
|
28
|
+
if (seen.has(id)) continue;
|
|
29
|
+
seen.add(id);
|
|
30
|
+
stack.push(...into.get(id));
|
|
31
|
+
}
|
|
32
|
+
return seen;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Tasks of `before` that served one of its goals (a goal = a task nothing waits for) and no longer serve a goal in `after`.
|
|
37
|
+
* Only the span the edit cut off is returned; new tasks and unrelated purposes are not judged.
|
|
38
|
+
*/
|
|
39
|
+
export function cutOffByEdit(before, after) {
|
|
40
|
+
const was = prerequisites(before);
|
|
41
|
+
const waited = new Set([...was.values()].flatMap((set) => [...set]));
|
|
42
|
+
const goals = [...was.keys()].filter((id) => !waited.has(id));
|
|
43
|
+
const now = served(prerequisites(after), goals);
|
|
44
|
+
const earlier = served(was, goals);
|
|
45
|
+
return after.tasks.map(({ task_id: id }) => id).filter((id) => earlier.has(id) && !now.has(id));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The advisory returned with an ordinary plan edit; null when nothing was cut off. */
|
|
49
|
+
export async function planEditAdvice({ repoRoot, before, after, states = [] }) {
|
|
50
|
+
const state = new Map(states.map((task) => [task.task_id, task.status]));
|
|
51
|
+
const findings = cutOffByEdit(before, after).filter((id) => state.get(id) !== 'retired').map((id) => ({
|
|
52
|
+
reason: 'unused_output', pointer: `/tasks/${id}`, task_id: id, task_state: state.get(id) ?? null,
|
|
53
|
+
candidate: 'retirement', cause: 'cut_off_by_edit' }));
|
|
54
|
+
if (findings.length === 0) return null;
|
|
55
|
+
return { schema: ADVICE_SCHEMA, advisory: true, plan_key: after.plan_key, findings,
|
|
56
|
+
handoff: await findingHandoff({ repoRoot, planKey: after.plan_key, findings }) };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const WHY = {
|
|
60
|
+
unused_output: (f) => f.cause === 'cut_off_by_edit'
|
|
61
|
+
? 'this edit left nothing waiting for its result, so no goal of the plan needs it any more'
|
|
62
|
+
: 'no goal result of the plan reaches its result',
|
|
63
|
+
planned_provider_has_observation: (f) => `its result was matched to the observation ${f.evidence_ref}`,
|
|
64
|
+
completed_result_matches_planned: (f) => `${f.completed_task} already completed a result with the identical capability and acceptance and recorded completion evidence (an evidence file or message alone does not prove equivalence)`,
|
|
65
|
+
};
|
|
66
|
+
const PROPOSE = (planKey) => ({
|
|
67
|
+
unused_output: (f) => `if it has no other purpose, retire it (lattice todo retire --plan ${planKey} --task ${f.task_id} --reason <text>); otherwise link a task that needs its result`,
|
|
68
|
+
duplicate_result: () => 'keep one provider of the result and retire or re-link the other',
|
|
69
|
+
completed_result_matches_planned: (f) => `compare the completion evidence of ${f.completed_task} with this task's scope (version, environment, behavior); if it already covers the result, retire this task`,
|
|
70
|
+
planned_provider_has_observation: () => 'compare that observation with the planned result (version, environment, behavior); if it already covers the result, retire the planned task',
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Who to tell and what to say. Recipient = the chart representative = K4 `readTodoChartMeta({repoRoot}).created_by`
|
|
75
|
+
* (K1 `charts list --json` `charts[].created_by`); unreadable or unrecorded stays an advisory with a manual lookup.
|
|
76
|
+
* Returns null when no finding is a candidate. Nothing is sent and nothing waits for an answer.
|
|
77
|
+
*/
|
|
78
|
+
export async function findingHandoff({ repoRoot, planKey, findings }) {
|
|
79
|
+
const eligible = findings.filter(({ reason }) => HANDOFF_REASONS.has(reason));
|
|
80
|
+
const items = eligible.flatMap((finding) => {
|
|
81
|
+
if (finding.reason === 'duplicate_result') {
|
|
82
|
+
// One item per provider task; results provided by an observation or an open question have no task to change.
|
|
83
|
+
const others = (tid) => finding.task_ids.filter((id) => id !== tid);
|
|
84
|
+
return (finding.task_ids ?? []).map((tid) => ({ task_id: tid, finding: finding.reason,
|
|
85
|
+
why: `${tid} provides the result "${finding.capability}" (${finding.feature_ids.join(', ')}), declared with the identical capability and acceptance${others(tid).length > 0 ? ` as ${others(tid).join(', ')}` : ' by another result'}`,
|
|
86
|
+
proposed_change: PROPOSE(planKey).duplicate_result() }));
|
|
87
|
+
}
|
|
88
|
+
return [{ task_id: finding.task_id ?? null, finding: finding.reason,
|
|
89
|
+
why: WHY[finding.reason](finding), proposed_change: PROPOSE(planKey)[finding.reason](finding),
|
|
90
|
+
...(finding.task_state === undefined ? {} : { task_state: finding.task_state }) }];
|
|
91
|
+
});
|
|
92
|
+
if (items.length === 0) return null;
|
|
93
|
+
const meta = await readTodoChartMeta({ repoRoot }).catch(() => null);
|
|
94
|
+
const createdBy = typeof meta?.created_by === 'string' && meta.created_by !== '' ? meta.created_by : null;
|
|
95
|
+
return {
|
|
96
|
+
schema: HANDOFF_SCHEMA, request: 'advisory', delivery: 'none',
|
|
97
|
+
recipient: {
|
|
98
|
+
role: 'chart_representative', created_by: createdBy,
|
|
99
|
+
source: 'readTodoChartMeta({repoRoot}).created_by; lattice charts list --json charts[].created_by',
|
|
100
|
+
lookup: createdBy === null
|
|
101
|
+
? 'created_by is not recorded here: read charts[].created_by of this chart in `lattice charts list --json`, or ask who created the chart' : null,
|
|
102
|
+
},
|
|
103
|
+
items,
|
|
104
|
+
ask: `Advisory, not a gate: tell ${createdBy ?? 'the chart representative'} the affected task, why it was flagged and the proposed change: `
|
|
105
|
+
+ items.map((item) => `${item.task_id ?? '(result)'}: ${item.why}; ${item.proposed_change}`).join(' | '),
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* `todo done`: the tasks the completion makes unnecessary, from the completed task and the evidence recorded with it.
|
|
111
|
+
* With recorded evidence and a feature chain, a live task that
|
|
112
|
+
* provides a feature with the identical capability and acceptance as one the completed task provides. Scope differences keep
|
|
113
|
+
* results distinct; missing evidence never creates a candidate. Null when nothing is affected. The completion itself is untouched.
|
|
114
|
+
* `plan` and `states` are the committed completion version (what the Store returned from the write), so no chart read is added
|
|
115
|
+
* and a concurrent edit cannot make the advisory describe another version.
|
|
116
|
+
*/
|
|
117
|
+
export async function completionAdvice({ repoRoot, plan, states, taskId, planVersion, evidence }) {
|
|
118
|
+
const state = new Map(states.map((task) => [task.task_id, task.status]));
|
|
119
|
+
const live = (id) => id !== taskId && !['done', 'retired'].includes(state.get(id));
|
|
120
|
+
const findings = [];
|
|
121
|
+
const binding = evidence === null ? null
|
|
122
|
+
: await (await import('./plan-backchain.mjs')).readPlanBackchainBinding({ repoRoot, plan }).catch(() => null);
|
|
123
|
+
if (binding !== null) {
|
|
124
|
+
const features = new Map(binding.chain.features.map((f) => [f.feature_id, f]));
|
|
125
|
+
const doneTask = binding.chain.tasks.find((t) => t.task_id === taskId);
|
|
126
|
+
for (const id of doneTask?.provides_feature_ids ?? []) {
|
|
127
|
+
const done = features.get(id);
|
|
128
|
+
for (const other of binding.chain.tasks) {
|
|
129
|
+
if (!live(other.task_id)) continue;
|
|
130
|
+
for (const fid of other.provides_feature_ids) {
|
|
131
|
+
const twin = features.get(fid);
|
|
132
|
+
if (twin?.capability.trim() === done.capability.trim() && twin.acceptance.trim() === done.acceptance.trim()) {
|
|
133
|
+
findings.push({ reason: 'completed_result_matches_planned', pointer: `/tasks/${other.task_id}`, task_id: other.task_id,
|
|
134
|
+
task_state: state.get(other.task_id) ?? null, candidate: 'retirement', completed_task: taskId,
|
|
135
|
+
feature_id: fid, completed_feature_id: id, evidence });
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (findings.length === 0) return null;
|
|
142
|
+
return { schema: ADVICE_SCHEMA, advisory: true, trigger: 'done', plan_key: plan.plan_key, plan_version: planVersion, completed_task: taskId, findings,
|
|
143
|
+
handoff: await findingHandoff({ repoRoot, planKey: plan.plan_key, findings }) };
|
|
144
|
+
}
|
package/src/plan-revise.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { planEditAdvice } from './plan-edit-advice.mjs';
|
|
2
3
|
import path from 'node:path';
|
|
3
4
|
|
|
4
5
|
import { canonicalizeTodoArtifact, exactRecord, isTodoIdentifier, todoSelfDigest } from './todo-contracts.mjs';
|
|
@@ -413,6 +414,8 @@ export async function applyPlanRevision({
|
|
|
413
414
|
}
|
|
414
415
|
const declarations = dryRun || touches.length === 0 ? null
|
|
415
416
|
: await (await import('./todo-cli.mjs')).declareTouches({ repoRoot, planKey: revision.plan_key, touches });
|
|
417
|
+
const advice = unchanged ? null : await planEditAdvice({ repoRoot, before: member.plan,
|
|
418
|
+
after: revision.desired_plan, states: member.tasks });
|
|
416
419
|
const result = {
|
|
417
420
|
schema: unchanged ? 'lattice.plan_revise_unchanged.v1' : 'lattice.plan_revise_result.v1',
|
|
418
421
|
project_id: revision.project_id, plan_key: revision.plan_key,
|
|
@@ -420,6 +423,7 @@ export async function applyPlanRevision({
|
|
|
420
423
|
dry_run: dryRun, revision: unchanged ? null : revision, applied,
|
|
421
424
|
continuity, rebound_task_ids: reboundTaskIds,
|
|
422
425
|
...(featureChainFindings === null ? {} : { feature_chain_findings: featureChainFindings }),
|
|
426
|
+
...(advice === null ? {} : { advice }),
|
|
423
427
|
...(declarations === null ? {} : { declarations }),
|
|
424
428
|
result_digest: '',
|
|
425
429
|
};
|
package/src/project-cli.mjs
CHANGED
|
@@ -817,7 +817,7 @@ export function validatePlanCreateInput(input) {
|
|
|
817
817
|
}
|
|
818
818
|
|
|
819
819
|
/** a17: repo root名をtodo identifierへ寄せる。小文字化し、使えない文字は'-'へ、前後の記号は落とす。 */
|
|
820
|
-
function identifierFromRepoRoot(repoRoot, fallback) {
|
|
820
|
+
export function identifierFromRepoRoot(repoRoot, fallback) {
|
|
821
821
|
const name = path.basename(repoRoot).toLowerCase().replace(/[^0-9a-z._-]+/gu, '-')
|
|
822
822
|
.replace(/^[^0-9a-z]+|[^0-9a-z]+$/gu, '').slice(0, 128);
|
|
823
823
|
return isTodoIdentifier(name) ? name : fallback;
|
|
@@ -1070,6 +1070,8 @@ export async function runPlanShow({ cwd, planKey, stdout }) {
|
|
|
1070
1070
|
max_frontier_width: dispatchShape.max_frontier_width,
|
|
1071
1071
|
serialization_ratio: dispatchShape.serialization_ratio,
|
|
1072
1072
|
},
|
|
1073
|
+
// The goal bound by `plan backchain` (null when the plan has none or its binding is unreadable), so the next author starts from it.
|
|
1074
|
+
goal: (await (await import('./plan-backchain.mjs')).readPlanBackchainBinding({ repoRoot, plan }).catch(() => null))?.chain.goal ?? null,
|
|
1073
1075
|
result_digest: '',
|
|
1074
1076
|
};
|
|
1075
1077
|
result.result_digest = resultDigest(result);
|
package/src/todo-cli.mjs
CHANGED
|
@@ -922,6 +922,17 @@ async function mutate({
|
|
|
922
922
|
// 導出ビュー`phases`から読む。
|
|
923
923
|
const resolvedAdvisory = advisory ?? (kind === 'done' ? terminalAuditDoneAdvisory(plan, phases)
|
|
924
924
|
: kind === 'reopen' ? reopenAdvisory(plan, phases, event.task_id) : null);
|
|
925
|
+
// The completion advisory reads what this write committed (plan version + task states returned by the Store), so it adds
|
|
926
|
+
// no chart read and cannot describe another version. Evidence-free completion skips it; it never changes the completion.
|
|
927
|
+
const recordedMessage = kind === 'done' && payload === 'authored' && message !== DONE_WITHOUT_MESSAGE ? message : null;
|
|
928
|
+
const completionAdvice = recordedMessage === null && testResult === null ? null
|
|
929
|
+
: kind !== 'done' || payload !== 'authored' ? null
|
|
930
|
+
: await (await import('./plan-edit-advice.mjs')).completionAdvice({
|
|
931
|
+
repoRoot, plan, states: snapshot.tasks, taskId: event.task_id, planVersion: event.plan_version,
|
|
932
|
+
evidence: { event_digest: event.event_digest,
|
|
933
|
+
message: recordedMessage === null ? null : recordedMessage.slice(0, 400),
|
|
934
|
+
test_result: testResult === null ? null : String(testResult).slice(0, 400) },
|
|
935
|
+
}).catch(() => null);
|
|
925
936
|
const includesNoteContext = kind === 'start';
|
|
926
937
|
if (includesNoteContext && noteContext === null) {
|
|
927
938
|
throw new TypeError('start mutation requires note context');
|
|
@@ -941,6 +952,7 @@ async function mutate({
|
|
|
941
952
|
snapshot_digest: snapshot.snapshot_digest,
|
|
942
953
|
status: task.status,
|
|
943
954
|
advisory: resolvedAdvisory,
|
|
955
|
+
...(completionAdvice === null ? {} : { advice: completionAdvice }),
|
|
944
956
|
...(includesNoteContext ? {
|
|
945
957
|
design_memo: designMemoProjection(authoredTask),
|
|
946
958
|
done_condition: authoredTask.done_condition ?? null,
|
|
@@ -1783,7 +1795,8 @@ async function dependencyRevision({
|
|
|
1783
1795
|
schema: 'lattice.todo_dependency_revision_result.v1', project_id: store.project_id,
|
|
1784
1796
|
plan_key: planKey, operation, from, to, reason, actor: desired.actor,
|
|
1785
1797
|
plan_version: applied.plan_version, revision_digest: applied.revision.revision_digest,
|
|
1786
|
-
rebound_task_ids: applied.rebound_task_ids,
|
|
1798
|
+
rebound_task_ids: applied.rebound_task_ids, ...(applied.advice === undefined ? {} : { advice: applied.advice }),
|
|
1799
|
+
result_digest: '',
|
|
1787
1800
|
};
|
|
1788
1801
|
result.result_digest = todoSelfDigest(result, 'result_digest');
|
|
1789
1802
|
return result;
|
|
@@ -1848,7 +1861,8 @@ async function addTask({ repoRoot, env, planKey, flags }) {
|
|
|
1848
1861
|
schema: 'lattice.todo_task_add_result.v2', project_id: store.project_id, plan_key: planKey,
|
|
1849
1862
|
task_id: taskId, after, before, reason, actor: desired.actor, declaration,
|
|
1850
1863
|
plan_version: applied.plan_version, revision_digest: applied.revision?.revision_digest ?? null,
|
|
1851
|
-
rebound_task_ids: applied.rebound_task_ids,
|
|
1864
|
+
rebound_task_ids: applied.rebound_task_ids, ...(applied.advice === undefined ? {} : { advice: applied.advice }),
|
|
1865
|
+
result_digest: '',
|
|
1852
1866
|
};
|
|
1853
1867
|
result.result_digest = todoSelfDigest(result, 'result_digest');
|
|
1854
1868
|
return result;
|
|
@@ -2725,10 +2739,22 @@ async function revise({ repoRoot, env, planKey, inputRef }) {
|
|
|
2725
2739
|
if (revision.plan_key !== planKey) {
|
|
2726
2740
|
throw new TodoStoreError('REVISION_INVALID', 'requested_plan_mismatch');
|
|
2727
2741
|
}
|
|
2728
|
-
|
|
2742
|
+
const member = (await readTodoStore({ repoRoot }).catch(() => null))?.members.find(({ plan }) => plan.plan_key === planKey);
|
|
2743
|
+
return withEditAdvice({ repoRoot, member, desired: revision.desired_plan, receipt: await applyTodoRevision({
|
|
2729
2744
|
repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }), revision,
|
|
2730
2745
|
actor: resolveTodoActor(env), recordedAt: new Date().toISOString(),
|
|
2731
|
-
});
|
|
2746
|
+
}) });
|
|
2747
|
+
}
|
|
2748
|
+
|
|
2749
|
+
/** The advisory of an ordinary plan edit (docs/architecture/dfd-finding-handoff.md) rides on the receipt; it never changes the write. */
|
|
2750
|
+
async function withEditAdvice({ repoRoot, member, desired, receipt }) {
|
|
2751
|
+
if (member === undefined || desired === undefined) return receipt;
|
|
2752
|
+
const { planEditAdvice } = await import('./plan-edit-advice.mjs');
|
|
2753
|
+
const advice = await planEditAdvice({ repoRoot, before: member.plan, after: desired, states: member.tasks }).catch(() => null);
|
|
2754
|
+
if (advice === null) return receipt;
|
|
2755
|
+
const next = { ...receipt, advice };
|
|
2756
|
+
if (typeof receipt.result_digest === 'string') next.result_digest = todoSelfDigest({ ...next, result_digest: '' }, 'result_digest');
|
|
2757
|
+
return next;
|
|
2732
2758
|
}
|
|
2733
2759
|
|
|
2734
2760
|
async function reviseSet({ repoRoot, env, inputRef }) {
|
|
@@ -2760,8 +2786,10 @@ async function revisePhase({ repoRoot, env, planKey, inputRef }) {
|
|
|
2760
2786
|
},
|
|
2761
2787
|
});
|
|
2762
2788
|
if (revision.plan_key !== planKey) throw new TodoStoreError('REVISION_INVALID', 'requested_plan_mismatch');
|
|
2763
|
-
|
|
2764
|
-
|
|
2789
|
+
const member = (await readTodoStore({ repoRoot }).catch(() => null))?.members.find(({ plan }) => plan.plan_key === planKey);
|
|
2790
|
+
return withEditAdvice({ repoRoot, member, desired: revision.desired_plan, receipt: await applyPhaseTodoRevision({
|
|
2791
|
+
repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }),
|
|
2792
|
+
revision, actor: resolveTodoActor(env), recordedAt: new Date().toISOString() }) });
|
|
2765
2793
|
}
|
|
2766
2794
|
|
|
2767
2795
|
async function splitTodo({ repoRoot, env, planKey, inputRef }) {
|