Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8114: fix(agent): preserve runtime config boundaries after formatting (#9382)
Junghwanba1a7958821e
diff --git a/server/internal/daemon/execenv/runtime_config.go b/server/internal/daemon/execenv/runtime_config.goindex 76e6e338b7..0bc4770d69 100644--- a/server/internal/daemon/execenv/runtime_config.go+++ b/server/internal/daemon/execenv/runtime_config.go@@ -8,6 +8,7 @@ import ("os""path/filepath""runtime"+ "strconv""strings""github.com/multica-ai/multica/server/pkg/agent"@@ -47,7 +48,9 @@ const (// precedes the block — write a missing file from scratch) from "file// that pre-existed" (managed separator precedes the block) so the// file's existence is preserved exactly across the inject→cleanup- // cycle, including empty / whitespace-only pre-existing files.+ // cycle, including empty / whitespace-only pre-existing files. Blocks+ // written by current daemons also carry boundary metadata, which is+ // itself proof the file pre-existed (see runtimeBoundaryPrefix).runtimeManagedSeparator = "\n\n")@@ -234,11 +237,15 @@ func runtimeConfigPath(workDir, provider string) string {// separator's bytes are part of the managed region so Cleanup can// restore the user's pre-injection bytes exactly (no trailing-newline// normalisation, no surprises for files that ended without a newline-// or with extra trailing newlines).+// or with extra trailing newlines). The block's first line records+// the file's original trailing CR/LF bytes and whether it was blank+// (see runtimeBoundaryPrefix), so Cleanup can still restore the exact+// boundary after a formatter normalises the separator.// - file present, marker block already there → replace the body between// the markers in place so repeated runs in the same workdir don't grow// the file unboundedly. The pre-block content (including any managed-// separator established by the first inject) is preserved verbatim.+// separator established by the first inject) and the first inject's+// boundary metadata are preserved verbatim.//// The previous implementation called os.WriteFile unconditionally, which// silently truncated a repository's CLAUDE.md / AGENTS.md the@@ -257,6 +264,12 @@ func writeRuntimeConfigFile(path, brief string) error {existingStr := string(existing)if start, end, ok := locateMarkerBlock(existingStr); ok {+ // Carry the boundary metadata recorded by the first Inject forward+ // so a re-injection never re-baselines against the already-injected+ // file (whose "original" bytes would include our own separator).+ if meta, ok := parseRuntimeBoundaryMeta(existingStr[start:end]); ok {+ block = runtimeBlockWithBoundaryMeta(block, meta)+ }// Replace the existing block in place. locateMarkerBlock already// consumes the trailing newline that closed the previous block, so// successive runs don't accumulate blank lines around the block.@@ -271,9 +284,111 @@ func writeRuntimeConfigFile(path, brief string) error {// that already end in two or more newlines — so the byte boundary// between user content and the managed region is deterministic, which// is what lets Cleanup roll back to the user's exact original bytes.+ //+ // The separator alone is not enough once a Markdown formatter runs+ // between Inject and Cleanup: formatters collapse the blank lines in+ // front of the block (or drop them entirely for a blank file), so the+ // user's own trailing newlines become indistinguishable from ours.+ // Record them inside the block, which formatters leave alone.+ trimmed := strings.TrimRight(existingStr, "\r\n")+ block = runtimeBlockWithBoundaryMeta(block, runtimeBoundaryMeta{+ boundary: existingStr[len(trimmed):],+ blank: trimmed == "",+ })return os.WriteFile(path, []byte(existingStr+runtimeManagedSeparator+block), 0o644)}+// runtimeBoundaryPrefix opens the metadata line written as the first line+// inside the marker block whenever Inject appends to a pre-existing file:+//+// <!-- MULTICA-RUNTIME original-boundary: "<quoted CR/LF bytes>"[ blank] -->+//+// Its presence also means "the file existed before Inject", so Cleanup never+// deletes a file that carries it. Daemons that predate the metadata strip it+// together with the block, so mixed-version inject/cleanup stays safe.+const runtimeBoundaryPrefix = "<!-- MULTICA-RUNTIME original-boundary: "++// runtimeBoundaryMeta is the pre-injection state Cleanup needs to undo a+// formatter-normalised separator.+type runtimeBoundaryMeta struct {+ // boundary is the run of trailing CR/LF bytes the user's file ended with.+ boundary string+ // blank reports that the file held nothing but those bytes. Cleanup+ // only restores the boundary into an empty prefix when this is set;+ // otherwise an empty prefix means the agent legitimately removed or+ // moved the original content, and re-adding the old newlines would+ // leak a stray blank line into the user's file.+ blank bool+}++func runtimeBlockWithBoundaryMeta(block string, meta runtimeBoundaryMeta) string {+ line := runtimeBoundaryPrefix + strconv.Quote(meta.boundary)+ if meta.blank {+ line += " blank"+ }+ line += " -->\n"+ return strings.Replace(block, runtimeMarkerBegin+"\n", runtimeMarkerBegin+"\n"+line, 1)+}++// parseRuntimeBoundaryMeta reads the metadata line from a marker block.+// Anything malformed is treated as absent so Cleanup falls back to the+// legacy fixed-separator behaviour instead of guessing.+func parseRuntimeBoundaryMeta(block string) (runtimeBoundaryMeta, bool) {+ line := strings.TrimLeft(strings.TrimPrefix(block, runtimeMarkerBegin), "\r\n")+ if !strings.HasPrefix(line, runtimeBoundaryPrefix) {+ return runtimeBoundaryMeta{}, false+ }+ rest := strings.TrimPrefix(line, runtimeBoundaryPrefix)+ quoted, err := strconv.QuotedPrefix(rest)+ if err != nil {+ return runtimeBoundaryMeta{}, false+ }+ boundary, err := strconv.Unquote(quoted)+ if err != nil || strings.Trim(boundary, "\r\n") != "" {+ return runtimeBoundaryMeta{}, false+ }+ meta := runtimeBoundaryMeta{boundary: boundary}+ switch tail := rest[len(quoted):]; {+ case strings.HasPrefix(tail, " blank -->"):+ meta.blank = true+ case strings.HasPrefix(tail, " -->"):+ default:+ return runtimeBoundaryMeta{}, false+ }+ return meta, true+}++// runtimeIsCollapsedSeparator reports whether gap (the CR/LF run between the+// user's last content byte and the marker block) is exactly two line breaks,+// i.e. the single blank line a Markdown formatter leaves before an HTML block.+// Line breaks may be LF or CRLF since formatters may rewrite line endings.+func runtimeIsCollapsedSeparator(gap string) bool {+ breaks := 0+ for rest := gap; rest != ""; breaks++ {+ switch {+ case strings.HasPrefix(rest, "\r\n"):+ rest = rest[2:]+ case rest[0] == '\n':+ rest = rest[1:]+ default:+ return false+ }+ }+ return breaks == 2+}++// runtimeBoundaryInStyle rewrites the recorded boundary into the line-ending+// style of the gap the formatter left behind, so restoring an original CRLF+// boundary into a file the formatter converted to LF (or vice versa) does+// not produce mixed line endings.+func runtimeBoundaryInStyle(boundary, gap string) string {+ lf := strings.ReplaceAll(boundary, "\r\n", "\n")+ if strings.HasPrefix(gap, "\r\n") {+ return strings.ReplaceAll(lf, "\n", "\r\n")+ }+ return lf+}+// locateMarkerBlock finds the [start, end) byte range of the Multica marker// block inside content. The returned `end` is one past the block's trailing// newline (if any) so callers can splice the block out without leaving an@@ -308,7 +423,11 @@ func locateMarkerBlock(content string) (start, end int, found bool) {return start, len(content), true}end = afterBegin + endRel + len(runtimeMarkerEnd)- if end < len(content) && content[end] == '\n' {+ // Consume the line break closing the block. A formatter that rewrites+ // the file to CRLF also rewrites the block's own LF, so accept both.+ if strings.HasPrefix(content[end:], "\r\n") {+ end += 2+ } else if end < len(content) && content[end] == '\n' {end++}return start, end, true@@ -325,9 +444,10 @@ func locateMarkerBlock(content string) (start, end int, found bool) {//// - file has no marker block → no-op (nothing was ever injected here);// - block is at the start of the file with no preceding managed-// separator → the file was created by Inject from a missing-file-// state. Remove the file outright so the post-cleanup directory-// listing is byte-identical to the pre-Inject one.+// separator and no boundary metadata → the file was created by Inject+// from a missing-file state. Remove the file outright so the+// post-cleanup directory listing is byte-identical to the pre-Inject+// one.// - block is preceded by the fixed managed separator → strip the// separator together with the block; whatever remains (which may be// an empty pre-existing file, a whitespace-only file, or arbitrary@@ -335,6 +455,11 @@ func locateMarkerBlock(content string) (start, end int, found bool) {// with NO trailing-newline normalisation and NO TrimSpace-based file// removal heuristic. Both of those were sources of subtle diff in// PR #3438 review feedback.+// - block carries boundary metadata and a formatter normalised the+// separator (collapsed to one blank line, or dropped in front of a+// blank file) → restore the recorded original boundary instead of+// stripping a fixed width, in the line-ending style the formatter+// left. Edits to the user content around the block are kept as-is.//// Required for the local_directory flow (WorkDir is the user's own repo):// without this pass, a manual `claude` / `codex` run started by@@ -366,18 +491,31 @@ func CleanupRuntimeConfig(workDir, provider string) error {pre := existingStr[:start]post := existingStr[end:]- // Detect — and strip — the fixed managed separator that Inject puts- // immediately before the block whenever it appended to a file that- // pre-existed. The absence of the separator is the marker that says- // "Inject created this file from scratch", which is the only case- // where Cleanup is allowed to delete the file.+ // Undo the managed separator. With boundary metadata (blocks written by+ // this version) two formatter-normalised shapes are restored from the+ // record instead of by stripping a fixed width:+ // - the separator collapsed to a single blank line after user content;+ // - a blank pre-existing file whose separator the formatter dropped,+ // and which is still blank apart from the block. If content now+ // follows the block, the agent wrote the file's new body; putting+ // the old blank lines back in front of it would leak a stray diff.+ // Every other shape — legacy blocks, untouched separators, or user edits+ // to the boundary — keeps the fixed-separator behaviour.hadManagedSeparator := strings.HasSuffix(pre, runtimeManagedSeparator)- if hadManagedSeparator {+ meta, hasMeta := parseRuntimeBoundaryMeta(existingStr[start:end])+ trimmedPre := strings.TrimRight(pre, "\r\n")+ gap := pre[len(trimmedPre):]+ switch {+ case hasMeta && trimmedPre != "" && runtimeIsCollapsedSeparator(gap):+ pre = trimmedPre + runtimeBoundaryInStyle(meta.boundary, gap)+ case hasMeta && meta.blank && pre == "" && post == "":+ pre = meta.boundary+ case hadManagedSeparator:pre = pre[:len(pre)-len(runtimeManagedSeparator)]}remainder := pre + post- if !hadManagedSeparator && remainder == "" {+ if !hadManagedSeparator && !hasMeta && remainder == "" {// Inject created the file (no managed separator → block was the// only content). Restore the missing-file state.if err := os.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) {diff --git a/server/internal/daemon/execenv/runtime_config_test.go b/server/internal/daemon/execenv/runtime_config_test.goindex 8fe7c94a2c..c94d3368b8 100644--- a/server/internal/daemon/execenv/runtime_config_test.go+++ b/server/internal/daemon/execenv/runtime_config_test.go@@ -1649,6 +1649,76 @@ func TestInjectThenCleanupRoundTripByteExactBoundaries(t *testing.T) {}}+// Markdown formatters collapse the blank lines before an HTML block to one+// and drop leading blank lines entirely. lfFormatter also rewrites CRLF to LF+// (Prettier's default endOfLine); crlfFormatter keeps the file's CRLF style+// and applies it to the whole file, including the managed block.+func lfFormatter(s string) string {+ s = strings.ReplaceAll(s, "\r\n", "\n")+ for strings.Contains(s, "\n\n\n") {+ s = strings.ReplaceAll(s, "\n\n\n", "\n\n")+ }+ return strings.TrimLeft(s, "\n")+}++func crlfFormatter(s string) string {+ return strings.ReplaceAll(lfFormatter(s), "\n", "\r\n")+}++func TestCleanupRuntimeConfigAfterFormatting(t *testing.T) {+ t.Parallel()+ for _, tc := range []struct {+ name, seed string+ format func(string) string+ want string+ }{+ {"no newline", "rules", lfFormatter, "rules"},+ {"one newline", "rules\n", lfFormatter, "rules\n"},+ {"two newlines", "rules\n\n", lfFormatter, "rules\n\n"},+ {"multi-line", "# Rules\n\n- a\n- b\n", lfFormatter, "# Rules\n\n- a\n- b\n"},+ {"empty file", "", lfFormatter, ""},+ {"blank file", "\n\n", lfFormatter, "\n\n"},+ // The formatter rewrote the user's line endings itself; the restored+ // boundary follows that style instead of leaving a stray CRLF.+ {"crlf to lf", "a\r\nb\r\n", lfFormatter, "a\nb\n"},+ {"crlf preserved", "a\r\nb\r\n", crlfFormatter, "a\r\nb\r\n"},+ {"crlf two newlines preserved", "a\r\n\r\n", crlfFormatter, "a\r\n\r\n"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ dir := t.TempDir()+ path := filepath.Join(dir, "CLAUDE.md")+ if err := os.WriteFile(path, []byte(tc.seed), 0o644); err != nil {+ t.Fatal(err)+ }+ if _, err := InjectRuntimeConfig(dir, "claude", TaskContextForEnv{}); err != nil {+ t.Fatal(err)+ }+ injected, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path, []byte(tc.format(string(injected))), 0o644); err != nil {+ t.Fatal(err)+ }+ // Re-inject after formatting: metadata must survive the replace path.+ if _, err := InjectRuntimeConfig(dir, "claude", TaskContextForEnv{}); err != nil {+ t.Fatal(err)+ }+ if err := CleanupRuntimeConfig(dir, "claude"); err != nil {+ t.Fatal(err)+ }+ got, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("file must survive cleanup: %v", err)+ }+ if string(got) != tc.want {+ t.Fatalf("cleanup changed user content after formatting: got %q, want %q", got, tc.want)+ }+ })+ }+}+// Idempotency across the byte-exact boundaries: when a second Inject runs// against a file that already carries a marker block (the "replace in// place" branch), the surrounding bytes must stay untouched and the@@ -1701,6 +1771,123 @@ func TestInjectReplaceThenCleanupRestoresByteExact(t *testing.T) {}}+func TestCleanupRuntimeConfigPreservesEditsAfterFormatting(t *testing.T) {+ t.Parallel()+ for _, tc := range []struct {+ name, seed, prefix, suffix, want string+ }{+ {"edited body", "rules\n", "updated rules\n\n", "", "updated rules\n"},+ {"added suffix", "rules\n", "rules\n\n", "\nnew section\n", "rules\n\nnew section\n"},+ {"edited boundary", "rules\n", "rules\n\n\n\n", "", "rules\n\n"},+ // An empty prefix only means "blank original" when the metadata says+ // so. Here the agent deleted the original body (and may have written+ // a replacement after the block); the old trailing newline must not+ // come back in front of the new content.+ {"body replaced after block", "# Old\n", "", "# New\n", "# New\n"},+ {"body deleted", "# Old\n", "", "", ""},+ {"blank file gains content after block", "", "", "# New\n", "# New\n"},+ // Newline-only originals: the formatter dropped the leading blank+ // lines and the agent wrote a body after the block. The recorded+ // newlines must not be restored in front of the new body.+ {"newline-only file gains content after block", "\n", "", "# New\n", "# New\n"},+ {"crlf-only file gains content after block", "\r\n", "", "# New\r\n", "# New\r\n"},+ {"newline-only file left blank", "\n", "", "", "\n"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ dir := t.TempDir()+ path := filepath.Join(dir, "CLAUDE.md")+ if err := os.WriteFile(path, []byte(tc.seed), 0o644); err != nil {+ t.Fatal(err)+ }+ if err := writeRuntimeConfigFile(path, "brief"); err != nil {+ t.Fatal(err)+ }+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ start, end, found := locateMarkerBlock(string(data))+ if !found {+ t.Fatal("missing block")+ }+ if err := os.WriteFile(path, []byte(tc.prefix+string(data[start:end])+tc.suffix), 0o644); err != nil {+ t.Fatal(err)+ }+ if err := CleanupRuntimeConfig(dir, "claude"); err != nil {+ t.Fatal(err)+ }+ got, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("pre-existing file must survive cleanup: %v", err)+ }+ if string(got) != tc.want {+ t.Fatalf("got %q, want %q", got, tc.want)+ }+ })+ }+}++func TestParseRuntimeBoundaryMeta(t *testing.T) {+ t.Parallel()+ for _, tc := range []struct {+ metadata string+ ok bool+ want runtimeBoundaryMeta+ }{+ {`"\n" -->` + "\n", true, runtimeBoundaryMeta{boundary: "\n"}},+ {`"\r\n\r\n" -->` + "\n", true, runtimeBoundaryMeta{boundary: "\r\n\r\n"}},+ {`"" blank -->` + "\n", true, runtimeBoundaryMeta{boundary: "", blank: true}},+ {`"\n" blank -->` + "\r\n", true, runtimeBoundaryMeta{boundary: "\n", blank: true}},+ {`"text" -->`, false, runtimeBoundaryMeta{}},+ {`"\n"`, false, runtimeBoundaryMeta{}},+ {`"\n" bogus -->`, false, runtimeBoundaryMeta{}},+ {`invalid -->`, false, runtimeBoundaryMeta{}},+ } {+ block := runtimeMarkerBegin + "\n" + runtimeBoundaryPrefix + tc.metadata+ got, ok := parseRuntimeBoundaryMeta(block)+ if ok != tc.ok || got != tc.want {+ t.Errorf("metadata %q: got (%+v, %v), want (%+v, %v)", tc.metadata, got, ok, tc.want, tc.ok)+ }+ }+}++// A daemon that predates boundary metadata strips the metadata line together+// with the block, and a current daemon cleaning a legacy block (no metadata)+// keeps the fixed-separator behaviour, including deleting files it created.+func TestCleanupRuntimeConfigLegacyBlockCompat(t *testing.T) {+ t.Parallel()+ legacyBlock := runtimeMarkerBegin + "\nbrief\n" + runtimeMarkerEnd + "\n"+ for _, tc := range []struct {+ name, content string+ want *string+ }{+ {"legacy appended", "rules\n" + runtimeManagedSeparator + legacyBlock, legacyWant("rules\n")},+ {"legacy created", legacyBlock, nil},+ } {+ dir := t.TempDir()+ path := filepath.Join(dir, "CLAUDE.md")+ if err := os.WriteFile(path, []byte(tc.content), 0o644); err != nil {+ t.Fatal(err)+ }+ if err := CleanupRuntimeConfig(dir, "claude"); err != nil {+ t.Fatal(err)+ }+ got, err := os.ReadFile(path)+ if tc.want == nil {+ if !os.IsNotExist(err) {+ t.Errorf("%s: created file must be removed, got %q (err %v)", tc.name, got, err)+ }+ continue+ }+ if err != nil || string(got) != *tc.want {+ t.Errorf("%s: got %q (err %v), want %q", tc.name, got, err, *tc.want)+ }+ }+}++func legacyWant(s string) *string { return &s }+// The fixed managed separator is the invariant that makes byte-exact// cleanup possible. This test pins it: writeRuntimeConfigFile must// produce exactly `<user-bytes><\n\n><marker-block>` for ANY non-empty