diff --git a/.agents/skills/archie-config-and-flags/SKILL.md b/.agents/skills/archie-config-and-flags/SKILL.md index cd1ab837d..8b8f48f5e 100644 --- a/.agents/skills/archie-config-and-flags/SKILL.md +++ b/.agents/skills/archie-config-and-flags/SKILL.md @@ -119,8 +119,6 @@ Do not expose these helper flags as daemon settings. | `dispatch.labels.*` | Missing keys default independently to `agent:*`. | production-wired | | `models.` | Workflow stages read requested role then fall back to `builder`; triage judge falls back `triage` to `planner`. | production-wired | | `providers..class`, `api_key_env`, `base_url` | Builds ai-sdk catalog. `base_url` rejects parse errors, userinfo, query, and fragment. | production-wired | -| `agent.mode` | Default `nats` when containers enabled, otherwise `inprocess`; validates `inprocess`, `subprocess`, or `nats`. | production-wired | -| `agent.command`, `agent.env` | Command defaults `archie-agent`; env entries must be nonblank names without `=`. | partially-wired | | `budgets.max_steps`, `max_tokens`, `wall_clock`, `gate_max_failures` | No loader defaults; `Budgets` documents zero as disabling. | production-wired | | `diff_cap_lines` | Zero replaced by `400` in `finalize`; `StageDiffCap` treats `<= 0` as disabled. TOML zero cannot disable; negative value does. | production-wired | | `web.listen` | Empty becomes `127.0.0.1:8484`; literal `off` disables. No authentication. | production-wired | @@ -154,10 +152,6 @@ looking at before reporting one: from the stored resource, on purpose. Check for that comment before filing a defect. -The default `agent.command = "archie-agent"` is not verified subprocess -operation. `SubprocessRunner` expects one JSON invocation on stdin and one JSON -response on stdout; `cmd/archie-agent` is a long-running NATS worker. - ### Repository settings | Keys | Effective behavior | Status | @@ -175,7 +169,6 @@ response on stdout; `cmd/archie-agent` is a long-running NATS worker. | Key | Effective behavior | | --- | --- | -| `enabled` | Requires non-empty `image`, `agent.mode = "nats"`, and non-empty `nats.url`. | | `image` | Required only when enabled. | | `max_concurrency` | Zero means no limit; used by general task dispatcher and container pool. | | `max_uptime` | Default `60m` only when enabled; caps container lifetime. | @@ -188,7 +181,7 @@ response on stdout; `cmd/archie-agent` is a long-running NATS worker. | Keys | Effective behavior | | --- | --- | | `chat.models` | Optional interactive catalog; empty falls back to workflow model references. | -| `chat.telegram.token_env` | Empty disables Telegram; non-empty names env variable; empty value is fatal. | +| `chat.telegram.token` | Unset disables Telegram; otherwise a secret reference resolved at channel start. | | `chat.telegram.allowed_user_ids` | Empty denies every sender; IDs match Telegram sender IDs, not chat IDs. | | `chat.telegram.update_check_command`, `update_install_command` | Argv arrays; check enables update status; install further enables approved installation. | | `chat.email.listen_addr`, `relay_addr` | Empty listen disables SMTP; relay configures outbound replies. | @@ -225,20 +218,17 @@ diff cap, notification, and forge host. `TaskConfig.ToConfig` reconstructs only those fields. Forge tokens, provider values, NATS credential references, repos, and infrastructure settings do not enter `TaskConfig`. -At top-level `[forge]`, prefer `token = {engine = "env", key = "NAME"}`. The -`token_env = "NAME"` form is converted only when structured reference is empty; -structured reference wins when both appear. This compatibility rule exists -because an earlier migration silently dropped deployed `token_env` values and -crash-looped the daemon. `finalize` does not apply that conversion inside each -identity: identity forges require explicit structured `token`. +Every credential except `nats.token_env` is a `{engine, key}` secret +reference; the flat `token_env` aliases for forge, artifacts and Telegram are +removed. A stale alias in a file is reported at startup as an unrecognised key +(`bootstrap.go`), not silently ignored. | Source | Archied | Subprocess | Agent container / standalone worker | | --- | --- | --- | --- | | Forge `token = {engine="env", key="X"}` | Resolves `X`; empty is fatal. | Not forwarded. | Not forwarded; forge ops proxy to daemon. | | Provider `api_key_env = "X"` | Runtime reads `X`. | Auto-allowlists selected provider's `X`. | Daemon forwards each present provider variable under original name. | | `nats.token_env = "X"` | Reads `X`; empty fatal when configured. | Not agent subprocess setting. | Daemon maps to fixed `NATS_TOKEN`; worker also reads `NATS_URL`. | -| Telegram `token_env = "X"` | Reads `X`. | Not forwarded. | Not forwarded. | -| `agent.env = ["X"]` | Names validated. | Copies present `X` from daemon env. | Not used by container construction. | +| Telegram `token = {engine="env", key="X"}` | Resolves `X`. | Not forwarded. | Not forwarded. | `internal/app/archied` creates `secret.NewRegistry`, which registers only the `env` engine. Non-env `SecretRef` values are not production-wired. diff --git a/.agents/skills/archie-debugging-playbook/SKILL.md b/.agents/skills/archie-debugging-playbook/SKILL.md index 14b020b52..cc8b68d27 100644 --- a/.agents/skills/archie-debugging-playbook/SKILL.md +++ b/.agents/skills/archie-debugging-playbook/SKILL.md @@ -145,8 +145,6 @@ For environment failures: launch environment rather than Compose. - `containerEnv` translates configured NATS token name into `NATS_TOKEN` and forwards configured provider key variables. -- Top-level `[forge] token_env` is converted to an env `SecretRef` by - `finalize`; explicit `[forge.token]` wins. Do not print secret values. diff --git a/.agents/skills/archie-failure-archaeology/SKILL.md b/.agents/skills/archie-failure-archaeology/SKILL.md index ce5cce6a3..23f709742 100644 --- a/.agents/skills/archie-failure-archaeology/SKILL.md +++ b/.agents/skills/archie-failure-archaeology/SKILL.md @@ -155,7 +155,7 @@ If current behavior differs from chronicle, update the packet. | Incident and date | Symptom | Root cause | Evidence and status | Settled rule | |---|---|---|---|---| | Container network auto-detection, 2026-07-27 | Every container task returns `nats: no responders`. | `selfNetwork` inspected hostnamed container, silently fell back to default bridge. | `37cf089` records incident, adds `containers.network`; `2ac306b` pins `archie-core_default`. **Status:** `conditional`. | Make cross-container network membership explicit in deployment. | -| SecretRef schema crash-loop, 2026-07-27 | Both identities demand `ARCHIE_GITHUB_TOKEN` despite Gitea config. | Removing old `token_env` field let TOML ignore deployed value. `1f8588d` restored precedence-compatible fallback; a later `308c199` removed the `Forge.TokenEnv` declaration while `finalize` still referenced it. | **Status: `settled`** as of 2026-09-18 — `config.Forge.TokenEnv` is declared (`internal/config/config.go`) and `configuration/defaults.go` converts it to an env `SecretRef` when the structured token is empty. | Preserve decoded compatibility until deployed files migrated and rejection of stale keys observable. | +| SecretRef schema crash-loop, 2026-07-27 | Both identities demand `ARCHIE_GITHUB_TOKEN` despite Gitea config. | Removing old `token_env` field let TOML ignore deployed value. `1f8588d` restored precedence-compatible fallback; a later `308c199` removed the `Forge.TokenEnv` declaration while `finalize` still referenced it. | **Status: `retired`** as of 2026-09-24 — the `token_env` alias is removed; a stale key is now reported at startup as unrecognised (`bootstrap.go` UnknownKeys warning), which is the observability this entry waited for. | Never drop a credential key without the unknown-key warning in place. | | Compose secret omission, 2026-07-27 | Config names valid env var, container sees it empty. | Compose forwards only listed environment entries. | `22fc0ef`, `d0624b7`. **Status:** `conditional`. | Trace every secret from config key to host value to Compose passthrough to process lookup. | | FullStream/TextStream deadlock, 2026-07-27 | Streamed Telegram reply renders empty cursor, typing never clears. | ai-sdk makes `FullStream` authoritative and backpressured; `TextStream` is best-effort. | `6a0bd27`. **Status:** `settled` with regression-test gap. | Drain authoritative stream through close. | | MCP Content-Length framing and mirrored fake, 2026-07-26 to 2026-07-27 | Internal MCP tests pass while official-SDK servers do not. | MCP stdio uses newline-delimited JSON. Test subprocess called same helpers, mirroring the same wrong protocol. | Compare `f2768eb:internal/tools/mcp/framing.go` with `dda4cde`. **Status:** `settled`. | For wire contracts, test raw canonical frames and independently implemented peer. | diff --git a/.agents/skills/archie-run-and-operate/SKILL.md b/.agents/skills/archie-run-and-operate/SKILL.md index 208a07666..2e91e1e26 100644 --- a/.agents/skills/archie-run-and-operate/SKILL.md +++ b/.agents/skills/archie-run-and-operate/SKILL.md @@ -192,10 +192,6 @@ It forwards only configured provider-key variables. Open limitations until code/tests prove otherwise: - `subprocess` + default `archie-agent` is protocol-incompatible. -- A deployed overlay previously using legacy `token_env` still converts: the - structured `forge.token` secret reference wins when both are present and - `config.Forge.TokenEnv` is otherwise converted by - `internal/infrastructure/configuration/defaults.go`. - Container RPC uses root forge/worktree for every identity. - Container orphan recovery lacks daemon-instance label. - `max_uptime` only bounds `Pool.Acquire` create/start; no lifetime timer. diff --git a/config.example.toml b/config.example.toml index 2ae7c1118..d7325e0b8 100644 --- a/config.example.toml +++ b/config.example.toml @@ -166,10 +166,8 @@ class = "ollama" # shell snippets). The check command must write a releaseupdate.Snapshot JSON # document to stdout; configure the installer as well to show Approve/Defer. # [chat.telegram] -# Preferred: resolve the bot token through a configured secret engine. +# The bot token from @BotFather, resolved through a configured secret engine. # token = { engine = "bws", key = "TELEGRAM_BOT_TOKEN" } -# Legacy compatibility: read the token from this environment variable. -# token_env = "TELEGRAM_BOT_TOKEN" # env var holding the bot token from @BotFather # Run by archie-messaging, which serves /update, so these commands execute on # whichever host runs that process. # update_check_command = ["/usr/local/bin/archie-update-check"] @@ -236,12 +234,11 @@ class = "ollama" # parallel_tool_calls = false # Publish artifacts (review reports, design docs) to the collaborative editor. -# An empty base_url disables publishing entirely. The token is runtime config: -# set WORKSPACE_INGEST_TOKEN in the daemon's environment or use a secret ref. +# An empty base_url disables publishing entirely. token defaults to the +# WORKSPACE_INGEST_TOKEN environment variable. [artifacts] # base_url = "https://offloaded.dev" # token = { engine = "env", key = "WORKSPACE_INGEST_TOKEN" } -# token_env = "WORKSPACE_INGEST_TOKEN" # archied's own liveness surface, always on. GET /healthz and /health answer # 200 once the daemon is serving (503 while it is still booting), and diff --git a/deployments/docker-nats-stack.toml b/deployments/docker-nats-stack.toml index 3554396c3..e2a1e64ba 100644 --- a/deployments/docker-nats-stack.toml +++ b/deployments/docker-nats-stack.toml @@ -124,6 +124,6 @@ gate = [ # Every env var named here must be present in the environment of the host # archied process, normally through its configured supervisor or launch shell. [chat.telegram] -token_env = "TELEGRAM_BOT_TOKEN" +token = { engine = "env", key = "TELEGRAM_BOT_TOKEN" } # Empty list denies everyone. allowed_user_ids = [] diff --git a/deployments/multi-forge-github-gitea.toml b/deployments/multi-forge-github-gitea.toml index 09ea48e2d..f5eca67b1 100644 --- a/deployments/multi-forge-github-gitea.toml +++ b/deployments/multi-forge-github-gitea.toml @@ -29,9 +29,9 @@ target = "172.17.0.1:9090" target_token = "change-me-state-store-token" [models] -triage = "openai/gpt-4o" -planner = "openai/gpt-4o" -builder = "openai/gpt-4o" +triage = "openai/gpt-6-luna" +planner = "openai/gpt-6-luna" +builder = "openai/gpt-6-luna" [providers.openai] class = "openai" diff --git a/deployments/single-forge-github.toml b/deployments/single-forge-github.toml index 0d9823dd0..0cc37a863 100644 --- a/deployments/single-forge-github.toml +++ b/deployments/single-forge-github.toml @@ -55,9 +55,9 @@ pr = "archie:pr" parked = "archie:parked" [models] -triage = "openai/gpt-4o" -planner = "openai/gpt-4o" -builder = "openai/gpt-4o" +triage = "openai/gpt-6-luna" +planner = "openai/gpt-6-luna" +builder = "openai/gpt-6-luna" [providers.openai] class = "openai" diff --git a/docs/architecture/identity.md b/docs/architecture/identity.md index cba27b4aa..41be34027 100644 --- a/docs/architecture/identity.md +++ b/docs/architecture/identity.md @@ -82,8 +82,7 @@ external account MUST NOT change ownership or historical attribution. Secret-bearing channel bindings remain configuration concerns rather than identity data. In particular, `[chat.telegram].token` is a `secret.SecretRef` resolved by the application through the configured secret -registry; the older `token_env` field remains a compatibility fallback. Neither -form changes the identity that owns or performs a chat action. +registry. It does not change the identity that owns or performs a chat action. ## Persistence diff --git a/docs/data/generated/dev-docs.json b/docs/data/generated/dev-docs.json index cb02657cb..1d03c1a89 100644 --- a/docs/data/generated/dev-docs.json +++ b/docs/data/generated/dev-docs.json @@ -52,7 +52,7 @@ "url": "/dev/architecture/identity/", "title": "Identity", "section": "Architecture", - "body": "# Identity\n\n**Status:** Approved foundation; lifecycle details are deferred \n**Date:** 2026-07-28 \n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Purpose\n\nIdentity answers which persistent actor owns or performed an action. It supplies\nstable cross-domain attribution and lifecycle semantics.\n\nIdentity kinds include:\n\n- the Archie system identity, such as `System` or `archied`;\n- agent or bot identities;\n- service-account identities;\n- future user identities.\n\nA user is another kind of identity rather than a separate foundation concept.\n\n## Ownership\n\n`internal/domain/identity` owns:\n\n- immutable canonical `IdentityID` values;\n- identity kind;\n- lifecycle state;\n- ownership and attribution semantics;\n- identity-related commands and events.\n\nDomains may record an identity reference on their own state and events when\nownership or attribution is required. They MUST NOT receive a complete\nper-identity application configuration bundle.\n\nPersona and communication style are separate from identity.\n\nEvery Agent has its own immutable acting `IdentityID`. Agent actions use that\nidentity for ownership and attribution in the same way an organisation records\nwhich user accessed a resource, changed a permission, or performed another\nauditable action.\n\nAgent and Identity remain separate aggregates. Identity supplies the stable\nactor reference; Agent owns assistant behaviour, memory, specialisation,\nconversations, and capability context.\n\nAgent identities MUST NOT be shared between Agents. Automated WorkflowExecutions\nMAY eventually act through a dedicated service-account identity when a specific\nunattended automation requires it. Such use is an explicit execution decision\nand audit principal, not the default for Agents or a substitute for recording\nthe initiating user when one exists.\n\nA Workflow is owned by an IdentityID and executes as its owner by default.\nFuture delegated execution MAY explicitly assign a different `RunAsIdentityID`,\nincluding a user or service-account identity. Ownership, effective execution\nidentity, initiating identity, and delegation provenance remain distinct audit\nfacts.\n\n## Canonical identity\n\nEvery identity has an immutable `IdentityID`. It is the only value used for\ncross-domain ownership, attribution, routing, persistence, commands, and events.\n\nIdentity kind is explicit:\n\n- system;\n- bot;\n- service account;\n- user.\n\nDisplay names are mutable and MUST NOT be used as identifiers. Forge usernames,\nchannel bot names, Git authors, provider account names, and other external\nidentifiers are bindings associated with an identity rather than identity\nitself.\n\n`System` is represented by a real identity and `IdentityID`. The empty string\nMUST NOT retain special meaning as a legacy system identity.\n\nConfiguration refers to identities by `IdentityID` and supplies external\nbindings and capability settings separately. Renaming an identity or changing an\nexternal account MUST NOT change ownership or historical attribution.\n\nSecret-bearing channel bindings remain configuration concerns rather than\nidentity data. In particular, `[chat.telegram].token` is a\n`secret.SecretRef` resolved by the application through the configured secret\nregistry; the older `token_env` field remains a compatibility fallback. Neither\nform changes the identity that owns or performs a chat action.\n\n## Persistence\n\nIdentity records are durable domain state. The Identity domain's repository is\nthe source of truth; infrastructure implements its persistence contract.\n\nConfiguration MAY bootstrap a missing identity through an explicit, audited\ncreation operation and MAY propose runtime capability bindings for an existing\n`IdentityID`. Configuration is not the identity registry.\n\nOmitting an identity from configuration stops assembling the omitted runtime\ncapabilities. It MUST NOT delete the identity record, erase history, or make\nhistorical references unresolvable.\n\nDisabling or retiring an identity requires an explicit Identity-domain command.\nRetired identities remain resolvable for historical attribution. A failed\nexternal binding affects capability availability without destroying or silently\nreplacing the identity.\n\n## Lifecycle\n\nIdentity lifecycle is deliberately small:\n\n- `active`: may participate in runtime composition;\n- `suspended`: deliberately prevented from initiating new work while ownership\n and history remain;\n- `retired`: terminal, unable to initiate work, and permanently retained for\n attribution.\n\nAllowed transitions are:\n\n```text\ncreate -\u003e active\nactive -\u003e suspended\nsuspended -\u003e active\nactive -\u003e retired\nsuspended -\u003e retired\n```\n\n`retired` has no outgoing transition.\n\nCapability health is separate from identity lifecycle. Forge, model, channel,\nworkspace, and other bindings report health independently. An active identity\nmay be partially degraded without becoming suspended or retired. Runtime\nsupervision isolates and restores affected bindings through the safe-change and\nrecovery protocol.\n\n## System identity\n\nArchie has exactly one built-in system identity. It is created during initial\nstore bootstrap, is strictly always active, and cannot be suspended or retired.\nIts `IdentityID` and kind are immutable.\n\nStartup, migration, supervision, remediation, and rollback actions performed by\nthe application use the system identity. The system identity MUST NOT be\ndelegated to individual identities. Every user, bot, service account, or other\nactor mutation records the identity that actually performed it.\n\nSystem capabilities may independently become unhealthy or unavailable without\nchanging the system identity.\n\n## Target placement and contracts\n\nThe Identity domain lives at `internal/domain/identity`.\n\nIt owns:\n\n- `IdentityID`, identity kind, display name, lifecycle, version, and audit\n timestamps;\n- create, rename, suspend, reactivate, and retire commands;\n- corresponding lifecycle events;\n- the repository contract required for durable identity records;\n- lookup of current and historical identities.\n\nExternal account bindings and capability settings remain with the domains that\nuse them and reference `IdentityID`.\n\n## Migration constraints\n\nMigration from the current string model MUST:\n\n- bootstrap the permanent system identity;\n- assign stable IDs to configured identities without losing their names;\n- replace empty-string legacy ownership with the system identity;\n- migrate tasks and sessions to canonical identity references;\n- include identity where task uniqueness and transport deduplication require\n independent ownership;\n- route container RPC through the task owner's capability bindings;\n- retain historical resolution after rename, suspension, or retirement;\n- remove identity-string equality from authentication or access semantics.\n\nThis completes the foundation required to restructure the current Identity\nbehaviour. Exact storage schemas and Go method signatures belong to\nimplementation design, not this architecture review.\n\n## Lifecycle\n\nIdentity lifecycle is deliberately small:\n\n- `active`: may participate in runtime composition;\n- `suspended`: deliberately prevented from initiating new work while ownership\n and history remain;\n- `retired`: terminal, unable to initiate work, and permanently retained for\n attribution.\n\nAllowed transitions are:\n\n```text\ncreate -\u003e active\nactive -\u003e suspended\nsuspended -\u003e active\nactive -\u003e retired\nsuspended -\u003e retired\n```\n\n`retired` has no outgoing transition.\n\nCapability health is separate from identity lifecycle. Forge, model, channel,\nworkspace, and other bindings report health independently. An active identity\nmay be partially degraded without becoming suspended or retired. Runtime\nsupervision isolates and restores affected bindings through the safe-change and\nrecovery protocol.\n\n## Explicit non-responsibilities\n\nIdentity is not authentication and is not access control.\n\nThe current architecture does not require authentication or authorization. Those\ncapabilities MAY be introduced later if deployment or product needs justify\nthem. They MUST remain separate from the identity model.\n\nAn identity reference therefore proves attribution within Archie's trusted\nsystem model; it does not by itself prove credentials or permission.\n\n## Per-identity configuration\n\nValues selected for an identity remain external configuration values. At\ncomposition time they are split into the runtime settings owned by the affected\ndomains and correlated by identity reference.\n\nThe existing `IdentityConfig` aggregate MUST be dissolved. Forge accounts,\nrepositories, models, providers, workspace behaviour, polling, budgets,\nnotifications, and transport namespaces retain their respective owners.\n\n## Audit\n\nConfiguration changes and other state changes are actions attributed to an\nidentity. System-initiated changes use the system identity. Their audit records\nMUST preserve the acting identity, the target, and the resulting change.\n\nThe command ownership and persistence mechanism for configuration changes is a\nseparate configuration-management decision.\n\n## Current implementation\n\nIdentity is not currently implemented as a domain. It is a collection of string\nfields and process-local associations:\n\n- `config.IdentityConfig.Name` is the daemon routing key.\n- `config.IdentityConfig.BotUser` is the external forge and Git author name.\n- `daemon.IdentityRunner` bundles the configured name with a forge client,\n worktree manager, repository list, configuration subset, logger, and polling\n goroutine.\n- `store.Task.Identity` persists the configured name on tasks.\n- NATS task messages copy the same configured name.\n- gateway routing accepts an identity name and uses it to select a repository\n profile.\n- gateway sessions persist `BotUser`, not the configured identity name.\n\nThere is no identity registry, identity record, identity lifecycle state,\nidentity persistence, or identity command/event model. Removing an identity from\nconfiguration makes existing task ownership unresolvable.\n\nAn empty identity string selects the legacy single-identity path. This gives the\nempty string behavioural meaning rather than representing a real system\nidentity.\n\n## Current enforcement and isolation\n\n## Withheld judgement verbs\n\n`approve`, `reject`, `abandon` and `archive` are not exposed to an agent. An agent\nthat can approve can approve its own work, and the one control this surface exists\nto keep is a human accepting it.\n\nThe constraint is attribution, not capability: a task action records the acting\nidentity and the authorising principal, so exposing the verbs requires that an\nagent's action be recorded as an agent's and the authority it used recorded\nseparately. Until a surface carries both, the verbs stay withheld. This is the\nreason the four verbs are absent from the dashboard's in-browser tools, and it is\nwhy releasing them is a change to this boundary rather than a change to the tools.\n\n\nThe current implementation uses identity equality as an authorization check for\nchat task approval and cancellation. This conflicts with the approved rule that\nidentity is attribution rather than authentication or access control and must be\nreassigned to an appropriate task-ownership or future access policy.\n\nFocused tests verify that:\n\n- a task resolves the forge client and repository list associated with its\n configured identity name;\n- cross-identity repository profiles do not leak;\n- chat task creation propagates the selected identity;\n- task persistence retains the identity string;\n- chat task control rejects a different identity string.\n\n## Current hazards\n\n- Task uniqueness is `(owner, repo, issue_number)` and excludes identity.\n Two identities discovering the same forge issue cannot own distinct task\n records.\n- NATS deduplication uses `owner/repo/issue` and excludes identity, so discovery\n by a second identity can be discarded as a duplicate.\n- Container-mode forge and worktree RPC servers are wired to the root clients,\n not the task owner's clients. The source documents this as an unresolved\n identity leak.\n- The shared task queue claims the oldest task without identity partitioning and\n relies on later string lookup to recover the correct runner.\n- Sessions use forge bot usernames where tasks use configured identity names, so\n there is no canonical cross-domain identity reference.\n- Identity lifecycle is process lifetime only; there is no disabled, degraded,\n retired, or unavailable state and no audit history.\n\nThe focused identity tests pass. Broader daemon and NATS suites could not open\nembedded listener ports in the current sandbox; their failures occurred before\nidentity behaviour executed.\n\n## Three-layer identity model\n\nAgreed 2026-07-30; the frame for SOUL\n([#68](https://github.com/samcharles93/archie-core/issues/68)) and the curator\n([#435](https://github.com/samcharles93/archie-core/issues/435)).\nRecovered 2026-08-09 from the pre-migration issue tracker.\n\n**Layer 1 — invariants.** Instruction precedence, core rules, and the `\u003ctools\u003e`\nand `\u003cenv\u003e` blocks live in `internal/gateway/templates/archie.md.tpl` and are\nunreachable at runtime by anyone.\n\n**Layer 2 — SOUL.** User-authored identity: agent name, register, warmth.\nEditable without a rebuild.\n\n**Enforcing the Layer 1 / Layer 2 boundary.** SOUL is rendered as the\n`Persona` field of `SystemPromptConfig` (`internal/gateway/prompt.go`) into a\n`\u003csoul purpose=\"identity_and_style\" trust=\"data\"\u003e` block, XML-escaped through\nthe same `xml` template helper used for tool and env metadata, and placed\n*before* `\u003cinstruction_precedence\u003e` in `archie.md.tpl`. Escaping means SOUL\ntext can never forge a live `\u003ccore_rules\u003e`, `\u003cinstruction_precedence\u003e`,\n`\u003ctools\u003e` or `\u003cenv\u003e` tag -- an attempt renders as inert escaped text\n(`\u0026lt;core_rules\u0026gt;...`), and `\u003cinstruction_precedence\u003e` explicitly tells the\nmodel the `\u003csoul\u003e` block is reference data, not an authority. This is\nguarded by `TestBuildSystemPromptSoulCannotOverrideInvariants` in\n`internal/gateway/prompt_test.go`, which renders a hostile SOUL that attempts\nto countermand `core_rules` and asserts the real invariant tags stay singular\nand their text stays intact. Keep this test in sync if the template's escaping\nor block structure changes -- do not relax it to make a future SOUL feature\n(e.g. curator-proposed edits) fit.\n\n**Layer 3 — representation.** Curator-derived knowledge about the user. It may\nonly **propose** changes to SOUL and never apply them. If derived conclusions can\nsilently rewrite tone, personality drifts and the user loses the control SOUL\nexists to give them. A proposal queue also makes the visibility requirement fall\nout for free, since pending conclusions are inherently reviewable.\n\n**Why SOUL comes first:** tone currently lives in Go string constants\n(`DefaultPersonas` in `internal/gateway/persona.go`), so fixing a rude reply on\n2026-07-29 required editing Go and rebuilding. SOUL is small, fixes a real\ndefect, and defines the boundary the curator must respect.\n" + "body": "# Identity\n\n**Status:** Approved foundation; lifecycle details are deferred \n**Date:** 2026-07-28 \n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Purpose\n\nIdentity answers which persistent actor owns or performed an action. It supplies\nstable cross-domain attribution and lifecycle semantics.\n\nIdentity kinds include:\n\n- the Archie system identity, such as `System` or `archied`;\n- agent or bot identities;\n- service-account identities;\n- future user identities.\n\nA user is another kind of identity rather than a separate foundation concept.\n\n## Ownership\n\n`internal/domain/identity` owns:\n\n- immutable canonical `IdentityID` values;\n- identity kind;\n- lifecycle state;\n- ownership and attribution semantics;\n- identity-related commands and events.\n\nDomains may record an identity reference on their own state and events when\nownership or attribution is required. They MUST NOT receive a complete\nper-identity application configuration bundle.\n\nPersona and communication style are separate from identity.\n\nEvery Agent has its own immutable acting `IdentityID`. Agent actions use that\nidentity for ownership and attribution in the same way an organisation records\nwhich user accessed a resource, changed a permission, or performed another\nauditable action.\n\nAgent and Identity remain separate aggregates. Identity supplies the stable\nactor reference; Agent owns assistant behaviour, memory, specialisation,\nconversations, and capability context.\n\nAgent identities MUST NOT be shared between Agents. Automated WorkflowExecutions\nMAY eventually act through a dedicated service-account identity when a specific\nunattended automation requires it. Such use is an explicit execution decision\nand audit principal, not the default for Agents or a substitute for recording\nthe initiating user when one exists.\n\nA Workflow is owned by an IdentityID and executes as its owner by default.\nFuture delegated execution MAY explicitly assign a different `RunAsIdentityID`,\nincluding a user or service-account identity. Ownership, effective execution\nidentity, initiating identity, and delegation provenance remain distinct audit\nfacts.\n\n## Canonical identity\n\nEvery identity has an immutable `IdentityID`. It is the only value used for\ncross-domain ownership, attribution, routing, persistence, commands, and events.\n\nIdentity kind is explicit:\n\n- system;\n- bot;\n- service account;\n- user.\n\nDisplay names are mutable and MUST NOT be used as identifiers. Forge usernames,\nchannel bot names, Git authors, provider account names, and other external\nidentifiers are bindings associated with an identity rather than identity\nitself.\n\n`System` is represented by a real identity and `IdentityID`. The empty string\nMUST NOT retain special meaning as a legacy system identity.\n\nConfiguration refers to identities by `IdentityID` and supplies external\nbindings and capability settings separately. Renaming an identity or changing an\nexternal account MUST NOT change ownership or historical attribution.\n\nSecret-bearing channel bindings remain configuration concerns rather than\nidentity data. In particular, `[chat.telegram].token` is a\n`secret.SecretRef` resolved by the application through the configured secret\nregistry. It does not change the identity that owns or performs a chat action.\n\n## Persistence\n\nIdentity records are durable domain state. The Identity domain's repository is\nthe source of truth; infrastructure implements its persistence contract.\n\nConfiguration MAY bootstrap a missing identity through an explicit, audited\ncreation operation and MAY propose runtime capability bindings for an existing\n`IdentityID`. Configuration is not the identity registry.\n\nOmitting an identity from configuration stops assembling the omitted runtime\ncapabilities. It MUST NOT delete the identity record, erase history, or make\nhistorical references unresolvable.\n\nDisabling or retiring an identity requires an explicit Identity-domain command.\nRetired identities remain resolvable for historical attribution. A failed\nexternal binding affects capability availability without destroying or silently\nreplacing the identity.\n\n## Lifecycle\n\nIdentity lifecycle is deliberately small:\n\n- `active`: may participate in runtime composition;\n- `suspended`: deliberately prevented from initiating new work while ownership\n and history remain;\n- `retired`: terminal, unable to initiate work, and permanently retained for\n attribution.\n\nAllowed transitions are:\n\n```text\ncreate -\u003e active\nactive -\u003e suspended\nsuspended -\u003e active\nactive -\u003e retired\nsuspended -\u003e retired\n```\n\n`retired` has no outgoing transition.\n\nCapability health is separate from identity lifecycle. Forge, model, channel,\nworkspace, and other bindings report health independently. An active identity\nmay be partially degraded without becoming suspended or retired. Runtime\nsupervision isolates and restores affected bindings through the safe-change and\nrecovery protocol.\n\n## System identity\n\nArchie has exactly one built-in system identity. It is created during initial\nstore bootstrap, is strictly always active, and cannot be suspended or retired.\nIts `IdentityID` and kind are immutable.\n\nStartup, migration, supervision, remediation, and rollback actions performed by\nthe application use the system identity. The system identity MUST NOT be\ndelegated to individual identities. Every user, bot, service account, or other\nactor mutation records the identity that actually performed it.\n\nSystem capabilities may independently become unhealthy or unavailable without\nchanging the system identity.\n\n## Target placement and contracts\n\nThe Identity domain lives at `internal/domain/identity`.\n\nIt owns:\n\n- `IdentityID`, identity kind, display name, lifecycle, version, and audit\n timestamps;\n- create, rename, suspend, reactivate, and retire commands;\n- corresponding lifecycle events;\n- the repository contract required for durable identity records;\n- lookup of current and historical identities.\n\nExternal account bindings and capability settings remain with the domains that\nuse them and reference `IdentityID`.\n\n## Migration constraints\n\nMigration from the current string model MUST:\n\n- bootstrap the permanent system identity;\n- assign stable IDs to configured identities without losing their names;\n- replace empty-string legacy ownership with the system identity;\n- migrate tasks and sessions to canonical identity references;\n- include identity where task uniqueness and transport deduplication require\n independent ownership;\n- route container RPC through the task owner's capability bindings;\n- retain historical resolution after rename, suspension, or retirement;\n- remove identity-string equality from authentication or access semantics.\n\nThis completes the foundation required to restructure the current Identity\nbehaviour. Exact storage schemas and Go method signatures belong to\nimplementation design, not this architecture review.\n\n## Lifecycle\n\nIdentity lifecycle is deliberately small:\n\n- `active`: may participate in runtime composition;\n- `suspended`: deliberately prevented from initiating new work while ownership\n and history remain;\n- `retired`: terminal, unable to initiate work, and permanently retained for\n attribution.\n\nAllowed transitions are:\n\n```text\ncreate -\u003e active\nactive -\u003e suspended\nsuspended -\u003e active\nactive -\u003e retired\nsuspended -\u003e retired\n```\n\n`retired` has no outgoing transition.\n\nCapability health is separate from identity lifecycle. Forge, model, channel,\nworkspace, and other bindings report health independently. An active identity\nmay be partially degraded without becoming suspended or retired. Runtime\nsupervision isolates and restores affected bindings through the safe-change and\nrecovery protocol.\n\n## Explicit non-responsibilities\n\nIdentity is not authentication and is not access control.\n\nThe current architecture does not require authentication or authorization. Those\ncapabilities MAY be introduced later if deployment or product needs justify\nthem. They MUST remain separate from the identity model.\n\nAn identity reference therefore proves attribution within Archie's trusted\nsystem model; it does not by itself prove credentials or permission.\n\n## Per-identity configuration\n\nValues selected for an identity remain external configuration values. At\ncomposition time they are split into the runtime settings owned by the affected\ndomains and correlated by identity reference.\n\nThe existing `IdentityConfig` aggregate MUST be dissolved. Forge accounts,\nrepositories, models, providers, workspace behaviour, polling, budgets,\nnotifications, and transport namespaces retain their respective owners.\n\n## Audit\n\nConfiguration changes and other state changes are actions attributed to an\nidentity. System-initiated changes use the system identity. Their audit records\nMUST preserve the acting identity, the target, and the resulting change.\n\nThe command ownership and persistence mechanism for configuration changes is a\nseparate configuration-management decision.\n\n## Current implementation\n\nIdentity is not currently implemented as a domain. It is a collection of string\nfields and process-local associations:\n\n- `config.IdentityConfig.Name` is the daemon routing key.\n- `config.IdentityConfig.BotUser` is the external forge and Git author name.\n- `daemon.IdentityRunner` bundles the configured name with a forge client,\n worktree manager, repository list, configuration subset, logger, and polling\n goroutine.\n- `store.Task.Identity` persists the configured name on tasks.\n- NATS task messages copy the same configured name.\n- gateway routing accepts an identity name and uses it to select a repository\n profile.\n- gateway sessions persist `BotUser`, not the configured identity name.\n\nThere is no identity registry, identity record, identity lifecycle state,\nidentity persistence, or identity command/event model. Removing an identity from\nconfiguration makes existing task ownership unresolvable.\n\nAn empty identity string selects the legacy single-identity path. This gives the\nempty string behavioural meaning rather than representing a real system\nidentity.\n\n## Current enforcement and isolation\n\n## Withheld judgement verbs\n\n`approve`, `reject`, `abandon` and `archive` are not exposed to an agent. An agent\nthat can approve can approve its own work, and the one control this surface exists\nto keep is a human accepting it.\n\nThe constraint is attribution, not capability: a task action records the acting\nidentity and the authorising principal, so exposing the verbs requires that an\nagent's action be recorded as an agent's and the authority it used recorded\nseparately. Until a surface carries both, the verbs stay withheld. This is the\nreason the four verbs are absent from the dashboard's in-browser tools, and it is\nwhy releasing them is a change to this boundary rather than a change to the tools.\n\n\nThe current implementation uses identity equality as an authorization check for\nchat task approval and cancellation. This conflicts with the approved rule that\nidentity is attribution rather than authentication or access control and must be\nreassigned to an appropriate task-ownership or future access policy.\n\nFocused tests verify that:\n\n- a task resolves the forge client and repository list associated with its\n configured identity name;\n- cross-identity repository profiles do not leak;\n- chat task creation propagates the selected identity;\n- task persistence retains the identity string;\n- chat task control rejects a different identity string.\n\n## Current hazards\n\n- Task uniqueness is `(owner, repo, issue_number)` and excludes identity.\n Two identities discovering the same forge issue cannot own distinct task\n records.\n- NATS deduplication uses `owner/repo/issue` and excludes identity, so discovery\n by a second identity can be discarded as a duplicate.\n- Container-mode forge and worktree RPC servers are wired to the root clients,\n not the task owner's clients. The source documents this as an unresolved\n identity leak.\n- The shared task queue claims the oldest task without identity partitioning and\n relies on later string lookup to recover the correct runner.\n- Sessions use forge bot usernames where tasks use configured identity names, so\n there is no canonical cross-domain identity reference.\n- Identity lifecycle is process lifetime only; there is no disabled, degraded,\n retired, or unavailable state and no audit history.\n\nThe focused identity tests pass. Broader daemon and NATS suites could not open\nembedded listener ports in the current sandbox; their failures occurred before\nidentity behaviour executed.\n\n## Three-layer identity model\n\nAgreed 2026-07-30; the frame for SOUL\n([#68](https://github.com/samcharles93/archie-core/issues/68)) and the curator\n([#435](https://github.com/samcharles93/archie-core/issues/435)).\nRecovered 2026-08-09 from the pre-migration issue tracker.\n\n**Layer 1 — invariants.** Instruction precedence, core rules, and the `\u003ctools\u003e`\nand `\u003cenv\u003e` blocks live in `internal/gateway/templates/archie.md.tpl` and are\nunreachable at runtime by anyone.\n\n**Layer 2 — SOUL.** User-authored identity: agent name, register, warmth.\nEditable without a rebuild.\n\n**Enforcing the Layer 1 / Layer 2 boundary.** SOUL is rendered as the\n`Persona` field of `SystemPromptConfig` (`internal/gateway/prompt.go`) into a\n`\u003csoul purpose=\"identity_and_style\" trust=\"data\"\u003e` block, XML-escaped through\nthe same `xml` template helper used for tool and env metadata, and placed\n*before* `\u003cinstruction_precedence\u003e` in `archie.md.tpl`. Escaping means SOUL\ntext can never forge a live `\u003ccore_rules\u003e`, `\u003cinstruction_precedence\u003e`,\n`\u003ctools\u003e` or `\u003cenv\u003e` tag -- an attempt renders as inert escaped text\n(`\u0026lt;core_rules\u0026gt;...`), and `\u003cinstruction_precedence\u003e` explicitly tells the\nmodel the `\u003csoul\u003e` block is reference data, not an authority. This is\nguarded by `TestBuildSystemPromptSoulCannotOverrideInvariants` in\n`internal/gateway/prompt_test.go`, which renders a hostile SOUL that attempts\nto countermand `core_rules` and asserts the real invariant tags stay singular\nand their text stays intact. Keep this test in sync if the template's escaping\nor block structure changes -- do not relax it to make a future SOUL feature\n(e.g. curator-proposed edits) fit.\n\n**Layer 3 — representation.** Curator-derived knowledge about the user. It may\nonly **propose** changes to SOUL and never apply them. If derived conclusions can\nsilently rewrite tone, personality drifts and the user loses the control SOUL\nexists to give them. A proposal queue also makes the visibility requirement fall\nout for free, since pending conclusions are inherently reviewable.\n\n**Why SOUL comes first:** tone currently lives in Go string constants\n(`DefaultPersonas` in `internal/gateway/persona.go`), so fixing a rude reply on\n2026-07-29 required editing Go and rebuilding. SOUL is small, fixes a real\ndefect, and defines the boundary the curator must respect.\n" }, { "url": "/dev/architecture/messaging-and-work-intake/", diff --git a/internal/app/archied/config_snapshot_channels_test.go b/internal/app/archied/config_snapshot_channels_test.go index 758a2b41d..3146b34b0 100644 --- a/internal/app/archied/config_snapshot_channels_test.go +++ b/internal/app/archied/config_snapshot_channels_test.go @@ -27,7 +27,7 @@ func TestPublishedProjectionAgreesWithFrontEndsOnConfiguredChannels(t *testing.T { name: "telegram token", cfg: config.Config{Chat: config.ChatConfig{ - Telegram: config.TelegramConfig{TokenEnv: "TELEGRAM_TOKEN"}, + Telegram: config.TelegramConfig{Token: config.SecretRef{Engine: "env", Key: "TELEGRAM_TOKEN"}}, }}, }, { diff --git a/internal/app/archied/pr_review.go b/internal/app/archied/pr_review.go index 30116537d..1f9cb0591 100644 --- a/internal/app/archied/pr_review.go +++ b/internal/app/archied/pr_review.go @@ -356,11 +356,8 @@ func (b *boot) artifactSender() artifactsync.Sender { return nil } if token == "" { - token = b.secrets.Getenv(cfg.TokenEnv) - } - if token == "" { - b.log.Warn("artifact publishing disabled: no service token; set the token secret or its environment variable", - "base_url", cfg.BaseURL, "token_env", cfg.TokenEnv) + b.log.Warn("artifact publishing disabled: the service token resolved empty", + "base_url", cfg.BaseURL, "token_engine", cfg.Token.Engine) return nil } return artifactsync.NewClient(cfg.BaseURL, token) diff --git a/internal/app/archied/reload.go b/internal/app/archied/reload.go index 9dfd00b39..e8dbf13fa 100644 --- a/internal/app/archied/reload.go +++ b/internal/app/archied/reload.go @@ -94,7 +94,7 @@ func reloadLoop(ctx context.Context, ch <-chan os.Signal, c *ReloadController, l // handlers re-read on every request. MaxRetries is the worked example: // its only consumer is api_tasks.go:380,383, reading per-request // s.Cfg.Get(), and nothing in the daemon reads it -- so it reloads. -// Chat.Telegram.TokenEnv is the counter-example: webui reads it per +// Chat.Telegram.Token is the counter-example: webui reads it per // request AND a telegram bot built at startup consumes it, so it is // NOT reloadable, and treating "webui reads it" as sufficient would // display a new token while the bot uses the old one. diff --git a/internal/app/archiemessaging/channel_reload_test.go b/internal/app/archiemessaging/channel_reload_test.go index cabfa56e1..373206d28 100644 --- a/internal/app/archiemessaging/channel_reload_test.go +++ b/internal/app/archiemessaging/channel_reload_test.go @@ -48,7 +48,7 @@ func TestReloadChannelReachesTheChannelsOwnSeam(t *testing.T) { dir := t.TempDir() cfgPath := filepath.Join(dir, "config.toml") write := func(userIDs string) { - content := "bot_user = \"testbot\"\n\n[chat.telegram]\ntoken_env = \"TEST_TG_TOKEN\"\nallowed_user_ids = " + userIDs + "\n" + content := "bot_user = \"testbot\"\n\n[chat.telegram]\ntoken = { engine = \"env\", key = \"TEST_TG_TOKEN\" }\nallowed_user_ids = " + userIDs + "\n" if err := os.WriteFile(cfgPath, []byte(content), 0o600); err != nil { t.Fatal(err) } @@ -83,7 +83,7 @@ func TestReloadCapabilityAndActionShareOneSource(t *testing.T) { srv, err := compose(t.Context(), deps{ Config: ResolvedConfig{ TelegramToken: "token-123", - Telegram: config.TelegramConfig{TokenEnv: "TEST_TG_TOKEN", AllowedUserIDs: []int64{1}}, + Telegram: config.TelegramConfig{Token: config.SecretRef{Engine: "env", Key: "TEST_TG_TOKEN"}, AllowedUserIDs: []int64{1}}, WebhookAddr: "127.0.0.1:0", Webhook: config.WebhookRoute{Path: "/smoke"}, }, diff --git a/internal/app/archiemessaging/compose.go b/internal/app/archiemessaging/compose.go index 6c5f198db..112752528 100644 --- a/internal/app/archiemessaging/compose.go +++ b/internal/app/archiemessaging/compose.go @@ -122,10 +122,9 @@ func (s *Service) add(name string, ch channels.Channel, cfg map[string]any) erro } // telegramValidateConfigMap builds the map Gateway.ValidateConfig expects -// from the typed config, carrying whichever credential source is set -// (token takes precedence, matching resolveTelegramToken). +// from the typed config. func telegramValidateConfigMap(cfg config.TelegramConfig) map[string]any { - m := map[string]any{"token_env": cfg.TokenEnv} + m := map[string]any{} if cfg.Token != (secret.SecretRef{}) { m["token"] = map[string]any{"engine": cfg.Token.Engine, "key": cfg.Token.Key} } diff --git a/internal/app/archiemessaging/config.go b/internal/app/archiemessaging/config.go index 8f74dcc64..1d1883e9e 100644 --- a/internal/app/archiemessaging/config.go +++ b/internal/app/archiemessaging/config.go @@ -150,17 +150,13 @@ func merge(o Options, p projection) Options { return o } -// resolveTelegramToken reads whichever credential source is configured. A -// secret ref takes precedence over token_env, so a deployment that moved to -// a secret engine is not silently served by a stale environment variable. +// resolveTelegramToken resolves the configured bot token; an unset +// reference means the channel is off. func resolveTelegramToken(cfg config.TelegramConfig, secrets *secret.Registry) (string, error) { - if cfg.Token != (secret.SecretRef{}) { - return secrets.Resolve(cfg.Token) + if cfg.Token == (secret.SecretRef{}) { + return "", nil } - if cfg.TokenEnv != "" { - return os.Getenv(cfg.TokenEnv), nil - } - return "", nil + return secrets.Resolve(cfg.Token) } func resolveWebhookSecret(route config.WebhookRoute, secrets *secret.Registry) (string, error) { diff --git a/internal/app/archiemessaging/config_test.go b/internal/app/archiemessaging/config_test.go index c8ce1e564..11834f5b4 100644 --- a/internal/app/archiemessaging/config_test.go +++ b/internal/app/archiemessaging/config_test.go @@ -48,7 +48,7 @@ target = "127.0.0.1:8999" target_token = "tok-123" [chat.telegram] -token_env = "TEST_TG_TOKEN" +token = { engine = "env", key = "TEST_TG_TOKEN" } allowed_user_ids = [12345] ` if err := os.WriteFile(cfgPath, []byte(content), 0o600); err != nil { diff --git a/internal/app/archiemessaging/service_test.go b/internal/app/archiemessaging/service_test.go index fee55bcad..bf02628f1 100644 --- a/internal/app/archiemessaging/service_test.go +++ b/internal/app/archiemessaging/service_test.go @@ -19,7 +19,7 @@ func TestServiceStartsConfiguredChannels(t *testing.T) { Config: ResolvedConfig{ TelegramToken: "token-123", Telegram: config.TelegramConfig{ - TokenEnv: "TEST_TG_TOKEN", + Token: config.SecretRef{Engine: "env", Key: "TEST_TG_TOKEN"}, AllowedUserIDs: []int64{123}, }, Email: config.EmailConfig{ @@ -79,7 +79,7 @@ func TestComposeRejectsInvalidChannelConfig(t *testing.T) { _, err = compose(t.Context(), deps{ Config: ResolvedConfig{ TelegramToken: "token-123", - // Neither token_env nor a token ref: telegram.ValidateConfig refuses. + // No token ref: telegram.ValidateConfig refuses. }, Log: slog.Default(), Chat: &dummyChatContract{}, diff --git a/internal/app/archiemessaging/telegram_features_test.go b/internal/app/archiemessaging/telegram_features_test.go index 185df8d76..3b0ea35ea 100644 --- a/internal/app/archiemessaging/telegram_features_test.go +++ b/internal/app/archiemessaging/telegram_features_test.go @@ -43,7 +43,7 @@ func telegramChannel(t *testing.T, srv *Service) *telegram.Gateway { func telegramConfig(t *testing.T, cfg ResolvedConfig, chat messaging.ChatContract) *telegram.Gateway { t.Helper() cfg.TelegramToken = "token-123" - cfg.Telegram.TokenEnv = "TEST_TG_TOKEN" + cfg.Telegram.Token = config.SecretRef{Engine: "env", Key: "TEST_TG_TOKEN"} cfg.Telegram.AllowedUserIDs = []int64{7} srv, err := compose(t.Context(), deps{Config: cfg, Log: slog.New(slog.DiscardHandler), Chat: chat}) if err != nil { @@ -173,7 +173,7 @@ func TestTelegramReloadRereadsTokenAndAllowlist(t *testing.T) { dir := t.TempDir() cfgPath := filepath.Join(dir, "config.toml") write := func(userIDs string) { - content := "bot_user = \"testbot\"\n\n[chat.telegram]\ntoken_env = \"TEST_TG_TOKEN\"\nallowed_user_ids = " + userIDs + "\n" + content := "bot_user = \"testbot\"\n\n[chat.telegram]\ntoken = { engine = \"env\", key = \"TEST_TG_TOKEN\" }\nallowed_user_ids = " + userIDs + "\n" if err := os.WriteFile(cfgPath, []byte(content), 0o600); err != nil { t.Fatal(err) } @@ -213,7 +213,7 @@ func TestTelegramReloadRereadsTokenAndAllowlist(t *testing.T) { func TestTelegramReloadRefusesAnEmptyToken(t *testing.T) { dir := t.TempDir() cfgPath := filepath.Join(dir, "config.toml") - content := "bot_user = \"testbot\"\n\n[chat.telegram]\ntoken_env = \"TEST_TG_TOKEN\"\nallowed_user_ids = [1]\n" + content := "bot_user = \"testbot\"\n\n[chat.telegram]\ntoken = { engine = \"env\", key = \"TEST_TG_TOKEN\" }\nallowed_user_ids = [1]\n" if err := os.WriteFile(cfgPath, []byte(content), 0o600); err != nil { t.Fatal(err) } diff --git a/internal/app/archiemessaging/telegram_token_test.go b/internal/app/archiemessaging/telegram_token_test.go index dbc842f65..f2bd2fc4f 100644 --- a/internal/app/archiemessaging/telegram_token_test.go +++ b/internal/app/archiemessaging/telegram_token_test.go @@ -18,66 +18,11 @@ func (testSecretEngine) Resolve(key string) (string, error) { return "", nil } -func TestResolveTelegramTokenPrefersSecretRef(t *testing.T) { - registry := secret.NewRegistry() - registry.Register(testSecretEngine{}) - cfg := config.TelegramConfig{ - Token: secret.SecretRef{Engine: "bws", Key: "telegram-token"}, - TokenEnv: "TELEGRAM_LEGACY_TOKEN", - } - t.Setenv("TELEGRAM_LEGACY_TOKEN", "token-from-env") - - got, err := resolveTelegramToken(cfg, registry) - if err != nil { - t.Fatalf("resolveTelegramToken returned error: %v", err) - } - if got != "token-from-bws" { - t.Fatalf("resolveTelegramToken = %q, want token-from-bws", got) - } -} - -func TestResolveTelegramTokenFallsBackToTokenEnv(t *testing.T) { - registry := secret.NewRegistry() - cfg := config.TelegramConfig{TokenEnv: "TELEGRAM_LEGACY_TOKEN"} - t.Setenv("TELEGRAM_LEGACY_TOKEN", "token-from-env") - - got, err := resolveTelegramToken(cfg, registry) - if err != nil { - t.Fatalf("resolveTelegramToken returned error: %v", err) - } - if got != "token-from-env" { - t.Fatalf("resolveTelegramToken = %q, want token-from-env", got) - } -} - -func TestResolveTelegramTokenDoesNotUseTokenEnvWhenSecretRefIsSet(t *testing.T) { - registry := secret.NewRegistry() - registry.Register(testSecretEngine{}) - cfg := config.TelegramConfig{ - Token: secret.SecretRef{Engine: "bws", Key: "telegram-token"}, - TokenEnv: "TELEGRAM_LEGACY_TOKEN", - } - t.Setenv("TELEGRAM_LEGACY_TOKEN", "token-from-env") - - got, err := resolveTelegramToken(cfg, registry) - if err != nil { - t.Fatalf("resolveTelegramToken returned error: %v", err) - } - if got == "token-from-env" { - t.Fatal("resolveTelegramToken used TokenEnv despite Token being configured") - } -} - -// TestResolveTelegramTokenAcceptsTokenRefWithoutTokenEnv is the regression -// guard for channels-telegram-5: a deployment configured only via -// chat.telegram.token must resolve, since Token takes precedence over -// TokenEnv and requiring both would reject every secret-engine setup. -func TestResolveTelegramTokenAcceptsTokenRefWithoutTokenEnv(t *testing.T) { +func TestResolveTelegramTokenResolvesSecretRef(t *testing.T) { registry := secret.NewRegistry() registry.Register(testSecretEngine{}) cfg := config.TelegramConfig{ Token: secret.SecretRef{Engine: "bws", Key: "telegram-token"}, - // TokenEnv deliberately left empty. } got, err := resolveTelegramToken(cfg, registry) diff --git a/internal/app/controlplane/channel_settings.go b/internal/app/controlplane/channel_settings.go index ab92f22da..3489821b7 100644 --- a/internal/app/controlplane/channel_settings.go +++ b/internal/app/controlplane/channel_settings.go @@ -33,7 +33,7 @@ func seedChannels(cfg config.Config) any { Operator: chat.Operator, Workspace: chat.Workspace, UnrestrictedFilesystem: chat.UnrestrictedFilesystem, ShowToolCalls: chat.ShowToolCalls, MaxSteps: chat.MaxSteps, Models: chat.Models, Email: emailSettings{ListenAddr: chat.Email.ListenAddr, RelayAddr: chat.Email.RelayAddr}, WebhookAddr: chat.WebhookAddr, - Telegram: telegramSettings{AllowedUserIDs: chat.Telegram.AllowedUserIDs, Token: chat.Telegram.Token, TokenEnv: chat.Telegram.TokenEnv, CredentialConfigured: chat.Telegram.TokenEnv != "" || chat.Telegram.Token != (config.SecretRef{})}, + Telegram: telegramSettings{AllowedUserIDs: chat.Telegram.AllowedUserIDs, Token: chat.Telegram.Token, CredentialConfigured: chat.Telegram.Token != (config.SecretRef{})}, Webhook: webhookChannelSettings{Path: chat.Webhook.Path, Secret: chat.Webhook.Secret, CredentialConfigured: chat.Webhook.Secret != (config.SecretRef{}), Template: chat.Webhook.Template, DeliverTo: chat.Webhook.DeliverTo}, RateLimit: rateLimitSettings{Window: channelDuration(chat.RateLimit.Window), MaxRequests: chat.RateLimit.MaxRequests}, } diff --git a/internal/channels/telegram/telegram.go b/internal/channels/telegram/telegram.go index 4c3d1750e..ef620b3e4 100644 --- a/internal/channels/telegram/telegram.go +++ b/internal/channels/telegram/telegram.go @@ -892,25 +892,15 @@ func updateThreadID(update *models.Update) int { } // ConfigSchema returns the JSON Schema for the Telegram channel config. -// The bot token may be supplied either directly as token_env (an -// environment variable name) or as token (a secret reference object with -// engine/key); token takes precedence when both are set, matching -// resolveTelegramToken's own precedence. +// The bot token is a secret reference object with engine/key. func (g *Gateway) ConfigSchema() json.RawMessage { return json.RawMessage(`{ "type": "object", - "anyOf": [ - { "required": ["token_env"] }, - { "required": ["token"] } - ], + "required": ["token"], "properties": { - "token_env": { - "type": "string", - "description": "Environment variable holding the Telegram bot token from @BotFather" - }, "token": { "type": "object", - "description": "Secret reference for the bot token, resolved through the configured secret engine. Takes precedence over token_env.", + "description": "Secret reference for the Telegram bot token from @BotFather, resolved through the configured secret engine.", "properties": { "engine": { "type": "string" }, "key": { "type": "string" } @@ -925,18 +915,14 @@ func (g *Gateway) ConfigSchema() json.RawMessage { }`) } -// ValidateConfig checks the Telegram channel configuration. A token is -// required, supplied either as token (a secret reference) or token_env -// (an environment variable name) -- either credential source is valid, -// matching resolveTelegramToken's precedence in the daemon's boot path. +// ValidateConfig checks the Telegram channel configuration. A token +// secret reference is required. func (g *Gateway) ValidateConfig(cfg map[string]any) error { if cfg == nil { return fmt.Errorf("telegram config is required") } - tokenEnv, _ := cfg["token_env"].(string) - _, hasTokenRef := cfg["token"] - if tokenEnv == "" && !hasTokenRef { - return fmt.Errorf("telegram.token or telegram.token_env is required") + if _, ok := cfg["token"]; !ok { + return fmt.Errorf("telegram.token is required") } return nil } diff --git a/internal/channels/telegram/telegram_test.go b/internal/channels/telegram/telegram_test.go index 6b3b1a709..2b94ab952 100644 --- a/internal/channels/telegram/telegram_test.go +++ b/internal/channels/telegram/telegram_test.go @@ -633,23 +633,16 @@ func TestLaunchDropsPendingUpdatesBeforePolling(t *testing.T) { } } -func TestValidateConfigAcceptsTokenEnv(t *testing.T) { - g := New("token", nil, slog.Default()) - if err := g.ValidateConfig(map[string]any{"token_env": "TELEGRAM_BOT_TOKEN"}); err != nil { - t.Errorf("ValidateConfig with token_env set = %v, want nil", err) - } -} - func TestValidateConfigAcceptsTokenRef(t *testing.T) { g := New("token", nil, slog.Default()) if err := g.ValidateConfig(map[string]any{"token": map[string]any{"engine": "env", "key": "TELEGRAM_BOT_TOKEN"}}); err != nil { - t.Errorf("ValidateConfig with a token secret ref set = %v, want nil: chat.telegram.token is an equally valid credential source to token_env", err) + t.Errorf("ValidateConfig with a token secret ref set = %v, want nil", err) } } -func TestValidateConfigRejectsNeitherCredential(t *testing.T) { +func TestValidateConfigRejectsMissingToken(t *testing.T) { g := New("token", nil, slog.Default()) if err := g.ValidateConfig(map[string]any{}); err == nil { - t.Error("ValidateConfig with neither token nor token_env set = nil, want an error") + t.Error("ValidateConfig with no token set = nil, want an error") } } diff --git a/internal/config/chat_frontends.go b/internal/config/chat_frontends.go index a3d4a7f1b..846ab4d87 100644 --- a/internal/config/chat_frontends.go +++ b/internal/config/chat_frontends.go @@ -34,7 +34,7 @@ func (c ChatConfig) FrontEnds() []ChatFrontEnd { { ID: "telegram", Name: "Telegram", - Configured: c.Telegram.Token != (SecretRef{}) || strings.TrimSpace(c.Telegram.TokenEnv) != "", + Configured: c.Telegram.Token != (SecretRef{}), }, { ID: "email", diff --git a/internal/config/chat_frontends_test.go b/internal/config/chat_frontends_test.go index 382e9f426..40f01ab70 100644 --- a/internal/config/chat_frontends_test.go +++ b/internal/config/chat_frontends_test.go @@ -18,11 +18,6 @@ func TestChatConfigFrontEnds(t *testing.T) { chat: ChatConfig{}, want: map[string]bool{"telegram": false, "email": false, "webhook": false}, }, - { - name: "telegram bot token from the environment", - chat: ChatConfig{Telegram: TelegramConfig{TokenEnv: "TELEGRAM_TOKEN"}}, - want: map[string]bool{"telegram": true, "email": false, "webhook": false}, - }, { name: "telegram bot token through the secret engine", chat: ChatConfig{Telegram: TelegramConfig{Token: SecretRef{Engine: "builtin", Key: "telegram"}}}, @@ -41,18 +36,16 @@ func TestChatConfigFrontEnds(t *testing.T) { { name: "every front-end at once", chat: ChatConfig{ - Telegram: TelegramConfig{TokenEnv: "TELEGRAM_TOKEN"}, + Telegram: TelegramConfig{Token: SecretRef{Engine: "env", Key: "TELEGRAM_TOKEN"}}, Email: EmailConfig{ListenAddr: "127.0.0.1:2525"}, WebhookAddr: "127.0.0.1:9099", }, want: map[string]bool{"telegram": true, "email": true, "webhook": true}, }, { - // Whitespace is not a value: an env var name of " " resolves - // to nothing and " " cannot be listened on. + // Whitespace is not a value: " " cannot be listened on. name: "whitespace-only values are not configured", chat: ChatConfig{ - Telegram: TelegramConfig{TokenEnv: " "}, Email: EmailConfig{ListenAddr: " "}, WebhookAddr: "\t", }, diff --git a/internal/config/config.go b/internal/config/config.go index 66b29d4bc..b4b5860b8 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -192,10 +192,9 @@ const ( // Forge configures the code forge integration. type Forge struct { - Type string `toml:"type" yaml:"type"` - Host string `toml:"host" yaml:"host"` - Token SecretRef `toml:"token" yaml:"token"` - TokenEnv string `toml:"token_env" yaml:"token_env"` + Type string `toml:"type" yaml:"type"` + Host string `toml:"host" yaml:"host"` + Token SecretRef `toml:"token" yaml:"token"` // Intake selects how forge issues become work: "poll" (default), // "webhook", or "both". Webhook intake reacts to forge events the moment // they arrive instead of up to poll_interval later. @@ -534,9 +533,6 @@ type ArtifactsConfig struct { BaseURL string `toml:"base_url" yaml:"base_url"` // Token is the service credential the editor's ingest route requires. Token SecretRef `toml:"token" yaml:"token"` - // TokenEnv names the environment variable holding the token when Token - // is unset. Defaults to WORKSPACE_INGEST_TOKEN. - TokenEnv string `toml:"token_env" yaml:"token_env"` } // IdentityConfig is a per-identity configuration subset. Each identity @@ -1046,12 +1042,9 @@ type TelegramConfig struct { // bot to a group does not grant that group's members access. Empty // denies everyone. AllowedUserIDs []int64 `toml:"allowed_user_ids" yaml:"allowed_user_ids"` - // Token references the bot token through the configured secret engine. - // It takes precedence over TokenEnv when both are set. + // Token references the bot token from @BotFather through the configured + // secret engine. Empty disables the Telegram channel. Token SecretRef `toml:"token" yaml:"token"` - // TokenEnv names the env var holding the bot token from @BotFather. - // Empty disables the Telegram channel. - TokenEnv string `toml:"token_env" yaml:"token_env"` // UpdateCheckCommand writes a releaseupdate.Snapshot JSON document to // stdout. UpdateInstallCommand applies an already-approved update. Both // are argv arrays, never shell snippets. diff --git a/internal/daemon/daemon_test.go b/internal/daemon/daemon_test.go index ad102e9b8..846bae809 100644 --- a/internal/daemon/daemon_test.go +++ b/internal/daemon/daemon_test.go @@ -1960,7 +1960,7 @@ func configWithCanarySecrets() config.Config { BotEmail: "archie@example.com", Label: "archie", Forge: config.Forge{ - Type: "gitea", Host: "gitea.example.com", TokenEnv: "GITEA_TOKEN", + Type: "gitea", Host: "gitea.example.com", Token: secret.SecretRef{Engine: "bws", Key: canaryForgeToken}, WebhookSecret: secret.SecretRef{Engine: "bws", Key: canaryWebhookSecret}, Intake: "webhook", @@ -1984,7 +1984,7 @@ func configWithCanarySecrets() config.Config { Notify: config.Notify{Webhook: "https://hooks.example.com/notify"}, Tools: config.ToolsConfig{Policy: config.ToolPolicy{MaxResultChars: 12000, SpillDir: "/tmp/spill"}}, NATS: config.NATSConfig{Mode: "external", URL: "nats://127.0.0.1:4222", TokenEnv: canaryNATSTokenEnv}, - Chat: config.ChatConfig{Operator: "sam", Telegram: config.TelegramConfig{TokenEnv: "TELEGRAM_TOKEN", Token: secret.SecretRef{Engine: "bws", Key: canaryTelegramToken}}}, + Chat: config.ChatConfig{Operator: "sam", Telegram: config.TelegramConfig{Token: secret.SecretRef{Engine: "bws", Key: canaryTelegramToken}}}, Services: config.Services{config.ServiceNameState: {Target: "127.0.0.1:50051", TargetToken: canaryStateStoreToken}}, ModelLimits: map[string]config.ModelLimits{ "openai/gpt-4": {ContextWindow: 128000, MaxOutputTokens: 4096}, diff --git a/internal/infrastructure/configuration/artifacts_config_test.go b/internal/infrastructure/configuration/artifacts_config_test.go index a7bef8923..233552910 100644 --- a/internal/infrastructure/configuration/artifacts_config_test.go +++ b/internal/infrastructure/configuration/artifacts_config_test.go @@ -11,7 +11,7 @@ import ( func TestArtifactsConfigDefaults(t *testing.T) { path := filepath.Join(t.TempDir(), "config.toml") contents := "bot_user = \"widget\"\n" + - "[forge]\ntype = \"gitea\"\nhost = \"https://git.example.test\"\ntoken_env = \"T\"\n" + "[forge]\ntype = \"gitea\"\nhost = \"https://git.example.test\"\n" if err := os.WriteFile(path, []byte(contents), 0o600); err != nil { t.Fatal(err) } @@ -22,8 +22,8 @@ func TestArtifactsConfigDefaults(t *testing.T) { if cfg.Artifacts.BaseURL != "" { t.Errorf("BaseURL = %q, want empty so the sender stays disabled", cfg.Artifacts.BaseURL) } - if cfg.Artifacts.TokenEnv != "WORKSPACE_INGEST_TOKEN" { - t.Errorf("TokenEnv = %q, want the documented fallback", cfg.Artifacts.TokenEnv) + if want := (config.SecretRef{Engine: "env", Key: "WORKSPACE_INGEST_TOKEN"}); cfg.Artifacts.Token != want { + t.Errorf("Token = %+v, want the documented fallback %+v", cfg.Artifacts.Token, want) } } @@ -31,8 +31,7 @@ func TestArtifactsConfigPreservesExplicitValues(t *testing.T) { path := filepath.Join(t.TempDir(), "config.toml") contents := "bot_user = \"widget\"\n" + "[artifacts]\nbase_url = \"https://offloaded.dev\"\n" + - "token = { engine = \"env\", key = \"ARCHIE_GITHUB_TOKEN\" }\n" + - "token_env = \"OTHER_TOKEN\"\n" + "token = { engine = \"env\", key = \"ARCHIE_GITHUB_TOKEN\" }\n" if err := os.WriteFile(path, []byte(contents), 0o600); err != nil { t.Fatal(err) } @@ -46,7 +45,4 @@ func TestArtifactsConfigPreservesExplicitValues(t *testing.T) { if want := (config.SecretRef{Engine: "env", Key: "ARCHIE_GITHUB_TOKEN"}); cfg.Artifacts.Token != want { t.Errorf("Token = %+v, want %+v", cfg.Artifacts.Token, want) } - if cfg.Artifacts.TokenEnv != "OTHER_TOKEN" { - t.Errorf("TokenEnv = %q, want the explicit value", cfg.Artifacts.TokenEnv) - } } diff --git a/internal/infrastructure/configuration/defaults.go b/internal/infrastructure/configuration/defaults.go index f88d09801..400648f08 100644 --- a/internal/infrastructure/configuration/defaults.go +++ b/internal/infrastructure/configuration/defaults.go @@ -281,22 +281,16 @@ func applyForgeDefaults(cfg *config.Config) { if cfg.Forge.Host == "" { cfg.Forge.Host = defaultForgeHost } - if cfg.Forge.Token.Engine == "" && cfg.Forge.Token.Key == "" && cfg.Forge.TokenEnv != "" { - cfg.Forge.Token = config.SecretRef{Engine: "env", Key: cfg.Forge.TokenEnv} - } if cfg.Forge.Intake == "" { cfg.Forge.Intake = config.ForgeIntakePoll } } -// applyArtifactsDefaults fills the artifacts section, promoting the -// token_env fallback to a secret reference when no explicit one was given. +// applyArtifactsDefaults reads the artifacts token from WORKSPACE_INGEST_TOKEN +// when no secret reference is given. func applyArtifactsDefaults(cfg *config.Config) { - if cfg.Artifacts.TokenEnv == "" { - cfg.Artifacts.TokenEnv = "WORKSPACE_INGEST_TOKEN" - } if cfg.Artifacts.Token == (config.SecretRef{}) { - cfg.Artifacts.Token = config.SecretRef{Engine: "env", Key: cfg.Artifacts.TokenEnv} + cfg.Artifacts.Token = config.SecretRef{Engine: "env", Key: "WORKSPACE_INGEST_TOKEN"} } } diff --git a/internal/infrastructure/configuration/loader_test.go b/internal/infrastructure/configuration/loader_test.go index a6f3f2a4d..9b616915e 100644 --- a/internal/infrastructure/configuration/loader_test.go +++ b/internal/infrastructure/configuration/loader_test.go @@ -171,57 +171,10 @@ func TestResolveSelectsFileFormatsAndDirectories(t *testing.T) { } } -// TestLoadForgeTokenEnvBackwardCompat guards against a real production -// incident: the secrets-engine migration replaced [forge]'s flat -// token_env string with a {engine, key} struct, but TOML silently ignores -// unknown fields — so deployed configs still using the old token_env key -// had their token config dropped entirely and finalize() defaulted to -// demanding ARCHIE_GITHUB_TOKEN, crash-looping a gitea-backed daemon. -func TestLoadForgeTokenEnvBackwardCompat(t *testing.T) { - path := filepath.Join(t.TempDir(), "config.toml") - contents := "bot_user = \"widget\"\n" + - "[forge]\ntype = \"gitea\"\nhost = \"https://git.example.test\"\ntoken_env = \"MY_GITEA_TOKEN\"\n" + - "[[repos]]\nowner = \"acme\"\nname = \"app\"\n" - if err := os.WriteFile(path, []byte(contents), 0o600); err != nil { - t.Fatal(err) - } - - cfg, err := loadFile(path) - if err != nil { - t.Fatal(err) - } - if cfg.Forge.Token != (secret.SecretRef{Engine: "env", Key: "MY_GITEA_TOKEN"}) { - t.Errorf("Forge.Token = %#v, want {env MY_GITEA_TOKEN} (from legacy token_env)", cfg.Forge.Token) - } -} - -// TestLoadForgeTokenTakesPrecedenceOverTokenEnv verifies the new-style -// [forge.token] wins when both the legacy token_env and the new token -// struct are present (e.g. mid-migration configs). -func TestLoadForgeTokenTakesPrecedenceOverTokenEnv(t *testing.T) { - path := filepath.Join(t.TempDir(), "config.toml") - contents := "bot_user = \"widget\"\n" + - "[forge]\ntype = \"gitea\"\ntoken_env = \"OLD_TOKEN\"\n" + - "[forge.token]\nengine = \"env\"\nkey = \"NEW_TOKEN\"\n" + - "[[repos]]\nowner = \"acme\"\nname = \"app\"\n" - if err := os.WriteFile(path, []byte(contents), 0o600); err != nil { - t.Fatal(err) - } - - cfg, err := loadFile(path) - if err != nil { - t.Fatal(err) - } - if cfg.Forge.Token != (secret.SecretRef{Engine: "env", Key: "NEW_TOKEN"}) { - t.Errorf("Forge.Token = %#v, want {env NEW_TOKEN} (new-style token wins)", cfg.Forge.Token) - } -} - -func TestLoadTelegramTokenSecretRefAndLegacyFallback(t *testing.T) { +func TestLoadTelegramTokenSecretRef(t *testing.T) { path := filepath.Join(t.TempDir(), "config.toml") contents := "bot_user = \"widget\"\n" + "[chat.telegram]\ntoken = { engine = \"bws\", key = \"TELEGRAM_BOT_TOKEN\" }\n" + - "token_env = \"TELEGRAM_LEGACY_TOKEN\"\n" + "[[repos]]\nowner = \"acme\"\nname = \"app\"\n" if err := os.WriteFile(path, []byte(contents), 0o600); err != nil { t.Fatal(err) @@ -235,9 +188,6 @@ func TestLoadTelegramTokenSecretRefAndLegacyFallback(t *testing.T) { if cfg.Chat.Telegram.Token != want { t.Errorf("Telegram.Token = %#v, want %#v", cfg.Chat.Telegram.Token, want) } - if cfg.Chat.Telegram.TokenEnv != "TELEGRAM_LEGACY_TOKEN" { - t.Errorf("Telegram.TokenEnv = %q, want TELEGRAM_LEGACY_TOKEN", cfg.Chat.Telegram.TokenEnv) - } } // TestLoadRejectsInvalidConfigEnumsAndGlobs pins which layer rejects each kind @@ -910,7 +860,7 @@ ecosystem = "go" func TestIdentitiesConfigFallsBackToLegacyWhenEmpty(t *testing.T) { cfg, err := loadBytes([]byte(` bot_user = "solo" -forge = { type = "github", host = "https://github.test", token_env = "GH_TOKEN" } +forge = { type = "github", host = "https://github.test", token = { engine = "env", key = "GH_TOKEN" } } [[repos]] owner = "acme" @@ -931,7 +881,7 @@ func TestIdentitiesConfigRejectsEmptyName(t *testing.T) { _, err := loadBytes([]byte(` [[identities]] bot_user = "no-name" -forge = { type = "github", token_env = "X" } +forge = { type = "github", token = { engine = "env", key = "X" } } `)) if err == nil { t.Error("expected error for identity with empty name") diff --git a/internal/infrastructure/configuration/setup/setup_test.go b/internal/infrastructure/configuration/setup/setup_test.go index 461f2b130..0d0dfac23 100644 --- a/internal/infrastructure/configuration/setup/setup_test.go +++ b/internal/infrastructure/configuration/setup/setup_test.go @@ -314,8 +314,8 @@ func TestRun_TelegramWithAllowedUserIDs(t *testing.T) { t.Fatalf("Commit: %v", err) } cfg := generateAndLoad(t, edits) - if cfg.Chat.Telegram.TokenEnv != "ARCHIE_TELEGRAM_TOKEN" { - t.Errorf("chat.telegram.token_env = %q, want ARCHIE_TELEGRAM_TOKEN", cfg.Chat.Telegram.TokenEnv) + if want := (config.SecretRef{Engine: "env", Key: "ARCHIE_TELEGRAM_TOKEN"}); cfg.Chat.Telegram.Token != want { + t.Errorf("chat.telegram.token = %+v, want %+v", cfg.Chat.Telegram.Token, want) } if len(cfg.Chat.Telegram.AllowedUserIDs) != 2 || cfg.Chat.Telegram.AllowedUserIDs[0] != 111 || cfg.Chat.Telegram.AllowedUserIDs[1] != 222 { t.Errorf("chat.telegram.allowed_user_ids = %v, want [111 222]", cfg.Chat.Telegram.AllowedUserIDs) diff --git a/internal/infrastructure/configuration/setup/step_chat.go b/internal/infrastructure/configuration/setup/step_chat.go index 63d2dff33..2b28c0666 100644 --- a/internal/infrastructure/configuration/setup/step_chat.go +++ b/internal/infrastructure/configuration/setup/step_chat.go @@ -10,10 +10,8 @@ import ( "github.com/samcharles93/archie-core/internal/infrastructure/configuration/tomlwrite" ) -// telegramTokenEnv is the env var Telegram's bot token is stored under. -// TelegramConfig has no secret.SecretRef field -- unlike the forge and -// provider steps, the config edit is a plain token_env string, not a -// {engine,key} inline table. +// telegramTokenEnv is the env var a prompted Telegram bot token is stored +// under. const telegramTokenEnv = "ARCHIE_TELEGRAM_TOKEN" func stepChat(ctx context.Context, p Prompter, secrets SecretSink, params Params) (tableEdits, error) { @@ -30,14 +28,11 @@ func stepChat(ctx context.Context, p Prompter, secrets SecretSink, params Params } // A reference means the value already lives in a secret engine: write the - // reference and ask nothing. A supplied reference may name any engine, which - // the legacy token_env form cannot express, so it writes the preferred - // secret-reference form instead. Otherwise the token comes from a prompt, and + // reference and ask nothing. Otherwise the token comes from a prompt, and // only from a prompt; see stepForgeWithToken. - tokenForm := "token_env" - tokenValue := tomlwrite.String(telegramTokenEnv) + tokenValue := tomlwrite.Ref("env", telegramTokenEnv) if ref := params.TelegramTokenRef; ref != (config.SecretRef{}) { - tokenForm, tokenValue = "token", tomlwrite.Ref(ref.Engine, ref.Key) + tokenValue = tomlwrite.Ref(ref.Engine, ref.Key) } else { token, err := p.ReadSecret(ctx, "Telegram bot token (from @BotFather): ") if err != nil { @@ -72,7 +67,7 @@ func stepChat(ctx context.Context, p Prompter, secrets SecretSink, params Params return tableEdits{ "chat.telegram": { - tokenForm: tokenValue, + "token": tokenValue, "allowed_user_ids": intArrayLiteral(ids), }, }, nil diff --git a/internal/infrastructure/controlplanerpc/client.go b/internal/infrastructure/controlplanerpc/client.go index a20a57b74..96da28943 100644 --- a/internal/infrastructure/controlplanerpc/client.go +++ b/internal/infrastructure/controlplanerpc/client.go @@ -95,7 +95,7 @@ func RuntimeChatConfigFrom(ctx context.Context, reader ResourceReader, base conf Operator: settings.Operator, ShowToolCalls: settings.ShowToolCalls, MaxSteps: settings.MaxSteps, Models: settings.Models, Email: config.EmailConfig{ListenAddr: settings.Email.ListenAddr, RelayAddr: settings.Email.RelayAddr}, WebhookAddr: settings.WebhookAddr, Webhook: config.WebhookRoute{Path: settings.Webhook.Path, Secret: settings.Webhook.Secret, Template: settings.Webhook.Template, DeliverTo: settings.Webhook.DeliverTo}, - Telegram: config.TelegramConfig{AllowedUserIDs: settings.Telegram.AllowedUserIDs, Token: settings.Telegram.Token, TokenEnv: settings.Telegram.TokenEnv, UpdateCheckCommand: check, UpdateInstallCommand: install}, + Telegram: config.TelegramConfig{AllowedUserIDs: settings.Telegram.AllowedUserIDs, Token: settings.Telegram.Token, UpdateCheckCommand: check, UpdateInstallCommand: install}, RateLimit: config.RateLimitConfig{Window: time.Duration(settings.RateLimit.Window), MaxRequests: settings.RateLimit.MaxRequests}, UnrestrictedFilesystem: settings.UnrestrictedFilesystem, Workspace: settings.Workspace, } diff --git a/internal/infrastructure/controlplanerpc/vocabulary.go b/internal/infrastructure/controlplanerpc/vocabulary.go index 10603d2ec..a2782c588 100644 --- a/internal/infrastructure/controlplanerpc/vocabulary.go +++ b/internal/infrastructure/controlplanerpc/vocabulary.go @@ -33,7 +33,6 @@ type ChannelSettings struct { type TelegramSettings struct { AllowedUserIDs []int64 `json:"allowed_user_ids"` Token config.SecretRef `json:"token_ref"` - TokenEnv string `json:"token_env,omitempty"` CredentialConfigured bool `json:"credential_configured"` } diff --git a/internal/webui/api_config_test.go b/internal/webui/api_config_test.go index c03a3e638..e891c17c5 100644 --- a/internal/webui/api_config_test.go +++ b/internal/webui/api_config_test.go @@ -35,10 +35,9 @@ func configWithFakeSecrets() *config.Holder { BotEmail: "archie@example.com", Label: "archie", Forge: config.Forge{ - Type: "gitea", - Host: "gitea.example.com", - TokenEnv: "GITEA_TOKEN", - Token: secret.SecretRef{Engine: "env", Key: fakeForgeToken}, + Type: "gitea", + Host: "gitea.example.com", + Token: secret.SecretRef{Engine: "env", Key: fakeForgeToken}, }, Models: map[string]string{"builder": "openai/gpt-4"}, Providers: map[string]config.Provider{ @@ -58,7 +57,7 @@ func configWithFakeSecrets() *config.Holder { }, NATS: config.NATSConfig{URL: "nats://127.0.0.1:4222", TokenEnv: "NATS_TOKEN"}, Chat: config.ChatConfig{ - Telegram: config.TelegramConfig{TokenEnv: "TELEGRAM_TOKEN"}, + Telegram: config.TelegramConfig{Token: secret.SecretRef{Engine: "env", Key: "TELEGRAM_TOKEN"}}, }, }) } @@ -109,7 +108,7 @@ func TestBuildConfigViewPublishesPerIdentityForges(t *testing.T) { }, { Name: "github-bot", - Forge: config.Forge{Type: "github", Host: "https://github.example", TokenEnv: fakeForgeToken}, + Forge: config.Forge{Type: "github", Host: "https://github.example", Token: secret.SecretRef{Engine: "env", Key: fakeForgeToken}}, Repos: []config.Repo{{Owner: "beta", Name: "app"}}, }, }, diff --git a/internal/webui/api_setup_test.go b/internal/webui/api_setup_test.go index fe6ed83fb..ecb6c0c7f 100644 --- a/internal/webui/api_setup_test.go +++ b/internal/webui/api_setup_test.go @@ -37,7 +37,7 @@ func TestSetupChecklistRendersFromTheProjection(t *testing.T) { Repos: []config.Repo{{Owner: "acme", Name: "widget"}}, Chat: config.ChatConfig{ Operator: "Sam", - Telegram: config.TelegramConfig{TokenEnv: "TELEGRAM_TOKEN"}, + Telegram: config.TelegramConfig{Token: config.SecretRef{Engine: "env", Key: "TELEGRAM_TOKEN"}}, }, }, wantOperator: "Sam", @@ -120,7 +120,7 @@ func TestSetupChecklistChatChannelStepCountsEveryFrontEnd(t *testing.T) { { name: "telegram token env", cfg: config.Config{Chat: config.ChatConfig{ - Telegram: config.TelegramConfig{TokenEnv: "TELEGRAM_TOKEN"}, + Telegram: config.TelegramConfig{Token: config.SecretRef{Engine: "env", Key: "TELEGRAM_TOKEN"}}, }}, want: true, },