@quolu/lattice 0.116.0 → 0.117.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 +99 -46
- package/src/plan-draft.mjs +448 -0
- package/src/project-cli.mjs +3 -1
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.117.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
|
@@ -18,7 +18,6 @@ import {
|
|
|
18
18
|
|
|
19
19
|
export const BACKCHAIN_SCHEMA = 'lattice.plan_backchain.v1';
|
|
20
20
|
const CREATE_SCHEMA = 'lattice.plan_create_input.v4';
|
|
21
|
-
const MAX_FEATURES = 2_048;
|
|
22
21
|
const MAX_TEXT_BYTES = 16_384;
|
|
23
22
|
const MAX_BINDING_BYTES = 8_388_608;
|
|
24
23
|
const BINDING_SCHEMA = 'lattice.plan_backchain_binding.v1';
|
|
@@ -36,7 +35,7 @@ function text(value) {
|
|
|
36
35
|
|
|
37
36
|
function identifiers(value, { nonempty = false } = {}) {
|
|
38
37
|
return Array.isArray(value) && (!nonempty || value.length > 0)
|
|
39
|
-
&& value.
|
|
38
|
+
&& value.every(isTodoIdentifier)
|
|
40
39
|
&& new Set(value).size === value.length;
|
|
41
40
|
}
|
|
42
41
|
|
|
@@ -128,8 +127,7 @@ export function validatePlanBackchain(chain, authoring) {
|
|
|
128
127
|
|| !identifiers(chain.goal.required_feature_ids, { nonempty: true })) {
|
|
129
128
|
fail('goal_invalid', '/goal');
|
|
130
129
|
}
|
|
131
|
-
if (!Array.isArray(chain.features) || chain.features.length === 0
|
|
132
|
-
|| chain.features.length > MAX_FEATURES) fail('features_invalid', '/features');
|
|
130
|
+
if (!Array.isArray(chain.features) || chain.features.length === 0) fail('features_invalid', '/features'); // no count cap (ADR 0201); bytes bound it
|
|
133
131
|
const features = new Map();
|
|
134
132
|
for (const [index, feature] of chain.features.entries()) {
|
|
135
133
|
if (!exactRecord(feature, [
|
|
@@ -257,7 +255,7 @@ export function validatePlanBackchain(chain, authoring) {
|
|
|
257
255
|
}
|
|
258
256
|
|
|
259
257
|
/** 決定的な順序(pointer, reason, 正準JSON)で並べ、同一の指摘は1件にする。 */
|
|
260
|
-
function sortFindings(list) {
|
|
258
|
+
export function sortFindings(list) {
|
|
261
259
|
const keyed = new Map(list.map((entry) => [canonicalizeTodoArtifact(entry), entry]));
|
|
262
260
|
return [...keyed.entries()].sort(([left, a], [right, b]) =>
|
|
263
261
|
a.pointer.localeCompare(b.pointer) || a.reason.localeCompare(b.reason)
|
|
@@ -386,34 +384,35 @@ function gitRoot(cwd) {
|
|
|
386
384
|
} catch { fail('repository_unresolved', '/'); }
|
|
387
385
|
}
|
|
388
386
|
|
|
389
|
-
|
|
387
|
+
/** null when the repo-relative ref is a readable regular file inside the repo, else unsafe | missing | unreadable. */
|
|
388
|
+
export async function existingReferenceProblem(canonicalRoot, ref) {
|
|
389
|
+
const absolute = path.resolve(canonicalRoot, ref);
|
|
390
|
+
if (!absolute.startsWith(`${canonicalRoot}${path.sep}`)) return 'unsafe';
|
|
391
|
+
let state;
|
|
392
|
+
try { state = await lstat(absolute); } catch { return 'missing'; }
|
|
393
|
+
let resolved;
|
|
394
|
+
try { resolved = await realpath(absolute); } catch { return 'unreadable'; }
|
|
395
|
+
return !state.isFile() || state.isSymbolicLink() || !resolved.startsWith(`${canonicalRoot}${path.sep}`)
|
|
396
|
+
? 'unsafe' : null;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** advisory (a draft): a receipt carried from an earlier version that is gone is reported, never invented or refused. */
|
|
400
|
+
async function verifyExistingFeatureReferences(repoRoot, chain, { advisory = false } = {}) {
|
|
390
401
|
const canonicalRoot = await realpath(repoRoot);
|
|
402
|
+
const unresolved = [];
|
|
391
403
|
for (const feature of chain.features) {
|
|
392
404
|
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,
|
|
405
|
+
const problem = await existingReferenceProblem(canonicalRoot, feature.provider.evidence_ref);
|
|
406
|
+
if (problem !== null && advisory) {
|
|
407
|
+
unresolved.push({ reason: 'observation_unresolved', pointer: `/features/${feature.feature_id}/provider`,
|
|
408
|
+
feature_id: feature.feature_id, evidence_ref: feature.provider.evidence_ref, cause: problem, carried: true });
|
|
409
|
+
} else if (problem !== null) {
|
|
410
|
+
fail(`existing_feature_reference_${problem}`, `/features/${feature.feature_id}/provider`, {
|
|
411
|
+
evidence_ref: feature.provider.evidence_ref,
|
|
414
412
|
});
|
|
415
413
|
}
|
|
416
414
|
}
|
|
415
|
+
return unresolved;
|
|
417
416
|
}
|
|
418
417
|
|
|
419
418
|
const DONE_CONDITION_PLAN_SCHEMA = 'lattice.todo_plan.v8';
|
|
@@ -457,7 +456,7 @@ function featureGraphDigest(chain) {
|
|
|
457
456
|
return digestTodoArtifact({ goal: chain.goal, features: chain.features, tasks: chain.tasks });
|
|
458
457
|
}
|
|
459
458
|
|
|
460
|
-
function taskSignature(chain, taskId) {
|
|
459
|
+
export function taskSignature(chain, taskId) {
|
|
461
460
|
const task = chain?.tasks?.find(({ task_id: id }) => id === taskId);
|
|
462
461
|
if (task === undefined) return null;
|
|
463
462
|
const byId = new Map(chain.features.map((feature) => [feature.feature_id, feature]));
|
|
@@ -493,7 +492,8 @@ function compileTaskMigration(previousPlan, oldChain, desiredSeed, newChain) {
|
|
|
493
492
|
return { from_task_id: id, to_task_id: 'removed', state_policy: 'removed' };
|
|
494
493
|
}
|
|
495
494
|
if (decision?.policy === 'retire') fail('continuity_live_task_mismatch', '/continuity', { task_id: id });
|
|
496
|
-
|
|
495
|
+
// No earlier chain = no earlier contract to compare: absence is not a change (it would reset every task's history).
|
|
496
|
+
const sameContract = oldChain === null || taskSignature(oldChain, id) === taskSignature(newChain, id);
|
|
497
497
|
const sameTask = oldTask.title === nextTask.title && oldTask.lane === nextTask.lane
|
|
498
498
|
&& oldTask.phase_id === nextTask.phase_id
|
|
499
499
|
&& oldTask.parent_task_id === nextTask.parent_task_id
|
|
@@ -506,7 +506,8 @@ function compileTaskMigration(previousPlan, oldChain, desiredSeed, newChain) {
|
|
|
506
506
|
|| (decision === undefined && sameContract && sameTask);
|
|
507
507
|
return { from_task_id: id, to_task_id: id,
|
|
508
508
|
state_policy: carry ? 'carry_reconciled_metadata' : 'reset_pending' };
|
|
509
|
-
|
|
509
|
+
// Code-unit order, as validTaskMigration requires (localeCompare misorders mixed-case ids such as T and split-…).
|
|
510
|
+
}).sort((left, right) => (left.from_task_id < right.from_task_id ? -1 : left.from_task_id > right.from_task_id ? 1 : 0));
|
|
510
511
|
}
|
|
511
512
|
|
|
512
513
|
export function compilePhaseMigration(previousPlan, desiredSeed, taskMigration) {
|
|
@@ -535,7 +536,7 @@ export function compilePhaseMigration(previousPlan, desiredSeed, taskMigration)
|
|
|
535
536
|
}
|
|
536
537
|
|
|
537
538
|
export async function compileBackchainRevision({ repoRoot, member, chain, authoring }) {
|
|
538
|
-
if (!['lattice.todo_plan.v7', DONE_CONDITION_PLAN_SCHEMA].includes(member.plan.schema)) {
|
|
539
|
+
if (!['lattice.todo_plan.v7', DONE_CONDITION_PLAN_SCHEMA, SPLIT_PLAN_SCHEMA].includes(member.plan.schema)) {
|
|
539
540
|
fail('predecessor_plan_schema_unsupported', '/plan_key', {
|
|
540
541
|
actual: member.plan.schema, next_action: 'author_a_new_backchain_plan',
|
|
541
542
|
});
|
|
@@ -578,7 +579,7 @@ export async function compileBackchainRevision({ repoRoot, member, chain, author
|
|
|
578
579
|
}
|
|
579
580
|
|
|
580
581
|
async function activeIntentUnchanged({ repoRoot, member, chain, authoring }) {
|
|
581
|
-
if (!['lattice.todo_plan.v7', DONE_CONDITION_PLAN_SCHEMA].includes(member.plan.schema)) return false;
|
|
582
|
+
if (!['lattice.todo_plan.v7', DONE_CONDITION_PLAN_SCHEMA, SPLIT_PLAN_SCHEMA].includes(member.plan.schema)) return false;
|
|
582
583
|
const binding = await readPlanBackchainBinding({ repoRoot, plan: member.plan });
|
|
583
584
|
if (binding === null || featureGraphDigest(binding.chain) !== featureGraphDigest(chain)) return false;
|
|
584
585
|
const amended = attachBackchainMemos(chain, authoring, { previousChain: binding.chain });
|
|
@@ -634,24 +635,55 @@ export async function rebindCarriedWork({ repoRoot, planKey, env,
|
|
|
634
635
|
return rebound;
|
|
635
636
|
}
|
|
636
637
|
|
|
637
|
-
|
|
638
|
+
const draftOutput = (report) => (report === null ? {} : { draft: report.summary, draft_findings: report.findings });
|
|
639
|
+
|
|
640
|
+
export async function runPlanBackchain({ cwd, inputRef = null, draftRef = null, stdout, dryRun = false, env = process.env }) {
|
|
638
641
|
const repoRoot = gitRoot(cwd);
|
|
639
|
-
const
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
642
|
+
const loadStore = async () => {
|
|
643
|
+
try {
|
|
644
|
+
await lstat(path.join(repoRoot, '.lattice', 'todo', 'manifest.json'));
|
|
645
|
+
return await readTodoStore({ repoRoot });
|
|
646
|
+
} catch (error) {
|
|
647
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
648
|
+
return null;
|
|
649
|
+
}
|
|
650
|
+
};
|
|
651
|
+
let chain;
|
|
652
|
+
let authoring;
|
|
653
|
+
let store;
|
|
654
|
+
let draftReport = null;
|
|
655
|
+
// The seat's structured-input route passes JSON through --input: a draft is recognized by its schema.
|
|
656
|
+
let given = draftRef !== null ? await readAuthoringJsonFile(repoRoot, draftRef, { invalidCode: 'PLAN_BACKCHAIN_INVALID' }) : null;
|
|
657
|
+
if (given === null) {
|
|
658
|
+
given = await readAuthoringJsonFile(repoRoot, inputRef, { invalidCode: 'PLAN_BACKCHAIN_INVALID' });
|
|
659
|
+
if (given?.schema === 'lattice.plan_draft.v1') draftRef = inputRef; else draftRef = null;
|
|
660
|
+
}
|
|
661
|
+
if (draftRef !== null) {
|
|
662
|
+
const draft = given;
|
|
663
|
+
store = await loadStore();
|
|
664
|
+
const { compilePlanDraft } = await import('./plan-draft.mjs');
|
|
665
|
+
({ chain, authoring, report: draftReport } = await compilePlanDraft({
|
|
666
|
+
repoRoot, draft, draftRef, store, env,
|
|
667
|
+
member: store?.members.find(({ plan }) => plan.plan_key === draft?.plan_key) ?? null,
|
|
668
|
+
}));
|
|
669
|
+
} else {
|
|
670
|
+
chain = given;
|
|
671
|
+
failOnShape(chain);
|
|
672
|
+
authoring = completeCreateInput(await readAuthoringJsonFile(repoRoot, chain.authoring_ref, {
|
|
673
|
+
invalidCode: 'PLAN_BACKCHAIN_INVALID',
|
|
674
|
+
}), { env, now: new Date() });
|
|
675
|
+
store = await loadStore();
|
|
676
|
+
}
|
|
677
|
+
const { findings: allFindings } = validatePlanBackchain(chain, authoring);
|
|
678
|
+
// A draft over a legacy plan declares only the branch it touches; tasks elsewhere are unassessed, not missing.
|
|
679
|
+
const featureChainFindings = draftReport === null ? allFindings
|
|
680
|
+
: allFindings.filter(({ reason }) => reason !== 'task_coverage_missing');
|
|
681
|
+
const carriedGaps = await verifyExistingFeatureReferences(repoRoot, chain, { advisory: draftReport !== null });
|
|
682
|
+
if (carriedGaps.length > 0) draftReport.findings = sortFindings([...draftReport.findings, ...carriedGaps]);
|
|
646
683
|
let member = null;
|
|
647
|
-
|
|
648
|
-
try {
|
|
649
|
-
await lstat(path.join(repoRoot, '.lattice', 'todo', 'manifest.json'));
|
|
650
|
-
store = await readTodoStore({ repoRoot });
|
|
684
|
+
if (store !== null) {
|
|
651
685
|
if (store.project_id !== chain.project_id) fail('project_id_mismatch', '/project_id');
|
|
652
686
|
member = store.members.find(({ plan }) => plan.plan_key === chain.plan_key) ?? null;
|
|
653
|
-
} catch (error) {
|
|
654
|
-
if (error?.code !== 'ENOENT') throw error;
|
|
655
687
|
}
|
|
656
688
|
if (member === null && (chain.continuity?.length ?? 0) > 0) {
|
|
657
689
|
fail('continuity_without_predecessor', '/continuity');
|
|
@@ -679,6 +711,7 @@ export async function runPlanBackchain({ cwd, inputRef, stdout, dryRun = false,
|
|
|
679
711
|
: store === null ? 'create' : 'add',
|
|
680
712
|
task_migration: revision?.task_migration ?? null,
|
|
681
713
|
feature_chain_findings: featureChainFindings,
|
|
714
|
+
...draftOutput(draftReport),
|
|
682
715
|
result_digest: '',
|
|
683
716
|
};
|
|
684
717
|
checked.result_digest = todoSelfDigest(checked, 'result_digest');
|
|
@@ -736,6 +769,7 @@ export async function runPlanBackchain({ cwd, inputRef, stdout, dryRun = false,
|
|
|
736
769
|
chain_digest: effectiveChain.chain_digest, authoring_result: created,
|
|
737
770
|
rebound_task_ids: reboundTaskIds,
|
|
738
771
|
feature_chain_findings: featureChainFindings,
|
|
772
|
+
...draftOutput(draftReport),
|
|
739
773
|
operation: unchanged ? 'unchanged' : revision !== null ? 'revise'
|
|
740
774
|
: store === null ? 'create' : 'add',
|
|
741
775
|
journal_head_digest: finalMember.journal.events.at(-1).event_digest,
|
|
@@ -746,6 +780,25 @@ export async function runPlanBackchain({ cwd, inputRef, stdout, dryRun = false,
|
|
|
746
780
|
return 0;
|
|
747
781
|
}
|
|
748
782
|
|
|
783
|
+
/** `plan backchain --template [--plan K]`: the draft skeleton, seeded from the active plan when one is named. */
|
|
784
|
+
export async function runPlanBackchainTemplate({ cwd, planKey = null, stdout }) {
|
|
785
|
+
const repoRoot = gitRoot(cwd);
|
|
786
|
+
let store = null;
|
|
787
|
+
try {
|
|
788
|
+
await lstat(path.join(repoRoot, '.lattice', 'todo', 'manifest.json'));
|
|
789
|
+
store = await readTodoStore({ repoRoot });
|
|
790
|
+
} catch (error) {
|
|
791
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
792
|
+
}
|
|
793
|
+
const member = planKey === null ? null : store?.members.find(({ plan }) => plan.plan_key === planKey) ?? null;
|
|
794
|
+
if (planKey !== null && member === null) {
|
|
795
|
+
fail('plan_not_active', '/plan', { plan_key: planKey, next_action: 'Run lattice todo status --json to list the active plan keys.' });
|
|
796
|
+
}
|
|
797
|
+
const { draftTemplate } = await import('./plan-draft.mjs');
|
|
798
|
+
stdout.write(`${JSON.stringify(await draftTemplate({ repoRoot, member, store }))}\n`);
|
|
799
|
+
return 0;
|
|
800
|
+
}
|
|
801
|
+
|
|
749
802
|
export async function backchainSchema() {
|
|
750
803
|
return JSON.parse(await readFile(new URL('../docs/schemas/lattice.plan_backchain.v1.schema.json', import.meta.url), 'utf8'));
|
|
751
804
|
}
|
|
@@ -0,0 +1,448 @@
|
|
|
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',
|
|
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.feature_id]);
|
|
396
|
+
}
|
|
397
|
+
for (const [capability, ids] of byCapability) {
|
|
398
|
+
if (ids.length > 1) found.push({ reason: 'duplicate_result', pointer: '/features', capability: capability.split('\u0000')[0], feature_ids: ids.sort() });
|
|
399
|
+
}
|
|
400
|
+
const canonicalRoot = await realpath(repoRoot);
|
|
401
|
+
for (const [index, entry] of (draft.observations ?? []).entries()) {
|
|
402
|
+
const at = `/observations/${index}`;
|
|
403
|
+
only(entry, ['feature_id', 'evidence_ref'], at, ['feature_id', 'evidence_ref']);
|
|
404
|
+
const feature = features.get(entry.feature_id);
|
|
405
|
+
const cause = typeof entry.evidence_ref === 'string' && isTodoRef(entry.evidence_ref)
|
|
406
|
+
? await existingReferenceProblem(canonicalRoot, entry.evidence_ref) : 'not_a_repo_file';
|
|
407
|
+
if (feature === undefined) {
|
|
408
|
+
found.push({ reason: 'observation_unresolved', pointer: at, feature_id: entry.feature_id, evidence_ref: entry.evidence_ref,
|
|
409
|
+
cause: 'feature_unknown' });
|
|
410
|
+
} else if (cause !== null) {
|
|
411
|
+
found.push({ reason: 'observation_unresolved', pointer: at, feature_id: feature.feature_id, evidence_ref: entry.evidence_ref, cause });
|
|
412
|
+
} else if (feature.provider.kind === 'task') {
|
|
413
|
+
found.push({ reason: 'planned_provider_has_observation', pointer: at, feature_id: feature.feature_id,
|
|
414
|
+
task_id: feature.provider.task_id, task_state: stateOf(feature.provider.task_id), evidence_ref: entry.evidence_ref });
|
|
415
|
+
} else {
|
|
416
|
+
// A result that has no planned task (an existing observation or an open question): the file is noted, never a refusal.
|
|
417
|
+
found.push({ reason: 'observation_noted', pointer: at, feature_id: feature.feature_id, provider_kind: feature.provider.kind,
|
|
418
|
+
evidence_ref: entry.evidence_ref });
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
return { findings: sortFindings([...found, ...extra]),
|
|
422
|
+
unreachedTaskIds: chain.features.filter((f) => f.provider.kind === 'task' && !reached.has(f.feature_id)).map((f) => f.provider.task_id) };
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/** The authoring entry: a skeleton to fill in, seeded from the active plan on revision. */
|
|
426
|
+
export async function draftTemplate({ repoRoot, member, store }) {
|
|
427
|
+
const projectId = store?.project_id ?? (await import('./project-cli.mjs')).identifierFromRepoRoot(repoRoot, 'project');
|
|
428
|
+
const step = { before: '<downstream task id already in the plan or an earlier step>',
|
|
429
|
+
task: { task_id: '<new task id>', title: '<title>', design_memo: '<what to do>', done: '<completion condition>' },
|
|
430
|
+
result: { capability: '<what the downstream task needs from this one>', acceptance: '<how to tell it is there>' },
|
|
431
|
+
after: ['<existing upstream task id to link, optional>'], unlink: [] };
|
|
432
|
+
if (member === null || member === undefined) {
|
|
433
|
+
return { schema: DRAFT_SCHEMA, project_id: projectId, plan_key: '<plan key>',
|
|
434
|
+
goal: { purpose: '<why>', outcome: '<final result>', acceptance: '<how the goal is judged>' },
|
|
435
|
+
final: { task: { task_id: '<goal task id>', title: '<title>', design_memo: '<what to do>', done: '<completion condition>' },
|
|
436
|
+
result: { capability: '<the observable result>', acceptance: '<how to tell it is there>' } },
|
|
437
|
+
steps: [step], observations: [] };
|
|
438
|
+
}
|
|
439
|
+
const binding = await readPlanBackchainBinding({ repoRoot, plan: member.plan });
|
|
440
|
+
const states = new Map(member.tasks.map((task) => [task.task_id, task.status]));
|
|
441
|
+
return { schema: DRAFT_SCHEMA, project_id: projectId, plan_key: member.plan.plan_key,
|
|
442
|
+
base_plan_version: member.plan.plan_version,
|
|
443
|
+
...(binding === null ? {} : { goal: {
|
|
444
|
+
purpose: binding.chain.goal.purpose, outcome: binding.chain.goal.outcome,
|
|
445
|
+
acceptance: binding.chain.goal.acceptance } }),
|
|
446
|
+
steps: [step], observations: [],
|
|
447
|
+
context: { tasks: member.plan.tasks.map(({ task_id: id, title }) => ({ task_id: id, title, state: states.get(id) })) } };
|
|
448
|
+
}
|
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);
|