Skip to content

Commit 681fec2

Browse files
fix(cli): migrate --write helper refusal names the blocking input and the site's items (#38631)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9JeHmqv6CKCkW8ewrPBLekk)_ Fixes #38319 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:做 18 升 19 升级、用命令自动改写元数据的作者,在组合多个包的项目里看到的"没写入"提示,改为点名真正挡路的那个输入和被挡住的包,并给出权限集、对象等条目的名字,而不再只给下标。 - 为什么做:替 HotCRM 的升级解决误导问题,他们 131 条提示都指向服务包,而要改的权限集其实在销售应用包里。 - 出错会怎样:只影响命令打印的提示文字,不改写任何文件、不改变哪些地方会被写入;提示措辞不好时作者仍能照路径手改,可直接撤回。 - 要你做什么:无 ## What changes `os migrate meta --write` on a `composeStacks([…])` project maps a site in `packages[N]` to input N only while every input before it is a stack literal (an earlier input could contribute any number of packages). That refusal stays exactly as it is: same sites refused, same `kind`. Only its text changes: - **The blocked package's reason names the blocker as the blocker.** When input `j` (before `N`) cannot be read, the loop in the `composedPackages` step used to let input `j`'s own refusal escape unchanged, so a site in `packages[6]` read "the value is built by `createHotCrmServiceStack(…)`, not written as a literal", which is input 0's builder and not the site's. It now reads, for the test fixture: > which input of `composeStacks(…)` built package 1 is unknown: input 0 (`ServiceStack`), before it, is not read as a stack literal (the value is built by `build(…)`, not written as a literal), so the packages it contributes cannot be counted The refusal `kind` is the one the blocking input raised, so `--json` `kind` values do not move. A site whose own input (j equal to N) is helper-built keeps naming that input's builder, as before. - **Each manual line names the items its path indexes into.** `ManualSite` gains an optional `items` (the indexed elements on the path, outermost first, each by its `name`, else `id`, else a package entry's `manifest.id` / `manifest.name`, read from the normalised stack), and the text report prints it between the site line and the `not written [kind]` line, as: where packages[1] is `com.probe.app`, objects[0] is `probe_room`. Files to read first, by risk: 1. `packages/cli/src/utils/authored-source-codemod.ts`, the `case 'composedPackages'` loop: the try now wraps `composedInput` and, for j below N only, the `manifest` lookup; j equal to N rethrows untouched, so the target's own refusal is byte-identical to before. 2. `packages/cli/src/utils/authored-source-codemod.ts`, `pathItems` / `itemName`: what counts as an item's name. 3. `packages/cli/src/commands/migrate/meta.ts`, `printWriteOutcome`: the one added line. ## Tests New case in `packages/cli/test/migrate-meta-composed.test.ts`: a two-input composition whose input 0 is built by a helper and whose input 1 carries a site. It asserts the refusal kind and the named subjects, not the prose: package 1's reason names the blocked package (package 1), the blocking input (input 0, quoted as ServiceStack) and the blocker's builder (build), and does not open with the old "the value is built by"; package 0's own reason still names its builder and no input index; the text report's line under the package-1 site names the package id com.probe.app and the object probe_room; no file is written. <details><summary>Unit layer of @objectstack/cli, build and typecheck (head 56e4c0e; the last commit after it only adds module-top imports to the test file, re-run below)</summary> ``` pnpm --filter @objectstack/cli build && pnpm --filter @objectstack/cli typecheck && pnpm --filter @objectstack/cli exec vitest run --project unit --maxWorkers=2 Test Files 449 passed (449) Tests 6428 passed (6428) os-verify-lock: VERDICT command-exit 0 ``` The integration layer is declared to CI (no spawn entry or integration-tier file is touched). </details> <details><summary>Ablation: the wrap removed, the new case goes red with the old misdirecting text</summary> `node scripts/ablation-replace.mjs` replaced the rethrow guard `if (j === seg || !(error instanceof Refusal)) throw error;` with an unconditional `throw error;` plus a marker (anchor 1 to 0, marker 0 to 1, blob changed), then ran the case: ``` AssertionError: expected 'the value is built by `build(…)`, not…' to contain 'package 1' Tests 1 failed | 8 skipped (9) ablation-replace: ok restored: blob == HEAD (120c05c) and `git diff HEAD` is empty ``` The test imports the command from `src/`, so no rebuild sits between the mutation and the run. A first attempt used a bare `throw error;` as the replacement; the tool refused it before running anything (that text already occurred 7 times, so the replacement count could not rise), and it did not count as a run. </details> ## Acceptance notes - The resolution strategy is unchanged, per the card's triage: an opaque earlier input still leaves a later package unmapped. On the reporting project the target input is itself helper-built (`createHotCrmAppStack(…)`), so even a mapped position would be refused, now naming that builder. - `items` is printed in the text report only; the `--json` `manual` rows keep their shape (`conversionId`, `path`, `kind`, `reason`). - A composition whose input list is assembled with a spread names the blocking input by index only: there is no source element to quote. ## Verification Two-minute check: `pnpm --filter @objectstack/cli exec vitest run --maxWorkers=2 test/migrate-meta-composed.test.ts`, which should show `Tests 9 passed (9)`. <details><summary>Local gate subset on head 547c0d0</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 73 commands for this diff; all 73 were run on head 547c0d0, exit codes captured before any pipe and reconciled with `--ran`: ``` Run reconciliation — 73 derived, 72 run, 1 NOT-MEASURED, 0 UNRUN. ✓ dispatch-gates --ran: 73 derived famil(ies) accounted for — 72 run, 1 NOT-MEASURED (1 DERIVED from a recorded exit 3). ``` 72 exited 0. NOT MEASURED: `node scripts/check-plugin-teardown-shape.mjs --self-test`, reason: exit 3, its positive control is pinned to a commit this shallow checkout cannot reach (checker-health self-test only; CI runs it). An earlier pass on a previous head was red on `pnpm check:test-source-alias` (the edited composed suite reached 13 dynamic imports from inside clocked cases); the last commit adds the module-top imports the gate names, as the sibling suite `migrate-meta-stored-failed.test.ts` does, and the gate is green on this head. Every other family, and the full farm, is CI's. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmSwS4mQyXWrddL4r6B)_ <!-- signed: repo:objectstack#3 · os-steve · session_01ADHkmSwS4mQyXWrddL4r6B --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent cb99e2d commit 681fec2

4 files changed

Lines changed: 161 additions & 3 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/cli': patch
3+
---
4+
5+
fix(cli): `os migrate meta --write` names the input that blocks a composed package, and the items a site sits in
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
In a `composeStacks([…])` project, a site in package N is written only while every input before it is a stack literal, because only then can the command count which input built package N. When an earlier input is built by a helper, the site is still refused (`not written [helper]`), but the reason used to be that earlier input's own one ("the value is built by `createServiceStack(…)`, not written as a literal"), which read as if that input had built the site. It now says which input of `composeStacks(…)` built package N is unknown, names the earlier input that blocks the count and why, and keeps the refusal kind. A site in a package whose own input is helper-built still names that input's builder, as before.
11+
12+
Each mechanical change left for the author is also printed with the items its path indexes into, by name, in a line such as: where packages[6] is `com.acme.sales`, permissions[3] is `sales_rep`. The path itself, the `--json` output and which sites are written do not change.

‎packages/cli/src/commands/migrate/meta.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -686,6 +686,8 @@ function printWriteOutcome(outcome: WriteOutcome, appliedCount: number): void {
686686
for (const m of plan.manual) {
687687
const a = m.application;
688688
console.log(` ${chalk.yellow('•')} ${a.path}: ${a.from} → ${a.to} ${chalk.dim(`(${a.conversionId})`)}`);
689+
// The path names its items by position; the line names them as the author does.
690+
if (m.items) console.log(chalk.dim(` where ${m.items.map((i) => `${i.at} is \`${i.name}\``).join(', ')}`));
689691
console.log(chalk.dim(` not written [${m.refusal.kind}]: ${m.refusal.reason}`));
690692
}
691693
console.log('');

‎packages/cli/src/utils/authored-source-codemod.ts‎

Lines changed: 76 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,20 @@ export interface WrittenSite {
144144
export interface ManualSite {
145145
application: MigrationApplication;
146146
refusal: CodemodRefusal;
147+
/**
148+
* The elements the site's path indexes into, by the name each goes by,
149+
* outermost first: the path names them by position only
150+
* (`packages[6].manifest.permissions[3]…`). Absent when no indexed element
151+
* on the path carries a name.
152+
*/
153+
items?: PathItem[];
154+
}
155+
156+
/** An indexed element on a site's path, and the name it goes by. */
157+
export interface PathItem {
158+
/** The indexed segment as the path spells it, e.g. `permissions[3]`. */
159+
at: string;
160+
name: string;
147161
}
148162

149163
/** One file the plan rewrites: its bytes before and after. */
@@ -257,6 +271,40 @@ export function formatPath(path: readonly Segment[]): string {
257271
return out;
258272
}
259273

274+
/**
275+
* The name an element of a collection goes by: its `name`, else its `id`, else
276+
* — for a composition's package entry, `{ manifest: … }` — its manifest's `id`
277+
* or `name`.
278+
*/
279+
function itemName(element: unknown): string | undefined {
280+
if (!isPlainObject(element)) return undefined;
281+
const own = [element.name, element.id];
282+
const manifest = element.manifest;
283+
const candidates = isPlainObject(manifest) ? [...own, manifest.id, manifest.name] : own;
284+
return candidates.find((c): c is string => typeof c === 'string' && c !== '');
285+
}
286+
287+
/** The named elements `path` (an `applied[].path`) indexes into in `stack`, outermost first. */
288+
export function pathItems(stack: unknown, path: string): PathItem[] {
289+
const items: PathItem[] = [];
290+
let node = stack;
291+
let at = '';
292+
for (const seg of parsePath(path)) {
293+
if (typeof seg === 'number') {
294+
if (!Array.isArray(node) || seg >= node.length) break;
295+
node = node[seg];
296+
at = `${at}[${seg}]`;
297+
const name = itemName(node);
298+
if (name !== undefined) items.push({ at, name });
299+
} else {
300+
if (!isPlainObject(node)) break;
301+
node = node[seg];
302+
at = seg;
303+
}
304+
}
305+
return items;
306+
}
307+
260308
/** Parse an `applied[].path` (`a.b[0].c`) into segments. */
261309
export function parsePath(path: string): Segment[] {
262310
const out: Segment[] = [];
@@ -1152,6 +1200,19 @@ class Locator {
11521200
return this.graph.resolveExpr(inputs.file, inputs.node.elements[index]!, trail);
11531201
}
11541202

1203+
/**
1204+
* Why package `seg` of a composition cannot be traced to its input: input
1205+
* `j`, before it, could not be read (`reason` is the refusal it raised), so
1206+
* the packages before `seg` cannot be counted.
1207+
*/
1208+
private unknownSource(node: Extract<SNode, { k: 'composedPackages' }>, j: number, seg: number, reason: string): string {
1209+
const { inputs } = node;
1210+
const element = inputs.k === 'array' ? inputs.node.elements[j] : undefined;
1211+
const input = inputs.k === 'array' && element ? `input ${j} (\`${this.graph.snippet(inputs.file, element)}\`)` : `input ${j}`;
1212+
return `which input of \`${node.describe}\` built package ${seg} is unknown: ${input}, before it, `
1213+
+ `is not read as a stack literal (${reason}), so the packages it contributes cannot be counted`;
1214+
}
1215+
11551216
private step(node: SNode, seg: Segment, trail: Trail, rtParent: unknown, atRoot: boolean): SNode {
11561217
const g = this.graph;
11571218
switch (node.k) {
@@ -1203,13 +1264,24 @@ class Locator {
12031264
// literal with a `manifest` and no `packages` list of its own. The
12041265
// inputs before i are read on a trail of their own — they are not
12051266
// the site, so their bindings take no part in its shared check.
1267+
//
1268+
// An input before i that cannot be read leaves the count unknown, so
1269+
// which input built package i is unknown too: the refusal names that
1270+
// input as the blocker and says so, never passing the reason it gives
1271+
// for itself off as the site's (input 0's builder is not package i's).
12061272
let input: SNode | undefined;
12071273
for (let j = 0; j <= seg; j++) {
1208-
input = this.composedInput(node.inputs, j, j === seg ? trail : new Trail());
1274+
try {
1275+
input = this.composedInput(node.inputs, j, j === seg ? trail : new Trail());
1276+
if (input.k === 'object' && j < seg) g.findProp(input, 'manifest');
1277+
} catch (error) {
1278+
if (j === seg || !(error instanceof Refusal)) throw error;
1279+
refuse(error.refusal.kind, this.unknownSource(node, j, seg, error.refusal.reason));
1280+
}
12091281
if (input.k !== 'object') {
12101282
refuse('helper', `input ${j} of \`${node.describe}\` is not written as a stack literal, so the package it contributes cannot be read`);
12111283
}
1212-
g.findProp(input, 'manifest');
1284+
if (j === seg) g.findProp(input, 'manifest');
12131285
if (writesKey(g, input, 'packages')) {
12141286
refuse('helper', `input ${j} of \`${node.describe}\` carries its own \`packages\`, so its packages are not one body each`);
12151287
}
@@ -1903,7 +1975,8 @@ export async function planAuthoredSourceWrite(input: AuthoredSourceWriteInput):
19031975
? { rewrite: input.range, status: 'manual', refusal: site.refusal }
19041976
: { rewrite: input.range, status: 'written', file: site.file, line: site.line };
19051977
} else if ('refusal' in site) {
1906-
manual.push({ application, refusal: site.refusal });
1978+
const items = pathItems(input.normalized, application.path);
1979+
manual.push({ application, refusal: site.refusal, ...(items.length > 0 ? { items } : {}) });
19071980
} else {
19081981
written.push({ application, file: site.file, line: site.line });
19091982
}

‎packages/cli/test/migrate-meta-composed.test.ts‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,21 @@ import { fileURLToPath } from 'node:url';
4646
import { stripVTControlCharacters } from 'node:util';
4747
import { applyMetaMigrations } from '@objectstack/spec/migrations';
4848
import MigrateMeta, { applyMetaMigrationsToPackages } from '../src/commands/migrate/meta.js';
49+
// The packages the command reaches through dynamic imports, loaded at module top so the
50+
// first load is paid during collection, never inside a clocked case (`check:test-source-alias`).
51+
import '@objectstack/cloud-connection';
52+
import '@objectstack/driver-sql';
53+
import '@objectstack/driver-turso';
54+
import '@objectstack/metadata';
55+
import '@objectstack/metadata-protocol';
56+
import '@objectstack/platform-objects/plugin';
57+
import '@objectstack/plugin-hono-server';
58+
import '@objectstack/plugin-security';
59+
import '@objectstack/rest';
60+
import '@objectstack/service-automation';
61+
import '@objectstack/service-datasource';
62+
import '@objectstack/service-settings';
63+
import '@objectstack/service-storage';
4964
import { loadConfig } from '../src/utils/config.js';
5065

5166
const CLI_ROOT = resolve(fileURLToPath(import.meta.url), '..', '..');
@@ -249,6 +264,62 @@ describe('a composed project migrates, and the package body’s conversion is ap
249264
expect(out.write.manual.map((m: { path: string; kind: string }) => [m.path, m.kind])).toEqual([[BODY_SITE.path, 'helper']]);
250265
expect(snapshot(dir)).toEqual(before);
251266
}, RUN_TIMEOUT);
267+
268+
// A site in a LATER package, behind an input the walk cannot read: the count
269+
// of packages before it is unknown, so its input is too. The refusal names
270+
// the unreadable input as the blocker and the package it blocks — never
271+
// input 0's builder as the site's — and the line names the items the path
272+
// indexes into (the package and the object), not only their positions.
273+
it('--write names the blocking input, the blocked package and the site’s items for a body behind an unreadable input', async () => {
274+
const dir = writeProject({
275+
...COMPOSED,
276+
'src/service.stack.ts': edit(
277+
edit(SERVICE_STACK, 'export const ServiceStack = defineStack({', 'const build = () => ({'),
278+
' ],\n});\n',
279+
' ],\n});\n\nexport const ServiceStack = defineStack(build());\n',
280+
),
281+
'src/app.stack.ts': edit(
282+
APP_STACK,
283+
"fields: { name: { type: 'text', label: 'Name' } }",
284+
"fields: { name: { type: 'text', label: 'Name' }, opens_at: { type: 'time', label: 'Opens', defaultValue: '09:00Z' } }",
285+
),
286+
});
287+
const before = snapshot(dir);
288+
const appSite = 'packages[1].manifest.objects[0].fields.opens_at.defaultValue';
289+
290+
const out = json(await runMeta(dir, ['--from', '17', '--write', '--json']));
291+
expect(out.write.files).toEqual([]);
292+
const manual = new Map<string, { kind: string; reason: string }>(
293+
out.write.manual.map((m: { path: string; kind: string; reason: string }) => [m.path, m]),
294+
);
295+
expect([...manual.keys()].sort()).toEqual([BODY_SITE.path, appSite].sort());
296+
297+
// Package 1: input 0 blocks it, named as such; package 1 is the subject.
298+
const blocked = manual.get(appSite)!;
299+
expect(blocked.kind).toBe('helper');
300+
expect(blocked.reason).toContain('package 1');
301+
expect(blocked.reason).toContain('input 0 (`ServiceStack`)');
302+
expect(blocked.reason).toContain('`build(…)`');
303+
expect(blocked.reason.startsWith('the value is built by')).toBe(false);
304+
305+
// Package 0: the site's own input built it, so its own builder is the reason.
306+
const own = manual.get(BODY_SITE.path)!;
307+
expect(own.kind).toBe('helper');
308+
expect(own.reason).toContain('`build(…)`');
309+
expect(own.reason).not.toContain('input 0');
310+
311+
const text = await runMeta(dir, ['--from', '17', '--write']);
312+
const lines = text.stdout.split('\n');
313+
// The `--write` group's bullet — the LAST one naming the site: the
314+
// applied-edits group above it prints the same line.
315+
const at = lines.reduce((hit, l, i) => (l.includes(`• ${appSite}:`) ? i : hit), -1);
316+
expect(at, text.stdout).toBeGreaterThanOrEqual(0);
317+
const where = lines.slice(at + 1, at + 3).join('\n');
318+
expect(where).toContain('packages[1] is `com.probe.app`');
319+
expect(where).toContain('objects[0] is `probe_room`');
320+
expect(where).toContain('not written [helper]');
321+
expect(snapshot(dir)).toEqual(before);
322+
}, RUN_TIMEOUT);
252323
});
253324

254325
describe('control: a one-package project is unchanged', () => {

0 commit comments

Comments
 (0)