diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index cebe5ad8d..678710f91 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -59,6 +59,7 @@ something else shows up as drift. - Codex's "subagents" field is `[agents] default_subagent_model`: only the model a subagent starts on when its lead names none in `spawn_agent` (codex-rs `core/src/agent/child_config.rs`). Unset, it isn't "same as model": the lead may still name another, so the GUI calls it the lead's pick, else the model (`leadPicks` in app.js), and its title points at the "subagent model" field. - Codex's "subagent model" field writes nothing to Codex's config: its lead names each subagent's model in `spawn_agent`, which `[agents]` can't overrule. It is magpie's setting (`settings.CodexSubagentModel`, [`codex_subagent.go`](../../internal/provider/codex_subagent.go)), and the gateway moves the subagent's request onto it (see [gateway routing](gateway-routing.md)). Its options are every model and routing group Codex's own lists show (`CatalogFor("codex")`, so a model taken out of them or not picked is left out here too), ChatGPT accounts' first (#1633: a lead on a chat provider wants its subagents there too). A task a ChatGPT-backed lead sealed opens only on a ChatGPT account, so the gateway keeps such a subagent on its own model when the one set is another provider's. Its setter takes any `provider/model` or `group/`, also one magpie doesn't serve now, so a profile or backup put back on another computer still applies (`ApplyFields` stops at the first failed Set), and refuses one of Codex's own bare names. - Snow CLI runs on one profile at a time (`profiles/.json` in `~/.snow` or `$SNOW_CONFIG_DIR`, named in `active-profile.json`) and copies the active one over `config.json` at every start, `snow --ask` too ([`snow.go`](../../internal/agent/snow.go)). magpie writes a `magpie` profile, makes it the active one, and copies it to `config.json` itself, so a Snow already running and Snow App's "Sync Snow CLI API config" see the same. It is made from the profile the user was on, their settings kept and its OAuth sign-in left out. A vision model of that profile comes along only with an endpoint and key of its own (`snowOwnVision`), since one on the profile's would now go to the gateway. `maxContextTokens`, `maxTokens` and `supportsVision` follow the model from the catalog (`snowSynced`; `supportsVision` as every agent is told, true while magpie's Vision describes images); what magpie last wrote of them is stashed, and one the user changed since in Snow's own settings is kept through later picks and syncs. The small field is magpie's profile's `basicModel`, Snow's light model for summaries, compaction and file search: empty while it follows the main model, a model through magpie of its own kept through new main models and syncs; on a profile of the user's it offers nothing and is hidden. The thinking field is magpie's profile's `chatThinking` (`{enabled: true, reasoning_effort}`), the only thinking setting Snow reads on the chat protocol; empty deletes it, Snow's default, which sends thinking disabled. A chatThinking the user brought from their profile is shown, not written over. The profile they were on (or that there was no `active-profile.json`) and a `magpie.json` of their own are stashed and put back by Disconnect. A Snow from before profiles (`config.json` alone) gets the `default.json` Snow itself would have made of it, so its next start doesn't take magpie's for the user's. Picking a model of another of the user's profiles switches Snow to that profile. On magpie's profile, a value that is neither a model through magpie nor the model of one of the user's profiles is refused and changes nothing (#1457: `magpie snow --help` used to take magpie out and write `--help` as the model of the profile it went back to). Gemini CLI's auth field refuses an auth it doesn't know before it unroutes, for the same reason. On the CLI, `-h`/`--help` after any command or agent only prints its usage, before `run` reads or moves anything, and any other flag given to `magpie …` is refused (`help_cli.go`; `TestHelpOnEveryCommandDoesNothing` walks `run`'s switch and every agent). +- omp's `enabledModels` in `config.yml` is the list it holds its default role to: a model left out of it isn't used, whatever `modelRoles.default` says (#1769). So a model picked for the default role is added to a list that is there and doesn't take it in already, by name or by one of omp's globs (`*` not crossing `/`, as `Bun.Glob`), and once nothing in `config.yml` is on magpie its plain `magpie/…` entries are taken out (a list left empty goes, never `[]`); a renamed provider's entries are renamed once, and folder-scoped entries are left alone (`ompScope*` in [`omp_scope.go`](../../internal/agent/omp_scope.go)). No list, no change: omp then takes every model. A list that leaves the default role's model out is drift, which Reapply mends. - A value an agent spells as its own provider's model is never taken for one of magpie's, even when magpie has a provider of the same name (`Spelled`, #835). - `Reapply` on `unwired` sets again every field on one of magpie's models and every field set to magpie itself (`magpieID`, as `Wired` takes it): Claude Desktop's drift shows on a tier, and its `provider` field is what writes the gateway back (dumplings on Discord). Claude Desktop's `Check` judges only the set of folders whose Claude-3p it ran in last (`desktopRead`, by `desktopdir.LastRun`), every set when it ran in none: magpie writes both of an MSIX install's sets, and 2.31226 reads the real `%LOCALAPPDATA%\Claude-3p`, so the package's copy being emptied is not Desktop off magpie. - `unreachable` never sets anything: the config is right, and the page's pill only says what has to listen. The exception is an address a WSL distro reached Windows at before (`distro.Was`, kept in `wsl.json`) while it reaches Windows at another now: the pill offers that one, and `Reapply` moves the config there (`Agent.move`, Codex's `codexMoveGateway`). An address no distro was seen at is the user's own and is never moved. An unknown answer (no probe yet) and a gateway down on loopback too are not drift. Tests stub `reachProbe` in `TestMain`. diff --git a/internal/agent/omp.go b/internal/agent/omp.go index 7c28ac55d..36ebe022f 100644 --- a/internal/agent/omp.go +++ b/internal/agent/omp.go @@ -244,14 +244,28 @@ func ompAt(at place, dir string, entry func() ompProviderEntry) *Agent { // the config is on magpie; while something is (a fallback chain, another // role), it writes it afresh instead, so a role set off magpie — applying // again what Check found — mends the wiring that is left. + // The plain entries of enabledModels on magpie, which magpie adds there + // (omp_scope.go), don't count: once nothing else is on magpie they go + // with its provider (#1769). Those scoped to folders are the user's, and + // count. dropMagpie := func() error { - used, err := onMagpie() + used := false + err := edit.EditYAMLStrings(path, slices.DeleteFunc(slices.Clone(ompRefKeys), func(k string) bool { return k == "enabledModels" }), func(v string) string { + ompRefs(v, func(m string) string { used = used || usesMagpie(m); return m }) + return v + }) + if err == nil && !used { + used, err = ompScopeFoldersOnMagpie(path) + } switch { case err != nil: return err case used: return writeMagpie() } + if err := ompScopeWithout(path); err != nil { + return err + } return edit.DelYAML(pick("models"), "providers."+magpieID) } // was are the stash's keys for the roles, one each @@ -372,6 +386,20 @@ func ompAt(at place, dir string, entry func() ompProviderEntry) *Agent { role("tiny", "tiny", "tiny", true), role("memory", "memory", "memory", true), } + // the default role's model is what a new session starts on only while + // enabledModels takes it in, so a model picked for it joins the list + // there is (omp_scope.go, #1769); a reset puts back what the user had, + // which is theirs to have scoped or not + setDefault := roles[0].Set + roles[0].Set = func(v string) error { + if err := setDefault(v); err != nil || v == "" { + return err + } + if model, _, one := ompSplit(roleGet("default")()); one && model != "" { + return ompScopeWith(path, model) + } + return nil + } // each role but the default one has a thinking level of its own, the // ":level" omp reads off the end of the role's model // (splitThinkingSuffix, resolveModelRoleValue): #1397, the slow role at @@ -447,6 +475,9 @@ func ompAt(at place, dir string, entry func() ompProviderEntry) *Agent { }); err != nil { return moved, err } + if err := ompScopeOnce(path); err != nil { + return moved, err + } for _, w := range was { s := stashLoad()[w] ns := move(s) @@ -476,8 +507,18 @@ func ompAt(at place, dir string, entry func() ompProviderEntry) *Agent { return "" } models := pick("models") - return wiringOff("omp", models, func(k string) (string, bool) { return edit.GetYAML(models, "providers."+magpieID+"."+k) }, - "baseUrl", at.v1()) + if d := wiringOff("omp", models, func(k string) (string, bool) { return edit.GetYAML(models, "providers."+magpieID+"."+k) }, + "baseUrl", at.v1()); d != "" { + return d + } + // a default role on magpie that enabledModels leaves out never + // starts; setting it again adds it there (#1769) + if def := roleGet("default")(); ompOnMagpie(def) { + if m := ompScopeLeavesOut(path, def); m != "" { + return "omp's enabledModels (" + filepath.Base(path) + ") leaves out " + m + ", so new sessions start on another of its models" + } + } + return "" }, Fields: append(fields, Field{ // the thinking level sessions start with, as omp's settings save diff --git a/internal/agent/omp_scope.go b/internal/agent/omp_scope.go new file mode 100644 index 000000000..7c9c950ea --- /dev/null +++ b/internal/agent/omp_scope.go @@ -0,0 +1,166 @@ +package agent + +import ( + "strings" + + "github.com/yetone/magpie/internal/edit" + "gopkg.in/yaml.v3" +) + +// omp's enabledModels (config.yml) is, as Pi's is (pi.go), the list a new +// session is held to while it names anything: the default role starts only +// when the list takes its model in, else omp picks another model from the +// list (main.ts buildSessionOptions, sdk.ts resolveAllowedModels and +// pickDefaultAvailableModel), so a model magpie picks outside it never +// starts (#1769). omp's other roles are resolved against every model it has +// (task/executor.ts resolveModelOverride, session/model-controls.ts +// resolveRoleModelFull, both on modelRegistry.getAvailable()), so only the +// default role is held to the list. +// +// The list is the user's: magpie adds the default role's model to it as Pi's +// fix did (#160), keeps the entries, their order and comments, +// and never makes a list where there is none or an empty one. Its plain +// entries hold in every folder; an entry scoped to folders ({path, models}) +// is the user's list for those projects and left as it is. + +// ompScopePlain are the plain entries of an enabledModels node. +func ompScopePlain(n *yaml.Node) []string { + if n == nil || n.Kind != yaml.SequenceNode { + return nil + } + var out []string + for _, c := range n.Content { + if c.Kind == yaml.ScalarNode && c.ShortTag() == "!!str" { + out = append(out, c.Value) + } + } + return out +} + +// ompTakes reports whether an enabledModels entry surely takes in model, a +// provider/model with no level: Pi's rules (piTakes), with the levels omp +// reads off an entry's end, auto among them. +func ompTakes(pattern, model string) bool { + p, _ := ompLevel(strings.TrimSpace(pattern)) + return piTakes(p, model) +} + +// ompScopeTakes says whether the plain entries take in model; true when +// there are none, as then nothing holds a session to them. +func ompScopeTakes(plain []string, model string) bool { + if len(plain) == 0 { + return true + } + for _, p := range plain { + if ompTakes(p, model) { + return true + } + } + return false +} + +// ompScopeWith adds model, a provider/model, to the end of config.yml's +// enabledModels when it has plain entries and none takes model in. +func ompScopeWith(cfg, model string) error { + return edit.EditYAMLNode(cfg, "enabledModels", func(n *yaml.Node) (bool, bool) { + if ompScopeTakes(ompScopePlain(n), model) { + return false, false + } + n.Content = append(n.Content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: model}) + return true, false + }) +} + +// ompScopeWithout takes magpie's models out of enabledModels's plain +// entries once nothing else in config.yml is on magpie, and its provider +// leaves models.yml: there they would name nothing. A list left empty is +// removed, never written as []. +func ompScopeWithout(cfg string) error { + return edit.EditYAMLNode(cfg, "enabledModels", func(n *yaml.Node) (bool, bool) { + if n == nil || n.Kind != yaml.SequenceNode { + return false, false + } + kept := n.Content[:0:0] + for _, c := range n.Content { + if c.Kind == yaml.ScalarNode && !strings.ContainsAny(c.Value, "*?[") && + strings.HasPrefix(strings.ToLower(strings.TrimSpace(c.Value)), magpieID+"/") { + continue + } + kept = append(kept, c) + } + if len(kept) == len(n.Content) { + return false, false + } + if len(kept) == 0 { + return false, true + } + n.Content = kept + return true, false + }) +} + +// ompScopeOnce drops a plain entry of enabledModels that an earlier one +// spells the same: a provider renamed has the default role, set again under +// the new id, join the list (ompScopeWith) before the old entry is renamed +// to it. +func ompScopeOnce(cfg string) error { + return edit.EditYAMLNode(cfg, "enabledModels", func(n *yaml.Node) (bool, bool) { + if n == nil || n.Kind != yaml.SequenceNode { + return false, false + } + seen := map[string]bool{} + kept := n.Content[:0:0] + for _, c := range n.Content { + if c.Kind == yaml.ScalarNode { + if seen[c.Value] { + continue + } + seen[c.Value] = true + } + kept = append(kept, c) + } + if len(kept) == len(n.Content) { + return false, false + } + n.Content = kept + return true, false + }) +} + +// ompScopeFoldersOnMagpie says whether an entry of enabledModels scoped to +// folders names one of magpie's models: the user's own, which keeps +// magpie's provider as a role on it does. +func ompScopeFoldersOnMagpie(cfg string) (used bool, err error) { + err = edit.EditYAMLNode(cfg, "enabledModels", func(n *yaml.Node) (bool, bool) { + if n == nil || n.Kind != yaml.SequenceNode { + return false, false + } + for _, c := range n.Content { + if c.Kind != yaml.MappingNode { + continue + } + var walk func(*yaml.Node) + walk = func(n *yaml.Node) { + if n.Kind == yaml.ScalarNode { + ompRefs(n.Value, func(m string) string { used = used || usesMagpie(m); return m }) + } + for _, c := range n.Content { + walk(c) + } + } + walk(c) + } + return false, false + }) + return used, err +} + +// ompScopeLeavesOut is the default role's model when enabledModels has +// plain entries and none takes it in: a new session would start on another. +func ompScopeLeavesOut(cfg, role string) string { + model, _, one := ompSplit(role) + if !one || model == "" || ompScopeTakes(edit.GetYAMLList(cfg, "enabledModels"), model) { + return "" + } + return model +} diff --git a/internal/agent/omp_scope_test.go b/internal/agent/omp_scope_test.go new file mode 100644 index 000000000..d44727514 --- /dev/null +++ b/internal/agent/omp_scope_test.go @@ -0,0 +1,206 @@ +package agent + +import ( + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/provider" + "gopkg.in/yaml.v3" +) + +// ompScopeHome is a home with omp's agent folder and a provider of magpie's. +func ompScopeHome(t *testing.T) (home, configPath, modelsPath string) { + t.Helper() + home = t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + for _, k := range []string{"PI_CODING_AGENT_DIR", "PI_CONFIG_DIR", "OMP_PROFILE", "PI_PROFILE"} { + t.Setenv(k, "") + } + if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro", "flash"}}); err != nil { + t.Fatal(err) + } + dir := filepath.Join(home, ".omp", "agent") + os.MkdirAll(dir, 0o755) + return home, filepath.Join(dir, "config.yml"), filepath.Join(dir, "models.yml") +} + +func ompScopeRead(t *testing.T, p string) (map[string]any, string) { + t.Helper() + b, _ := os.ReadFile(p) + var m map[string]any + yaml.Unmarshal(b, &m) + return m, string(b) +} + +// The reporter's case (#1769): omp's config.yml already has a non-empty +// enabledModels, and the default role is set to one of magpie's models +// outside it. omp would start new sessions on a model from the list, so the +// model joins its end, without its level; the user's entries, their order +// and comments stay. Only the default role is held to the list (omp +// resolves its other roles against every model it has). +func TestOmpDefaultJoinsEnabledModels(t *testing.T) { + home, configPath, _ := ompScopeHome(t) + os.WriteFile(configPath, []byte("# mine\nenabledModels:\n - provider-a/model-a # first\n - provider-b/model-b\nmodelRoles:\n default: provider-a/model-a\n"), 0o644) + a := omp(home) + if err := a.Field("model").Set("magpie/deepseek/pro:high"); err != nil { + t.Fatal(err) + } + want := []string{"provider-a/model-a", "provider-b/model-b", "magpie/deepseek/pro"} + if got := edit.GetYAMLList(configPath, "enabledModels"); !slices.Equal(got, want) { + t.Fatalf("enabledModels: %q, want %q", got, want) + } + if _, raw := ompScopeRead(t, configPath); !strings.Contains(raw, "# mine") || !strings.Contains(raw, "# first") { + t.Fatalf("comments lost:\n%s", raw) + } + if v, _ := edit.GetYAML(configPath, "modelRoles.default"); v != "magpie/deepseek/pro:high" { + t.Fatalf("default: %q", v) + } + // set again, or at another level: listed once + for _, v := range []string{"magpie/deepseek/pro:high", "magpie/deepseek/pro:low"} { + if err := a.Field("model").Set(v); err != nil { + t.Fatal(err) + } + } + if got := edit.GetYAMLList(configPath, "enabledModels"); !slices.Equal(got, want) { + t.Fatalf("set again: %q", got) + } + // a role other than the default isn't held to the list + if err := a.Field("small").Set("magpie/deepseek/flash"); err != nil { + t.Fatal(err) + } + if got := edit.GetYAMLList(configPath, "enabledModels"); !slices.Equal(got, want) { + t.Fatalf("smol: %q", got) + } + // the user's own model outside the list joins it too, as it would never + // start either + if err := a.Field("model").Set("provider-c/model-c"); err != nil { + t.Fatal(err) + } + if got := edit.GetYAMLList(configPath, "enabledModels"); !slices.Contains(got, "provider-c/model-c") { + t.Fatalf("own model: %q", got) + } +} + +// No list is made where there is none, an empty one stays as it is, and so +// does one with only entries scoped to folders (a plain entry would hold +// every other folder to it). An entry that already takes the model in — +// the same model at a level, a glob — is enough. +func TestOmpEnabledModelsLeftAlone(t *testing.T) { + cases := []struct{ name, config string }{ + {"none", "modelRoles:\n default: a/b\n"}, + {"empty", "enabledModels: []\nmodelRoles:\n default: a/b\n"}, + {"folders only", "enabledModels:\n - path: /work\n models:\n - a/b\n"}, + {"same at a level", "enabledModels:\n - a/b\n - magpie/deepseek/pro:max\n"}, + {"glob", "enabledModels:\n - a/b\n - magpie/deepseek/*\n"}, + // omp matches a glob against provider/id and the id alone (Bun.Glob, + // whose * stops at a slash), and a model of magpie's id is + // provider/model + {"glob on the id", "enabledModels:\n - a/b\n - deepseek/*\n"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + home, configPath, _ := ompScopeHome(t) + os.WriteFile(configPath, []byte(c.config), 0o644) + before, _ := ompScopeRead(t, configPath) + if err := omp(home).Field("model").Set("magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + after, raw := ompScopeRead(t, configPath) + bs, _ := yaml.Marshal(before["enabledModels"]) + as, _ := yaml.Marshal(after["enabledModels"]) + if string(bs) != string(as) { + t.Fatalf("enabledModels changed:\n%s", raw) + } + }) + } +} + +// Once nothing else is on magpie, its models leave the list with its +// provider; a list left with nothing goes, never written as []. One scoped +// to folders is the user's and keeps the provider. +func TestOmpEnabledModelsCleared(t *testing.T) { + hasMagpie := func(modelsPath string) bool { + m, _ := ompScopeRead(t, modelsPath) + p, _ := m["providers"].(map[string]any) + return p["magpie"] != nil + } + + home, configPath, modelsPath := ompScopeHome(t) + os.WriteFile(configPath, []byte("enabledModels:\n - provider-a/model-a # mine\nmodelRoles:\n default: provider-a/model-a\n"), 0o644) + f := omp(home).Field("model") + if err := f.Set("magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + if err := f.Set(""); err != nil { + t.Fatal(err) + } + if v, _ := edit.GetYAML(configPath, "modelRoles.default"); v != "provider-a/model-a" { + t.Fatalf("reset: %q", v) + } + if got := edit.GetYAMLList(configPath, "enabledModels"); !slices.Equal(got, []string{"provider-a/model-a"}) { + t.Fatalf("enabledModels: %q", got) + } + if _, raw := ompScopeRead(t, configPath); !strings.Contains(raw, "# mine") { + t.Fatalf("comment lost:\n%s", raw) + } + if hasMagpie(modelsPath) { + t.Fatal("magpie's provider stayed") + } + + // the list had only magpie's model: the key goes + os.WriteFile(configPath, []byte("enabledModels:\n - magpie/deepseek/flash\nmodelRoles:\n default: magpie/deepseek/flash\n"), 0o644) + if err := f.Set(""); err != nil { + t.Fatal(err) + } + if c, raw := ompScopeRead(t, configPath); c["enabledModels"] != nil || strings.Contains(raw, "enabledModels") { + t.Fatalf("emptied list kept:\n%s", raw) + } + + // a folder's own list on magpie keeps it, and its entries + os.WriteFile(configPath, []byte("enabledModels:\n - magpie/deepseek/flash\n - path: /work\n models:\n - magpie/deepseek/pro\nmodelRoles:\n default: magpie/deepseek/flash\n"), 0o644) + if err := f.Set("magpie/deepseek/flash"); err != nil { + t.Fatal(err) + } + if err := f.Set(""); err != nil { + t.Fatal(err) + } + if !hasMagpie(modelsPath) { + t.Fatal("a folder's list on magpie lost magpie's provider") + } + if _, raw := ompScopeRead(t, configPath); !strings.Contains(raw, "magpie/deepseek/pro") { + t.Fatalf("folder's entry dropped:\n%s", raw) + } +} + +// A default role on magpie that a list written by hand leaves out shows as +// a model that won't start, and setting it again (Reapply) mends it. +func TestOmpEnabledModelsLeavingOutIsDrift(t *testing.T) { + home, configPath, _ := ompScopeHome(t) + os.WriteFile(configPath, []byte("modelRoles:\n default: provider-a/model-a\n"), 0o644) + a := omp(home) + if err := a.Field("model").Set("magpie/deepseek/pro:high"); err != nil { + t.Fatal(err) + } + if d := a.Check(); d != "" { + t.Fatalf("no list: %q", d) + } + if err := edit.SetYAML(configPath, edit.KV{Path: "enabledModels", Value: []string{"provider-a/model-a"}}); err != nil { + t.Fatal(err) + } + if d := a.Check(); !strings.Contains(d, "enabledModels") || !strings.Contains(d, "magpie/deepseek/pro") { + t.Fatalf("check: %q", d) + } + if err := a.Field("model").Set(a.Field("model").Get()); err != nil { + t.Fatal(err) + } + if d := a.Check(); d != "" { + t.Fatalf("set again: %q", d) + } +} diff --git a/internal/edit/yaml.go b/internal/edit/yaml.go index db58fc79b..385777f55 100644 --- a/internal/edit/yaml.go +++ b/internal/edit/yaml.go @@ -171,6 +171,26 @@ func DelYAML(path string, keyPaths ...string) error { return writeYAML(path, root) } +// EditYAMLNode hands fn the node at a key path, nil when there is none, to +// change in place: a list grown by one item keeps the comments on the rest, +// where SetYAML would write the whole value anew. fn says whether it changed +// the node, and whether the key is to go instead. The file is written only +// on a change. +func EditYAMLNode(path, keyPath string, fn func(n *yaml.Node) (changed, remove bool)) error { + root, err := loadYAMLForEdit(path) + if err != nil || root == nil { + return err + } + changed, remove := fn(lookupYAML(root, strings.Split(keyPath, "."))) + switch { + case remove: + return DelYAML(path, keyPath) + case changed: + return writeYAML(path, root) + } + return nil +} + // EditYAMLStrings calls fn on every string under the key paths — mapping // keys and values, sequence items, at any depth — and puts fn's answer in // its place, comments and quoting kept. The file is written only when an