From 90b28ccba6d3dc3074ca8d16c83bae80095c1e92 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 23:07:31 +0000 Subject: [PATCH 1/2] fix(cli): os migrate meta --write writes a moved form's destination with its source, or neither A conversion that moves content to another collection (the protocol-19 form move, its translation tails) reports the site it took the content from and names the destination only in `to`. The planner tied the destination's change to no entry, so it was never written while the source's removal was: the form was deleted from the view and written nowhere. The planner now reads an absolute destination path from `to` and joins its change to the entry, so the two are written together or left together. Claude-Session: https://claude.ai/code/session_016WV4cxRh6Sbfo2Xm49JPx6 Co-authored-by: Claude --- packages/cli/src/commands/migrate/meta.ts | 11 +- .../meta.write-form-move-39392.test.ts | 431 ++++++++++++++++++ .../cli/src/utils/authored-source-codemod.ts | 105 ++++- 3 files changed, 540 insertions(+), 7 deletions(-) create mode 100644 packages/cli/src/commands/migrate/meta.write-form-move-39392.test.ts diff --git a/packages/cli/src/commands/migrate/meta.ts b/packages/cli/src/commands/migrate/meta.ts index ef2312ca649..b18674c8033 100644 --- a/packages/cli/src/commands/migrate/meta.ts +++ b/packages/cli/src/commands/migrate/meta.ts @@ -669,6 +669,8 @@ export function writeOutcomeJson(outcome: WriteOutcome) { path: w.application.path, file: w.file, line: w.line, + // A move to another place of the stack: where its destination was written. + ...(w.movedTo ? { movedTo: w.movedTo } : {}), })), manual: plan.manual.map((m) => ({ conversionId: m.application.conversionId, @@ -842,7 +844,8 @@ function printWriteOutcome(outcome: WriteOutcome, appliedCount: number): void { console.log(''); } else { // The files holding the chain's edits; a file holding only the range is the range group's. - const chainFiles = plan.rewrites.filter((r) => plan.written.some((w) => w.file === r.file)); + // A moved item's destination counts too: it is the half that keeps the content. + const chainFiles = plan.rewrites.filter((r) => plan.written.some((w) => w.file === r.file || w.movedTo?.file === r.file)); // A partial write says so on its first line, and what it left and why (#38922). const left = plan.manual.length > 0 ? `; ${plan.manual.length} left because of ${leftBecause(plan)}, listed below` : ''; console.log(chalk.bold( @@ -853,6 +856,12 @@ function printWriteOutcome(outcome: WriteOutcome, appliedCount: number): void { for (const w of plan.written.filter((x) => x.file === r.file)) { console.log(` ${chalk.dim(`:${w.line}`)} ${w.application.path} ${chalk.dim(`(${w.application.conversionId})`)}`); } + for (const w of plan.written.filter((x) => x.movedTo?.file === r.file)) { + console.log( + ` ${chalk.dim(`:${w.movedTo!.line}`)} ${w.application.to} ← ${w.application.path} ` + + chalk.dim(`(${w.application.conversionId})`), + ); + } } console.log(''); } diff --git a/packages/cli/src/commands/migrate/meta.write-form-move-39392.test.ts b/packages/cli/src/commands/migrate/meta.write-form-move-39392.test.ts new file mode 100644 index 00000000000..f0a59071490 --- /dev/null +++ b/packages/cli/src/commands/migrate/meta.write-form-move-39392.test.ts @@ -0,0 +1,431 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `os migrate meta --from 18 --write` — a form the protocol-19 move takes out + * of `views[]` is written as a `form` item, or left where it is; never deleted + * from the source and written nowhere. + * + * ## What is pinned + * + * 1. The blank scaffold's wiring (`exportsOf(…)`, no `forms:` key): a named + * form view (`formViews.intake`) is written into a new `forms:` list in the + * stack literal, with the body the chain converted, and only then is the + * block taken out of the view file. The re-run is clean and the stack valid. + * The internal record form beside it (`form`, no link) is still deleted. + * 2. A public form and its zh-CN `submitBehavior` tail: both halves of each + * move are written — the form into `forms:`, the tail into the bundle's + * `forms['OBJECT.KEY']` — and nothing is reported unexplained. + * 3. Refuse-and-keep: where the destination cannot be written (the stack's + * `forms` is built by a call), the view file keeps its bytes, the move is + * listed `not written`, and the run says the write was partial (exit 1). + * + * In-process over the real command (`MigrateMeta.run`), against temp projects + * that link the real `@objectstack/spec`: no process is spawned and no kernel + * is booted, so this file sits in the `unit` tier. + */ + +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, relative, resolve } from 'node:path'; +import { createRequire } from 'node:module'; +import { fileURLToPath } from 'node:url'; +import { stripVTControlCharacters } from 'node:util'; +import MigrateMeta from './meta.js'; +// The packages the command reaches through dynamic imports, loaded at module top so the +// first load is paid during collection, never inside a clocked case (`check:test-source-alias`). +import '@objectstack/cloud-connection'; +import '@objectstack/driver-sql'; +import '@objectstack/driver-turso'; +import '@objectstack/metadata'; +import '@objectstack/metadata-protocol'; +import '@objectstack/platform-objects/plugin'; +import '@objectstack/plugin-hono-server'; +import '@objectstack/plugin-security'; +import '@objectstack/rest'; +import '@objectstack/service-automation'; +import '@objectstack/service-datasource'; +import '@objectstack/service-settings'; +import '@objectstack/service-storage'; + +const CLI_ROOT = resolve(fileURLToPath(import.meta.url), '..', '..', '..', '..'); +const RUN_TIMEOUT = 120_000; + +/** `packages/cli` depends on `@objectstack/spec`; resolved as a package, not a source path. */ +const requireFromCli = createRequire(import.meta.url); +const SPEC_PACKAGE_ROOT = dirname(requireFromCli.resolve('@objectstack/spec/package.json')); + +let root: string; +let specLink: string; +let caseSeq = 0; + +/** Write a fresh project (relative path → text) under the temp root; returns its directory. */ +function writeProject(files: Record): string { + const dir = join(root, `case-${++caseSeq}`); + for (const [rel, text] of Object.entries(files)) { + const path = join(dir, rel); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, text); + } + return dir; +} + +/** Every file under a project (node_modules excluded), relative path → bytes. */ +function snapshot(dir: string): Record { + const out: Record = {}; + const walk = (d: string) => { + for (const name of readdirSync(d)) { + if (name === 'node_modules') continue; + const p = join(d, name); + if (statSync(p).isDirectory()) walk(p); + else out[relative(dir, p).split('\\').join('/')] = readFileSync(p, 'utf8'); + } + }; + walk(dir); + return out; +} + +interface Run { + stdout: string; + stderr: string; + exitCode: number | undefined; +} + +/** Run the real command in-process, capturing both streams and any exit. */ +async function runMeta(dir: string, flags: string[]): Promise { + const out: string[] = []; + const err: string[] = []; + const priorExitCode = process.exitCode; + const write = vi.spyOn(process.stdout, 'write').mockImplementation(((chunk: unknown, ...rest: unknown[]) => { + out.push(String(chunk)); + const done = rest.find((r) => typeof r === 'function') as (() => void) | undefined; + done?.(); + return true; + }) as never); + const log = vi.spyOn(console, 'log').mockImplementation((...a: unknown[]) => { out.push(a.join(' ')); }); + const warn = vi.spyOn(console, 'warn').mockImplementation((...a: unknown[]) => { err.push(a.join(' ')); }); + const error = vi.spyOn(console, 'error').mockImplementation((...a: unknown[]) => { err.push(a.join(' ')); }); + let exitCode: number | undefined; + try { + await MigrateMeta.run([join(dir, 'objectstack.config.ts'), '--from', '18', ...flags], { root: CLI_ROOT }); + } catch (e: any) { + if (typeof e?.oclif?.exit !== 'number') throw e; + exitCode = e.oclif.exit; + } finally { + write.mockRestore(); + log.mockRestore(); + warn.mockRestore(); + error.mockRestore(); + if (exitCode === undefined && typeof process.exitCode === 'number' && process.exitCode !== 0) { + exitCode = process.exitCode; + } + process.exitCode = priorExitCode; + } + return { + stdout: stripVTControlCharacters(out.join('\n')), + stderr: stripVTControlCharacters(err.join('\n')), + exitCode, + }; +} + +function json(run: Run): any { + return JSON.parse(run.stdout); +} + +const sites = (list: Array<{ conversionId: string; path: string }>) => + list.map((a) => `${a.path} (${a.conversionId})`).sort(); + +beforeAll(() => { + root = mkdtempSync(join(tmpdir(), 'os-migrate-meta-form-move-')); + mkdirSync(join(root, 'node_modules', '@objectstack'), { recursive: true }); + specLink = join(root, 'node_modules', '@objectstack', 'spec'); + symlinkSync(SPEC_PACKAGE_ROOT, specLink, 'dir'); +}); + +afterAll(() => { + // Unlinked BEFORE the recursive remove, and named explicitly: this symlink + // points at the real `packages/spec`, and a cleanup must never follow it. + try { unlinkSync(specLink); } catch { /* already gone */ } + try { rmSync(root, { recursive: true, force: true }); } catch { /* ignore */ } +}); + + + +/** The 1-based line of the one line of `text` that contains `needle`. */ +function lineOf(text: string, needle: string): number { + const hits = text.split('\n').flatMap((l, i) => (l.includes(needle) ? [i + 1] : [])); + expect(hits, `expected exactly one line containing ${JSON.stringify(needle)}`).toHaveLength(1); + return hits[0]!; +} + +const EXPORTS_OF = 'const exportsOf = (barrel: M): M[keyof M][] => Object.values(barrel);'; + +/** The blank template's config, cut to what the reproduction reaches. */ +function config(opts: { imports?: string; extra?: string } = {}): string { + return `import { defineStack } from '@objectstack/spec'; +import * as objects from './src/objects'; +import * as views from './src/views'; +${opts.imports ?? ''} +${EXPORTS_OF} + +export default defineStack({ + manifest: { + id: 'com.example.blank', + namespace: 'blank', + version: '0.1.0', + type: 'app', + name: 'Blank Starter', + engines: { protocol: '^19' }, + }, + objects: exportsOf(objects), + views: exportsOf(views), +${opts.extra ?? ''}}); +`; +} + +const OBJECTS: Record = { + 'src/objects/index.ts': `export { Company } from './company.object';\n`, + 'src/objects/company.object.ts': `import { ObjectSchema, Field } from '@objectstack/spec/data'; + +export const Company = ObjectSchema.create({ + name: 'blank_company', + sharingModel: 'public_read_write', + label: 'Company', + fields: { + name: Field.text({ label: 'Company Name', required: true }), + }, +}); +`, + 'src/views/index.ts': `export { default as company } from './company.view';\n`, +}; + +/** The company view of the reproduction: a list, the internal record form, and the named form `intake`. */ +const COMPANY_VIEW = `import { defineView } from '@objectstack/spec'; + +const CompanyViews = defineView({ + list: { + label: 'All Companies', + type: 'grid', + data: { provider: 'object', object: 'blank_company' }, + columns: [{ field: 'name' }], + }, + form: { + type: 'simple', + sections: [{ fields: [{ field: 'name' }] }], + }, + formViews: { + intake: { + type: 'simple', + data: { provider: 'object', object: 'blank_company' }, + sections: [{ fields: [{ field: 'name' }] }], + }, + }, +}); + +export default CompanyViews; +`; + +/** The view file once both form sites have left it. */ +const COMPANY_VIEW_AFTER = `import { defineView } from '@objectstack/spec'; + +const CompanyViews = defineView({ + list: { + label: 'All Companies', + type: 'grid', + data: { provider: 'object', object: 'blank_company' }, + columns: [{ field: 'name' }], + }, +}); + +export default CompanyViews; +`; + +const INTAKE_FORM = { name: 'blank_company.intake', object: 'blank_company', type: 'simple', sections: [{ fields: [{ field: 'name' }] }] }; + +describe('a moved form is written as a `form` item before its view block is taken out', () => { + it('the blank scaffold: `formViews.intake` lands in a new `forms:` list, the internal record form is deleted', async () => { + const dir = writeProject({ 'objectstack.config.ts': config(), ...OBJECTS, 'src/views/company.view.ts': COMPANY_VIEW }); + const before = config(); + const run = await runMeta(dir, ['--write', '--json']); + expect(run.exitCode, run.stdout + run.stderr).toBeUndefined(); + const out = json(run); + expect(sites(out.applied)).toEqual([ + 'views[0].form (view-forms-to-form-items)', + 'views[0].formViews.intake (view-forms-to-form-items)', + ]); + expect(out.write.status).toBe('written'); + expect(sites(out.write.written)).toEqual(sites(out.applied)); + expect(out.write.manual).toEqual([]); + expect(out.write.unexplained).toEqual([]); + expect(out.write.verification).toEqual({ ok: true, stillApplied: [], vanished: [] }); + // The move names where its destination went; the deletion names none. + const intake = out.write.written.find((w: any) => w.path === 'views[0].formViews.intake'); + expect(intake.movedTo).toEqual({ file: 'objectstack.config.ts', line: lineOf(before, 'export default defineStack({') }); + + const snap = snapshot(dir); + expect(snap['src/views/company.view.ts']).toBe(COMPANY_VIEW_AFTER); + expect(snap['objectstack.config.ts']).toBe(config({ + extra: ` forms: [ + { + name: 'blank_company.intake', + object: 'blank_company', + type: 'simple', + sections: [{ fields: [{ field: 'name' }] }], + }, + ], +`, + })); + + // The written sources load to the form item, and nothing is left to convert. + const again = json(await runMeta(dir, ['--json'])); + expect(again.applied).toEqual([]); + expect(again.schemaValid).toBe(true); + const outFile = join(dir, 'after.json'); + await runMeta(dir, ['--json', '--out', outFile]); + expect(JSON.parse(readFileSync(outFile, 'utf8')).forms).toEqual([INTAKE_FORM]); + }, RUN_TIMEOUT); + + it('the human report lists the destination beside the site, and warns of nothing unexplained', async () => { + const dir = writeProject({ 'objectstack.config.ts': config(), ...OBJECTS, 'src/views/company.view.ts': COMPANY_VIEW }); + const run = await runMeta(dir, ['--write']); + expect(run.exitCode, run.stdout + run.stderr).toBeUndefined(); + const text = run.stdout + run.stderr; + expect(text).toContain('Wrote 2 of 2 mechanical change(s) into 2 file(s)'); + expect(text).toContain('forms[name=blank_company.intake] ← views[0].formViews.intake'); + expect(text).not.toContain('named by no applied entry'); + expect(text).toContain('no mechanical change remains'); + }, RUN_TIMEOUT); + + it('a public form and its zh-CN `submitBehavior` tail: the form and the tail are both written at their destinations', async () => { + const view = `import { defineView } from '@objectstack/spec'; + +const CompanyViews = defineView({ + list: { + type: 'grid', + data: { provider: 'object', object: 'blank_company' }, + columns: [{ field: 'name' }], + }, + formViews: { + contact: { + type: 'simple', + sharing: { enabled: true, allowAnonymous: true, publicLink: '/forms/contact-us' }, + sections: [{ fields: [{ field: 'name' }] }], + }, + }, +}); + +export default CompanyViews; +`; + const translations = `export const zhCN = { + 'zh-CN': { + objects: { + blank_company: { + _views: { + contact: { + submitBehavior: { title: '谢谢', message: '我们已收到。' }, + }, + }, + }, + }, + }, +}; +`; + const dir = writeProject({ + 'objectstack.config.ts': config({ imports: "import { zhCN } from './src/translations/zh-CN';", extra: ' translations: [zhCN],\n' }), + ...OBJECTS, + 'src/views/company.view.ts': view, + 'src/translations/zh-CN.ts': translations, + }); + const run = await runMeta(dir, ['--write', '--json']); + expect(run.exitCode, run.stdout + run.stderr).toBeUndefined(); + const out = json(run); + expect(sites(out.write.written)).toEqual([ + 'translations[0].zh-CN.objects.blank_company._views.contact.submitBehavior (translation-view-form-tails-to-forms)', + 'views[0].formViews.contact (view-forms-to-form-items)', + ]); + expect(out.write.manual).toEqual([]); + expect(out.write.unexplained).toEqual([]); + const tail = out.write.written.find((w: any) => w.conversionId === 'translation-view-form-tails-to-forms'); + expect(tail.movedTo.file).toBe('src/translations/zh-CN.ts'); + + const snap = snapshot(dir); + expect(snap['src/views/company.view.ts']).not.toContain('formViews'); + expect(snap['objectstack.config.ts']).toContain("publicLink: '/forms/contact-us'"); + expect(snap['src/translations/zh-CN.ts']).not.toContain('_views'); + expect(snap['src/translations/zh-CN.ts']).toContain("'blank_company.contact': { submitBehavior: { title: '谢谢', message: '我们已收到。' } }"); + + const outFile = join(dir, 'after.json'); + const again = json(await runMeta(dir, ['--json', '--out', outFile])); + expect(again.applied).toEqual([]); + expect(again.schemaValid).toBe(true); + const stack = JSON.parse(readFileSync(outFile, 'utf8')); + expect(stack.forms.map((f: any) => [f.name, f.sharing?.publicLink])).toEqual([['blank_company.contact', '/forms/contact-us']]); + expect(stack.translations[0]['zh-CN'].forms['blank_company.contact'].submitBehavior.title).toBe('谢谢'); + }, RUN_TIMEOUT); +}); + +describe('where the destination cannot be written, the form stays in its view', () => { + it('a `forms:` list built by a call: the view file keeps its bytes and the move is listed `not written`', async () => { + const forms = { + 'src/forms/index.ts': `export { Existing } from './existing.form';\n`, + 'src/forms/existing.form.ts': `import { defineForm } from '@objectstack/spec'; + +export const Existing = defineForm({ + name: 'blank_company.existing', + object: 'blank_company', + type: 'simple', + sections: [{ fields: [{ field: 'name' }] }], +}); +`, + }; + const cfg = config({ imports: "import * as forms from './src/forms';", extra: ' forms: exportsOf(forms),\n' }); + const dir = writeProject({ 'objectstack.config.ts': cfg, ...OBJECTS, ...forms, 'src/views/company.view.ts': COMPANY_VIEW }); + const run = await runMeta(dir, ['--write', '--json']); + expect(run.exitCode).toBe(1); + const out = json(run); + // The internal record form is a deletion with no destination: it is still written. + expect(sites(out.write.written)).toEqual(['views[0].form (view-forms-to-form-items)']); + expect(out.write.manual.map((m: any) => `${m.path} (${m.conversionId})`)).toEqual([ + 'views[0].formViews.intake (view-forms-to-form-items)', + ]); + expect(out.write.unexplained).toEqual([]); + expect(out.write.verification).toEqual({ ok: true, stillApplied: [], vanished: [] }); + + const snap = snapshot(dir); + // `formViews.intake` stands where it was; only the internal `form` left the file. + expect(snap['src/views/company.view.ts']).toBe(COMPANY_VIEW.replace(` form: { + type: 'simple', + sections: [{ fields: [{ field: 'name' }] }], + }, +`, '')); + expect(snap['src/views/company.view.ts']).toContain('intake: {'); + expect(snap['objectstack.config.ts']).toBe(cfg); + + // The re-run still owes the move, so it is never reported done. + const again = json(await runMeta(dir, ['--json'])); + expect(sites(again.applied)).toEqual(['views[0].formViews.intake (view-forms-to-form-items)']); + }, RUN_TIMEOUT); + + it('the human report names the move as not written', async () => { + const forms = { + 'src/forms/index.ts': `export { Existing } from './existing.form';\n`, + 'src/forms/existing.form.ts': `import { defineForm } from '@objectstack/spec'; + +export const Existing = defineForm({ + name: 'blank_company.existing', + object: 'blank_company', + type: 'simple', + sections: [{ fields: [{ field: 'name' }] }], +}); +`, + }; + const cfg = config({ imports: "import * as forms from './src/forms';", extra: ' forms: exportsOf(forms),\n' }); + const dir = writeProject({ 'objectstack.config.ts': cfg, ...OBJECTS, ...forms, 'src/views/company.view.ts': COMPANY_VIEW }); + const run = await runMeta(dir, ['--write']); + expect(run.exitCode).toBe(1); + const text = run.stdout; + expect(text).toMatch(/views\[0\]\.formViews\.intake: views\[0\]\.formViews\.intake → forms\[name=blank_company\.intake\]/); + expect(text).toContain('not written ['); + expect(text).not.toContain('no mechanical change remains'); + }, RUN_TIMEOUT); +}); diff --git a/packages/cli/src/utils/authored-source-codemod.ts b/packages/cli/src/utils/authored-source-codemod.ts index d273cadfe41..ff384618aa9 100644 --- a/packages/cli/src/utils/authored-source-codemod.ts +++ b/packages/cli/src/utils/authored-source-codemod.ts @@ -169,6 +169,12 @@ export interface WrittenSite { file: string; /** 1-based line of the site in the file as it was before the write. */ line: number; + /** + * For an entry that moves content to another place of the stack + * ({@link moveDestination}): where the destination was written, as the file + * read before the write (the literal the new key went into). + */ + movedTo?: { file: string; line: number }; } /** A mechanical change left for the author, with the reason it was not written. */ @@ -476,13 +482,93 @@ const ATTRIBUTION_RULES: ReadonlyArray<(applied: readonly Segment[], change: rea (applied, change) => applied.length >= 3 && isPrefix(applied.slice(0, -2), change), ]; -/** The applied entries (by index) that explain a change at `change`, by {@link ATTRIBUTION_RULES}. */ -function explainingEntries(appliedPaths: readonly (readonly Segment[])[], change: readonly Segment[]): number[] { +/** + * The applied entries (by index) that explain a change at `change`: those of + * the first of {@link ATTRIBUTION_RULES} that finds any, joined by every entry + * whose {@link moveDestination} the change is at, inside or around. The join + * is unconditional: a move's destination written apart from its source is the + * one way a write loses content, so it never yields to a looser rule. + */ +function explainingEntries( + appliedPaths: readonly (readonly Segment[])[], + change: readonly Segment[], + destinations: readonly (readonly Segment[] | null)[] = [], +): number[] { + const moved = destinations.flatMap((d, i) => (d && (isPrefix(d, change) || isPrefix(change, d)) ? [i] : [])); for (const rule of ATTRIBUTION_RULES) { const hits = appliedPaths.flatMap((p, i) => (rule(p, change) ? [i] : [])); - if (hits.length > 0) return hits; + if (hits.length > 0) return [...new Set([...hits, ...moved])].sort((a, b) => a - b); + } + return moved; +} + +/** + * Where an entry that MOVES content to another place of the stack put it, read + * from its `to` — the concrete path in the migrated stack, or `null`. + * + * A move to another collection reports the site it took the content from and + * names where it went only in `to` (the protocol-19 form move: + * `views[1].formViews.intake` → `forms[name=OBJECT.KEY]`; the translation tail + * move: `….objects.OBJECT._views.KEY.title` → `….forms['OBJECT.KEY'].title`). + * No path rule ties the destination's change (a new `forms` collection, a new + * `forms` group in a bundle) to that entry, and a change no entry explains is + * never written — so the source's removal used to be written alone, deleting + * the content from the authored source and writing it nowhere. + * + * No conversion is known by name. `to` names a destination only when the whole + * of it parses as an ABSOLUTE path of at least two steps — keys, `[0]`, + * `['a.b']`, and `[name=X]` for the element of a collection named X — read from + * the body the entry belongs to (`packages[i].manifest` where its `path` starts + * there, else the stack), and reaches a value the chain changed. A display + * value (`mongodb`, `(removed)`, `{ kind: … }`), a single key, a path relative + * to the site, or one that does not resolve names none. A wrong reading can + * only join a source and a destination into one unit, written together or not + * at all: a site left by hand, never a site lost. + */ +export function moveDestination( + application: Pick, + normalized: unknown, + migrated: unknown, +): Segment[] | null { + const steps: Array = []; + const token = /\[(\d+)\]|\['([^']*)'\]|\["([^"]*)"\]|\[name=([^\]]+)\]|(^|\.)([A-Za-z_$][\w$-]*)/y; + let at = 0; + while (at < application.to.length) { + token.lastIndex = at; + const m = token.exec(application.to); + if (!m) return null; + if (m[1] !== undefined) steps.push(Number(m[1])); + else if (m[2] !== undefined || m[3] !== undefined) steps.push((m[2] ?? m[3])!); + else if (m[4] !== undefined) steps.push({ name: m[4] }); + else steps.push(m[6]!); + at = token.lastIndex; + } + if (steps.length < 2 || typeof steps[0] !== 'string') return null; + const body = /^packages\[(\d+)\]\.manifest(?:\.|$)/.exec(application.path); + const path: Segment[] = body ? ['packages', Number(body[1]), 'manifest'] : []; + let node = valueAtPath(migrated, path); + for (const step of steps) { + if (typeof step === 'object') { + const index = Array.isArray(node) ? node.findIndex((el) => isPlainObject(el) && el.name === step.name) : -1; + if (index < 0) return null; + path.push(index); + } else { + path.push(step); + } + node = valueAtPath(node, [path[path.length - 1]!]); + if (node === undefined) return null; + } + return deepEqual(valueAtPath(normalized, path), node) ? null : path; +} + +function valueAtPath(root: unknown, path: readonly Segment[]): unknown { + let node = root; + for (const seg of path) { + if (typeof seg === 'number') node = Array.isArray(node) ? node[seg] : undefined; + else node = isPlainObject(node) ? node[seg] : undefined; + if (node === undefined) return undefined; } - return []; + return node; } // ── the authored module graph, read statically ────────────────────────────── @@ -1939,7 +2025,8 @@ export async function planAuthoredSourceWrite(input: AuthoredSourceWriteInput): // Attribution: each change to the entries that explain it. const changes = diffStacks(input.normalized, migrated); const appliedPaths = applied.map((a) => parsePath(a.path)); - const entriesOf = changes.map((c) => explainingEntries(appliedPaths, c.path)); + const destinations = applied.map((a) => moveDestination(a, input.normalized, migrated)); + const entriesOf = changes.map((c) => explainingEntries(appliedPaths, c.path, destinations)); // Components: entries that share a change are written together or not at all. const parent = applied.map((_, i) => i); @@ -2157,7 +2244,13 @@ export async function planAuthoredSourceWrite(input: AuthoredSourceWriteInput): const found = finder.find(input.config, parsePath(application.path)); manual.push({ application, refusal: site.refusal, ...(items.length > 0 ? { items } : {}), ...(found ? { found } : {}) }); } else { - written.push({ application, file: site.file, line: site.line }); + const dest = destinations[i]; + const at = dest + ? (changesOf.get(componentOf(i)) ?? []).find((ci) => isPrefix(dest, changes[ci]!.path) || isPrefix(changes[ci]!.path, dest)) + : undefined; + const r = at === undefined ? undefined : resolved.get(at); + const movedTo = r ? { file: graph.rel(r.container.node.file), line: r.line } : undefined; + written.push({ application, file: site.file, line: site.line, ...(movedTo ? { movedTo } : {}) }); } } From b587c8f6b13c671e875855e5ebfc9b5dcb8efbf1 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 23:16:43 +0000 Subject: [PATCH 2/2] chore(changeset): cli patch for the form-move write Claude-Session: https://claude.ai/code/session_016WV4cxRh6Sbfo2Xm49JPx6 Co-authored-by: Claude --- .changeset/39392-write-form-move-destination.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 .changeset/39392-write-form-move-destination.md diff --git a/.changeset/39392-write-form-move-destination.md b/.changeset/39392-write-form-move-destination.md new file mode 100644 index 00000000000..90f98957e60 --- /dev/null +++ b/.changeset/39392-write-form-move-destination.md @@ -0,0 +1,17 @@ +--- +'@objectstack/cli': patch +--- + +fix(cli): `os migrate meta --from 18 --write` writes a moved form as a `form` item, or leaves it in its view; it no longer deletes it from the source and writes it nowhere + +Clause-②: no +Metadata-protocol: none + +Who sees it: a developer upgrading a project with view forms (`form`, `formViews.KEY`, `viewKind: 'form'` items) to protocol 19 with `os migrate meta --from 18 --write`. + +- **A moved form is written, with its view block taken out only then.** Before, `--write` listed each form move to `forms[name=OBJECT.KEY]` as written, deleted the block from the view file and wrote no `form` item, so the form (a public intake form included) was gone, the re-run said "no mechanical change remains" and `os validate` could pass. Now the form is written into the stack's `forms:` list with the body the chain converted, and the write report names that line beside the view site (`forms[name=OBJECT.KEY] ← views[i].formViews.KEY`; `--json` adds `movedTo` to the written site). +- **A form's translation tails move the same way.** A `_views.KEY.title` or `submitBehavior` tail moves into the bundle's `forms['OBJECT.KEY']` in the same file, instead of being deleted. +- **Where the destination cannot be written, nothing of the move is.** When the stack's `forms` is built by a call (`forms: exportsOf(forms)`) or another value `--write` cannot edit, the view block stays where it is, the move is listed under "left for you to apply by hand" with the reason, and the run exits 1. Move such a form into your `forms` barrel by hand as a `form` item named `OBJECT.KEY`, then run the command again. +- An internal record form (a record-form slot, no public link, no action that opens it) is still deleted, as before. + +If you already ran `--write` on 19.0.0-next.4 or earlier: restore the deleted `form` / `formViews` blocks from version control (or from a `--out` snapshot taken before the write) and run `os migrate meta --from 18 --write` again.