Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/docs/content/docs/cli/reference.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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 <path>` | 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 <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 <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 <name>` | No | The workflow name (default: the source's). |
| `--folder <path>` | No | The folder to create it in (default: the root). |
Expand Down
2 changes: 1 addition & 1 deletion apps/docs/content/docs/cli/workflows.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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 <path>` | 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 <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 <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 <name>` | No | The workflow name (default: the source's). |
| `--folder <path>` | No | The folder to create it in (default: the root). |
Expand Down
1 change: 1 addition & 0 deletions packages/sim-cli/src/commands/protocol/source-dir/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export {
FILE_CONCURRENCY,
isMissing,
listSourceFiles,
normalizeSourceText,
readPreviousLock,
readSourceJson,
readSourceText,
Expand Down
42 changes: 28 additions & 14 deletions packages/sim-cli/src/commands/protocol/source-loop-help.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,24 @@ const GET_LINE = ` sim workflows source get <workflow> --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<PrimerSurface, string> = {
cli: `A new workflow: \`sim workflows source create --dir ./new --workspace <workspaceId> && 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 <workspaceId>\` 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
Expand All @@ -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 (<workflow>: its id or exact name):
${GET_LINE}
edit every file, then: ${WORKFLOW_LOOP}
Expand All @@ -72,7 +87,7 @@ and once it completes, deploy that draft with sim_cli:
workflows deploy <workflowId> --expected-draft-fingerprint <fingerprint in ./wf/.sim/base.json>
${CHAIN_STOPS} check
compiles and type-checks (--no-types skips it); apply re-checks, saves the draft and rewrites the
files.`,
files, ${REWROTE}.`,
}

/**
Expand All @@ -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 '<Block>' '<Block>' --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 <workspaceId>\` 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')}`
Expand All @@ -101,14 +115,14 @@ The loop, two shell calls:
sim workspaces source check --dir ./ws && sim workspaces source apply --dir ./ws --yes --run <key>='{…}'
${CHAIN_STOPS} check
compiles and type-checks (TypeScript installs on first run; --no-types skips it); apply re-checks
and writes the workspace; --run <key>='{…}' (one per workflow, <key> its workflows/<key>/ 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 '<key>.<trigger>={…}' per trigger (its
const, block key or id). Use --run when the apply changes a workflow. A workflow deploys on
apply when deployments/<key>.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 <key>='{…}' (one per workflow, <key> its
workflows/<key>/ 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 '<key>.<trigger>={…}' per
trigger (its const, block key or id). Use --run when the apply changes a workflow. A workflow
deploys on apply when deployments/<key>.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 <workspaceId> --dry\`, then --yes.
Expand Down
4 changes: 2 additions & 2 deletions packages/sim-cli/src/commands/protocol/source-primer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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/<key>/\`'s draft (one \`--run\` per workflow you changed; drop it when you changed none; several triggers: \`--run '<key>.<const>={…}'\` 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/<key>/\`'s draft (one \`--run\` per workflow you changed; drop it when you changed none; several triggers: \`--run '<key>.<const>={…}'\` 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.
Expand Down
85 changes: 85 additions & 0 deletions packages/sim-cli/src/commands/protocol/source-rewrites.ts
Original file line number Diff line number Diff line change
@@ -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<Record<string, string[]>>): 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<Record<string, string>>,
printed: Readonly<Record<string, string>>,
prior: Readonly<Record<string, string[]>> = {}
): Record<string, string[]> {
const result: Record<string, string[]> = { ...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<Record<string, string[]>>): 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<Record<string, string[]>>): void {
for (const [path, lines] of Object.entries(rewrote)) {
printError(`Rewrote ${path}:\n${lines.map(colorLine).join('\n')}`)
}
}
2 changes: 1 addition & 1 deletion packages/sim-cli/src/commands/protocol/source-status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
14 changes: 8 additions & 6 deletions packages/sim-cli/src/commands/protocol/source-tree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown> & { primer?: string }
result: Record<string, unknown> & { 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}`)
}
Expand Down
48 changes: 39 additions & 9 deletions packages/sim-cli/src/commands/protocol/source-ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> = new Set()
): void {
const groups = new Map<string, Diagnostic[]>()
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}`
Expand All @@ -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
Expand Down Expand Up @@ -284,6 +313,7 @@ export function findingsOutput(
dir?: string
): FindingsOutput {
const printed = new Set<string>()
const hints = new Set<string>()
const machine = isMachineFormat(format)
return {
machine,
Expand All @@ -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) =>
Expand Down
Loading
Loading