@quolu/lattice 0.100.0 → 0.101.1
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 +32 -2
- package/package.json +1 -1
- package/src/chart-cli.mjs +348 -0
- package/src/cli-help.mjs +14 -0
- package/src/project-cli.mjs +3 -1
package/bin/lattice.mjs
CHANGED
|
@@ -7,18 +7,38 @@ import packageJson from '../package.json' with { type: 'json' };
|
|
|
7
7
|
|
|
8
8
|
installPipeCloseGuard();
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
let args = withImpliedJson(process.argv.slice(2));
|
|
11
11
|
// 作業ディレクトリを読まないsurface。cwdが消えた席(閉じたworktree)からでも動かす。
|
|
12
|
-
const CWD_FREE_COMMANDS = new Set(['runtime-errors', 'bridge', 'hooks', 'setup', 'factory-diagnostics']);
|
|
12
|
+
const CWD_FREE_COMMANDS = new Set(['runtime-errors', 'bridge', 'hooks', 'setup', 'factory-diagnostics', 'charts']);
|
|
13
13
|
// 内部故障の観測(下のobserveInternalFailure)が終わるのを、exit前に待つための置き場。
|
|
14
14
|
let pendingObservation = Promise.resolve();
|
|
15
15
|
installSqliteExperimentalWarningFilter();
|
|
16
16
|
const help = renderCliHelp(args);
|
|
17
|
+
// K8/K5 (a101, docs/architecture/dfd-charts-read.md): a host addresses a chart by project id; a Store-creating
|
|
18
|
+
// command makes it, and a failed run removes only the dir it made (below the dispatch).
|
|
19
|
+
let chartCreated = null;
|
|
20
|
+
let chartRefusal = null;
|
|
21
|
+
if (help === null && args[0] !== '--version' && !CWD_FREE_COMMANDS.has(args[0])
|
|
22
|
+
&& process.env.LATTICE_CHARTS_ROOT && process.env.LATTICE_PROJECT_ID) {
|
|
23
|
+
const { enterAddressedChart } = await import('../src/chart-cli.mjs');
|
|
24
|
+
try {
|
|
25
|
+
const chart = await enterAddressedChart({ env: process.env, argv: args, cwd: workingDirectory() ?? '.' });
|
|
26
|
+
args = chart.argv;
|
|
27
|
+
chartCreated = chart.created;
|
|
28
|
+
process.chdir(chart.dir);
|
|
29
|
+
} catch (error) {
|
|
30
|
+
chartRefusal = error;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
17
33
|
|
|
18
34
|
if (help !== null) {
|
|
19
35
|
process.stdout.write(help);
|
|
20
36
|
} else if (args.length === 1 && args[0] === '--version') {
|
|
21
37
|
process.stdout.write(`${packageJson.version}\n`);
|
|
38
|
+
} else if (chartRefusal !== null) {
|
|
39
|
+
process.stderr.write(`${JSON.stringify({ schema: 'lattice.cli_error.v2', code: chartRefusal?.code ?? 'INTERNAL_FAILURE',
|
|
40
|
+
message: chartRefusal?.message ?? String(chartRefusal), detail: chartRefusal?.detail ?? null })}\n`);
|
|
41
|
+
process.exitCode = 1;
|
|
22
42
|
} else if (!CWD_FREE_COMMANDS.has(args[0]) && workingDirectory() === null) {
|
|
23
43
|
// 呼び出し元のcwdが削除済み(閉じたworktreeに残ったshell等)。`process.cwd()`のENOENTが
|
|
24
44
|
// 各分岐で生のstackや内部故障(LATTICE.CLI_INTERNAL_FAILED)として漏れていた。製品の故障ではなく
|
|
@@ -29,6 +49,10 @@ if (help !== null) {
|
|
|
29
49
|
detail: { next_action: 'cd_to_existing_project_directory_then_retry' },
|
|
30
50
|
})}\n`);
|
|
31
51
|
process.exitCode = 1;
|
|
52
|
+
} else if (args[0] === 'charts' || args[0] === 'chart') {
|
|
53
|
+
const { runChartCli } = await import('../src/chart-cli.mjs');
|
|
54
|
+
process.exitCode = await runChartCli({ argv: args, cwd: process.cwd(), env: process.env,
|
|
55
|
+
stdout: process.stdout, stderr: process.stderr, created: chartCreated !== null });
|
|
32
56
|
} else if (args.length === 2 && args[0] === 'session-context' && args[1] === '--json') {
|
|
33
57
|
const { runSessionContext } = await import('../src/project-cli.mjs');
|
|
34
58
|
process.exitCode = await runSessionContext({
|
|
@@ -254,6 +278,12 @@ if (help !== null) {
|
|
|
254
278
|
}
|
|
255
279
|
|
|
256
280
|
await pendingObservation;
|
|
281
|
+
if (chartCreated !== null && (process.exitCode ?? 0) !== 0) {
|
|
282
|
+
// shortcut: an exception that escapes the dispatch skips this removal; every branch above returns a typed exit.
|
|
283
|
+
const { rm } = await import('node:fs/promises');
|
|
284
|
+
process.chdir(process.env.LATTICE_CHARTS_ROOT);
|
|
285
|
+
await rm(chartCreated, { recursive: true, force: true });
|
|
286
|
+
}
|
|
257
287
|
await scheduleRuntimeErrorReport();
|
|
258
288
|
|
|
259
289
|
/**
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@quolu/lattice",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.101.1",
|
|
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",
|
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
// Host connection (a101, docs/architecture/dfd-charts-read.md): K8 addressing, K5 chart creation, K1/K2 chart list
|
|
2
|
+
// and change tokens, K4 naming, K7 code-chart repo. A host reads charts only through these commands.
|
|
3
|
+
|
|
4
|
+
import { execFile } from 'node:child_process';
|
|
5
|
+
import { createHash } from 'node:crypto';
|
|
6
|
+
import { appendFile, lstat, mkdir, readdir, readFile, rm } from 'node:fs/promises';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { Writable } from 'node:stream';
|
|
9
|
+
import { promisify } from 'node:util';
|
|
10
|
+
|
|
11
|
+
import { parseFlagMap } from './todo-authoring-input.mjs';
|
|
12
|
+
import { TODO_CHARTS_ROOT_ENV } from './todo-external.mjs';
|
|
13
|
+
import {
|
|
14
|
+
readTodoChartMeta, readTodoStoreDisplaySource, TodoStoreError, writeTodoChartMeta,
|
|
15
|
+
} from './todo-store.mjs';
|
|
16
|
+
|
|
17
|
+
export const PROJECT_ID_ENV = 'LATTICE_PROJECT_ID';
|
|
18
|
+
const SEAT_ID_ENV = 'LATTICE_SEAT_ID';
|
|
19
|
+
const MANIFEST = path.join('.lattice', 'todo', 'manifest.json');
|
|
20
|
+
// Relative file arguments keep meaning the caller's cwd after K8 moves the process into the chart.
|
|
21
|
+
const FILE_FLAGS = new Set(['--input', '--plan-input', '--review']);
|
|
22
|
+
const runGit = promisify(execFile);
|
|
23
|
+
|
|
24
|
+
/** A project id names one direct child of the charts root, never a path. */
|
|
25
|
+
function isChartId(id) {
|
|
26
|
+
return typeof id === 'string' && id !== '' && id !== '.' && id !== '..' && !/[/\\\0]/u.test(id);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Commands that make the chart when it does not exist yet (K5). Reads never create one. */
|
|
30
|
+
function createsChart(argv) {
|
|
31
|
+
return (argv[0] === 'plan' && argv[1] === 'create' && !['--schema', '--schema-version', '--template'].includes(argv[2]))
|
|
32
|
+
|| (argv[0] === 'chart' && argv[1] === 'set');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function refusal(code, reason, detail) {
|
|
36
|
+
return new TodoStoreError(code, reason, undefined, detail);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function lstatOrNull(target) {
|
|
40
|
+
try { return await lstat(target); } catch (error) {
|
|
41
|
+
if (error?.code === 'ENOENT') return null;
|
|
42
|
+
throw error;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* K8 + K5: with `LATTICE_CHARTS_ROOT` and `LATTICE_PROJECT_ID` both set, the command runs in `<root>/<id>`.
|
|
48
|
+
* Returns `null` when not addressed, else `{dir, created, argv}` (`created` = the dir this run made, for removal on
|
|
49
|
+
* failure). Throws `CHART_PATH_INVALID` (named protection: writes outside the root or through a link) or
|
|
50
|
+
* `CHART_NOT_FOUND` (protection: a read would otherwise run on the caller's cwd, the wrong chart; self-exit: create it).
|
|
51
|
+
*/
|
|
52
|
+
export async function enterAddressedChart({ env, argv, cwd }) {
|
|
53
|
+
const rootValue = env[TODO_CHARTS_ROOT_ENV];
|
|
54
|
+
const id = env[PROJECT_ID_ENV];
|
|
55
|
+
if (typeof rootValue !== 'string' || rootValue === '' || typeof id !== 'string' || id === '') return null;
|
|
56
|
+
const root = path.resolve(rootValue);
|
|
57
|
+
const dir = path.join(root, id);
|
|
58
|
+
if (!isChartId(id)) {
|
|
59
|
+
throw refusal('CHART_PATH_INVALID', 'chart_id_not_a_name', { project_id: id,
|
|
60
|
+
next_action: `Set ${PROJECT_ID_ENV} to a chart directory name (no path separators).` });
|
|
61
|
+
}
|
|
62
|
+
let stat = await lstatOrNull(dir);
|
|
63
|
+
let created = null;
|
|
64
|
+
if (stat === null && createsChart(argv)) {
|
|
65
|
+
await mkdir(root, { recursive: true });
|
|
66
|
+
try {
|
|
67
|
+
await mkdir(dir, { mode: 0o700 });
|
|
68
|
+
created = dir;
|
|
69
|
+
} catch (error) {
|
|
70
|
+
if (error?.code !== 'EEXIST') throw error;
|
|
71
|
+
}
|
|
72
|
+
stat = await lstat(dir);
|
|
73
|
+
if (created !== null) {
|
|
74
|
+
try { await runGit('git', ['init', '--quiet'], { cwd: dir }); } catch (error) {
|
|
75
|
+
await rm(dir, { recursive: true, force: true });
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
if (stat === null) {
|
|
81
|
+
throw refusal('CHART_NOT_FOUND', 'chart_missing', { project_id: id, path: dir,
|
|
82
|
+
next_action: 'lattice chart set --name <text> (or plan create --input <file>) creates the chart' });
|
|
83
|
+
}
|
|
84
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
|
85
|
+
throw refusal('CHART_PATH_INVALID', 'chart_path_not_a_directory', { project_id: id, path: dir,
|
|
86
|
+
next_action: `Remove or rename ${dir}; a chart is a plain directory under ${TODO_CHARTS_ROOT_ENV}.` });
|
|
87
|
+
}
|
|
88
|
+
const absolute = argv.map((word, index) => (FILE_FLAGS.has(argv[index - 1]) && !word.startsWith('--')
|
|
89
|
+
&& !path.isAbsolute(word) ? path.resolve(cwd, word) : word));
|
|
90
|
+
return { dir, created, argv: absolute };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const digest = (value) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
94
|
+
const reasonOf = (error) => error?.detail?.reason ?? error?.code ?? 'chart_unreadable';
|
|
95
|
+
|
|
96
|
+
/** One chart's identity and change token; never throws (K1/K2). */
|
|
97
|
+
async function readChart(root, id) {
|
|
98
|
+
const dir = path.join(root, id);
|
|
99
|
+
const findings = [];
|
|
100
|
+
let meta = null;
|
|
101
|
+
let display = null;
|
|
102
|
+
try { meta = await readTodoChartMeta({ repoRoot: dir }); } catch (error) {
|
|
103
|
+
findings.push({ project_id: id, reason: reasonOf(error) });
|
|
104
|
+
}
|
|
105
|
+
try { display = await readTodoStoreDisplaySource({ repoRoot: dir }); } catch (error) {
|
|
106
|
+
findings.push({ project_id: id, reason: reasonOf(error) });
|
|
107
|
+
}
|
|
108
|
+
return { meta, findings, source: meta === null || display === null ? null : digest([display, meta]) };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Direct children of the root that hold a Store manifest, sorted; a missing root has none. */
|
|
112
|
+
async function chartIds(root) {
|
|
113
|
+
let entries;
|
|
114
|
+
try { entries = await readdir(root, { withFileTypes: true }); } catch (error) {
|
|
115
|
+
if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') return [];
|
|
116
|
+
throw error;
|
|
117
|
+
}
|
|
118
|
+
const ids = [];
|
|
119
|
+
for (const entry of entries) {
|
|
120
|
+
if (entry.isDirectory() && await lstatOrNull(path.join(root, entry.name, MANIFEST)) !== null) ids.push(entry.name);
|
|
121
|
+
}
|
|
122
|
+
return ids.sort((left, right) => (left < right ? -1 : left > right ? 1 : 0));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function chartsRoot(env) {
|
|
126
|
+
const value = env[TODO_CHARTS_ROOT_ENV];
|
|
127
|
+
return typeof value === 'string' && value !== '' ? path.resolve(value) : null;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** K1 `lattice.charts_list_result.v1`. */
|
|
131
|
+
export async function listCharts(env) {
|
|
132
|
+
const root = chartsRoot(env);
|
|
133
|
+
if (root === null) {
|
|
134
|
+
return { schema: 'lattice.charts_list_result.v1', charts_root: null, charts: [],
|
|
135
|
+
findings: [{ project_id: null, reason: 'charts_root_unset' }] };
|
|
136
|
+
}
|
|
137
|
+
const charts = [];
|
|
138
|
+
const findings = [];
|
|
139
|
+
for (const id of await chartIds(root)) {
|
|
140
|
+
const chart = await readChart(root, id);
|
|
141
|
+
findings.push(...chart.findings);
|
|
142
|
+
charts.push({ project_id: id, name: chart.meta?.name ?? null, created_by: chart.meta?.created_by ?? null,
|
|
143
|
+
created_at: chart.meta?.created_at ?? null, source: chart.source });
|
|
144
|
+
}
|
|
145
|
+
return { schema: 'lattice.charts_list_result.v1', charts_root: root, charts, findings };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** K2 `lattice.charts_source_result.v1`; no ids = every chart; an id with no chart (or unreadable) is null. */
|
|
149
|
+
export async function chartSources(env, ids) {
|
|
150
|
+
const root = chartsRoot(env);
|
|
151
|
+
const chosen = ids.length > 0 ? ids : root === null ? [] : await chartIds(root);
|
|
152
|
+
const charts = {};
|
|
153
|
+
for (const id of chosen) {
|
|
154
|
+
const present = root !== null && isChartId(id) && await lstatOrNull(path.join(root, id, MANIFEST)) !== null;
|
|
155
|
+
charts[id] = present ? (await readChart(root, id)).source : null;
|
|
156
|
+
}
|
|
157
|
+
return { schema: 'lattice.charts_source_result.v1', charts };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** BellTeam's rule: 1-40 characters, already trimmed, no control characters. */
|
|
161
|
+
function validChartName(value) {
|
|
162
|
+
return typeof value === 'string' && value === value.trim() && [...value].length >= 1 && [...value].length <= 40
|
|
163
|
+
&& !/\p{Cc}/u.test(value);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function repoRoot(cwd) {
|
|
167
|
+
try {
|
|
168
|
+
return path.resolve((await runGit('git', ['rev-parse', '--show-toplevel'], { cwd })).stdout.trim());
|
|
169
|
+
} catch {
|
|
170
|
+
throw refusal('REPO_UNRESOLVED', 'git_toplevel_unresolved');
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function projectIdOf(env, dir) {
|
|
175
|
+
return env[PROJECT_ID_ENV] || path.basename(dir);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* K4 `chart set [--name <text>] [--created-by <id>]`, at least one; `created` = K5 made the chart in this run.
|
|
180
|
+
* Without --name the patch has no `name` key, so the name stays as is (null stays null): the a102 sidecar migration.
|
|
181
|
+
*/
|
|
182
|
+
async function chartSet({ cwd, env, flags, created }) {
|
|
183
|
+
if (!('name' in flags) && !('created-by' in flags)) {
|
|
184
|
+
throw refusal('CHART_NAME_INVALID', 'chart_set_flag_missing', { field: '--name',
|
|
185
|
+
rule: '--name, --created-by or both',
|
|
186
|
+
next_action: 'lattice chart set --name <text> [--created-by <id>] (or --created-by <id> alone)' });
|
|
187
|
+
}
|
|
188
|
+
const name = 'name' in flags ? (typeof flags.name === 'string' ? flags.name.trim() : null) : undefined;
|
|
189
|
+
if (name !== undefined && !validChartName(name)) {
|
|
190
|
+
throw refusal('CHART_NAME_INVALID', 'chart_name_invalid', { field: '--name',
|
|
191
|
+
rule: '1-40 characters after trimming, no control characters',
|
|
192
|
+
next_action: 'lattice chart set --name <text>' });
|
|
193
|
+
}
|
|
194
|
+
const explicit = 'created-by' in flags ? (typeof flags['created-by'] === 'string' ? flags['created-by'].trim() : null)
|
|
195
|
+
: undefined;
|
|
196
|
+
if (explicit !== undefined && !validChartName(explicit)) {
|
|
197
|
+
throw refusal('CHART_NAME_INVALID', 'chart_created_by_invalid', { field: '--created-by',
|
|
198
|
+
rule: '1-40 characters after trimming, no control characters',
|
|
199
|
+
next_action: 'lattice chart set --created-by <id>' });
|
|
200
|
+
}
|
|
201
|
+
const dir = await repoRoot(cwd);
|
|
202
|
+
const createdBy = explicit ?? (created ? env[SEAT_ID_ENV] || null : undefined);
|
|
203
|
+
const { meta, unchanged } = await writeTodoChartMeta({ repoRoot: dir,
|
|
204
|
+
patch: { ...(name === undefined ? {} : { name }), ...(createdBy === undefined ? {} : { created_by: createdBy }) } });
|
|
205
|
+
return { schema: 'lattice.chart_set_result.v1', project_id: projectIdOf(env, dir), name: meta.name,
|
|
206
|
+
created_by: meta.created_by, created_at: meta.created_at, unchanged };
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const URL_PATTERN = /^(?:https:\/\/|ssh:\/\/|file:\/\/|git@)[^\s\p{Cc}]+$/u;
|
|
210
|
+
|
|
211
|
+
/** K7 bind: record `{url, branch, accepted_tip}`; a new url or branch drops the old baseline. */
|
|
212
|
+
async function chartRepoBind({ cwd, env, flags }) {
|
|
213
|
+
const { url, branch } = flags;
|
|
214
|
+
if (typeof url !== 'string' || !URL_PATTERN.test(url)) {
|
|
215
|
+
throw refusal('CHART_REPO_INVALID', 'repo_url_invalid', { field: '--url',
|
|
216
|
+
rule: 'https://, ssh://, file:// or git@ URL without spaces', next_action: 'lattice chart repo bind --url <url> --branch <branch>' });
|
|
217
|
+
}
|
|
218
|
+
const branchOk = typeof branch === 'string' && await runGit('git', ['check-ref-format', '--branch', branch], { cwd })
|
|
219
|
+
.then(() => true, () => false);
|
|
220
|
+
if (!branchOk) {
|
|
221
|
+
throw refusal('CHART_REPO_INVALID', 'repo_branch_invalid', { field: '--branch',
|
|
222
|
+
rule: 'a valid git branch name', next_action: 'lattice chart repo bind --url <url> --branch <branch>' });
|
|
223
|
+
}
|
|
224
|
+
const dir = await repoRoot(cwd);
|
|
225
|
+
const current = (await readTodoChartMeta({ repoRoot: dir })).repo;
|
|
226
|
+
const same = current?.url === url && current?.branch === branch;
|
|
227
|
+
const { meta, unchanged } = await writeTodoChartMeta({ repoRoot: dir,
|
|
228
|
+
patch: { repo: { url, branch, accepted_tip: same ? current.accepted_tip ?? null : null } } });
|
|
229
|
+
return { schema: 'lattice.chart_repo_result.v1', project_id: projectIdOf(env, dir), status: 'bound',
|
|
230
|
+
repo: meta.repo, unchanged };
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Run the bundled sensor in process; `{command, exit_code, code}` (`code` = its typed error code or null). */
|
|
234
|
+
async function runSensor(command, dir) {
|
|
235
|
+
const { runSensorCli } = await import('./sensor-cli.mjs');
|
|
236
|
+
let errorText = '';
|
|
237
|
+
const sink = () => new Writable({ write(chunk, _encoding, done) { errorText += chunk; done(); } });
|
|
238
|
+
const exitCode = await runSensorCli({ argv: [command, dir, '--json'], stdout: sink(), stderr: sink() });
|
|
239
|
+
const code = errorText.split('\n').map((line) => { try { return JSON.parse(line).code; } catch { return null; } })
|
|
240
|
+
.find((value) => typeof value === 'string') ?? null;
|
|
241
|
+
return { command, exit_code: exitCode, code };
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* K7 sync. Named protection: never reset, clean, force or repoint; tracked edits make it `dirty` and a HEAD that is
|
|
246
|
+
* not the accepted baseline makes it `diverged` (nothing moves). Self-exit: a failed step is reported and the next
|
|
247
|
+
* sync tries again. A depth-1 tip has no parent, so `--ff-only` cannot see the link: HEAD moves only from the baseline.
|
|
248
|
+
*/
|
|
249
|
+
async function chartRepoSync({ cwd, env }) {
|
|
250
|
+
const dir = await repoRoot(cwd);
|
|
251
|
+
const meta = await readTodoChartMeta({ repoRoot: dir });
|
|
252
|
+
const result = (status, fields = {}) => ({ schema: 'lattice.chart_repo_result.v1', project_id: projectIdOf(env, dir),
|
|
253
|
+
status, tip: null, accepted_tip: meta.repo?.accepted_tip ?? null, sensor: null, failure: null, ...fields });
|
|
254
|
+
if (meta.repo === null || meta.repo === undefined) {
|
|
255
|
+
return result('failed', { failure: { step: 'bind', message: 'no repository bound to this chart',
|
|
256
|
+
next_action: 'lattice chart repo bind --url <url> --branch <branch>' } });
|
|
257
|
+
}
|
|
258
|
+
const { url, branch } = meta.repo;
|
|
259
|
+
const git = async (step, args) => {
|
|
260
|
+
try { return (await runGit('git', args, { cwd: dir })).stdout.trim(); } catch (error) {
|
|
261
|
+
throw Object.assign(new Error(String(error?.stderr || error?.message).trim().split('\n')[0]), { step });
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
const optional = (args) => runGit('git', args, { cwd: dir }).then(({ stdout }) => stdout.trim() || null, () => null);
|
|
265
|
+
try {
|
|
266
|
+
const exclude = path.join(dir, '.git', 'info', 'exclude');
|
|
267
|
+
const excluded = await readFile(exclude, 'utf8').catch(() => '');
|
|
268
|
+
if (!excluded.split(/\r?\n/u).includes('.lattice/')) {
|
|
269
|
+
await mkdir(path.dirname(exclude), { recursive: true });
|
|
270
|
+
await appendFile(exclude, `${excluded === '' || excluded.endsWith('\n') ? '' : '\n'}.lattice/\n`);
|
|
271
|
+
}
|
|
272
|
+
if (await git('status', ['status', '--porcelain', '--untracked-files=no'])) return result('dirty');
|
|
273
|
+
// A lazily fetching (promisor) clone fetches each missing blob on every full object walk; never fetch lazily.
|
|
274
|
+
for (const key of ['remote.origin.promisor', 'remote.origin.partialclonefilter', 'extensions.partialclone']) {
|
|
275
|
+
await optional(['config', '--unset-all', key]);
|
|
276
|
+
}
|
|
277
|
+
// Charts moved before 0.101.0 kept the baseline in refs/remotes/origin/<branch>.
|
|
278
|
+
const accepted = meta.repo.accepted_tip ?? await optional(['rev-parse', '--verify', '--quiet', `refs/remotes/origin/${branch}`]);
|
|
279
|
+
await git('fetch', ['fetch', '--quiet', '--depth=1', '--no-tags', url, branch]);
|
|
280
|
+
const tip = await git('fetch', ['rev-parse', 'FETCH_HEAD']);
|
|
281
|
+
const head = await optional(['rev-parse', '--verify', '--quiet', 'HEAD']);
|
|
282
|
+
if (head !== null && head !== tip && head !== accepted) return result('diverged', { tip, accepted_tip: accepted });
|
|
283
|
+
if (head !== tip) await git('checkout', ['checkout', '--quiet', '-B', branch, tip]);
|
|
284
|
+
if (meta.repo.accepted_tip !== tip) {
|
|
285
|
+
await writeTodoChartMeta({ repoRoot: dir, patch: { repo: { url, branch, accepted_tip: tip } } });
|
|
286
|
+
}
|
|
287
|
+
let sensor = await runSensor('sync', dir);
|
|
288
|
+
if (sensor.code === 'LATTICE_SENSOR_NOT_INITIALIZED') sensor = await runSensor('init', dir);
|
|
289
|
+
if (sensor.exit_code !== 0) {
|
|
290
|
+
return result('failed', { tip, accepted_tip: tip, sensor,
|
|
291
|
+
failure: { step: 'sensor', message: sensor.code ?? 'sensor failed' } });
|
|
292
|
+
}
|
|
293
|
+
return result(head === tip ? 'current' : 'synced', { tip, accepted_tip: tip, sensor });
|
|
294
|
+
} catch (error) {
|
|
295
|
+
return result('failed', { failure: { step: error?.step ?? 'sync', message: String(error?.message ?? error) } });
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function usage(stderr, args) {
|
|
300
|
+
stderr.write(`${JSON.stringify({ schema: 'lattice.cli_error.v2', code: 'USAGE', message: `usage: lattice ${args}`,
|
|
301
|
+
detail: { next_action: 'lattice chart --help' } })}\n`);
|
|
302
|
+
return 2;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function failure(stderr, error) {
|
|
306
|
+
stderr.write(`${JSON.stringify({ schema: 'lattice.cli_error.v2', code: error?.code ?? 'INTERNAL_FAILURE',
|
|
307
|
+
message: error?.message ?? String(error), detail: error?.detail ?? null })}\n`);
|
|
308
|
+
return 1;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** `lattice charts list|source` (root-level, never addressed) and `lattice chart set|repo bind|repo sync`. */
|
|
312
|
+
export async function runChartCli({ argv, cwd, env, stdout, stderr, created = false }) {
|
|
313
|
+
const words = argv.filter((word) => word !== '--json');
|
|
314
|
+
const [group, command, sub] = words;
|
|
315
|
+
try {
|
|
316
|
+
let result;
|
|
317
|
+
if (group === 'charts' && command === 'list' && words.length === 2) {
|
|
318
|
+
result = await listCharts(env);
|
|
319
|
+
} else if (group === 'charts' && command === 'source') {
|
|
320
|
+
const ids = [];
|
|
321
|
+
for (let index = 2; index < words.length; index += 2) {
|
|
322
|
+
if (words[index] !== '--project' || words[index + 1] === undefined) return usage(stderr, 'charts source [--project <id>]... [--json]');
|
|
323
|
+
ids.push(words[index + 1]);
|
|
324
|
+
}
|
|
325
|
+
result = await chartSources(env, ids);
|
|
326
|
+
} else if (group === 'chart' && command === 'set') {
|
|
327
|
+
const { flags, rest } = parseFlagMap(words.slice(2));
|
|
328
|
+
if (rest.length > 0 || Object.keys(flags).some((key) => !['name', 'created-by'].includes(key))) {
|
|
329
|
+
return usage(stderr, 'chart set [--name <text>] [--created-by <id>] [--json]');
|
|
330
|
+
}
|
|
331
|
+
result = await chartSet({ cwd, env, flags, created });
|
|
332
|
+
} else if (group === 'chart' && command === 'repo' && sub === 'bind') {
|
|
333
|
+
const { flags, rest } = parseFlagMap(words.slice(3));
|
|
334
|
+
if (rest.length > 0 || Object.keys(flags).some((key) => !['url', 'branch'].includes(key))) {
|
|
335
|
+
return usage(stderr, 'chart repo bind --url <url> --branch <branch> [--json]');
|
|
336
|
+
}
|
|
337
|
+
result = await chartRepoBind({ cwd, env, flags });
|
|
338
|
+
} else if (group === 'chart' && command === 'repo' && sub === 'sync' && words.length === 3) {
|
|
339
|
+
result = await chartRepoSync({ cwd, env });
|
|
340
|
+
} else {
|
|
341
|
+
return usage(stderr, `${group} --help`);
|
|
342
|
+
}
|
|
343
|
+
stdout.write(`${JSON.stringify(result)}\n`);
|
|
344
|
+
return 0;
|
|
345
|
+
} catch (error) {
|
|
346
|
+
return failure(stderr, error);
|
|
347
|
+
}
|
|
348
|
+
}
|
package/src/cli-help.mjs
CHANGED
|
@@ -15,6 +15,12 @@ Commands:
|
|
|
15
15
|
bridge <command> Configure the optional network bridge
|
|
16
16
|
hooks <command> Install and run sensor-awareness hooks
|
|
17
17
|
setup [status] AI別のMCP登録・製品hook準備・接続確認
|
|
18
|
+
charts <list|source> LATTICE_CHARTS_ROOT配下の工程表一覧と変更検知(host向け, a101)
|
|
19
|
+
chart <set|repo> 工程表の名前・作成者とコード工程表のrepo(host向け, a101)
|
|
20
|
+
|
|
21
|
+
Environment:
|
|
22
|
+
LATTICE_CHARTS_ROOT + LATTICE_PROJECT_ID 両方あれば <root>/<id> の工程表で動く。
|
|
23
|
+
無ければ plan create / chart set が作る(git init込み)
|
|
18
24
|
|
|
19
25
|
Options:
|
|
20
26
|
-h, --help Show help
|
|
@@ -312,6 +318,14 @@ const SUBCOMMAND_USAGE = Object.freeze({
|
|
|
312
318
|
'todo wait': 'todo wait --plan <key> --task <id> [--reason <text>] | --cancel [--json] # lattice.todo_wait_result.v1 {state: waiting|startable_now|not_pending|cancelled}',
|
|
313
319
|
'todo bindings': 'todo bindings [--plan <key>] [--json]',
|
|
314
320
|
'todo display': 'todo display read [--json] | source [--json] # host表示用の読取。不整合でも断らずstateで返す',
|
|
321
|
+
charts: 'charts list [--json] | source [--project <id>]... [--json] # LATTICE_CHARTS_ROOT配下の全工程表を1プロセスで読む',
|
|
322
|
+
'charts list': 'charts list [--json] # lattice.charts_list_result.v1 {charts_root, charts:[{project_id, name, created_by, created_at, source}], findings}',
|
|
323
|
+
'charts source': 'charts source [--project <id>]... [--json] # lattice.charts_source_result.v1 {charts:{<id>: <source>|null}}(--project無し=全工程表)',
|
|
324
|
+
chart: 'chart set [--name <text>] [--created-by <id>] [--json] | repo bind --url <url> --branch <branch> [--json] | repo sync [--json]',
|
|
325
|
+
'chart set': 'chart set [--name <text>] [--created-by <id>] [--json] # lattice.chart_set_result.v1(どちらか1つ以上。名前は1-40字・制御文字なし。--nameが無ければ名前はそのまま。--created-byは作成者が空の時だけ)',
|
|
326
|
+
'chart repo': 'chart repo bind --url <url> --branch <branch> [--json] | sync [--json] # lattice.chart_repo_result.v1',
|
|
327
|
+
'chart repo bind': 'chart repo bind --url <url> --branch <branch> [--json] # コード工程表のrepoを記録する',
|
|
328
|
+
'chart repo sync': 'chart repo sync [--json] # depth-1 fetch、accepted_tipからだけ前進(reset/forceしない)、その後sensor。status current|synced|dirty|diverged|failed',
|
|
315
329
|
'todo display read': 'todo display read [--json] # lattice.todo_display_read_result.v1(state: verified|unverified|last_verified|unavailable)',
|
|
316
330
|
'todo display source': 'todo display source [--json] # lattice.todo_store_display_source.v1(安い変更検知。変わった時だけreadする)',
|
|
317
331
|
'todo independence': 'todo independence [--plan <key>] [--json] | mode --plan <key> --set <witness|conversation|enforced> --reason <text>'
|
package/src/project-cli.mjs
CHANGED
|
@@ -864,7 +864,9 @@ export async function runPlanCreate({
|
|
|
864
864
|
};
|
|
865
865
|
const store = manifest === null
|
|
866
866
|
? await initializeAuthoredTodoStore({ ...options,
|
|
867
|
-
projectId: input.project_id, repositories: [{ repo_id: 'self', path: '.' }]
|
|
867
|
+
projectId: input.project_id, repositories: [{ repo_id: 'self', path: '.' }],
|
|
868
|
+
// K4 (a101): the seat that creates the Store is the chart's creator unless one is already recorded.
|
|
869
|
+
chartCreator: env.LATTICE_SEAT_ID || null })
|
|
868
870
|
: await appendAuthoredTodoPlan(options).catch((error) => {
|
|
869
871
|
// a27: Storeの拒否はkeyを持たないので、断りの文が名指せるようにここで添える。
|
|
870
872
|
if (error?.detail?.reason !== 'plan_key_already_exists') throw error;
|