@olierjs/fugue-cli 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +99 -2
  3. package/THIRD_PARTY_NOTICES +467 -0
  4. package/bin/fugue-cli.mjs +23 -0
  5. package/dist/darwin-arm64/fugue-cli +0 -0
  6. package/dist/darwin-x64/fugue-cli +0 -0
  7. package/dist/linux-arm64/fugue-cli +0 -0
  8. package/dist/linux-x64/fugue-cli +0 -0
  9. package/dist/win32-arm64/fugue-cli.exe +0 -0
  10. package/dist/win32-x64/fugue-cli.exe +0 -0
  11. package/package.json +27 -4
  12. package/scripts/postinstall.mjs +13 -0
  13. package/scripts/skills.mjs +104 -0
  14. package/skills/fugue-show-me/SKILL.md +16 -0
  15. package/skills/fugue-stack/SKILL.md +10 -0
  16. package/skills/plan-with-remote/SKILL.md +60 -0
  17. package/skills/plan-with-remote/references/configuration.md +43 -0
  18. package/skills/plan-with-remote/scripts/client.mjs +61 -0
  19. package/skills/plan-with-remote/scripts/config.mjs +53 -0
  20. package/skills/plan-with-remote/scripts/planning.mjs +279 -0
  21. package/skills/plan-with-remote/scripts/protocol.mjs +147 -0
  22. package/skills/plan-with-remote/scripts/service.mjs +146 -0
  23. package/skills/plan-with-remote/scripts/storage.mjs +74 -0
  24. package/skills/show-me/SKILL.md +128 -0
  25. package/skills/show-me/agents/openai.yaml +2 -0
  26. package/skills/statechart/SKILL.md +36 -0
  27. package/skills/statechart/scripts/bug-states.mjs +81 -0
  28. package/skills/statechart/scripts/chart-edges.mjs +68 -0
  29. package/skills/statechart/scripts/chart-parts.mjs +21 -0
  30. package/skills/statechart/scripts/chart-to-tla.mjs +205 -0
  31. package/skills/statechart/scripts/compare-charts.mjs +74 -0
  32. package/skills/statechart/scripts/lib.mjs +970 -0
  33. package/skills/statechart/scripts/map-view.mjs +92 -0
  34. package/skills/statechart/scripts/property-loop.mjs +60 -0
  35. package/skills/statechart/scripts/read-check.mjs +79 -0
  36. package/skills/statechart/scripts/regions-chart.mjs +307 -0
  37. package/skills/statechart/scripts/render.mjs +531 -0
  38. package/skills/statechart/scripts/rule-book.mjs +84 -0
  39. package/skills/statechart/scripts/second-replay.mjs +122 -0
  40. package/skills/statechart/scripts/snapshot.mjs +74 -0
  41. package/skills/statechart/scripts/spec-text.mjs +126 -0
  42. package/skills/statechart/scripts/statechart-help.mjs +350 -0
  43. package/skills/statechart/scripts/statechart.mjs +903 -0
  44. package/skills/statechart/scripts/test/band.mmd +15 -0
  45. package/skills/statechart/scripts/test/regions.mmd +62 -0
  46. package/skills/statechart/scripts/test/statechart.test.mjs +6854 -0
  47. package/skills/statechart/scripts/test/sync.mmd +19 -0
  48. package/skills/statechart/scripts/test/upload.mmd +16 -0
  49. package/skills/statechart/scripts/tlc-to-chart-args.mjs +52 -0
  50. package/skills/statechart/scripts/tlc-to-chart.mjs +802 -0
  51. package/skills/statechart/scripts/tlc-tools.mjs +69 -0
  52. package/skills/statechart/scripts/ways-in.mjs +69 -0
  53. package/upstream-skills.json +18 -0
@@ -0,0 +1,147 @@
1
+ import { digest } from './storage.mjs';
2
+ import { validateDocuments } from './service.mjs';
3
+
4
+ const record = (value, name) => {
5
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${name} is invalid`);
6
+ return value;
7
+ };
8
+ const positive = value => Number.isSafeInteger(value) && value > 0;
9
+ const same = (left, right) => digest(left) === digest(right);
10
+
11
+ export function buildAcceptSolutionReviewCommand(input) {
12
+ return { type: 'accept_solution_review', ...input };
13
+ }
14
+ export function buildFeedbackSolutionReviewCommand(input) {
15
+ return { type: 'feedback_solution_review', ...input };
16
+ }
17
+ export function parseSolutionReviewOperationAccepted(response, command) {
18
+ const data = record(response?.data, 'solution review acceptance');
19
+ if (data.type !== 'solution_review_operation_accepted' || data.requirementId !== command.requirementId || data.commandId !== command.commandId || typeof data.operationId !== 'string' || data.polling?.operationId !== data.operationId || data.review?.reviewRevision !== command.reviewRevision || !same(data.review?.sourceBinding, command.sourceBinding) || !positive(data.lifecycle?.snapshotRevision)) throw new Error('solution review operation does not match the submitted decision');
20
+ }
21
+
22
+ export async function waitForProjectPreparation(input, accepted, deps) {
23
+ const data = record(accepted?.data, 'preparation acceptance');
24
+ if (data.requirementId !== input.requirementId || !data.operationId || !positive(data.polling?.nextPollAfterMs)) throw new Error('preparation acceptance identity is invalid');
25
+ while (deps.now() - input.startedAt < input.timeoutMs) {
26
+ const response = record((await deps.read())?.data, 'project context');
27
+ const preparation = response.preparation;
28
+ if (response.project?.projectId !== input.projectId || preparation?.projectId !== input.projectId || preparation?.requirementId !== input.requirementId || preparation?.runId !== data.operationId) throw new Error('project preparation identity mismatch');
29
+ if (preparation.status === 'failed') throw new Error(`project preparation failed: ${preparation.error?.code ?? 'unknown'}: ${preparation.error?.message ?? 'no details'}`);
30
+ if (preparation.status === 'succeeded' && preparation.baselineId && response.baseline?.baselineId === preparation.baselineId) return;
31
+ await deps.wait(Math.min(data.polling.nextPollAfterMs, input.timeoutMs - (deps.now() - input.startedAt)));
32
+ }
33
+ throw new Error('project preparation timed out');
34
+ }
35
+
36
+ export async function continuePlanningAfterHumanInput(input, deps) {
37
+ const response = await deps.post(input.command);
38
+ const data = record(response?.data, 'human input response');
39
+ if (data.operationId) return runPlanningFromAcceptedOperation({ requirementId: input.requirementId, operationId: data.operationId, timeoutMs: input.timeoutMs }, deps);
40
+ if (data.type !== 'submit_stage_clarification' || data.requirementId !== input.requirementId) throw new Error('human input response identity mismatch');
41
+ const pending = record(data.pendingStageResolution, 'pending stage resolution');
42
+ return { status: 'needs_human_input', requirementId: input.requirementId, viewVersion: pending.expectedSnapshotRevision, snapshotRevision: pending.expectedSnapshotRevision, questions: (pending.actions ?? []).map(action => ({ kind: 'stage', questionKey: action.questionKey, questionRef: action.questionRef, blockerRef: action.blockerRef, prompt: action.question })), resolution: { kind: 'stage', expectedSnapshotRevision: pending.expectedSnapshotRevision } };
43
+ }
44
+
45
+ export async function runPlanningFromAcceptedOperation(input, deps) {
46
+ const started = deps.now();
47
+ while (deps.now() - started < input.timeoutMs) {
48
+ const response = await deps.post(flowCommand(input.requirementId, input.operationId, 'summary'));
49
+ const summary = record(response?.data, 'planning flow');
50
+ summary.polling = response.polling;
51
+ summary.limits = response.limits;
52
+ if (summary.requirementId !== input.requirementId || summary.operation?.operationId !== input.operationId) throw new Error('planning flow identity mismatch');
53
+ if (input.expectedPlanningMode && summary.planningMode !== input.expectedPlanningMode) throw new Error('planning mode differs from the submitted request');
54
+ const operation = summary.operation;
55
+ if (summary.pendingStageResolution || summary.pendingOwnerResolution) return humanInput(summary);
56
+ if (summary.displayStatus === 'awaiting_revision' && ['finished', 'failed'].includes(operation.status)) {
57
+ const outcome = await readRevisionDocuments(input, deps, summary);
58
+ if (outcome) return outcome;
59
+ const remaining = input.timeoutMs - (deps.now() - started);
60
+ const interval = summary.polling?.nextPollAfterMs;
61
+ if (!positive(interval)) throw new Error('planning polling interval is invalid');
62
+ if (remaining > 0) await deps.wait(Math.min(interval, remaining));
63
+ continue;
64
+ }
65
+ const recovering = summary.currentStage === 'failed' && ['queued', 'running'].includes(operation.status);
66
+ if (summary.currentStage === 'failed' && !recovering || operation.status === 'failed' || summary.currentStage === 'stopped') return { status: 'failed', requirementId: input.requirementId, viewVersion: summary.viewVersion, code: operation.error?.code ?? 'runtime_failed', message: operation.error?.message ?? 'planning failed', retryable: operation.error?.retryable === true };
67
+ if (summary.currentStage === 'awaiting_solution_review' && operation.status === 'finished') {
68
+ if (summary.planningMode !== 'standard') throw new Error('lightweight planning cannot require solution acknowledgement');
69
+ const data = record((await deps.post({ type: 'get_solution_review', requirementId: input.requirementId }))?.data, 'solution review');
70
+ if (data.requirementId !== input.requirementId || data.snapshotRevision !== summary.viewVersion || data.review?.reviewRevision !== operation.solutionReviewResult?.reviewRevision || !same(data.review?.sourceBinding, operation.solutionReviewResult?.sourceBinding)) throw new Error('solution review is not bound to the current flow');
71
+ return { status: 'awaiting_solution_review', requirementId: input.requirementId, planningMode: summary.planningMode, viewVersion: summary.viewVersion, snapshotRevision: data.snapshotRevision, solutionReview: data.review, flow: summary };
72
+ }
73
+ if (summary.currentStage === 'awaiting_execution_doc_approval' && operation.status === 'finished') {
74
+ const fullResponse = await deps.post(flowCommand(input.requirementId, input.operationId, 'full'));
75
+ const flow = record(fullResponse?.data, 'full planning flow');
76
+ flow.limits = fullResponse.limits;
77
+ if (flow.requirementId !== input.requirementId || flow.operation?.operationId !== input.operationId || flow.operation?.status !== 'finished' || flow.currentStage !== 'awaiting_execution_doc_approval' || flow.viewVersion !== summary.viewVersion || flow.pageInfo?.hasMore || flow.limits?.omittedCollections?.some(value => ['artifacts', 'gateResults'].includes(value)) || !Array.isArray(flow.gateResults) || !flow.gateResults.length) throw new Error('full planning flow is incomplete or mismatched');
78
+ if (flow.pendingStageResolution || flow.pendingOwnerResolution) return humanInput(flow);
79
+ const documents = (await deps.post({ type: 'get_planning_candidate_documents', requirementId: input.requirementId }))?.data?.documents;
80
+ validateDocuments(documents, input.requirementId);
81
+ if (documents.snapshotRevision !== flow.viewVersion) throw new Error('candidate document version differs from planning flow');
82
+ if (flow.displayStatus === 'awaiting_revision') {
83
+ const revision = flow.planningRevision;
84
+ if (revision?.available !== true || revision.reason !== 'quality_blocked' || revision.candidateRevision !== documents.candidateRevision) throw new Error('quality revision documents do not match the candidate');
85
+ for (const [kind, ref] of [['execution_doc', documents.executionDocumentRef], ['acceptance_doc', documents.acceptanceDocumentRef]]) {
86
+ const entry = flow.planningDocuments?.[kind];
87
+ if (entry?.candidateRevision !== documents.candidateRevision || !same(entry.documentRef, ref)) throw new Error('quality revision document reference differs from flow');
88
+ }
89
+ return { status: 'awaiting_revision', planningMode: flow.planningMode, flow, ...documents };
90
+ }
91
+ if (summary.planningMode === 'standard' && !flow.boundedReview) throw new Error('full planning flow is missing bounded review');
92
+ const gateIds = flow.gateResults.map(gate => gate?.gateId).filter(value => typeof value === 'string');
93
+ const gate = documents.gate;
94
+ if (gate.status !== 'decided' || (summary.currentStageStatus === 'gate_blocked' && gate.decision !== 'blocked') || (gateIds.length && !gateIds.includes(`gate-decision-${gate.gateRevision}`))) throw new Error('candidate Gate differs from planning flow');
95
+ const report = (await deps.post({ type: 'inspect_requirement', requirementId: input.requirementId }))?.data?.report;
96
+ if (report?.requirementId !== input.requirementId || report.snapshotRevision !== documents.snapshotRevision || report?.approvalReport?.requirement_id !== input.requirementId || report.approvalReport.candidate_revision !== documents.candidateRevision || report.approvalReport.gate_revision !== gate.gateRevision || report.approvalReport.decision !== gate.decision) throw new Error('candidate Gate differs from current approval report');
97
+ return { status: gate.decision === 'pass' ? 'ready_for_approval' : 'awaiting_revision', planningMode: flow.planningMode, flow, ...documents };
98
+ }
99
+ const remaining = input.timeoutMs - (deps.now() - started);
100
+ const interval = summary.polling?.nextPollAfterMs;
101
+ if (!positive(interval)) throw new Error('planning polling interval is invalid');
102
+ await deps.wait(Math.min(interval, remaining));
103
+ }
104
+ return { status: 'failed', requirementId: input.requirementId, viewVersion: 0, code: 'planning_wait_timeout', message: 'planning wait timed out', retryable: true };
105
+ }
106
+
107
+ function flowCommand(requirementId, operationId, mode) {
108
+ const full = mode === 'full';
109
+ return { type: 'get_requirement_flow_view', requirementId, operationId, responseMode: mode, include: { stages: true, artifacts: full, runtimeRuns: full, gateResults: true, projectionJobs: full, externalProjections: full, evidenceRefs: full }, limit: { maxArtifacts: 200, maxRuntimeRuns: 200, maxEvidenceRefs: 200 }, maxItemsPerSection: 200 };
110
+ }
111
+ function humanInput(flow) {
112
+ const resolution = flow.pendingOwnerResolution ?? flow.pendingStageResolution;
113
+ const owner = !!flow.pendingOwnerResolution;
114
+ const actions = owner ? [resolution] : resolution.actions ?? [];
115
+ const questions = actions.map(action => {
116
+ if (!owner) return { kind: 'stage', questionKey: action.questionKey, questionRef: action.questionRef, blockerRef: action.blockerRef, prompt: action.question };
117
+ if (!['replan_required', 'human_resolution_required'].includes(action.outcome)) throw new Error('owner resolution outcome is invalid');
118
+ return { kind: 'owner', pendingResolutionIdentity: action.pendingResolutionIdentity, action: action.outcome === 'replan_required' ? 'confirm_replan' : 'clarify', prompt: action.reason };
119
+ });
120
+ return { status: 'needs_human_input', requirementId: flow.requirementId, viewVersion: flow.viewVersion, snapshotRevision: resolution.expectedSnapshotRevision, questions, resolution: { kind: owner ? 'owner' : 'stage', expectedSnapshotRevision: resolution.expectedSnapshotRevision } };
121
+ }
122
+
123
+ async function readRevisionDocuments(input, deps, summary) {
124
+ const fullResponse = await deps.post(flowCommand(input.requirementId, input.operationId, 'full'));
125
+ const flow = record(fullResponse?.data, 'full planning flow');
126
+ flow.limits = fullResponse.limits;
127
+ if (flow.requirementId !== input.requirementId || flow.operation?.operationId !== input.operationId) throw new Error('quality revision flow identity mismatch');
128
+ if (flow.limits?.omittedCollections?.some(value => ['artifacts', 'gateResults'].includes(value)) || !Array.isArray(flow.gateResults)) throw new Error('quality revision flow is missing required collections');
129
+ if (flow.pageInfo?.hasMore) throw new Error('quality revision flow has more pages');
130
+ if (!['finished', 'failed'].includes(flow.operation?.status) || flow.displayStatus !== 'awaiting_revision' || flow.viewVersion !== summary.viewVersion) return undefined;
131
+ if (flow.pendingStageResolution || flow.pendingOwnerResolution) return humanInput(flow);
132
+ const documents = (await deps.post({ type: 'get_planning_candidate_documents', requirementId: input.requirementId }))?.data?.documents;
133
+ validateDocuments(documents, input.requirementId);
134
+ if (documents.snapshotRevision !== flow.viewVersion || flow.planningRevision?.available !== true || flow.planningRevision.reason !== 'quality_blocked' || flow.planningRevision.candidateRevision !== documents.candidateRevision) throw new Error('quality revision documents do not match the candidate');
135
+ for (const [kind, ref] of [['execution_doc', documents.executionDocumentRef], ['acceptance_doc', documents.acceptanceDocumentRef]]) {
136
+ const entry = flow.planningDocuments?.[kind];
137
+ if (entry?.candidateRevision !== documents.candidateRevision || !same(entry.documentRef, ref)) throw new Error('quality revision document reference differs from flow');
138
+ }
139
+ return { status: 'awaiting_revision', planningMode: flow.planningMode, flow, ...documents };
140
+ }
141
+ export function parseDeliveryPackage(pkg) {
142
+ if (!pkg || !['ready', 'not_approved', 'unavailable'].includes(pkg.status)) throw new Error('delivery package is invalid');
143
+ if (pkg.status === 'ready') {
144
+ if (!pkg.planningDelivery || typeof pkg.planningDelivery.requirementId !== 'string' || pkg.planningCandidateRevision !== pkg.planningDelivery.planningCandidateRevision || !same(pkg.executionDocumentRef, pkg.planningDelivery.executionDocumentRef) || !same(pkg.acceptanceDocumentRef, pkg.planningDelivery.acceptanceDocumentRef) || typeof pkg.executionDocument !== 'string' || typeof pkg.acceptanceDocument !== 'string') throw new Error('delivery package binding is invalid');
145
+ }
146
+ return pkg;
147
+ }
@@ -0,0 +1,146 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { digest } from './storage.mjs';
4
+
5
+ export function transport(baseUrl, timeoutMs) {
6
+ async function request(path, command) {
7
+ const response = await fetch(baseUrl + path, {
8
+ ...(command ? { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(command) } : {}),
9
+ signal: AbortSignal.timeout(timeoutMs), redirect: 'error',
10
+ });
11
+ const text = await response.text();
12
+ let body;
13
+ try { body = JSON.parse(text); }
14
+ catch {
15
+ const error = new Error('服务未返回有效响应,请检查服务地址或稍后重试原任务。');
16
+ error.detail = text;
17
+ error.status = response.status;
18
+ throw error;
19
+ }
20
+ if (!response.ok || body?.ok !== true || !body.data) {
21
+ const error = new Error('服务未完成请求。请检查服务配置和项目登记;已有任务请勿改用新任务重复提交。');
22
+ error.detail = body;
23
+ error.status = response.status;
24
+ throw error;
25
+ }
26
+ return body;
27
+ }
28
+ return { request, post: command => request('/v1/reconcile/command', command) };
29
+ }
30
+
31
+ export async function resolveProject(api, remote, cwd) {
32
+ const repository = execFileSync('git', ['-C', cwd, 'remote', 'get-url', remote], { encoding: 'utf8' }).trim();
33
+ const identity = normalizeRepositoryIdentity(repository);
34
+ if (!identity) throw new Error('目标仓库需要有效的 HTTPS 或 SSH Git remote。');
35
+ const response = await api.request(`/v1/reconcile/projects/resolve?repository=${encodeURIComponent(repository)}`);
36
+ const project = response.data;
37
+ if (!project || typeof project.projectId !== 'string' || typeof project.repositoryIdentity !== 'string') throw new Error('服务返回的项目登记信息无效。');
38
+ if (project.repositoryIdentity !== identity) throw new Error('服务返回的项目与当前仓库不一致。');
39
+ return project.projectId;
40
+ }
41
+
42
+ export async function readInput(path) {
43
+ const value = JSON.parse(await readFile(path, 'utf8'));
44
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('需求文件必须是 JSON 对象。');
45
+ for (const key of Object.keys(value)) {
46
+ if (!['title', 'description', 'sources'].includes(key)) throw new Error(`未知需求字段:${key}`);
47
+ }
48
+ if (typeof value.description !== 'string' || !value.description.trim()) throw new Error('description 必须包含需求正文。');
49
+ if (value.title !== undefined && (typeof value.title !== 'string' || !value.title.trim())) throw new Error('title 必须是非空文本。');
50
+ if (value.sources !== undefined && !Array.isArray(value.sources)) throw new Error('sources 必须是数组。');
51
+ for (const source of value.sources ?? []) {
52
+ if (!source || Object.keys(source).some(key => !['label', 'content'].includes(key)) || typeof source.label !== 'string' || !source.label.trim() || typeof source.content !== 'string' || !source.content.trim()) {
53
+ throw new Error('每项来源只需提供 label 和已读取的 content 正文。');
54
+ }
55
+ }
56
+ return value;
57
+ }
58
+
59
+ export function requestPackage(input, id, projectId, mode, agent) {
60
+ return { requestId: id, planningTargetKey: projectId, planningMode: mode,
61
+ requirement: { description: input.description, ...(input.title ? { title: input.title } : {}) },
62
+ materials: (input.sources ?? []).map(source => ({ kind: 'text', ...source })),
63
+ ...(agent ? { agent } : {}),
64
+ };
65
+ }
66
+
67
+ function positive(value) { return Number.isSafeInteger(value) && value > 0; }
68
+ function validRef(ref, fields) {
69
+ return ref && typeof ref === 'object' && fields.every(([key, check]) => check(ref[key]));
70
+ }
71
+ const text = value => typeof value === 'string';
72
+ const nonEmpty = value => text(value) && value.length > 0;
73
+ const integer = value => Number.isSafeInteger(value) && value > 0;
74
+ export function validateDocuments(documents, requirementId) {
75
+ if (!documents || documents.requirementId !== requirementId || !positive(documents.snapshotRevision) || !positive(documents.candidateRevision)) {
76
+ throw new Error('返回的规划文档身份或版本无效。');
77
+ }
78
+ for (const [key, stage] of [['requirementArtifactRef', 'prd_understanding'], ['technicalDesignArtifactRef', 'technical_design']]) {
79
+ const ref = documents[key];
80
+ if (!validRef(ref, [['stage', nonEmpty], ['artifact_revision', integer], ['content_digest', nonEmpty]])) throw new Error('规划来源绑定不匹配。');
81
+ if (ref.stage !== stage) throw new Error('规划来源绑定不匹配。');
82
+ }
83
+ const gate = documents.gate;
84
+ if (!gate || (gate.status !== 'not_decided' && (gate.status !== 'decided' || !positive(gate.gateRevision) || !['pass', 'blocked'].includes(gate.decision)))) {
85
+ throw new Error('规划文档的检查信息缺失或无效。');
86
+ }
87
+ const rendered = {};
88
+ for (const [key, type, filename] of [['executionDocumentMarkdown', 'execution_doc', 'execution.md'], ['acceptanceDocumentMarkdown', 'acceptance_doc', 'acceptance.md']]) {
89
+ const ref = documents[key === 'executionDocumentMarkdown' ? 'executionDocumentRef' : 'acceptanceDocumentRef'];
90
+ const markdown = documents[key];
91
+ if (!validRef(ref, [['document_type', nonEmpty], ['document_revision', integer], ['content_digest', nonEmpty]]) || ref.document_type !== type || !nonEmpty(markdown)) throw new Error('正式文档 Markdown 或其版本引用缺失,请更新规划服务后重试。');
92
+ rendered[filename] = markdown;
93
+ }
94
+ return rendered;
95
+ }
96
+
97
+ export function normalizeRepositoryIdentity(source) {
98
+ if (source.startsWith('/') || /^[A-Za-z]:[\\/]/u.test(source)) return undefined;
99
+ let protocol;
100
+ let host;
101
+ let port = '';
102
+ let path;
103
+ const scp = /^git@([A-Za-z0-9.-]+):([A-Za-z0-9._/-]+)$/u.exec(source);
104
+ if (scp) {
105
+ host = scp[1]; path = scp[2]; protocol = 'ssh';
106
+ if (path.includes('..')) return undefined;
107
+ } else {
108
+ if (!/^https:\/\//iu.test(source) && !/^ssh:\/\//iu.test(source)) return undefined;
109
+ const match = /^(https|ssh):\/\/([^/?#]+)(\/[^?#]*)$/iu.exec(source);
110
+ const rawPath = match?.[3];
111
+ if (!match || !rawPath || rawPath.includes('//') || rawPath.includes('\\') || /%2f/iu.test(rawPath) || rawPath.split('/').some(part => part === '.' || part === '..')) return undefined;
112
+ let url;
113
+ try { url = new URL(source); } catch { return undefined; }
114
+ if (!url.hostname || url.password || url.search || url.hash || (url.protocol === 'https:' && url.username) || (url.protocol === 'ssh:' && url.username && url.username !== 'git')) return undefined;
115
+ protocol = url.protocol === 'https:' ? 'https' : 'ssh'; host = url.hostname.toLowerCase(); port = url.port;
116
+ try { path = decodeURIComponent(rawPath.replace(/^\//u, '')); } catch { return undefined; }
117
+ if (!path || path.split('/').some(part => part === '.' || part === '..')) return undefined;
118
+ }
119
+ path = path.replace(/\/$/u, '').replace(/\.git$/u, '').replace(/\/$/u, '');
120
+ if (!path) return undefined;
121
+ const defaultPort = (protocol === 'https' && port === '443') || (protocol === 'ssh' && port === '22');
122
+ return !port || defaultPort ? `${host.toLowerCase()}/${path}` : `${protocol}://${host.toLowerCase()}:${port}/${path}`;
123
+ }
124
+
125
+ export async function assertFresh(api, state, outcome) {
126
+ if (outcome.status === 'awaiting_solution_review') {
127
+ const response = await api.post({ type: 'get_solution_review', requirementId: state.requirementId });
128
+ const current = response.data;
129
+ if (!current || current.type !== 'get_solution_review' || !current.review || !current.review.overview) throw new Error('服务返回的方案审阅信息无效。');
130
+ if (current.requirementId !== state.requirementId || current.snapshotRevision !== outcome.snapshotRevision || digest(current.review.sourceBinding) !== digest(outcome.solutionReview.sourceBinding) || current.review.reviewRevision !== outcome.solutionReview.reviewRevision || current.review.overview.markdown !== outcome.solutionReview.overview.markdown) {
131
+ throw new Error('方案已变化,请重新读取并请用户审阅;旧决定不能用于新方案。');
132
+ }
133
+ } else if (['ready_for_approval', 'awaiting_revision'].includes(outcome.status)) {
134
+ const current = (await api.post({ type: 'get_planning_candidate_documents', requirementId: state.requirementId })).data.documents;
135
+ validateDocuments(current, state.requirementId);
136
+ for (const key of ['snapshotRevision', 'candidateRevision', 'gate', 'requirementArtifactRef', 'technicalDesignArtifactRef', 'executionDocumentRef', 'acceptanceDocumentRef']) {
137
+ if (digest(current[key]) !== digest(outcome[key])) throw new Error('规划文档已变化,请重新读取并请用户审阅;旧决定不能用于新文档。');
138
+ }
139
+ for (const key of ['executionDocumentMarkdown', 'acceptanceDocumentMarkdown']) {
140
+ if (current[key] !== outcome[key]) throw new Error('规划文档正文已变化,请重新读取并请用户审阅;旧决定不能用于新文档。');
141
+ }
142
+ } else {
143
+ const report = (await api.post({ type: 'inspect_requirement', requirementId: state.requirementId })).data.report;
144
+ if (report?.requirementId !== state.requirementId || report.snapshotRevision !== outcome.snapshotRevision) throw new Error('待处理问题已变化,请重新读取后再回答。');
145
+ }
146
+ }
@@ -0,0 +1,74 @@
1
+ import { randomUUID, createHash } from 'node:crypto';
2
+ import { mkdir, readFile, writeFile, rename, open, unlink } from 'node:fs/promises';
3
+ import { dirname, resolve } from 'node:path';
4
+
5
+ export const digest = value => `sha256:${createHash('sha256').update(typeof value === 'string' ? value : JSON.stringify(value)).digest('hex')}`;
6
+ export const readJson = async path => JSON.parse(await readFile(path, 'utf8'));
7
+
8
+ export async function saveSession(path, state) {
9
+ const temp = `${path}.${randomUUID()}.tmp`;
10
+ await writeFile(temp, JSON.stringify(state, null, 2) + '\n', { mode: 0o600, flag: 'wx' });
11
+ await rename(temp, path);
12
+ }
13
+
14
+ export async function createSession(output, state) {
15
+ const directory = resolve(output);
16
+ await mkdir(directory, { recursive: true });
17
+ const path = resolve(directory, 'session.json');
18
+ await writeFile(path, JSON.stringify(state, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
19
+ return path;
20
+ }
21
+
22
+ export async function loadSession(path) {
23
+ const state = await readJson(path);
24
+ if (state.version !== 1 || !state.requirementId || !state.baseUrl) throw new Error('任务文件无效。请使用脚本返回的 session 路径。');
25
+ return state;
26
+ }
27
+
28
+ export async function lockSession(path, work) {
29
+ const lock = `${path}.lock`;
30
+ try {
31
+ const handle = await open(lock, 'wx', 0o600);
32
+ await handle.writeFile(String(process.pid));
33
+ await handle.close();
34
+ } catch (error) {
35
+ if (error.code !== 'EEXIST') throw error;
36
+ const pid = Number(await readFile(lock, 'utf8'));
37
+ if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error('任务锁无法识别,请确认没有其他命令运行后清理锁文件。');
38
+ try { process.kill(pid, 0); }
39
+ catch (cause) {
40
+ if (cause.code === 'ESRCH') { await unlink(lock); return lockSession(path, work); }
41
+ throw cause;
42
+ }
43
+ throw new Error('此任务已有命令运行,请等待该命令结束。');
44
+ }
45
+ try { return await work(); }
46
+ finally { await unlink(lock); }
47
+ }
48
+
49
+ export async function writeReview(sessionPath, state, outcome, documents) {
50
+ const directory = resolve(dirname(sessionPath), `review-${randomUUID()}`);
51
+ await mkdir(directory);
52
+ const files = {};
53
+ const hashes = {};
54
+ for (const [name, text] of Object.entries(documents)) {
55
+ const path = resolve(directory, name);
56
+ await writeFile(path, text, { flag: 'wx' });
57
+ files[name] = path;
58
+ hashes[path] = digest(text);
59
+ }
60
+ const path = resolve(directory, 'review.json');
61
+ await writeFile(path, JSON.stringify({ version: 1, session: resolve(sessionPath), requirementId: state.requirementId, baseUrl: state.baseUrl, outcome, hashes }, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
62
+ return { review: path, documents: files };
63
+ }
64
+
65
+ export async function loadReview(path) {
66
+ const review = await readJson(path);
67
+ if (review.version !== 1 || !review.session || !review.outcome || !review.hashes) throw new Error('审阅凭据无效,请重新读取文档。');
68
+ const state = await loadSession(review.session);
69
+ if (review.requirementId !== state.requirementId || review.baseUrl !== state.baseUrl) throw new Error('审阅凭据与任务不匹配。');
70
+ for (const [file, hash] of Object.entries(review.hashes)) {
71
+ if (digest(await readFile(file, 'utf8')) !== hash) throw new Error('审阅文档已被修改,请重新读取正式文档后再作决定。');
72
+ }
73
+ return review;
74
+ }
@@ -0,0 +1,128 @@
1
+ ---
2
+ name: show-me
3
+ description: Help the user understand the current topic visually with concise diagrams, code-shape sketches, and focused HTML artifacts.
4
+ disable-model-invocation: true
5
+ ---
6
+
7
+ Help the user understand the current topic of conversation visually. Skip the preamble and keep prose brief. Pick the smallest view that makes the key point clear.
8
+
9
+ - Show logic or an algorithm as pseudocode:
10
+
11
+ ```text
12
+ on(save)
13
+ if content is unchanged
14
+ return cached result
15
+ write new content
16
+ return fresh result
17
+ ```
18
+
19
+ - Show runtime control flow as a call tree:
20
+
21
+ ```text
22
+ submitForm
23
+ createSession
24
+ persistPrompt
25
+ launchAgent
26
+ navigateToSession
27
+ ```
28
+
29
+ - Show UI structure as a component tree, including state and module boundaries that matter:
30
+
31
+ ```tsx
32
+ <SessionPage> (apps/example/src/routes/session.tsx)
33
+ useSessionEvents()
34
+ <SessionToolbar>
35
+ <RunSkillButton> (packages/ui)
36
+ ```
37
+
38
+ - Show file responsibility or a broad refactor as a shallow file tree:
39
+
40
+ ```text
41
+ src/
42
+ ├── commands/ # parses user actions
43
+ ├── sessions/ # owns session state
44
+ └── transport/ # sends API requests
45
+ ```
46
+
47
+ - Show component interaction, control flow, or data flow with Mermaid:
48
+
49
+ ```mermaid
50
+ sequenceDiagram
51
+ participant User
52
+ participant UI
53
+ participant Daemon
54
+ User->>UI: choose command
55
+ UI->>Daemon: send expanded prompt
56
+ Daemon-->>UI: stream result
57
+ ```
58
+
59
+ - Use `diff` when the point is what changes and the surrounding shape already exists. Match the diff shape to the topic.
60
+
61
+ For a component change:
62
+
63
+ ```diff
64
+ <SessionPage>
65
+ useSessionEvents()
66
+ <SessionToolbar>
67
+ + <RunSkillButton />
68
+ <SessionTimeline>
69
+ + <SkillResultCard />
70
+ ```
71
+
72
+ For a file-layout change:
73
+
74
+ ```diff
75
+ src/
76
+ ├── commands/
77
+ +│ └── show-me.ts # expands the slash command
78
+ ├── sessions/
79
+ -└── transport.ts
80
+ +└── transport/
81
+ + ├── client.ts
82
+ + └── stream.ts
83
+ ```
84
+
85
+ For a call-tree or call-stack change:
86
+
87
+ ```diff
88
+ submitForm
89
+ createSession
90
+ persistPrompt
91
+ + expandSkillMention
92
+ launchAgent
93
+ - navigateToSession
94
+ + navigateToSession
95
+ + subscribeToEvents
96
+ ```
97
+
98
+ For a state or control-flow change:
99
+
100
+ ```diff
101
+ on(save)
102
+ - write content
103
+ + if content is unchanged
104
+ + return cached result
105
+ + write new content
106
+ + invalidate cache
107
+ ```
108
+
109
+ - Show the whole block when most of it is new, when omitted context would hide ownership or order, or when the user needs a copyable target shape:
110
+
111
+ ```ts
112
+ function expandSkill(command: string): string {
113
+ const skillName = command.slice(1)
114
+ return `use the ${skillName} skill`
115
+ }
116
+ ```
117
+
118
+ - For a visual UI, layout, state comparison, or concept too dense for Mermaid, write one focused HTML file — a diagram, an infographic, or a short slide deck, whichever fits the point. Match the product's colors, type, spacing, and components; use real labels and data; support desktop and mobile. Then open it for the user:
119
+
120
+ ```
121
+ Bash(open path/to/show-me-{description}.html)
122
+ ```
123
+
124
+ ### guidance
125
+
126
+ Place each visual next to the short text it supports. Keep only the calls, files, props, states, and boundaries needed to answer the user's current question or the options to resolve the current discussion point.
127
+
128
+ You may use one of these, you may use several, it is unlikely you will use all of them. Use your judgement and don't overwhelm the user.
@@ -0,0 +1,2 @@
1
+ policy:
2
+ allow_implicit_invocation: false
@@ -0,0 +1,36 @@
1
+ ---
2
+ name: statechart
3
+ description: "Draw how any system moves between states, such as a product flow, a protocol, or a service, as a Mermaid statechart from a TLA+ model. Each bug is a numbered path with blue borders to a state that breaks a rule. Use for /statechart, to show a bug as a path through states, or to turn an agreed chart into a TLA+ skeleton."
4
+ disable-model-invocation: true
5
+ ---
6
+
7
+ # Statechart
8
+
9
+ The chart shows how a system moves between states, in the words of the person who reads it. The scripts call that person the reader, as in `readerActions` and reader steps. The reader decides whether the behavior is right. The reader can be a PM who reads a product flow, an engineer who reads a protocol or a service, or a reviewer who reads a design. Label each state with what the reader can observe or cares about, such as "Paying" in an app or "Lease held, write pending" in a lock service. Label each step with the event that moves the system, such as "tap Pay" in an app, "the request reads the count" in a service, or "the lease expires" in a lock service. Keep variable and action names out of labels.
10
+
11
+ Run `node <skill dir>/scripts/statechart.mjs --help` for the commands and for how to read a chart. Work in a scratch folder outside the repo. The command writes its files next to its input. The first run installs TLC and Java with mise, which downloads about 305 MB and needs the network. The help's TLC section tells how to use a TLC and Java that you have.
12
+
13
+ ## Pick the direction
14
+
15
+ Use `from-spec` when a TLA+ model exists, or when the code or design is concrete enough to model. Use `from-chart` when there is no model, and the people who own the behavior should agree on it before anyone builds or changes it.
16
+
17
+ If the code already has a TLA+ spec, start from a copy of that spec. Add the variables that the labels and rules need, and keep the spec's existing invariants. To audit the code against that spec, make the copy model what the code does, and pass the spec unchanged as `--against`. Check it with the config that its authors say it passes, and pass that config as `--against-config` unless it has the spec's file name. One mapping labels both models, so label states and steps from variables that both have. A label that reads a variable that only the copy has must test `"name" in v` first, and label the spec's states another way. When a model describes code, tie every variable and action to code that a reviewer can open, and take its name from that code. Make each action one indivisible step in the code. Put the file and line of the code that checks each condition of an action in a comment on that condition, as in `\* pay.ts:120`.
18
+
19
+ ## Spec to chart
20
+
21
+ 1. Choose the chart's states. When the reader cares about something that a label would hide, put it in the label, such as "Paying, charged twice" when the screen still says "Paying" after a second charge. Start with few states. Split a state when the split separates two bugs, or when the reader must see a step that leaves the label the same, such as a request that reads a count, because the chart does not draw such a step.
22
+ 2. Write each rule that the reader agrees to as one invariant, with the reader's sentence as its comment. A rule can be about any state in the model: what a screen shows, what a request returns, a stored value, or a message between parts. When the model describes code, the rule also names the code that can change that state. If the model has no variable for what a rule is about, add the variable. Do not drop the rule. For a rule that applies once everything settles, define `Settled == ~ENABLED System`, where `System` is the disjunction of the actions that happen without the reader. For a rule that applies at a narrower point, such as after each request finishes, write a predicate for that point and make the rule hold where it is true. For a goal that the system must be able to reach, write a rule that says the goal never happens, and pass that rule with `--expect-broken`. The path that breaks it is then a way to the goal. The chart still draws the goal as a state that breaks a rule, and `stories.md` tells it as a bug, so name each goal rule in the hand-off. Report each other broken rule as a bug. Never weaken a rule to make the chart pass.
23
+ 3. Run `from-spec`, then fill in the mapping file it writes. Put the labels in `state` and `step`. When the chart must separate what the reader does from what happens around the reader, list the reader's actions in `readerActions` by action name. Leave the list empty when every action counts the same. When the overview is too large to read, add `--cover`. The overview then keeps only the shortest path to each settled state, plus every bug path, and the command lists what it leaves out. When two bugs end in the same state for different reasons, add `cause` and make it name each reason. To color the states by what the reader cares about, such as "Order shipped", return that group from `group`. The legend names the groups, and in the PNG a state that breaks a rule is red in place of its group color.
24
+ 4. If there is a proposed fix, model it and pass that model as `--fixed`.
25
+ 5. Render each chart with `--png` and look at every PNG. Check that each numbered path reads in order. If a label reads like code, fix `state` or `step` and run the command again.
26
+ 6. When the model describes code, replay each bug's story against the real code, as a test or a live repro, one step per model action. Drive only entry points that a user, a client, or another part of the system reaches, and assert only what they can observe. A test that asserts a flag that it sets, or that searches the source text, proves nothing. When a run proves part of the story and reading the code proves the rest, say which part each proves. When the test copies code that it cannot import, give the commit and line range of the copy, and list what the copy leaves out. If a bug does not reproduce, assume the model is wrong until you show otherwise. Fix the model, not the rule. For a design with no code yet, the TLC trace is the evidence, and the hand-off must say so.
27
+
28
+ ## Chart to spec
29
+
30
+ 1. Draw the chart that the reader agrees to. Use one region for each part that changes independently, such as a device's connection and the job that the device runs. Add one `%% never` line per rule, with the reader's sentence. Draw an event that stops or restarts a part, such as "the app closes" or "the process restarts", as an edge to the state that comes next. Run `render CHART.mmd` to get a PNG of the chart for the reader.
31
+ 2. Run `from-chart`. If a rule breaks, the agreed chart has a design bug. Take the bug to the people who agreed to the chart.
32
+ 3. Add the real code's guards and variables to the spec that `from-chart` wrote, and run `from-chart` again. For each difference it prints, ask the reader whether the code is wrong or the chart needs a correction.
33
+
34
+ ## Hand off
35
+
36
+ Give the PNG and the Mermaid source of each chart to the person who must decide. Add one line per bug with the rule it breaks, its steps as the chart numbers them, whether it reproduced, and whether the proposed fix fixes it. A broken PROPERTY has no path on the chart, so give the TLC counterexample that `stories.md` names for it. With `--against`, also say whether the spec already lists it: in the configs that `stories.md` names, in the spec's notes on what the model leaves out, or not at all. When the model describes code, do not report that a rule holds while the command lists conditions with no file and line. Take every count you quote from `summary.json`. Attach `stories.md` and the command that regenerates everything. Say what the model leaves out.
@@ -0,0 +1,81 @@
1
+ import fs from "node:fs";
2
+ import { BROKEN_MARK, parseValue, stateKey } from "./lib.mjs";
3
+ import { SEP } from "./chart-parts.mjs";
4
+
5
+ export function firstBad(raw) {
6
+ const badStates = new Map();
7
+ for (const t of raw) {
8
+ if (!badStates.has(t.invariant)) badStates.set(t.invariant, new Set());
9
+ badStates.get(t.invariant).add(stateKey(t.steps[t.steps.length - 1].vars));
10
+ }
11
+ const cuts = [];
12
+ const seen = new Set();
13
+ for (const t of raw) {
14
+ const first = t.steps.findIndex((s) => badStates.get(t.invariant).has(stateKey(s.vars)));
15
+ const cut = { invariant: t.invariant, steps: t.steps.slice(0, first + 1) };
16
+ const id = `${t.invariant}${SEP}${stateKey(cut.steps[cut.steps.length - 1].vars)}`;
17
+ if (seen.has(id)) continue;
18
+ seen.add(id);
19
+ cuts.push(cut);
20
+ }
21
+ return cuts;
22
+ }
23
+
24
+ export const byOrder = (a, b) =>
25
+ a.steps - b.steps ||
26
+ a.trace.steps.length - b.trace.steps.length ||
27
+ (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
28
+
29
+ const lastKey = (t) => stateKey(t.steps[t.steps.length - 1].vars);
30
+ export const badOf = (raw, rule) => new Set(raw.filter((t) => t.invariant === rule).map(lastKey));
31
+ export function reachableAvoiding({ graph: g, stateKeys }, bad) {
32
+ const ok = (id) => !bad.has(stateKeys.get(id));
33
+ const next = new Map();
34
+ for (const e of g.edges) {
35
+ if (!next.has(e.from)) next.set(e.from, []);
36
+ next.get(e.from).push(e.to);
37
+ }
38
+ const clean = new Set([...g.nodes.values()].filter((n) => n.init && ok(n.id)).map((n) => n.id));
39
+ for (const id of clean) for (const to of next.get(id) ?? []) if (ok(to)) clean.add(to);
40
+ return clean;
41
+ }
42
+
43
+ export const diverges = (c) => c.second?.key !== undefined;
44
+ export function readBroken(file) {
45
+ if (!file) return [];
46
+ const lines = fs.readFileSync(file, "utf8").split("\n");
47
+ const marked = new RegExp(`^<<\\s*"${BROKEN_MARK}",`);
48
+ const out = [];
49
+ for (let i = 0; i < lines.length; i++) {
50
+ if (!marked.test(lines[i])) continue;
51
+ let text = lines[i];
52
+ while (typeof parseValue(text) === "string" && i + 1 < lines.length) text += `\n${lines[++i]}`;
53
+ const [, vars, broken] = parseValue(text);
54
+ out.push({ key: stateKey(vars), rules: broken });
55
+ }
56
+ return out;
57
+ }
58
+ export const badStates = (raw, broken, counts = () => true) =>
59
+ new Set([
60
+ ...raw.filter((t) => counts(t.invariant)).map(lastKey),
61
+ ...broken.filter((b) => b.rules.some(counts)).map((b) => b.key),
62
+ ]);
63
+ export function labelStatus(m, keys, bad) {
64
+ const good = reachableAvoiding(m, bad);
65
+ const kinds = new Map();
66
+ for (const n of m.graph.nodes.values()) {
67
+ const k = keys.get(n.id);
68
+ if (!kinds.has(k)) kinds.set(k, new Set());
69
+ kinds.get(k).add(bad.has(m.stateKeys.get(n.id)) ? "bad" : good.has(n.id) ? "good" : "after");
70
+ }
71
+ return (k) => {
72
+ const has = kinds.get(k);
73
+ if (!has) return undefined;
74
+ if (has.has("bad")) return has.has("good") ? "mixed" : "wrong";
75
+ return has.has("good") ? "works" : "after";
76
+ };
77
+ }
78
+
79
+ export const RANK = ["works", "fixed", "after", "mixed", "wrong", "worse"];
80
+ export const worst = (...all) =>
81
+ all.filter(Boolean).reduce((a, b) => (RANK.indexOf(b) > RANK.indexOf(a) ? b : a), "works");