@joplo-app/core 0.2.12 → 0.2.13

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.
@@ -65,10 +65,14 @@ function joploBody() {
65
65
  ...list(START_ORDER).map(line => line.replace(/^(\d+)/, (_, n) => String(Number(n) + 1))),
66
66
  `${START_ORDER.length + 2}. When the user asks to share or publish: npx joplo share --format json (picked options), or npx joplo share --review for reviewers comparing every option. Confirmation of a local option alone does not request publication. To share only part of the project, add --scenario <scenario id> or --feature <feature id> (repeatable): everything else stays out of the uploaded files; tell the user about any data.scope.borrowed items. Apply review results with the joplo-feedback skill.`,
67
67
  '',
68
+ 'When a product uses Joplo to design itself, keep one project with stable feature IDs and multiple options/scenarios (repository example: examples/joplo). Preserve actual evidence and label historical reconstructions; never invent review or approval history. Public design narration must be explicitly curated into visible scenarios because build strips private authoring fields. See npx joplo skill authoring. For authorized CI publication, separate PR comparison previews from the fixed main share, isolate credentials from author-code builds, and verify actual workflow runs after activation; see npx joplo skill diff.',
69
+ '',
70
+ 'For comparing feature changes across versions or a PR, read npx joplo skill diff. Preserve stable .key() identities, treat repeated candidates as uncertain, and build two real publish versions. If an embedded player changes scenario independently, use Realign and wait for both target positions before resuming. Use prepare → uncredentialed build → trusted publish only within the user’s authorized scope.',
71
+ '',
68
72
  '## Common pitfalls',
69
73
  ...PITFALLS.map(([text, topic]) => `- ${text}. See npx joplo skill ${topic}.`),
70
74
  '',
71
- 'Exact APIs: npx joplo skill <topic> prints guidance matching the installed version (authoring, story, demo, focus, diagram, components, cases, check, selection, review, publish). Run npx joplo skill for the overview; npx joplo components <Name> shows props and an example.',
75
+ 'Exact APIs: npx joplo skill <topic> prints guidance matching the installed version (authoring, story, demo, focus, diagram, components, cases, check, selection, review, diff, publish). Run npx joplo skill for the overview; npx joplo components <Name> shows props and an example.',
72
76
  'After the user Alt+clicks a board element, run npx joplo selection and edit only that location.',
73
77
  'Pin these skills to a release: npx skills add https://github.com/Joplo-app/Joplo/tree/v<version> (Joplo-app/Joplo@v<version> does not work).',
74
78
  ].join('\n');
package/dist/compile.js CHANGED
@@ -394,7 +394,15 @@ export function compile(src, mode, opts = {}) {
394
394
  // 镜头状态(与 player.cameraAt 同一规则,逐步累积):判断焦点提示的目标在不在当前镜头里(D70)
395
395
  const frame = new Map();
396
396
  let director = hasLayers ? Object.keys(layers)[0] : PAGE_LAYER;
397
+ const stepKeys = new Set();
397
398
  const steps = fl.steps.map((st, i) => {
399
+ if (st.key !== undefined) {
400
+ if (!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(st.key))
401
+ err('STEP_KEY_INVALID', 'Step key must start with a letter and contain at most 64 letters, digits, underscores or hyphens', st.source);
402
+ if (stepKeys.has(st.key))
403
+ err('STEP_KEY_DUPLICATE', `Duplicate step key ${st.key} in ${sid}; use a distinct key for each action`, st.source);
404
+ stepKeys.add(st.key);
405
+ }
398
406
  const effects = [];
399
407
  const ruleIds = [];
400
408
  const explains = [];
@@ -590,6 +598,7 @@ export function compile(src, mode, opts = {}) {
590
598
  const generated = st.caption === undefined ? autoCaption(st, (hasLayers && actionTarget ? layerSceneWith(actionTarget) : undefined) ?? sceneBefore) : null;
591
599
  return {
592
600
  id: `${sid}#${i + 1}`,
601
+ ...(st.key !== undefined ? { key: st.key } : {}),
593
602
  kind: st.kind,
594
603
  action: st.action,
595
604
  caption: st.caption ?? generated.caption,
@@ -0,0 +1,188 @@
1
+ /** Public feature comparison. Positional ids are addresses, never cross-version identities. */
2
+ import { z } from 'zod';
3
+ import { Project, type Step } from './schema.js';
4
+ export declare const GitSha: z.ZodString;
5
+ export declare const DiffSource: z.ZodObject<{
6
+ sha: z.ZodNullable<z.ZodString>;
7
+ }, z.core.$strict>;
8
+ export declare const DiffStep: z.ZodObject<{
9
+ before: z.ZodNullable<z.ZodObject<{
10
+ id: z.ZodString;
11
+ position: z.ZodNumber;
12
+ key: z.ZodOptional<z.ZodString>;
13
+ caption: z.ZodOptional<z.ZodString>;
14
+ }, z.core.$strict>>;
15
+ after: z.ZodNullable<z.ZodObject<{
16
+ id: z.ZodString;
17
+ position: z.ZodNumber;
18
+ key: z.ZodOptional<z.ZodString>;
19
+ caption: z.ZodOptional<z.ZodString>;
20
+ }, z.core.$strict>>;
21
+ status: z.ZodEnum<{
22
+ added: "added";
23
+ modified: "modified";
24
+ removed: "removed";
25
+ unchanged: "unchanged";
26
+ uncertain: "uncertain";
27
+ }>;
28
+ match: z.ZodEnum<{
29
+ action: "action";
30
+ key: "key";
31
+ none: "none";
32
+ uncertain: "uncertain";
33
+ content: "content";
34
+ }>;
35
+ reasons: z.ZodArray<z.ZodString>;
36
+ results: z.ZodOptional<z.ZodArray<z.ZodObject<{
37
+ kind: z.ZodEnum<{
38
+ state: "state";
39
+ outcome: "outcome";
40
+ message: "message";
41
+ }>;
42
+ label: z.ZodString;
43
+ before: z.ZodNullable<z.ZodString>;
44
+ after: z.ZodNullable<z.ZodString>;
45
+ }, z.core.$strict>>>;
46
+ }, z.core.$strict>;
47
+ export declare const DiffScenario: z.ZodObject<{
48
+ featureId: z.ZodString;
49
+ featureName: z.ZodString;
50
+ name: z.ZodString;
51
+ before: z.ZodNullable<z.ZodString>;
52
+ after: z.ZodNullable<z.ZodString>;
53
+ status: z.ZodEnum<{
54
+ added: "added";
55
+ modified: "modified";
56
+ removed: "removed";
57
+ unchanged: "unchanged";
58
+ uncertain: "uncertain";
59
+ }>;
60
+ reasons: z.ZodArray<z.ZodString>;
61
+ steps: z.ZodArray<z.ZodObject<{
62
+ before: z.ZodNullable<z.ZodObject<{
63
+ id: z.ZodString;
64
+ position: z.ZodNumber;
65
+ key: z.ZodOptional<z.ZodString>;
66
+ caption: z.ZodOptional<z.ZodString>;
67
+ }, z.core.$strict>>;
68
+ after: z.ZodNullable<z.ZodObject<{
69
+ id: z.ZodString;
70
+ position: z.ZodNumber;
71
+ key: z.ZodOptional<z.ZodString>;
72
+ caption: z.ZodOptional<z.ZodString>;
73
+ }, z.core.$strict>>;
74
+ status: z.ZodEnum<{
75
+ added: "added";
76
+ modified: "modified";
77
+ removed: "removed";
78
+ unchanged: "unchanged";
79
+ uncertain: "uncertain";
80
+ }>;
81
+ match: z.ZodEnum<{
82
+ action: "action";
83
+ key: "key";
84
+ none: "none";
85
+ uncertain: "uncertain";
86
+ content: "content";
87
+ }>;
88
+ reasons: z.ZodArray<z.ZodString>;
89
+ results: z.ZodOptional<z.ZodArray<z.ZodObject<{
90
+ kind: z.ZodEnum<{
91
+ state: "state";
92
+ outcome: "outcome";
93
+ message: "message";
94
+ }>;
95
+ label: z.ZodString;
96
+ before: z.ZodNullable<z.ZodString>;
97
+ after: z.ZodNullable<z.ZodString>;
98
+ }, z.core.$strict>>>;
99
+ }, z.core.$strict>>;
100
+ }, z.core.$strict>;
101
+ export declare const FeatureDiffManifest: z.ZodObject<{
102
+ formatVersion: z.ZodLiteral<1>;
103
+ kind: z.ZodLiteral<"joplo-feature-diff">;
104
+ base: z.ZodObject<{
105
+ sha: z.ZodNullable<z.ZodString>;
106
+ }, z.core.$strict>;
107
+ head: z.ZodObject<{
108
+ sha: z.ZodNullable<z.ZodString>;
109
+ }, z.core.$strict>;
110
+ status: z.ZodEnum<{
111
+ unchanged: "unchanged";
112
+ uncertain: "uncertain";
113
+ changed: "changed";
114
+ incompatible: "incompatible";
115
+ }>;
116
+ reasons: z.ZodArray<z.ZodString>;
117
+ summary: z.ZodObject<{
118
+ added: z.ZodArray<z.ZodString>;
119
+ modified: z.ZodArray<z.ZodString>;
120
+ removed: z.ZodArray<z.ZodString>;
121
+ }, z.core.$strict>;
122
+ scenarios: z.ZodArray<z.ZodObject<{
123
+ featureId: z.ZodString;
124
+ featureName: z.ZodString;
125
+ name: z.ZodString;
126
+ before: z.ZodNullable<z.ZodString>;
127
+ after: z.ZodNullable<z.ZodString>;
128
+ status: z.ZodEnum<{
129
+ added: "added";
130
+ modified: "modified";
131
+ removed: "removed";
132
+ unchanged: "unchanged";
133
+ uncertain: "uncertain";
134
+ }>;
135
+ reasons: z.ZodArray<z.ZodString>;
136
+ steps: z.ZodArray<z.ZodObject<{
137
+ before: z.ZodNullable<z.ZodObject<{
138
+ id: z.ZodString;
139
+ position: z.ZodNumber;
140
+ key: z.ZodOptional<z.ZodString>;
141
+ caption: z.ZodOptional<z.ZodString>;
142
+ }, z.core.$strict>>;
143
+ after: z.ZodNullable<z.ZodObject<{
144
+ id: z.ZodString;
145
+ position: z.ZodNumber;
146
+ key: z.ZodOptional<z.ZodString>;
147
+ caption: z.ZodOptional<z.ZodString>;
148
+ }, z.core.$strict>>;
149
+ status: z.ZodEnum<{
150
+ added: "added";
151
+ modified: "modified";
152
+ removed: "removed";
153
+ unchanged: "unchanged";
154
+ uncertain: "uncertain";
155
+ }>;
156
+ match: z.ZodEnum<{
157
+ action: "action";
158
+ key: "key";
159
+ none: "none";
160
+ uncertain: "uncertain";
161
+ content: "content";
162
+ }>;
163
+ reasons: z.ZodArray<z.ZodString>;
164
+ results: z.ZodOptional<z.ZodArray<z.ZodObject<{
165
+ kind: z.ZodEnum<{
166
+ state: "state";
167
+ outcome: "outcome";
168
+ message: "message";
169
+ }>;
170
+ label: z.ZodString;
171
+ before: z.ZodNullable<z.ZodString>;
172
+ after: z.ZodNullable<z.ZodString>;
173
+ }, z.core.$strict>>>;
174
+ }, z.core.$strict>>;
175
+ }, z.core.$strict>>;
176
+ }, z.core.$strict>;
177
+ export type FeatureDiffManifest = z.infer<typeof FeatureDiffManifest>;
178
+ export type DiffScenario = z.infer<typeof DiffScenario>;
179
+ export type DiffStep = z.infer<typeof DiffStep>;
180
+ /** Canonical object ordering; arrays preserve execution order. */
181
+ export declare function canonical(value: unknown): string;
182
+ export declare function compareSteps(before: Step[], after: Step[]): DiffStep[];
183
+ /** Refuse private IR instead of projecting potentially private unknown fields into a public comparison. */
184
+ export declare function readPublicProject(value: unknown): Project;
185
+ export declare function featureDiff(before: unknown, after: unknown, source?: {
186
+ baseSha?: string;
187
+ headSha?: string;
188
+ }): FeatureDiffManifest;
@@ -0,0 +1,236 @@
1
+ /** Public feature comparison. Positional ids are addresses, never cross-version identities. */
2
+ import { z } from 'zod';
3
+ import { Project } from "./schema.js";
4
+ import { JoploError } from "./result.js";
5
+ export const GitSha = z.string().regex(/^[a-f0-9]{40}$/);
6
+ export const DiffSource = z.strictObject({ sha: GitSha.nullable() });
7
+ /** caption is the public step caption, shown so readers can tell which step changed without playing it. */
8
+ const Ref = z.strictObject({ id: z.string(), position: z.number().int().positive(), key: z.string().optional(), caption: z.string().max(300).optional() });
9
+ /**
10
+ * What a reader can see change when the step runs: state values written by set/stream/append,
11
+ * toast text and the scenario outcome. null = this version's step does not produce it.
12
+ */
13
+ const Result = z.strictObject({ kind: z.enum(['state', 'message', 'outcome']), label: z.string().max(120), before: z.string().max(200).nullable(), after: z.string().max(200).nullable() });
14
+ const Status = z.enum(['added', 'modified', 'removed', 'unchanged', 'uncertain']);
15
+ export const DiffStep = z.strictObject({
16
+ before: Ref.nullable(), after: Ref.nullable(), status: Status,
17
+ match: z.enum(['key', 'content', 'action', 'none', 'uncertain']), reasons: z.array(z.string()),
18
+ results: z.array(Result).max(12).optional(),
19
+ });
20
+ export const DiffScenario = z.strictObject({
21
+ featureId: z.string(), featureName: z.string(), name: z.string(),
22
+ before: z.string().nullable(), after: z.string().nullable(), status: Status,
23
+ reasons: z.array(z.string()), steps: z.array(DiffStep),
24
+ });
25
+ export const FeatureDiffManifest = z.strictObject({
26
+ formatVersion: z.literal(1), kind: z.literal('joplo-feature-diff'),
27
+ base: DiffSource, head: DiffSource,
28
+ status: z.enum(['changed', 'unchanged', 'uncertain', 'incompatible']),
29
+ reasons: z.array(z.string()),
30
+ summary: z.strictObject({ added: z.array(z.string().max(200)).max(100), modified: z.array(z.string().max(200)).max(100), removed: z.array(z.string().max(200)).max(100) }),
31
+ scenarios: z.array(DiffScenario),
32
+ });
33
+ /** Canonical object ordering; arrays preserve execution order. */
34
+ export function canonical(value) {
35
+ if (Array.isArray(value))
36
+ return `[${value.map(canonical).join(',')}]`;
37
+ if (value && typeof value === 'object')
38
+ return `{${Object.entries(value).filter(([, v]) => v !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(',')}}`;
39
+ return JSON.stringify(value) ?? 'null';
40
+ }
41
+ const stepContent = ({ id: _id, key: _key, source: _source, ruleIds: _rules, ...rest }) => rest;
42
+ const identity = (s) => {
43
+ const a = s.action;
44
+ return canonical([s.kind, a.type, 'target' in a ? a.target : 'name' in a ? a.name : 'keys' in a ? a.keys : 'title' in a ? a.title : null]);
45
+ };
46
+ const ref = (s, index) => ({ id: s.id, position: index + 1, ...(s.key ? { key: s.key } : {}), caption: s.caption.slice(0, 300) });
47
+ /** Presentation-only step fields, grouped into reader-facing reasons. Unlisted content changes fall back to 'presentation'. */
48
+ const PRESENTATION = [
49
+ ['caption', ['caption', 'captionAuto']], ['explain', ['explain']], ['camera', ['shots', 'directorLayer']],
50
+ ['annotations', ['marks', 'cues', 'callouts']], ['voice', ['say', 'narrate']], ['timing', ['hold']],
51
+ ['trace', ['traces']], ['forks', ['forks']], ['kind', ['kind']],
52
+ ];
53
+ const KIND_ORDER = { state: 0, message: 1, outcome: 2 };
54
+ const shown = (v) => (typeof v === 'string' ? v : canonical(v)).slice(0, 200);
55
+ /** Final visible value per result slot; the last write in a step wins, appends and toasts accumulate. */
56
+ function resultSlots(effects) {
57
+ const slots = new Map();
58
+ const add = (key, kind, label, value, accumulate = false) => {
59
+ const prev = slots.get(key);
60
+ slots.set(key, { kind, label, value: (accumulate && prev ? `${prev.value} · ${value}` : value).slice(0, 200) });
61
+ };
62
+ for (const e of effects) {
63
+ if (e.type === 'set' || e.type === 'stream')
64
+ add(`s:${e.path}`, 'state', e.path, shown(e.value));
65
+ else if (e.type === 'append')
66
+ add(`a:${e.path}`, 'state', `${e.path} +`, shown(e.value), true);
67
+ else if (e.type === 'toast')
68
+ add('toast', 'message', 'toast', e.text, true);
69
+ else if (e.type === 'complete')
70
+ add('done', 'outcome', 'done', e.outcome === 'success' ? e.text : `${e.text} (${e.outcome})`);
71
+ }
72
+ return slots;
73
+ }
74
+ function resultChanges(before, after) {
75
+ const b = resultSlots(before), a = resultSlots(after);
76
+ const keys = [...new Set([...a.keys(), ...b.keys()])];
77
+ return keys
78
+ .map(k => ({ slot: (a.get(k) ?? b.get(k)), before: b.get(k)?.value ?? null, after: a.get(k)?.value ?? null }))
79
+ .filter(r => r.before !== r.after)
80
+ .sort((x, y) => KIND_ORDER[x.slot.kind] - KIND_ORDER[y.slot.kind])
81
+ .slice(0, 12)
82
+ .map(r => ({ kind: r.slot.kind, label: r.slot.label.slice(0, 120), before: r.before, after: r.after }));
83
+ }
84
+ const groups = (steps, fn) => {
85
+ const map = new Map();
86
+ steps.forEach((s, i) => { const k = fn(s); map.set(k, [...(map.get(k) ?? []), i]); });
87
+ return map;
88
+ };
89
+ export function compareSteps(before, after) {
90
+ const pairs = new Map();
91
+ const used = new Set();
92
+ const uncertainBefore = new Set(), uncertainAfter = new Set();
93
+ // Shared keys are authoritative. Different explicit keys never fall back to each other.
94
+ for (const [key, bs] of groups(before, s => s.key ?? '')) {
95
+ if (!key)
96
+ continue;
97
+ const as = groups(after, s => s.key ?? '').get(key) ?? [];
98
+ if (bs.length === 1 && as.length === 1) {
99
+ pairs.set(as[0], { index: bs[0], match: 'key' });
100
+ used.add(bs[0]);
101
+ }
102
+ else if (bs.length > 1 || as.length > 1) {
103
+ bs.forEach(i => uncertainBefore.add(i));
104
+ as.forEach(i => uncertainAfter.add(i));
105
+ }
106
+ }
107
+ for (const [key, as] of groups(after, s => s.key ?? ''))
108
+ if (key && as.length > 1)
109
+ as.forEach(i => uncertainAfter.add(i));
110
+ for (const [fn, match] of [[(s) => canonical(stepContent(s)), 'content'], [identity, 'action']]) {
111
+ const bg = groups(before, fn), ag = groups(after, fn);
112
+ for (const [key, bs] of bg) {
113
+ const as = ag.get(key) ?? [];
114
+ const b = bs.filter(i => !used.has(i));
115
+ const a = as.filter(i => !pairs.has(i));
116
+ // Count original candidates too: matching another occurrence must not make an ambiguous one unique.
117
+ if (b.length === 1 && a.length === 1 && bs.length === 1 && as.length === 1 && !(before[b[0]].key && after[a[0]].key)) {
118
+ pairs.set(a[0], { index: b[0], match });
119
+ used.add(b[0]);
120
+ }
121
+ }
122
+ }
123
+ const bg = groups(before, identity), ag = groups(after, identity);
124
+ before.forEach((s, i) => { if (!used.has(i) && (ag.get(identity(s)) ?? []).some(j => !(s.key && after[j].key) && !pairs.has(j)))
125
+ uncertainBefore.add(i); });
126
+ after.forEach((s, i) => { if (!pairs.has(i) && (bg.get(identity(s)) ?? []).some(j => !(s.key && before[j].key) && !used.has(j)))
127
+ uncertainAfter.add(i); });
128
+ const rows = [];
129
+ const removed = new Set();
130
+ const addBefore = (i) => {
131
+ if (used.has(i) || removed.has(i))
132
+ return;
133
+ removed.add(i);
134
+ const uncertain = uncertainBefore.has(i);
135
+ rows.push({ before: ref(before[i], i), after: null, status: uncertain ? 'uncertain' : 'removed', match: uncertain ? 'uncertain' : 'none', reasons: uncertain ? ['ambiguous-match'] : ['step-removed'] });
136
+ };
137
+ after.forEach((s, j) => {
138
+ const pair = pairs.get(j);
139
+ if (!pair) {
140
+ const uncertain = uncertainAfter.has(j);
141
+ rows.push({ before: null, after: ref(s, j), status: uncertain ? 'uncertain' : 'added', match: uncertain ? 'uncertain' : 'none', reasons: uncertain ? ['ambiguous-match'] : ['step-added'] });
142
+ return;
143
+ }
144
+ for (let i = 0; i < pair.index; i++)
145
+ addBefore(i);
146
+ const old = before[pair.index];
147
+ const reasons = [];
148
+ if (canonical(old.action) !== canonical(s.action))
149
+ reasons.push('action');
150
+ if (canonical(old.effects) !== canonical(s.effects))
151
+ reasons.push('effects');
152
+ const presentation = PRESENTATION.filter(([, fields]) => fields.some(f => canonical(old[f]) !== canonical(s[f]))).map(([reason]) => reason);
153
+ reasons.push(...presentation);
154
+ if (canonical(stepContent(old)) !== canonical(stepContent(s)) && !reasons.length)
155
+ reasons.push('presentation');
156
+ if ([...pairs].some(([otherJ, other]) => (otherJ - j) * (other.index - pair.index) < 0))
157
+ reasons.push('order');
158
+ const results = reasons.includes('effects') ? resultChanges(old.effects, s.effects) : [];
159
+ rows.push({ before: ref(old, pair.index), after: ref(s, j), status: reasons.length ? 'modified' : 'unchanged', match: pair.match, reasons, ...(results.length ? { results } : {}) });
160
+ });
161
+ before.forEach((_, i) => addBefore(i));
162
+ return rows;
163
+ }
164
+ /** Refuse private IR instead of projecting potentially private unknown fields into a public comparison. */
165
+ export function readPublicProject(value) {
166
+ const parsed = Project.safeParse(value);
167
+ if (!parsed.success)
168
+ throw new JoploError('INVALID_SCHEMA', 'Invalid public playback IR; rebuild both versions with a compatible CLI');
169
+ const p = parsed.data;
170
+ if (p.mode !== 'publish')
171
+ throw new JoploError('INVALID_SCHEMA', 'Feature diff requires two publish builds, not dev or review IR');
172
+ const nodePrivate = (n) => n.source !== undefined || n.note !== undefined || (n.children ?? []).some(nodePrivate);
173
+ if (Object.keys(p.rules).length || Object.keys(p.cases).length || Object.keys(p.issues).length || p.voiceConfig ||
174
+ Object.values(p.routes).some(r => r.source) || Object.values(p.scenes).some(s => nodePrivate(s.root)) ||
175
+ Object.values(p.features).some(f => f.source || f.constraints.length || f.caseIds.length) ||
176
+ Object.values(p.options).some(o => o.source || o.decisionFocus || o.tradeoffs.length || Object.keys(o.coverage).length) ||
177
+ Object.values(p.scenarios).some(s => s.source || s.caseIds.length || s.steps.some(st => st.source || st.ruleIds.length)))
178
+ throw new JoploError('INVALID_SCHEMA', 'Private authoring data found; rebuild both sites with joplo build');
179
+ for (const [id, sc] of Object.entries(p.scenarios)) {
180
+ const op = p.options[sc.optionId];
181
+ if (sc.id !== id || !op || !p.features[op.featureId] || !p.scenes[sc.initial.sceneId] ||
182
+ Object.values(op.layers).some(l => !p.scenes[l.sceneId]) ||
183
+ sc.steps.some(st => st.effects.some(e => e.type === 'navigate' && !p.scenes[e.sceneId])) ||
184
+ new Set(sc.steps.map(st => st.id)).size !== sc.steps.length)
185
+ throw new JoploError('INVALID_REFERENCE', 'Public build contains missing or ambiguous playback references; rebuild that version');
186
+ }
187
+ return p;
188
+ }
189
+ function sceneInputs(p, s) {
190
+ const ids = new Set([s.initial.sceneId, ...Object.values(p.options[s.optionId]?.layers ?? {}).map(l => l.sceneId)]);
191
+ for (const st of s.steps)
192
+ for (const e of st.effects)
193
+ if (e.type === 'navigate')
194
+ ids.add(e.sceneId);
195
+ return [...ids].sort().map(id => p.scenes[id] ?? { missing: id });
196
+ }
197
+ export function featureDiff(before, after, source = {}) {
198
+ if ([source.baseSha, source.headSha].some(sha => sha !== undefined && !GitSha.safeParse(sha).success))
199
+ throw new JoploError('USAGE', 'Source SHAs must be normalized 40-character hexadecimal git commits');
200
+ const base = DiffSource.parse({ sha: source.baseSha ?? null }), head = DiffSource.parse({ sha: source.headSha ?? null });
201
+ const result = { formatVersion: 1, kind: 'joplo-feature-diff', base, head, status: 'unchanged', reasons: [], summary: { added: [], modified: [], removed: [] }, scenarios: [] };
202
+ if (before?.schemaVersion !== 2 || after?.schemaVersion !== 2)
203
+ return { ...result, status: 'incompatible', reasons: ['schema-version'] };
204
+ const b = readPublicProject(before), a = readPublicProject(after);
205
+ for (const id of new Set([...Object.keys(a.scenarios), ...Object.keys(b.scenarios)])) {
206
+ const old = b.scenarios[id], next = a.scenarios[id], s = next ?? old, p = next ? a : b;
207
+ const option = p.options[s.optionId], feature = p.features[option?.featureId ?? ''];
208
+ if (!feature)
209
+ throw new JoploError('INVALID_SCHEMA', 'Scenario references a missing public feature');
210
+ const steps = compareSteps(old?.steps ?? [], next?.steps ?? []), reasons = [];
211
+ let status = !old ? 'added' : !next ? 'removed' : 'unchanged';
212
+ if (old && next) {
213
+ const bo = b.options[old.optionId], bf = b.features[bo.featureId];
214
+ if (canonical(old.initial) !== canonical(next.initial))
215
+ reasons.push('initial-state');
216
+ if (canonical(sceneInputs(b, old)) !== canonical(sceneInputs(a, next)))
217
+ reasons.push('scenes');
218
+ if (canonical([b.theme, b.themes, b.autoFocus]) !== canonical([a.theme, a.themes, a.autoFocus]))
219
+ reasons.push('theme');
220
+ if (canonical([bo?.layers, bf?.roles]) !== canonical([option?.layers, feature.roles]))
221
+ reasons.push('layers-roles');
222
+ if (canonical([old.name, old.description, old.expected, old.mock, bf?.name, bf?.goal, bo?.name, bo?.idea]) !== canonical([next.name, next.description, next.expected, next.mock, feature.name, feature.goal, option?.name, option?.idea]))
223
+ reasons.push('description');
224
+ status = steps.some(st => st.status === 'uncertain') ? 'uncertain' : reasons.length || steps.some(st => st.status !== 'unchanged') ? 'modified' : 'unchanged';
225
+ }
226
+ result.scenarios.push({ featureId: feature.id, featureName: feature.name, name: s.name, before: old?.id ?? null, after: next?.id ?? null, status, reasons, steps });
227
+ const group = status === 'uncertain' ? 'modified' : status;
228
+ if (group !== 'unchanged' && result.summary[group].length < 100)
229
+ result.summary[group].push(`${feature.name} / ${s.name}`.slice(0, 200));
230
+ }
231
+ // Project metadata / unused shared scenes still changed even when no scenario can display it.
232
+ if (canonical([b.name, b.description, b.features, b.options, b.scenes, b.theme, b.themes, b.routes, b.featureIds, b.autoFocus]) !== canonical([a.name, a.description, a.features, a.options, a.scenes, a.theme, a.themes, a.routes, a.featureIds, a.autoFocus]))
233
+ result.reasons.push('project-presentation');
234
+ result.status = result.scenarios.some(s => s.status === 'uncertain') ? 'uncertain' : result.reasons.length || result.scenarios.some(s => s.status !== 'unchanged') ? 'changed' : 'unchanged';
235
+ return FeatureDiffManifest.parse(result);
236
+ }
package/dist/guide.d.ts CHANGED
@@ -28,6 +28,9 @@ export declare const SKILL_TOPICS: readonly [{
28
28
  }, {
29
29
  readonly name: "review";
30
30
  readonly description: "Local live feedback, Share polling, prompt acknowledgement, session/version isolation, and recovery";
31
+ }, {
32
+ readonly name: "diff";
33
+ readonly description: "Compare public feature builds, stable step identity, uncertain matches, isolated PR CI publication";
31
34
  }, {
32
35
  readonly name: "publish";
33
36
  readonly description: "pick, build, share, review version, feedback write-back, deployment";
package/dist/guide.js CHANGED
@@ -14,20 +14,22 @@ export const SKILL_TOPICS = [
14
14
  { name: 'check', description: 'Read diagnostics, UNBOUND_INTERACTIVE, and fix the indicated file and line' },
15
15
  { name: 'selection', description: 'Edit only the element selected by the user in the board' },
16
16
  { name: 'review', description: 'Local live feedback, Share polling, prompt acknowledgement, session/version isolation, and recovery' },
17
+ { name: 'diff', description: 'Compare public feature builds, stable step identity, uncertain matches, isolated PR CI publication' },
17
18
  { name: 'publish', description: 'pick, build, share, review version, feedback write-back, deployment' },
18
19
  ];
19
20
  const related = {
20
- authoring: ['story', 'demo', 'focus', 'diagram', 'components', 'cases', 'check', 'selection', 'review', 'publish'],
21
+ authoring: ['story', 'demo', 'focus', 'diagram', 'components', 'cases', 'check', 'selection', 'review', 'publish', 'diff'],
21
22
  story: ['authoring', 'cases', 'demo', 'focus', 'check'],
22
23
  demo: ['story', 'focus', 'authoring', 'diagram', 'components', 'check', 'review', 'publish'],
23
24
  focus: ['demo', 'diagram', 'check', 'authoring'],
24
25
  diagram: ['demo', 'focus', 'components', 'check'],
25
26
  components: ['authoring', 'demo', 'focus', 'diagram', 'check'],
26
27
  cases: ['story', 'authoring', 'check'],
27
- check: ['authoring', 'selection'],
28
+ check: ['authoring', 'selection', 'diff'],
28
29
  selection: ['check', 'authoring', 'review'],
29
30
  review: ['selection', 'check', 'publish'],
30
- publish: ['demo', 'authoring', 'check', 'review'],
31
+ publish: ['diff', 'demo', 'authoring', 'check', 'review'],
32
+ diff: ['publish', 'authoring', 'demo', 'check'],
31
33
  };
32
34
  /** CLI 传入其 package.json 版本;行数来自同一次生成的主题正文。 */
33
35
  export function skillIndex(version, docs) {
@@ -237,6 +239,11 @@ ${START_ORDER.map((s, i) => `${i + 1}. ${s}`).join('\n')}
237
239
  Describe designs in TS/TSX. Source files are authoritative; Git manages versions. The board and published site consume compiled IR.
238
240
  Read only the topics needed, usually one or two at a time. See components for components, cases for questions before starting, and demo for organizing and presenting demos.
239
241
 
242
+ ## Designing your own product with Joplo
243
+ Keep one Joplo project per product and model each real product feature under features/<id>; keep alternatives as options and cases as scenarios. The repository's examples/joplo is Joplo's own design workspace: historical workbench choices, authoring, player, sharing, feedback and feature diffs. Keep those feature IDs when iterating; do not create another joplo-<feature> project for each change.
244
+
245
+ Use the actual source and decisions as evidence. Label reconstructed history and pending choices; never invent reviews or approvals. A design prototype is not proof of the production implementation. For public design histories, deliberately curate safe narration into visible scenarios: ordinary build only includes picked options and strips rules, questions, tradeoffs and private review data. Keep original alternatives in the authoring project; do not expose a private review manifest to fill in the public story. Inspect both live playback and actual exported PNGs, including opening/closing cards over terminals or diagrams; a clean DOM warning report alone cannot prove that text is unobscured.
246
+
240
247
  ## Directory conventions
241
248
  - joplo.config.ts: export default config({ name, layout: 'app', home: '/' }).
242
249
  - layouts/app.tsx: export default layout(<AppShell header={{ height: 56 }} navbar={{ width: 240, breakpoint: 'sm' }}><AppShell.Navbar>…</AppShell.Navbar><AppShell.Main><Outlet/></AppShell.Main><Slot name="overlay"/></AppShell>).
@@ -632,7 +639,7 @@ Pick relevant cases to ask the user before starting. Do not include every preset
632
639
  - usage_retry · async · How should failed billing event delivery retry with idempotency?
633
640
  - model_failed · async · How should model failure or timeout be explained and recovered from?
634
641
 
635
- ### CLI / developer tools (source: examples/joplo-dist)
642
+ ### CLI / developer tools (source: examples/joplo/features/npm)
636
643
  - first_run · main · How should a new user succeed within three commands?
637
644
  - env_old · input · How should an outdated runtime be explained and fixed?
638
645
  - version_skew · consistency · How should global and project version mismatches prompt alignment?
@@ -642,7 +649,7 @@ Pick relevant cases to ask the user before starting. Do not include every preset
642
649
  - user_modified · conflict · How should user edits be protected from overwriting?
643
650
  - offline · async · How should offline limitations and recovery be explained?
644
651
 
645
- ### Local tools / multiple projects (source: examples/joplo-board)
652
+ ### Local tools / multiple projects (source: examples/joplo/features/home)
646
653
  - first_open · main · How should a first visit with no data offer a starting point?
647
654
  - single_instance · conflict · How should an existing instance be reused instead of starting another?
648
655
  - stale_resource · lifecycle · How should records for missing directories or resources be cleaned up?
@@ -671,6 +678,8 @@ See authoring for flow and rule syntax; check for locating coverage diagnostics.
671
678
  No mobile example yet; create a separate demo when mobile is needed (D44).`,
672
679
  check: `# Joplo diagnostics: check
673
680
 
681
+ STEP_KEY_INVALID: use a letter followed by up to 63 letters/digits/underscores/hyphens. STEP_KEY_DUPLICATE: each step key must be unique within its scenario; keep the same key only for the same action across versions. See diff for identity guidance.
682
+
674
683
  Run npx joplo check [dir]. Use --option feature.option to narrow structure checks and replay; --format json gives machine output.
675
684
  The whole project still compiles. Option filtering does not hide project compilation errors. Source files load locally.
676
685
 
@@ -837,6 +846,53 @@ It reads .joplo/selection.json directly without recompiling, avoiding a whole-pa
837
846
  Edit → npx joplo check → npx joplo dev to view the board (a running board just adds the project) → user ⌥+clicks → npx joplo selection → edit only that location.
838
847
  Run check again afterward. Preserve other options, pages, and existing user decisions.
839
848
  .joplo/ is local runtime state, not the design authority. Do not commit it to Git.`,
849
+ diff: `# Joplo feature changes: diff
850
+
851
+ Use this when comparing two versions of authored feature demos, or publishing cumulative PR changes. It does not verify a real application, run pixel regression, or infer implementation from source lines.
852
+
853
+ ## Stable identity
854
+ - Give an action a key AFTER declaring it: flow('Invite').click('send', set($.ui.sending, true)).key('send-invitation').
855
+ - A key starts with a letter and has at most 64 letters, digits, underscores or hyphens. Keys are unique within one scenario. Keep a key when editing or moving the same action; use a new key for a different action. STEP_KEY_DUPLICATE / STEP_KEY_INVALID must be fixed in source.
856
+ - Existing step ids (scenario#1, scenario#2) still address playback positions. They are not stable identities across versions.
857
+ - Public playback IR keeps the old shape for strict older Readers. Stable keys are in a separate, versioned joplo-step-keys JSON script. Core validates every scenario/step reference and uniqueness before using it. Never hand-edit generated metadata.
858
+ - Old builds without keys use unique content, then unique action identity, conservatively. Repeated candidates are uncertain, never guessed from their order. Add distinct keys in both versions where practical, or review those steps separately. If only one side has keys, a unique legacy content/action match is still allowed and recorded as heuristic; different explicit keys are never paired.
859
+
860
+ ## Build a local comparison
861
+ 1. Obtain the two real source versions. Run check/build for EACH in an isolated checkout. A missing or failed baseline build must fail; never substitute an empty project.
862
+ 2. Use the SAME fixed diff-capable CLI for both source versions (do not resolve the baseline checkout's older CLI). Run npx joplo build ./before-project --out ./before-site and npx joplo build ./after-project --out ./after-site.
863
+ 3. Run npx joplo diff ./before-site ./after-site --out ./diff-site. The output directory must not exist and must be separate from the inputs. Optional --base-sha / --head-sha record normalized 40-character commit SHAs; they are required for PR publication.
864
+ 4. Open diff-site/index.html through a static server. Font responses need Access-Control-Allow-Origin: * because the nested players use opaque sandboxes (Joplo Cloud already supplies this). Check the rendered states, not only the JSON summary.
865
+
866
+ The bundle has root index.html, before/, after/ and feature-diff.json. Only publish builds are accepted; dev/review IR, private authoring fields, symlinks and project files are rejected. Incompatible IR or a missing diff-player capability marker gets a local diagnostic viewer without copied version payloads, and cannot be published.
867
+
868
+ ## Read the result
869
+ - Added scenarios play the new version full width; removed scenarios play the old version full width. Only existing modified scenarios compare both versions: by default as one large stage (Space or the version tabs flip old/new in place, so differences at the same spot stand out); Side by side shows both, and clicking a version's bar enlarges just that one. Players hide their own control bars; the diff page drives both. Unchanged scenarios are hidden until requested.
870
+ - Action, effects, captions/presentation, initial state, reachable screens/layers, roles and theme changes count. Shared screen/theme changes conservatively affect scenarios. Private rule text is intentionally outside the public comparison; an observable rule change must change effects or public presentation.
871
+ - The sidebar lists each changed scenario and, under the selected one, every change by its public step caption with old/new positions. The change card above the players says what kind of change it is: an inserted or removed step (the side without it pauses just before it), or which step fields changed (action, result effects, caption, explanation, camera, annotations, voice, timing, call trace, branches, step type, order). A changed caption is shown old vs new, and changed result values (state written by set, toast text, done outcome) are listed as old → new.
872
+ - Captions are how reviewers recognize a change without playing it. Write a distinct, specific caption for every step; repeated generic captions ("Next", "Click") make the change list unreadable.
873
+ - The viewer defaults to changed fragments. Both players rebuild ALL preceding state with goto, including unchanged steps, and confirm their positions before automatic playback continues. Switch to Full flow to inspect everything. A screen/initial/theme change exposes the whole affected scenario.
874
+ - Uncertain matches, incompatible builds, no feature changes, and project presentation changes without a playable scenario have distinct states. No changes is a successful comparison, not a build failure.
875
+ - If an embedded player changes scenario or moves independently, comparison playback stops and prior alignment confirmations expire. Use Realign: both panes must report the requested scenario AND step again, including a pane whose step did not change. A late message or returning independently does not resume playback; after alignment, press Play changes yourself. If either player fails to confirm, playback stops; Reload players or Realign retries. Initial-state comparisons show the actual screen rather than the scenario cover. Synchronized narration is muted; no dual-version speech synchronization is claimed.
876
+ - The manifest is public business data, not a private review manifest. Root HTML is a comparison viewer, not one Project. In the tested Cloud comparison integration, root HTML works while root Markdown/JSON negotiation returns 422 IR_UNAVAILABLE. Nested before/after Markdown/JSON routes return each single version's public resources; they do not expose a cross-version Agent diff model. Verify the deployed Cloud version before relying on those routes. Direct feature-diff.json is the business manifest.
877
+
878
+ ## Prepare, build, publish in isolated CI jobs
879
+ - Use a trusted fixed CLI version, installed outside the PR checkout. Never let PR code run in a job/runner holding JOPLO_API_KEY. Use a trusted default-branch workflow_run publisher and separate fresh hosted runners; keep the key in a publishing environment restricted to that branch, never in PR-editable workflows. Do not execute PR code in pull_request_target. Fork PRs without publication credentials must explicitly skip.
880
+ - In the trusted prepare job, calculate git merge-base for the candidate and run npx joplo diff prepare --repo owner/name --pr <number> --sha <current-head> --base-sha <candidate> --out comparison.json.
881
+ - The receipt contains comparisonId, generation and the pinned baseSha returned by Cloud. It contains no credential. Every prepare increments generation; do not prepare again between build and publish. Build using the RETURNED base, even after rebase/force-push. If it cannot be fetched, stop and report it.
882
+ - In the uncredentialed build job, build both SHAs, then run npx joplo diff before-site after-site --out diff-site --base-sha <receipt-base> --head-sha <receipt-head>. Pass only static artifacts to the publisher. Keep the original trusted receipt separate from build artifacts.
883
+ - In a fresh trusted publishing job with no PR checkout, run the fixed CLI directly (avoid project-local npx resolution): joplo diff publish diff-site --prepared comparison.json --repo owner/name --pr <number> --sha <current-head> --format json.
884
+ - API keys need shares:publish. The CLI validates receipt/source, recomputes the semantic manifest, verifies its hash in the upload list, then uses prepare/upload/finalize. It never executes project code in publish, includes no private review data, and never replaces a completed comparison Share. It does not downgrade failed comparisons to ordinary shares.
885
+ - Only publish when the user's existing authorization includes publication; building a local diff does not itself authorize uploading or PR comments.
886
+ - A workflow_run publisher must exist on the default branch before it can trigger. Verify the expected CI workflow ID, successful result, same-repository open PR and current head; skip stale/fork/failed runs. Select one CI event per PR head to avoid duplicate prepares. Keep the trusted receipt separate from artifacts produced by author code.
887
+ - A continuously published main design needs a pre-created fixed Share ID (Pro) owned by the CI key account (a local device session may be another account), current-head checks before preparation and each finalize attempt, and a separate main-only credential environment. Verify the real main update and a real PR preview/comment after activation; a YAML file or local test alone does not prove automation is running. If Cloud uses an account-level publish lock, queue credentialed prepare/publish jobs across PRs and main; per-PR serialization alone is insufficient. On GitHub, queue: max keeps pending jobs instead of the default replacement; recheck head after waiting. Preserve the existing npm/tag release process.
888
+
889
+ ## Failures and recovery
890
+ - PR_APP_MISSING: configure/install/link the GitHub App with repository access, then prepare again.
891
+ - PR_CLOSED: stop this publication. PR_STALE_HEAD: prepare and build the newest head against the pinned base. PR_STALE_GENERATION: a newer prepare exists; prepare and rebuild instead of reusing the old package.
892
+ - PR_MISMATCH: correct repo/number/base/head against the receipt. PR_UNAVAILABLE: retry later; never fall back to unverified publication. CONFLICT: retry a concurrent request; comparison shares must be new rather than replaced.
893
+ - AUTH_REQUIRED / AUTH_EXPIRED exit 3. USAGE exits 2. Validation, mismatch, upload and PR errors exit 1. Local unchanged/uncertain/incompatible diagnostic bundles exit 0 with their explicit manifest status; CI publish rejects incompatible bundles.
894
+ - A successful finalize may be a historical link after a newer generation wins; do not claim it is the current PR pointer without Cloud confirmation. pr.comment=failed means publication succeeded but the comment did not; Cloud handles retry.
895
+ `,
840
896
  publish: `# Joplo publishing: publish
841
897
 
842
898
  Compare cases and options in the board, then decide which option to publish for each feature.
@@ -899,6 +955,9 @@ Deploy only dist output, not author source files. MCP, comments, and collaborati
899
955
  - CI: set JOPLO_API_KEY (jpk_..., created in Settings → API keys) instead of logging in. Every cloud command then uses it; credentials.json and browser login are never touched. An invalid or revoked key returns AUTH_EXPIRED: ask the user for a new key.
900
956
  - PR previews: in GitHub Actions run npx joplo share --new --pr <number> --format json; repo, commit, and run URL come from the Actions environment. Outside Actions pass --repo owner/name. data.pr.comment "skipped" means the Joplo GitHub App is not installed; tell the user, the share itself succeeded.
901
957
 
958
+ ## Feature changes across versions
959
+ For local comparisons and PR CI, read npx joplo skill diff. It compares two real publish builds and creates one immutable bundle; ordinary share --pr remains a single preview.
960
+
902
961
  ## Review and feedback (the joplo-feedback skill has the same steps)
903
962
  - npx joplo share --review publishes the review version: every option of every feature, so reviewers can compare A/B. Rules, questions, cases, and AI assumptions still never appear in uploaded files; they go only to the review page through the request body. Plain share publishes only picked options.
904
963
  - After reviewers comment and the owner decides on the review page, run npx joplo feedback --format json (uses the review share in .joplo/cloud.json, else the main share, or --share <id>). data.decisions are decisions not yet applied; data.comments are unresolved viewer comments with scenario, step, stepId, and element.
package/dist/index.d.ts CHANGED
@@ -19,3 +19,5 @@ export * from './outline.js';
19
19
  export * from './diagram/index.js';
20
20
  export * from './voice.js';
21
21
  export * from './local-review.js';
22
+ export * from './feature-diff.js';
23
+ export * from './step-identity.js';
package/dist/index.js CHANGED
@@ -19,3 +19,5 @@ export * from "./outline.js";
19
19
  export * from "./diagram/index.js";
20
20
  export * from "./voice.js";
21
21
  export * from "./local-review.js";
22
+ export * from "./feature-diff.js";
23
+ export * from "./step-identity.js";
package/dist/schema.d.ts CHANGED
@@ -202,6 +202,7 @@ export declare const Callout: z.ZodObject<{
202
202
  }, z.core.$strict>;
203
203
  export declare const Step: z.ZodObject<{
204
204
  id: z.ZodString;
205
+ key: z.ZodOptional<z.ZodString>;
205
206
  kind: z.ZodEnum<{
206
207
  user: "user";
207
208
  system: "system";
@@ -370,6 +371,7 @@ export declare const Scenario: z.ZodObject<{
370
371
  }, z.core.$strict>;
371
372
  steps: z.ZodDefault<z.ZodArray<z.ZodObject<{
372
373
  id: z.ZodString;
374
+ key: z.ZodOptional<z.ZodString>;
373
375
  kind: z.ZodEnum<{
374
376
  user: "user";
375
377
  system: "system";
@@ -858,6 +860,7 @@ export declare const Project: z.ZodObject<{
858
860
  }, z.core.$strict>;
859
861
  steps: z.ZodDefault<z.ZodArray<z.ZodObject<{
860
862
  id: z.ZodString;
863
+ key: z.ZodOptional<z.ZodString>;
861
864
  kind: z.ZodEnum<{
862
865
  user: "user";
863
866
  system: "system";
package/dist/schema.js CHANGED
@@ -137,6 +137,8 @@ export const CALLOUT_SIDES = ['top', 'right', 'bottom', 'left'];
137
137
  export const Callout = z.strictObject({ target: z.string().min(1), text: z.string().min(1), side: z.enum(CALLOUT_SIDES).optional() });
138
138
  export const Step = z.strictObject({
139
139
  id: Qid,
140
+ /** Author identity, unique within a scenario. id remains the legacy playback address. */
141
+ key: Id.optional(),
140
142
  kind: z.enum(['user', 'system', 'card']),
141
143
  action: Action,
142
144
  caption: z.string().min(1),
@@ -0,0 +1,14 @@
1
+ /** Stable author identities are separate from public playback IR for strict legacy readers. */
2
+ import { z } from 'zod';
3
+ import { Project } from './schema.js';
4
+ export declare const StepIdentity: z.ZodObject<{
5
+ formatVersion: z.ZodLiteral<1>;
6
+ scenarios: z.ZodRecord<z.ZodString, z.ZodRecord<z.ZodString, z.ZodString>>;
7
+ }, z.core.$strict>;
8
+ export type StepIdentity = z.infer<typeof StepIdentity>;
9
+ /** Only stable keys and existing public playback addresses; no authoring metadata. */
10
+ export declare function stepIdentity(project: Project): StepIdentity | undefined;
11
+ /** Validate references and uniqueness before enriching an in-memory IR. Never mutate the serialized public IR. */
12
+ export declare function applyStepIdentity(value: unknown, metadata: unknown): Project;
13
+ /** Read inert JSON only; never execute either build. Unknown IR versions remain explicit incompatible inputs. */
14
+ export declare function readFeatureDiffBuild(html: string): unknown;
@@ -0,0 +1,70 @@
1
+ /** Stable author identities are separate from public playback IR for strict legacy readers. */
2
+ import { z } from 'zod';
3
+ import { Id, Project, Qid, SCHEMA_VERSION } from "./schema.js";
4
+ import { JoploError } from "./result.js";
5
+ export const StepIdentity = z.strictObject({
6
+ formatVersion: z.literal(1),
7
+ scenarios: z.record(Qid, z.record(Qid, Id)),
8
+ });
9
+ /** Only stable keys and existing public playback addresses; no authoring metadata. */
10
+ export function stepIdentity(project) {
11
+ const scenarios = Object.fromEntries(Object.values(project.scenarios).flatMap(s => {
12
+ const entries = s.steps.filter(st => st.key !== undefined).map(st => [st.id, st.key]);
13
+ return entries.length ? [[s.id, Object.fromEntries(entries)]] : [];
14
+ }));
15
+ if (!Object.keys(scenarios).length)
16
+ return undefined;
17
+ const identity = StepIdentity.parse({ formatVersion: 1, scenarios });
18
+ applyStepIdentity(project, identity);
19
+ return identity;
20
+ }
21
+ /** Validate references and uniqueness before enriching an in-memory IR. Never mutate the serialized public IR. */
22
+ export function applyStepIdentity(value, metadata) {
23
+ const parsed = Project.safeParse(value), parsedIdentity = StepIdentity.safeParse(metadata);
24
+ if (!parsed.success || !parsedIdentity.success)
25
+ throw new JoploError('INVALID_SCHEMA', 'Invalid or unsupported public step identity; rebuild both versions with a compatible CLI');
26
+ const project = parsed.data, identity = parsedIdentity.data;
27
+ for (const [id, keys] of Object.entries(identity.scenarios)) {
28
+ const scenario = project.scenarios[id];
29
+ if (!scenario || scenario.id !== id)
30
+ throw new JoploError('INVALID_REFERENCE', 'Step identity refers to a missing scenario');
31
+ if (new Set(scenario.steps.map(st => st.id)).size !== scenario.steps.length)
32
+ throw new JoploError('INVALID_REFERENCE', 'Step identity has ambiguous playback addresses');
33
+ for (const [stepId, key] of Object.entries(keys)) {
34
+ const step = scenario.steps.find(st => st.id === stepId);
35
+ if (!step)
36
+ throw new JoploError('INVALID_REFERENCE', 'Step identity refers to a missing step');
37
+ if (step.key !== undefined && step.key !== key)
38
+ throw new JoploError('INVALID_REFERENCE', 'Conflicting step identities');
39
+ step.key = key;
40
+ }
41
+ const all = scenario.steps.flatMap(st => st.key === undefined ? [] : [st.key]);
42
+ if (new Set(all).size !== all.length)
43
+ throw new JoploError('INVALID_REFERENCE', 'Stable step keys must be unique within each scenario');
44
+ }
45
+ return project;
46
+ }
47
+ /** Read inert JSON only; never execute either build. Unknown IR versions remain explicit incompatible inputs. */
48
+ export function readFeatureDiffBuild(html) {
49
+ const read = (id, required) => {
50
+ const matches = [...html.matchAll(new RegExp(`<script type="application/json" id="${id}">([\\s\\S]*?)<\\/script>`, 'g'))];
51
+ if (matches.length > 1 || required && matches.length !== 1)
52
+ throw new JoploError('INVALID_SCHEMA', `Expected one ${id} payload. Rebuild both versions; a missing baseline is not a new feature`);
53
+ if (!matches.length)
54
+ return undefined;
55
+ try {
56
+ return JSON.parse(matches[0][1]);
57
+ }
58
+ catch {
59
+ throw new JoploError('INVALID_SCHEMA', `Invalid ${id} JSON`);
60
+ }
61
+ };
62
+ const payload = read('joplo-ir', true);
63
+ if (!payload || typeof payload !== 'object' || !payload.project)
64
+ throw new JoploError('INVALID_SCHEMA', 'Missing public playback project');
65
+ // Future IR must reach featureDiff's explicit incompatible result, never be parsed as today's Project.
66
+ if (payload.project.schemaVersion !== SCHEMA_VERSION)
67
+ return payload.project;
68
+ const identity = read('joplo-step-keys', false);
69
+ return identity === undefined ? payload.project : applyStepIdentity(payload.project, identity);
70
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joplo-app/core",
3
- "version": "0.2.12",
3
+ "version": "0.2.13",
4
4
  "description": "Joplo 编译器、校验器与播放器(IR v2)",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -19,7 +19,7 @@
19
19
  "dist"
20
20
  ],
21
21
  "dependencies": {
22
- "@joplo-app/kit": "0.2.12",
22
+ "@joplo-app/kit": "0.2.13",
23
23
  "elkjs": "0.12.1",
24
24
  "zod": "4.6.7"
25
25
  },