diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index a81f1d86093..2dbdb5468f2 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8716,7 +8716,7 @@ sim workflows source create [options] | --- | --- | --- | | `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | | `--summary-file ` | No | Also write the plan as Markdown to this file (or set SIM_SUMMARY_FILE), replacing it each run; its first line is a comment that names the directory, for a CI step that updates one pull-request comment. | -| `--dir ` | Yes | Source directory: workflow.ts and functions/*. Without workflow.ts, writes a starter and the types instead (an error with --dry or --yes). | +| `--dir ` | Yes | Source directory: workflow.ts and functions/*. Without workflow.ts, writes a starter, the types and the guide instead (an error with --dry or --yes; --verbose also prints the guide's primer in a JSON result). | | `--dry` | No | Check the source and show the outcome without creating anything. | | `--name ` | No | The workflow name (default: the source's). | | `--folder ` | No | The folder to create it in (default: the root). | diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index f6a9ab42ae3..4f883b9dfb8 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -1443,7 +1443,7 @@ sim workflows source create [options] | --- | --- | --- | | `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | | `--summary-file ` | No | Also write the plan as Markdown to this file (or set SIM_SUMMARY_FILE), replacing it each run; its first line is a comment that names the directory, for a CI step that updates one pull-request comment. | -| `--dir ` | Yes | Source directory: workflow.ts and functions/*. Without workflow.ts, writes a starter and the types instead (an error with --dry or --yes). | +| `--dir ` | Yes | Source directory: workflow.ts and functions/*. Without workflow.ts, writes a starter, the types and the guide instead (an error with --dry or --yes; --verbose also prints the guide's primer in a JSON result). | | `--dry` | No | Check the source and show the outcome without creating anything. | | `--name ` | No | The workflow name (default: the source's). | | `--folder ` | No | The folder to create it in (default: the root). | diff --git a/packages/sim-cli/src/commands/protocol/source-dir/index.ts b/packages/sim-cli/src/commands/protocol/source-dir/index.ts index 0667c6cb9d2..d81d1323265 100644 --- a/packages/sim-cli/src/commands/protocol/source-dir/index.ts +++ b/packages/sim-cli/src/commands/protocol/source-dir/index.ts @@ -27,6 +27,7 @@ export { FILE_CONCURRENCY, isMissing, listSourceFiles, + normalizeSourceText, readPreviousLock, readSourceJson, readSourceText, diff --git a/packages/sim-cli/src/commands/protocol/source-loop-help.ts b/packages/sim-cli/src/commands/protocol/source-loop-help.ts index d387fa542bf..3fe99b36d74 100644 --- a/packages/sim-cli/src/commands/protocol/source-loop-help.ts +++ b/packages/sim-cli/src/commands/protocol/source-loop-help.ts @@ -46,9 +46,24 @@ const GET_LINE = ` sim workflows source get --dir ./wf && cat ./wf/$ const WORKFLOW_LOOP = 'sim workflows source check --dir ./wf && sim workflows source apply --dir ./wf --yes' +/** What an apply prints about the files it rewrote, so an agent need not reread them. */ +const REWROTE = 'listing the lines it changed under rewrote' + const CHAIN_STOPS = 'A non-zero exit stops the chain at the first failure; fix what it reported and run it again.' +/** + * How `sim workflows source --help` starts a new workflow on each surface: a coding agent reads the + * starter's guide in the same shell call, as it does after a get; the chat has the primer already. + */ +const NEW_WORKFLOW_LINES: Record = { + cli: `A new workflow: \`sim workflows source create --dir ./new --workspace && cat +./new/${SOURCE_AGENTS_FILE}\` writes a starter and its guide; edit and check it, then +\`create --dir ./new --yes --run '{…}' --deploy\`.`, + chat: `A new workflow: \`sim workflows source create --dir ./new --workspace \` writes a +starter; edit and check it, then \`create --dir ./new --yes\`.`, +} + /** * The loop lines of `sim workflows source --help` on each surface: a coding agent chains the test * run and the deploy onto the apply, while the chat's shell refuses a synchronous run, so it tests @@ -60,9 +75,9 @@ ${GET_LINE} edit every file, then: ${WORKFLOW_LOOP} --run '{…}' --deploy ${CHAIN_STOPS} check compiles and type-checks (TypeScript installs on first run; --no-types skips it); apply re-checks, -saves the draft and rewrites the files; --run dry-runs that input on the saved draft (writes -stubbed, listed under run.sideEffects); --deploy deploys only if that run completed (without it the -draft stays undeployed).`, +saves the draft and rewrites the files, ${REWROTE}; --run dry-runs +that input on the saved draft (writes stubbed, listed under run.sideEffects); --deploy deploys only +if that run completed (without it the draft stays undeployed).`, chat: `The loop, two calls in run_code's shell (: its id or exact name): ${GET_LINE} edit every file, then: ${WORKFLOW_LOOP} @@ -72,7 +87,7 @@ and once it completes, deploy that draft with sim_cli: workflows deploy --expected-draft-fingerprint ${CHAIN_STOPS} check compiles and type-checks (--no-types skips it); apply re-checks, saves the draft and rewrites the -files.`, +files, ${REWROTE}.`, } /** @@ -86,8 +101,7 @@ prints the plan; get --force replaces unapplied edits or another workflow's sour A large workflow: chain \`&& sim workflows source find '' '' --dir ./wf\` onto the get, naming every block the change touches: it prints only those (lines, function file, wiring, readers), not the whole workflow.ts. -A new workflow: \`sim workflows source create --dir ./new --workspace \` writes a -starter; edit and check it, then \`create --dir ./new --yes${surface === 'chat' ? '' : " --run '{…}' --deploy"}\`. +${NEW_WORKFLOW_LINES[surface]} ${WORKSPACE_LINE} ${RUN_LOGS_LINE} ${statusLine('sim workflows source', './wf')}` @@ -101,14 +115,14 @@ The loop, two shell calls: sim workspaces source check --dir ./ws && sim workspaces source apply --dir ./ws --yes --run ='{…}' ${CHAIN_STOPS} check compiles and type-checks (TypeScript installs on first run; --no-types skips it); apply re-checks -and writes the workspace; --run ='{…}' (one per workflow, its workflows// folder) -dry-runs that input on the saved draft: code runs and GET fetches are sent (point them at test -resources); writes are stubbed and listed under runs[].sideEffects, whose .unchecked lists -sandboxed code that really ran, network requests included, and .omitted counts entries left -out. A workflow with several triggers takes one --run '.={…}' per trigger (its -const, block key or id). Use --run when the apply changes a workflow. A workflow deploys on -apply when deployments/.ts declares it; with --run, deployments/ is applied only after -every run completed, and only when every draft it publishes was test-run. +and writes the workspace, ${REWROTE}; --run ='{…}' (one per workflow, its +workflows// folder) dry-runs that input on the saved draft: code runs and GET fetches are +sent (point them at test resources); writes are stubbed and listed under runs[].sideEffects, whose +.unchecked lists sandboxed code that really ran, network requests included, and .omitted counts +entries left out. A workflow with several triggers takes one --run '.={…}' per +trigger (its const, block key or id). Use --run when the apply changes a workflow. A workflow +deploys on apply when deployments/.ts declares it; with --run, deployments/ is applied only +after every run completed, and only when every draft it publishes was test-run. --allow-delete lets an edit remove a resource, column, rows, document, or a workflow's block or variable; apply --dry only prints the plan; get --force replaces edits no apply has saved. Promote dev to prod: \`sim workspaces source apply --dir ./ws --to --dry\`, then --yes. diff --git a/packages/sim-cli/src/commands/protocol/source-primer.ts b/packages/sim-cli/src/commands/protocol/source-primer.ts index b441f702efe..9e6b05825eb 100644 --- a/packages/sim-cli/src/commands/protocol/source-primer.ts +++ b/packages/sim-cli/src/commands/protocol/source-primer.ts @@ -90,7 +90,7 @@ const WORKSPACE_LOOP = `sim workspaces source check --dir . && sim workspaces so const EDIT_LOOP_LEAD = '**Edit loop**: write every file, then run one chained command' -const APPLY_REWRITES = `\`check\` also type-checks (no \`tsc\`). Apply re-checks (\`apply --dry\` only plans) and rewrites \`${SOURCE_ENTRY_FILE}\`: reread it before editing.` +const APPLY_REWRITES = `\`check\` also type-checks (no \`tsc\`). Apply re-checks (\`apply --dry\` only plans) and rewrites \`${SOURCE_ENTRY_FILE}\`, printing its changed lines as \`rewrote\` (\`{}\`: none): reread it only if that says to.` /** * The workflow edit loop of each surface. A coding agent chains the test run and the deploy onto @@ -127,7 +127,7 @@ const WORKSPACE_PRIMER = `# Sim workspace source: primer A Sim workspace as files; nothing here runs. Commands here (table ones too) act on the workspace \`${SOURCE_BASE_FILE}\` names. Every \`.ts\` file starts with \`// @sim-sdk ${SDK_MAJOR}\`. -**Edit loop**: write every file, then run one chained command; fix what it reports: \`${WORKSPACE_LOOP}\` dry-runs \`workflows//\`'s draft (one \`--run\` per workflow you changed; drop it when you changed none; several triggers: \`--run '.={…}'\` each) and deploys only if all complete and every draft it deploys was tested. \`check\` also type-checks (no \`tsc\`). Apply re-checks (\`apply --dry\` only plans) and rewrites files: reread before editing. +**Edit loop**: write every file, then run one chained command; fix what it reports: \`${WORKSPACE_LOOP}\` dry-runs \`workflows//\`'s draft (one \`--run\` per workflow you changed; drop it when you changed none; several triggers: \`--run '.={…}'\` each) and deploys only if all complete and every draft it deploys was tested. \`check\` also type-checks (no \`tsc\`). Apply re-checks (\`apply --dry\` only plans) and rewrites files, printing their changed lines as \`rewrote\` (\`{}\`: none): reread a file only if that says to. - **Deletes**: removing anything (file, column, block) needs \`apply --allow-delete\` and is permanent. - **Exit ${SOURCE_HELD_EXIT_CODE}**: partly written: what needs an unset secret or unbound credential waits; set it, reapply. diff --git a/packages/sim-cli/src/commands/protocol/source-rewrites.ts b/packages/sim-cli/src/commands/protocol/source-rewrites.ts new file mode 100644 index 00000000000..6983b6163ea --- /dev/null +++ b/packages/sim-cli/src/commands/protocol/source-rewrites.ts @@ -0,0 +1,85 @@ +/** + * What a stored source write changed in the files the agent sent: the server reprints every file + * it stores, so an agent editing again needs only the lines that reprint changed, not the whole + * file reread. + */ +import { compareStrings } from '@sim/utils/string' +import { structuredPatch } from 'diff' +import { printError } from '#sim-cli/output/io' +import { normalizeSourceText } from './source-dir' +import { colorLine } from './source-status' + +/** + * At most this many diff lines across every file of one command's writes; past it, a file's + * remaining lines are counted (or, once none are left, not diffed at all) and the agent rereads + * that file instead. + */ +const REWRITE_LINES = 60 + +/** How long one file's diff may take before it is given up for a reread, in milliseconds. */ +const DIFF_TIMEOUT_MS = 200 + +/** Diff lines already listed in `rewrote`, which a later write's lines share the budget with. */ +function listedLines(rewrote: Readonly>): number { + return Object.values(rewrote).reduce((total, lines) => total + lines.length, 0) +} + +/** + * The lines a write's reprint changed, per file (path → unified-diff hunks without context, the + * `@@` header naming the lines), added to `prior` (an earlier write's of the same command, whose + * lines count toward {@link REWRITE_LINES}): a file reprinted as sent is left out, so `{}` means + * every file is on disk as the agent wrote it. `sent` is what the directory sent (path → text), + * `printed` what the server stored and the CLI wrote back; a file only `printed` holds is new. + */ +export function rewrites( + sent: Readonly>, + printed: Readonly>, + prior: Readonly> = {} +): Record { + const result: Record = { ...prior } + let budget = REWRITE_LINES - listedLines(prior) + for (const path of Object.keys(printed).sort(compareStrings)) { + // A `.sim/` record (a workflow folder's lock and base) is the CLI's, never edited by hand. + if (sent[path] === printed[path] || path.split('/').includes('.sim')) continue + const before = normalizeSourceText(sent[path] ?? '') + const after = normalizeSourceText(printed[path]) + if (before === after) continue + const patch = + budget > 0 + ? structuredPatch(path, path, before, after, undefined, undefined, { + context: 0, + timeout: DIFF_TIMEOUT_MS, + }) + : undefined + if (!patch) { + result[path] = [`… changed: reread ${path}`] + continue + } + const lines = patch.hunks.flatMap((hunk) => [ + `@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`, + ...hunk.lines, + ]) + const shown = lines.slice(0, budget) + budget -= shown.length + const rest = lines.length - shown.length + result[path] = + rest > 0 + ? [...shown, `… ${rest} more diff line${rest === 1 ? '' : 's'}: reread ${path}`] + : shown + } + return result +} + +/** The rewrites as one display field: `none`, or each file with its diff line count. */ +export function rewritesText(rewrote: Readonly>): string { + const files = Object.entries(rewrote) + if (files.length === 0) return 'none: every file is as you wrote it' + return files.map(([path, lines]) => `${path} (${lines.length} diff lines)`).join(', ') +} + +/** Prints each rewritten file's diff on stderr for a person, under the file it is in. */ +export function printRewrites(rewrote: Readonly>): void { + for (const [path, lines] of Object.entries(rewrote)) { + printError(`Rewrote ${path}:\n${lines.map(colorLine).join('\n')}`) + } +} diff --git a/packages/sim-cli/src/commands/protocol/source-status.ts b/packages/sim-cli/src/commands/protocol/source-status.ts index 670bc8184bc..6ff9f822cf3 100644 --- a/packages/sim-cli/src/commands/protocol/source-status.ts +++ b/packages/sim-cli/src/commands/protocol/source-status.ts @@ -338,7 +338,7 @@ export function textDiff( } /** Colors one patch line the way `git diff` does: headers bold, hunks cyan, `-` red, `+` green. */ -function colorLine(line: string): string { +export function colorLine(line: string): string { const s = styles() if (line.startsWith('---') || line.startsWith('+++')) return s.bold(line) if (line.startsWith('@@')) return s.cyan(line) diff --git a/packages/sim-cli/src/commands/protocol/source-tree.ts b/packages/sim-cli/src/commands/protocol/source-tree.ts index 89364534640..2655960e981 100644 --- a/packages/sim-cli/src/commands/protocol/source-tree.ts +++ b/packages/sim-cli/src/commands/protocol/source-tree.ts @@ -606,19 +606,21 @@ export function finishTree( } /** - * Prints a tree write's result: the fields, then the primer as text when the result carries one - * (in JSON or YAML it is the document's `primer` field). Only a new directory's starter prints - * it; a get leaves it at the top of `.sim/AGENTS.md`. + * Prints a tree write's result: the fields, then the primer as text when the result carries one. + * Only a new directory's starter carries it, and a get leaves it at the top of `.sim/AGENTS.md`. + * A machine result names that guide instead (an agent reads it, or holds the primer already, as + * Mothership does), so it is not read twice; `verbose` keeps it as the document's `primer` field. */ export function printTreeResult( format: OutputFormat, - result: Record & { primer?: string } + result: Record & { primer?: string }, + { verbose = false }: { verbose?: boolean } = {} ): void { + const { primer, ...fields } = result if (isMachineFormat(format)) { - printProtocolResult(format, result) + printProtocolResult(format, verbose ? result : fields) return } - const { primer, ...fields } = result printProtocolResult(format, fields) if (primer !== undefined) printLine(`\n${primer}`) } diff --git a/packages/sim-cli/src/commands/protocol/source-ui.ts b/packages/sim-cli/src/commands/protocol/source-ui.ts index 595f563c7f0..dde601e0386 100644 --- a/packages/sim-cli/src/commands/protocol/source-ui.ts +++ b/packages/sim-cli/src/commands/protocol/source-ui.ts @@ -103,18 +103,47 @@ function locationOf(diagnostic: Diagnostic): string { .trim() } +/** Whether a code frame line is the caret line under a marked one: ` | ^^^^`. */ +const CARET_LINE = /^\s*\|\s*\^/ + /** - * Prints a write's findings on stderr for a person: every error with its location, frame and - * hint; the first warning of each code the same way, and the rest of that code on one line - * listing where they are, each with its own message when it differs from the first (one fix - * usually serves them all, and twenty frames of the same warning buried the errors); each info - * code folded into one line. + * A code frame cut to the lines it marks (`>`) and their carets: the lines around them are in the + * file the location names, and each finding's frame repeated them. */ -function printDiagnostics(diagnostics: readonly Diagnostic[]): void { +function markedFrame(frame: string): string { + const lines = frame.split('\n') + const marked = (line: string | undefined) => line?.trimStart().startsWith('>') ?? false + const kept = lines.filter( + (line, index) => marked(line) || (CARET_LINE.test(line) && marked(lines[index - 1])) + ) + return kept.length > 0 ? kept.join('\n') : frame +} + +/** + * Prints a write's findings on stderr for a person: every error with its location, the marked + * line of its frame and its hint, a hint already printed for the same code (`hints`, shared by + * every print of one command) left out; the first + * warning of each code the same way, and the rest of that code on one line listing where they + * are, each with its own message when it differs from the first (one fix usually serves them + * all, and twenty frames of the same warning buried the errors); each info code folded into one + * line. + */ +function printDiagnostics( + diagnostics: readonly Diagnostic[], + hints: Set = new Set() +): void { const groups = new Map() + const compact = (diagnostic: Diagnostic): Diagnostic => ({ + ...diagnostic, + frame: diagnostic.frame === undefined ? undefined : markedFrame(diagnostic.frame), + hint: + diagnostic.hint !== undefined && fresh(hints, `${diagnostic.code}\0${diagnostic.hint}`) + ? diagnostic.hint + : undefined, + }) for (const diagnostic of diagnostics) { if (diagnostic.severity === 'error') { - printError(formatDiagnostic(diagnostic)) + printError(formatDiagnostic(compact(diagnostic))) continue } const key = `${diagnostic.severity}:${diagnostic.code}` @@ -131,7 +160,7 @@ function printDiagnostics(diagnostics: readonly Diagnostic[]): void { ) continue } - printError(formatDiagnostic(first)) + printError(formatDiagnostic(compact(first))) if (rest.length === 0) continue // A collapsed finding saying something else than the first keeps its words beside its place. const listed = rest @@ -284,6 +313,7 @@ export function findingsOutput( dir?: string ): FindingsOutput { const printed = new Set() + const hints = new Set() const machine = isMachineFormat(format) return { machine, @@ -295,7 +325,7 @@ export function findingsOutput( fresh(printed, findingKey(diagnostic)) ) .map((diagnostic) => boundFindingText(withCliHint(diagnostic))) - if (!machine) printDiagnostics(unseen) + if (!machine) printDiagnostics(unseen, hints) printAnnotations(unseen.flatMap((diagnostic) => findingAnnotation(diagnostic, dir))) }, result: (diagnostics) => diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts index d86005b8ecd..c82ef51a5ff 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts @@ -800,6 +800,51 @@ describe('sim workflows source apply', () => { ).toBe(true) }) + it('lists the lines the reprint changed in the files it sent, so the next edit need not reread them', async () => { + setTerminal(false) + writeFileSync(join(dir, 'workflow.ts'), ENTRY.replace("'W'", '"W"')) + request.mockResolvedValue(outcome()) + + await apply(WORKFLOW_ID, '--dir', dir, '--yes') + + expect(stdoutJson().rewrote).toEqual({ + 'workflow.ts': [ + '@@ -2,1 +2,2 @@', + '-export default workflow("W", () => {})', + "+export default workflow('W', () => {})", + '+// stored', + ], + }) + }) + + it('lists no rewritten file when the reprint is what the directory sent, and none on a dry run', async () => { + setTerminal(false) + writeFileSync(join(dir, 'workflow.ts'), `${ENTRY}// stored\n`) + request.mockResolvedValue(outcome()) + + await apply(WORKFLOW_ID, '--dir', dir, '--yes') + expect(stdoutJson().rewrote).toEqual({}) + + vi.mocked(console.log).mockClear() + request.mockResolvedValue(outcome({ dry: true })) + await apply(WORKFLOW_ID, '--dir', dir, '--dry') + expect(stdoutJson()).not.toHaveProperty('rewrote') + }) + + it('cuts a long rewrite and names the file to reread', async () => { + setTerminal(false) + const long = Array.from({ length: 100 }, (_, index) => `// line ${index}`).join('\n') + request.mockResolvedValue({ + data: { ...outcome().data, files: { 'workflow.ts': `${ENTRY}${long}\n` } }, + }) + + await apply(WORKFLOW_ID, '--dir', dir, '--yes') + + const lines = (stdoutJson().rewrote as Record)['workflow.ts'] + expect(lines).toHaveLength(61) + expect(lines.at(-1)).toBe('… 41 more diff lines: reread workflow.ts') + }) + it('prints every note on a dry run, so a kept name or a dropped tool is never silent', async () => { setTerminal(false) contextMockState.output = 'text' @@ -839,6 +884,33 @@ describe('sim workflows source apply', () => { ) }) + it('at a terminal, never repeats on the write a hint the preview printed for the same code', async () => { + setTerminal(true) + contextMockState.output = 'text' + const untyped = (line: number) => ({ + code: 'W_JSON_REF_UNTYPED', + severity: 'warning', + message: `Nothing declares the type of .`, + file: 'workflow.ts', + line, + column: 7, + hint: 'Leave it bare when it holds a number.', + }) + request.mockImplementation(async (_path: string, options: { query?: { dry?: boolean } }) => + outcome({ + dry: options.query?.dry === true, + diagnostics: options.query?.dry === true ? [untyped(4)] : [untyped(4), untyped(9)], + }) + ) + prompt.question.mockResolvedValue('y') + + await apply(WORKFLOW_ID, '--dir', dir) + + const printed = stderrLines().join('\n') + expect(printed).toContain('workflow.ts:9:7 warning W_JSON_REF_UNTYPED') + expect(printed.split('hint: Leave it bare when it holds a number.')).toHaveLength(2) + }) + it('at a terminal, prints a warning and a note the preview showed once, not again on the write', async () => { setTerminal(true) contextMockState.output = 'text' @@ -904,6 +976,39 @@ describe('sim workflows source apply', () => { column: 3, } + it('in a display format, prints each error with only its marked lines and a hint once per code', async () => { + setTerminal(false) + contextMockState.output = 'text' + const unknown = (line: number) => ({ + code: 'E_UNKNOWN_PARAM', + severity: 'error', + message: `Function has no param bogus${line}.`, + file: 'workflow.ts', + line, + column: 9, + frame: [ + ` ${line - 1} | const before = 1`, + `> ${line} | bogus${line}: 1,`, + ' | ^^^^^', + ` ${line + 1} | const after = 2`, + ].join('\n'), + hint: 'Run `sim workflows source params fn` for its params.', + }) + request.mockResolvedValue(outcome({ dry: true, diagnostics: [unknown(4), unknown(7)] })) + + await apply(WORKFLOW_ID, '--dir', dir, '--dry').catch(() => {}) + + const printed = stderrLines().join('\n') + expect(printed).toContain( + 'workflow.ts:4:9 error E_UNKNOWN_PARAM: Function has no param bogus4.\n> 4 | bogus4: 1,\n | ^^^^^' + ) + expect(printed).toContain( + 'workflow.ts:7:9 error E_UNKNOWN_PARAM: Function has no param bogus7.\n> 7 | bogus7: 1,' + ) + expect(printed).not.toContain('const before') + expect(printed.split('hint: Run `sim workflows source params fn`')).toHaveLength(2) + }) + it('with --output json, prints findings only in the JSON on stdout, never as frames on stderr', async () => { setTerminal(false) request.mockResolvedValue(outcome({ dry: true, diagnostics: [untyped(4)] })) @@ -2366,6 +2471,24 @@ describe('sim workflows source create on a directory with no workflow.ts', () => next: { command: expect.stringContaining('sim workflows source create --dir') }, }) expect(printed.files).toBeGreaterThan(0) + // The guide holds the primer; the JSON names it, as a get's does, unless --verbose. + expect(printed).not.toHaveProperty('primer') + expect(readFileSync(join(empty, '.sim/AGENTS.md'), 'utf8')).toContain('source: primer') + }) + + it("prints a starter's primer in the JSON result with --verbose", async () => { + setTerminal(false) + vi.stubEnv('SIM_CONFIG_DIR', join(dir, 'config')) + request.mockImplementation(async (path: string) => { + if (path.endsWith('/workflows/source/catalog')) return { data: CATALOG } + if (path.endsWith('/workflows/source/resources')) return MANIFEST + throw new Error(`unexpected request ${path}`) + }) + + await create('--dir', join(dir, 'new'), '--verbose') + + const printed = JSON.parse(vi.mocked(console.log).mock.calls.at(-1)?.join(' ') ?? '{}') + expect(printed.primer).toMatch(/^# Sim workflow source: primer/) }) it("names a starter's create with the --name and --folder the caller chose", async () => { diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts index 71daf537f80..000d3319df1 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts @@ -55,6 +55,7 @@ import { } from './source-dir' import { sourceExitCodesHelp } from './source-exit-codes' import { primerSurface } from './source-primer' +import { printRewrites, rewrites, rewritesText } from './source-rewrites' import { cachedCatalogByHash, printTreeResult, refreshWorkflowWorkspaceTypes } from './source-tree' import { type CreatedResource, @@ -251,6 +252,7 @@ async function writeWorkflowSource(args: marker: summaryMarker(options.dir), }) const details = summarize(data, creating, findings.machine) + const rewrote = stored(data) ? rewrites(args.body.files, data.files) : undefined const errors = countOf(data, 'error') const warnings = countOf(data, 'warning') // `deployed.version` is the version the deploy admitted, which may not be live yet: a person @@ -261,6 +263,7 @@ async function writeWorkflowSource(args: // One run keeps the `run` field a single `--run` always had; several are listed in order. ...(runs.length === 1 ? { run: runs[0] } : runs.length > 1 ? { runs } : {}), ...(deployed && findings.machine ? { deployed } : {}), + ...(rewrote ? { rewrote } : {}), ...outcome, ...findings.result(data.diagnostics), errors, @@ -272,8 +275,10 @@ async function writeWorkflowSource(args: for (const run of findings.machine ? [] : runs) { if (run.sideEffects) printSideEffects(run.sideEffects, undefined, data.workflowId) } + if (rewrote && !findings.machine) printRewrites(rewrote) printProtocolResult(args.output, result, { ...(details.created ? { created: createdText(details.created) } : {}), + ...(rewrote ? { rewrote: rewritesText(rewrote) } : {}), ...(outcome.urls?.length ? { urls: deployedUrlsText(outcome.urls) } : {}), }) } @@ -848,7 +853,7 @@ export function attachWorkflowSourceCreate(source: Command): void { command .requiredOption( '--dir ', - 'Source directory: workflow.ts and functions/*. Without workflow.ts, writes a starter and the types instead (an error with --dry or --yes)' + "Source directory: workflow.ts and functions/*. Without workflow.ts, writes a starter, the types and the guide instead (an error with --dry or --yes; --verbose also prints the guide's primer in a JSON result)" ) .option('--dry', 'Check the source and show the outcome without creating anything') .option('--name ', "The workflow name (default: the source's)") @@ -889,12 +894,11 @@ export function attachWorkflowSourceCreate(source: Command): void { } const machine = isMachineFormat(profile.output) if (!machine) printError(`${next.reason} Next: ${next.command}`) - printTreeResult(profile.output, { - created: false, - scaffolded: true, - ...tree, - ...(machine ? { next } : {}), - }) + printTreeResult( + profile.output, + { created: false, scaffolded: true, ...tree, ...(machine ? { next } : {}) }, + { verbose: options.verbose } + ) return } const { client, profile } = connectCreate() diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts index f26f018b776..f80809f60e0 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts @@ -223,6 +223,34 @@ describe('workspaces source apply', () => { expect(vi.mocked(console.error).mock.calls.flat().join('\n')).toContain('+ leads') }) + it('lists the lines the reprint changed in the files it sent, and none on a dry run', async () => { + write('tables/leads.ts', LEADS.replace("'leads'", '"leads"')) + request.mockResolvedValue(answer({ dry: true })) + await apply('--dry') + expect(JSON.parse(vi.mocked(console.log).mock.calls[0].join(' '))).not.toHaveProperty('rewrote') + + vi.mocked(console.log).mockClear() + request.mockResolvedValue( + answer({ + applied: [{ kind: 'table', key: 'leads', action: 'update', id: 'tbl_1' }], + files: { + 'tables/leads.ts': LEADS, + 'workflows/ingest/.sim/base.json': INGEST_BASE.replace('sf1:a', 'sf1:b'), + }, + }) + ) + await apply('--yes') + + // A workflow folder's records are the CLI's: their reprint is never listed. + expect(JSON.parse(vi.mocked(console.log).mock.calls[0].join(' ')).rewrote).toEqual({ + 'tables/leads.ts': [ + '@@ -2,1 +2,1 @@', + '-export default defineTable({ name: "leads", columns: {} })', + "+export default defineTable({ name: 'leads', columns: {} })", + ], + }) + }) + it('counts and lists a resource the server changed or deleted, never as unchanged, and keeps its warning in the JSON', async () => { const drift = (code: string, kind: string, key: string) => ({ code, diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts index 803220144e6..9c90bbd8fb9 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -64,6 +64,7 @@ import { writtenRecord, } from './source-dir' import { sourceExitCodesHelp } from './source-exit-codes' +import { printRewrites, rewrites, rewritesText } from './source-rewrites' import { destructiveChanges } from './source-status' import { cachedCatalog } from './source-tree' import { @@ -900,6 +901,8 @@ export function attachWorkspaceSourceApply(source: Command): void { const findings = findingsOutput(profile.output, options.verbose, options.dir) const notSent = notSentFindings(submission.ignored) findings.print(notSent) + /** The lines each saved write's reprint changed in the files it sent (`rewrites`). */ + let rewrote: Record | undefined /** Prints `data` as the result, with the findings about files the CLI did not send. */ const report = ( data: ApplyData, @@ -928,8 +931,10 @@ export function attachWorkspaceSourceApply(source: Command): void { ...(workflows.length > 0 ? { workflows } : {}), ...(urls.length > 0 ? { urls } : {}), ...(tested.length > 0 ? { runs: tested } : {}), + ...(rewrote ? { rewrote } : {}), ...(next ? { next } : {}), } + if (rewrote && !findings.machine) printRewrites(rewrote) printProtocolResult( profile.output, { ...result, ...findings.result(diagnostics) }, @@ -938,6 +943,7 @@ export function attachWorkspaceSourceApply(source: Command): void { ...(workflows.length > 0 ? { workflows: writtenWorkflowsText(workflows) } : {}), ...(urls.length > 0 ? { urls: workflowUrlsText(urls) } : {}), ...(tested.length > 0 ? { runs: testRunsText(tested) } : {}), + ...(rewrote ? { rewrote: rewritesText(rewrote) } : {}), } ) } @@ -994,6 +1000,7 @@ export function attachWorkspaceSourceApply(source: Command): void { ? await workflowFolderRecords(client, workspaceId, workspaceCatalog, answer.files) : { records: [], unrecorded: [] } await saveApplied(options.dir, answer, commit, held, records) + rewrote = rewrites(commit.files, answer.files, rewrote) const unrecordedWarning = unrecordedFoldersWarning(unrecorded) if (unrecordedWarning) printError(unrecordedWarning) },