Commit Graph
124 Commits
Author SHA1 Message Date
sam 3917afeeb3 refactor(logging): pass the caller's context to TaskRegistry.Write
Write built its own context.Background() for the handler call, which meant
any new caller with a context to offer could not hand it over. Taking the
caller's context is what the next commit's park-reason writer needs, and it
is what contextcheck requires of a daemon-side writer.

No behaviour change: the context is used for the handler's own attribute
extraction and never consulted for cancellation -- a park is recorded at
exactly the moment a run's context has been cancelled, so a cancelled
context must not suppress the entry.
2026-09-18 01:49:42 +10:00
sam efff23d922 fix(staterpc): never decode a collection field to a nil slice
Every client method that decodes a repeated proto field goes through
mapValues, which returned nil for nil input. Protobuf decodes an empty
repeated field to nil, so an empty collection crossed the wire as JSON null
rather than an empty list: the field's type depended on whether it happened
to have contents, and the wire path disagreed with the local path, which
normalises its own slices.

This is the nil-slice class the contract-conformance audit deferred, arriving
by the route its own revisit condition names -- a handler that can produce
nil. The audit checked the webui handlers (clean, as it said) and did not
cover the wire mapping added afterwards, so the regressed field was the new
one: ReadTaskLog's components, observed as "components": null from the live
dashboard.

mapValues now returns []B{} for empty input, which fixes the class once at
the mapping helper rather than at each of its 36 call sites -- none of them
compares the result to nil, so nothing depended on the old behaviour.
TaskLog also normalises components, which is read straight from the proto
rather than through mapValues.

Red first: the test drives the existing local/grpc matrix and asserts the
marshalled JSON, so it fails on a null collection without depending on which
path is under test. Both collections are exercised empty -- entries present
with components empty, and a log file that exists with no lines -- because
the first shape alone leaves the entries side untested. Verified by mutation:
restoring the nil return fails it on "entries marshalled to null".
2026-09-17 14:58:14 +00:00
sam 29e5e0130d Merge pull request #846 from samcharles93/feat/835-disk-readiness-probe-watches-only-work-dir-so-a-full-root-fi
Disk readiness probe watches only work_dir, so a full root filesystem goes unreported (archie)
2026-09-17 22:39:15 +10:00
sam 2fd0f23971 Merge pull request #848 from samcharles93/feat/state-store-task-log-download
feat(staterpc): read task logs through the State Store and make them downloadable
2026-09-17 22:38:16 +10:00
sam cf7cc9d891 feat(webui): read a task's log through the State Store and let it be downloaded
The dashboard's attempt-log panel answered every read with "task logging is
optional and was not enabled for this run". That message was false: logging is
wired unconditionally in the daemon, and the log files exist. The dashboard
process simply had no reader -- composition left TaskLogs absent because no
contract carried it -- so the handler saw a nil registry and reported the
disabled shape, which the page rendered as a claim about configuration.

internal/logging now answers whether an attempt has a log at all: Tail sets
Result.Found, so "this attempt has no log" is a value rather than an empty
list indistinguishable from a read that never happened. Its registry gains
TaskLog (a decoded page) and TaskLogContent (the file verbatim, streamed,
because a log is unbounded input), and an absent reader reports
ErrTaskLogsUnavailable rather than an empty page -- a process that cannot read
logs must not implicate the attempt.

Those two answers travel the State Store contract as storecontract.TaskLogStore
(ReadTaskLog, StreamTaskLogContent) and are rehydrated on the client by
(Unavailable, canonical message), so archie-ui composes the reader from its own
store client instead of opening another process's files. The daemon's registry
is wired as the server-side reader in the State Store process only.

On top of that read, GET /api/tasks/{id}/logs/download serves the attempt's log
as a Content-Disposition attachment named task-<id>-attempt-<n>.log, and the
panel offers it. The JSON route keeps its shape and gains found, so the page
states the attempt has no log instead of blaming a setting.

Task log files stay owned by their directory's owner: archiving still removes a
task's log directory, and that removal is the daemon's, not the dashboard's.
2026-09-17 12:12:43 +00:00
sam ea128443e0 feat(gateway): persist the channel-native sender id on messages
Slice 1 of docs/prds/memory-engine-unification.md: persist the
participant, so a later curator can address agent-user memory scope.

- messages gains sender_id: schema, ALTER migration (idempotent via
  duplicate-column detection), both inserts, and both history selects.
  Pre-existing rows default to empty.
- curator.SessionSummary gains AgentID and ConversationMessage gains
  SenderID; the sessioncurator adapter fills them from the session's bot
  identity and the stored record.

The memory contract is untouched and nothing consumes the new fields
yet. Deriving a session's participant from its user-role messages, and
failing closed on ambiguity, stays with the curator rewrite.
2026-09-17 22:06:54 +10:00
sam 9b566b8ad4 fix(readiness): keep required status when an optional target shares a path
Targets are deduplicated by path so a shared filesystem is probed once, but
the first target seen won. With root, then an optional /var, then a required
data path that resolves to /var, the optional target is the one that survived
-- so its rules were applied to a path the daemon requires. An absent /var is
skipped as "optional absent", and with another healthy target present the
probe reported OK while a required path was unavailable.

Deduplication now keeps the strictest requirement any target places on a
path, and its name, so the failure is both visible and correctly attributed
rather than reported against the optional target that happened to come first.

Red first: the new test drives the reported scenario through an injected
statfs and failed with `status = "ok", want degraded` before the fix.
Verified by mutation -- restoring first-wins dedup fails it again.
2026-09-17 11:48:23 +00:00
samcharles93 f34c4076d6 Disk readiness probe watches only work_dir, so a full root filesystem goes unreported (archie)
Implements #835
2026-09-17 11:34:38 +00:00
sam af3a8a2a61 refactor(config): delete the two decoded-but-unread policy fields
MemoryConfig.SessionTTL and ToolPolicy.ParallelExecution were decoded by
config loading and read nowhere, so setting either silently did nothing.
Removing them routes both keys into the unknown-key detector, which names
them in a boot warning instead. A live-looking knob wired to nothing is
the worse state, and the sibling memory.provider already earned a loud
load-time rejection for exactly this.

Also drops the config.example.toml line that shipped session_ttl into
every first-run config.toml via configtemplate.go, and the commented-out
dir_test.go assertions that would have re-created both fields under that
file's "make these pass without modifying them" header.
2026-09-17 00:32:02 +10:00
sam f4e32ee6d4 docs(skill): drop comments that named the deleted skill.Discover
Lane F deleted skill.Discover/skill.DiscoverPlugins/skill.Skill (no
production caller) in 952bf4d, which left three comments in packages it did
not own describing or contrasting behaviour against a symbol that no longer
exists -- a dangling reference is the same drift class as an unreachable
code path, just cheaper to fix.

The behavioural statements are kept; only the dead names go. internal/skill's
Catalog skips a SKILL.md it cannot read, while this curator's store reports
the per-skill failure as an Action, so the test's rationale still holds
without naming the removed function.

Comment-only: no behaviour change, task check exit 0.
2026-09-15 13:17:54 +10:00
sam fbcfd68cd1 fix(taskactions): resolve max_retries from the task's owning identity
WIRE, not delete: per-repo max_retries is a configured field with a real
consumer (the retry gate), and it works for the legacy single-identity
[[repos]] list. In a multi-identity deployment repositories live under
[[identities.repos]] and there is no global [[repos]] at all, so the resolver
never saw the override and a parked task was killed at the global cap rather
than the configured one.

MaxRetries now consults the identity named on the task before the legacy list,
then falls back to the global cap. Identity name is the only thing that says
which repository list owns a persisted row.

Red-then-green: TestMaxRetriesResolvesFromTheOwningIdentity gained the
multi-identity cases; "identity repo override wins over the global cap" failed
with `MaxRetries = 3, want 7`. Two neighbouring cases keep the fix honest:
another identity's override must not leak, and the legacy path must still
resolve. Mutation-verified by deleting only the identity lookup, keeping the
extracted helper and the API intact.
2026-09-15 12:59:06 +10:00
sam 8b06d4192c merge: lane E (tools-media-1, transport-nats-2, release-1) 2026-09-15 12:55:07 +10:00
sam cd775f8705 merge: lane D (curator-1, staterpc-2) 2026-09-15 12:53:32 +10:00
sam bb780e63b4 fix(scheduling): record a completed run so a recurring job stops re-firing every tick
WIRE, not delete: cronstore.Store.MarkRun is the documented run-completion
step ("once the ticker has dispatched a job, the runner ... calls MarkRun to
keep next_run fresh") and the scheduling engine is now started at boot, but
nothing in production called it. Due returns every job whose NextRun is at or
before now, so with NextRun frozen in the past a job with a 1h interval was
handed to the runner on every tick.

The delivery Router is the single Runner the engine is given and, per this
package's own doc, the only place that knows a job store exists, so it is the
producer-side site. RouterStore (SpecLookup + RunRecorder) widens only what
the Router takes; the per-kind runners keep the narrow SpecLookup, and
NewRouter's signature is unchanged, so no call site moved.

Only a successful run records, matching the store's own contract that an
interval or cron schedule fires "after the last successful run". A one-shot
schedule reports ErrScheduleUnsupported -- it has no recurring next run by
definition -- which is swallowed rather than returned, because propagating it
would make the engine emit KindJobError for a job that actually succeeded.

Red-then-green: TestRouterAdvancesTheScheduleAfterASuccessfulRun asserts
LastRun is set and NextRun moved past now, and failed on both counts before
the change. TestRouterToleratesAOnceScheduleWithoutANextRun pins the
sentinel half. Mutation-verified by replacing only the record call with
`return nil`, keeping the API intact.
2026-09-15 12:53:02 +10:00
sam 0a73394c23 fix(servicediscovery/nats): validate config after defaults
Root-cause fix: Connect validated the raw config before withDefaults, so
the Heartbeat<TTL guard was skipped whenever Heartbeat was unset and a
custom TTL below DefaultHeartbeat passed as a silently expiring registry.
Apply defaults first so the documented invariant is enforced. No
WIRE/DELETE decision applies: this is a producer-ordering bug, not
unreachable code.
2026-09-15 12:51:17 +10:00
sam 4268a25d30 fix(staterpc): preserve marshal_error marker in eventDataJSON
WIRE: docs/prds/state-store-contract.md §11 requires the remote wire and the
local adapter to behave identically. The local adapter (internal/store/events.go)
records a {"marshal_error":%q} marker when json.Marshal of event Data fails,
while eventDataJSON silently returned "" on the same failure, emptying the
event's Data on the wire. Carry the same marker so an unmarshalable Data
value survives the hop with the local adapter's fidelity.
2026-09-15 12:50:57 +10:00
sam b0050ff20a refactor(state): delete the dead IncrementRetryCount RPC (breaking change, accepted)
IncrementRetryCount had zero production callers -- only tests and the
staterpc plumbing referenced it. taskactions.Service.applyRetry already
uses the atomic RetryTask exclusively, which increments retry_count and
requeues in one transaction.

Unlike ListCaptures/ListUndispatchedCaptures (kept as declared-unconsumed
compatibility surfaces because a rolling deploy could have an old
client/server pairing mid-flight), this repo has one production consumer
(see AGENTS.md's solo-project note), so the breaking removal is accepted
outright rather than deprecated-and-kept. Deleted the Go method, the
storecontract interface entry, the staterpc server/client methods, and the
RPC/messages from state.proto, regenerating the .pb.go/_grpc.pb.go pair.

Test fixtures that used IncrementRetryCount as a setup helper now drive
retry_count through the real path instead: queries_test.go bumps it via
direct SQL (same package, no contract to route through), and
api_tasks_actions_test.go now loops RetryTask+Transition, which exercises
production code instead of a deleted one.
2026-09-15 11:24:57 +10:00
sam 0da70ca8f4 refactor(staterpc): delete the superseded single-token auth interceptor
UnaryTokenInterceptor/TokenValidator/checkToken (auth.go) and
constantTimeTokenValidator (state_store.go) had no production caller:
server auth on the bridge-address listener is wired through
TaskGrants.UnaryInterceptor/StreamInterceptor, which replaced this
all-or-nothing token check with per-task scoped grants. Removed the
dead cluster and its now-pointless tests; TaskGrants' own auth
rejection paths are already covered in task_grants_test.go.
2026-09-15 10:18:25 +10:00
sam 9b2fb4a82c feat(configuration): report config keys no decode target consumed
decodeTOML discarded toml.DecodeFile's metadata, so a misspelled or
renamed key parsed, validated and silently did nothing. Document.UnknownKeys
now carries the dotted key paths a loaded file's decode targets left
undecoded.

One file feeds two decode targets (&doc.Config and &doc.Scheduling), so a
key legitimately owned by one shows up as undecoded in the other -- a key
is only reported when both leave it undecoded (unknownKeys intersects the
two sets), which is what keeps a valid [scheduling] block from being
misreported as unknown on every config that uses it.

YAML config sources are unchanged for now (no equivalent metadata hook in
the yaml decoder); this covers the TOML path, which is what
config.example.toml, every shipped deployments/*.toml profile, and
install.sh's generated config.toml all use.
2026-09-15 05:07:54 +10:00
sam c0dbb6410c fix(archied): disable a provider whose credential is missing instead of refusing to boot
configuration.md's startup policy -- "a missing credential disables a capability.
Only an invalid config stops the daemon" -- names this exact case: "Apply the same
reasoning to any future capability credential, LLM keys especially: start, report
the capability as unavailable, let the operator see it." The code did the
opposite. resolveProviderMap returned an error when a provider's api_key could not
be resolved, and again when it resolved empty, so configuredSecretRegistry failed
and the daemon would not start. A provider nobody referenced still blocked boot,
because the walk covers every entry in cfg.Providers rather than the ones [models]
uses.

The forge path was fixed to degrade for precisely this reason (resolveForge,
guarded by TestResolveForgeDegradesInsteadOfFailing); this is its provider
counterpart. A credential that cannot be resolved now disables that provider with
a warning naming it and why, and the daemon starts.

Disabling clears the reference rather than leaving it. webui's ProviderView
derives Configured from api_key or APIKeyEnv, so an unresolvable reference left in
place would advertise a provider nothing can use -- the "looks configured and is
not" shape this codebase keeps having to remove. Consumers already treat an empty
APIKeyEnv as no credential (agentexec/runtime skips such a provider, the daemon
exports nothing to the agent container), so clearing it is the whole disable.

The other half of the policy is kept: a reference naming only one of engine and
key is a config error, not a missing credential, and stays fatal.
applyForgeDefaults only ever builds a ref with both halves, so a half-named one can
only come from a hand-edited config.

This also defuses the trap 89cfa44 introduced. archied setup can now write a
provider reference to any engine (-provider-secret-ref bws:OPENAI_API_KEY), and on
a machine without that engine the config used to load clean and then brick the
daemon. It now starts with that provider disabled and a warning.

The comment on templateDefaultActiveProvider described the old fatal behaviour and
is corrected rather than left to mislead the next reader.

All three behaviours are mutation-verified: returning an error again, accepting a
half-named reference, and disabling without clearing the reference each fail the
corresponding test. The red was an assertion failure, not a compile error -- the
logger parameter was threaded through first so the new test could be run against
unchanged behaviour.
2026-09-15 03:28:35 +10:00
sam 89cfa44b5e feat(configuration): let setup reference a secret without carrying its value
A parameterised install could not configure a cloud provider without a terminal:
the only way a secret value entered was the prompt, so an unattended run was
limited to the keyless self-hosted provider. The missing piece is the reference
form.

A reference is not a secret. An engine name and a key name are not sensitive --
which is exactly why a reference may be a parameter while a value may not -- so
setup gains -forge-secret-ref, -provider-secret-ref and -telegram-secret-ref,
each taking engine:key, parsed by one new setup.ParseSecretRef. When a reference
is given the step writes it to TOML and asks nothing, and setup neither reads nor
stores the value, because the value is not its to hold. That is the difference
from the prompt path, where the operator supplies a value and setup writes it
into the env engine and references it there.

Engine names are identifiers, not paths: the shipped engines are registered as
age, sops and vault, so a reference like vault/openbao:KEY is refused rather than
written into a config that could never resolve it.

Two refusals guard the silent no-op. A reference naming a key for the keyless
self-hosted provider, or for a forge that is disabled, would sit in the config
looking configured while nothing read it -- the failure shape this flow exists to
remove -- so both are refused rather than written.

telegram keeps writing token_env for the prompt path, because that form names an
env var and the prompt path is the env engine; a supplied reference may name any
engine, which token_env cannot express, so the reference path writes the
preferred token = {engine, key} form. Noted as the one asymmetry.

Also folded stepCloudProvider's key handling into cloudKeyEdit and cloudModel.
That was a lint fix for nested blocks, but the split is the honest shape: the two
branches obtain a key edit by different means and then resolve a model the same
way.

Every new test was mutation-verified by reintroducing the absence: ignoring the
forge reference, making ParseSecretRef validate nothing, and dropping the keyless
-provider guard each fail the corresponding test.
2026-09-15 03:23:08 +10:00
sam 3f7dc7c088 fix(configuration): stop letting a secret value be set from the command line
archied setup took -forge-token, -provider-api-key and -telegram-token, each
carrying a secret VALUE. That is wrong twice over: the value lands in shell
history and in every process listing, and it is a second way to set a secret
that no secret engine knows about.

The codebase already holds the opposite invariant, and had before this landed:

- configuration.md:423-425 states it directly -- "setup writes the reference to
  TOML and the value to the secret engine".
- No CLI flag anywhere in the repository accepted a secret value; these three
  were the only ones.
- install.sh already does it correctly: read_secret prompts without echoing so
  the value never reaches scrollback, and set_env_key writes it into the systemd
  EnvironmentFile, which is the env engine's backing store.

So the SecretSink half was right -- writing the value to the env file IS writing
it to the secret engine, for the env engine -- and the prompt path was right.
Only the three value-carrying flags were wrong.

Removed: Params.ForgeToken, Params.ProviderAPIKey, Params.TelegramToken and the
flags that fed them, along with the parameter plumbing in step_forge,
step_provider and step_chat. Those steps now always read the secret from the
prompt surface. Params gains a comment recording why it deliberately has no
secret-valued field, so the absence is a decision rather than an oversight.

TelegramUserIDs stays: an allowlist of user IDs is access policy, not a
credential.

Two tests pinned the wrong behaviour and are replaced rather than deleted:

- TestRunParams_ProviderAPIKeyNeverPrompts asserted a secret could arrive as a
  parameter. It becomes TestRunParams_SecretsComeOnlyFromThePrompter, which
  supplies every non-secret answer through Params and scripts only the secret
  reads, so it fails if a secret ever comes from anywhere else.
- TestRunSetup_DefaultsWithForgeTokenWritesEnv exercised the removed flag. It
  becomes TestRunSetupRejectsSecretValueFlags, which asserts all three flags are
  rejected with exit 2 and that neither a config nor an env file is written --
  verified by re-adding -forge-token and watching it fail.

The unused rejectingPrompter went with them; its remaining replacement uses a
scripted prompter instead.
2026-09-15 03:15:53 +10:00
sam ef0d61782b feat(configuration): add archied setup, the caller the first-run flow was built for
docs/architecture/configuration.md decides that "install.sh must stop generating
config.toml; archied setup owns it", and gives the reason: the installer
hand-rolling TOML already drifted from the schema once, and "the durable fix is
that the code writing the config is the code that reads it". setup.Run,
tomlwrite, configtemplate.Example and terminalprompt were all built for that and
had no production caller between them. This adds the caller.

setup.Run's own doc comment states the obligations, and they are the shape of
installValidatedConfig: render the edits, prove the result loads through a real
configuration.Loader, and only then install the file and commit the secrets. A
validation failure returns before either write, so a bad config leaves neither a
config nor a secret on disk. The rendered bytes are proven from a temp file, so
a load failure cannot have already installed anything. The config is written
0600 via same-directory temp and rename.

Parameterisation is typed, not matched against prompt text. A flag-to-prompt
mapping would have to match strings, which is the brittleness removed in
1f3f54b, so setup.Params is consulted before each question instead and the
prompts are only reached for answers nothing supplied. Run stays a wrapper
passing the zero value, so the package's existing tests keep passing untouched.
No environment variable is consulted anywhere: flags and prompts are the only
two ways an answer arrives.

--defaults is a known-valid unattended baseline, not "each prompt's own default".
That cannot work, and the test proves it: the provider step's first option is
OpenAI, whose model prompt hard-errors on an empty answer. The baseline therefore
covers every required answer and leaves optional ones to answer themselves as
"skip" -- ollama is the only keyless provider, so an unattended install boots
without needing a secret.

Two gaps closed after review rather than left as accepted work:

- A cloud provider was not configurable without a terminal, because the provider
  API key had no typed parameter: unattended setup could only ever pick the
  keyless self-hosted provider. Params.ProviderAPIKey and -provider-api-key fix
  that. The key goes to the env file and TOML carries only the secret reference.
- The write order was unpinned. Inverting installValidatedConfig's two writes --
  committing secrets before the config -- left every test green, so nothing held
  the invariant the SecretSink contract states. The new
  TestInstallValidatedConfig_ConfigWriteFailureLeavesNoSecret fails on that
  inversion; the existing validation-failure test does not cover it.

Also fixed three lint failures in the first pass (gocyclo on RunSetup, and two
ineffectual `choice` initialisers): RunSetup's flag surface, the flag-to-Params
mapping, the prompter choice and the existing-config read are now separate
functions, which is the real fix for the complexity rather than a suppression.

The setup flow no longer hand-rolls its own answer format: -telegram-user-ids
reuses setup.ParseTelegramUserIDs, the same parser the prompt path uses, so the
allowlist cannot be parsed two ways.

Found by an adversarial package sweep (temp tracker: config-1,
repo-root-deployment-2, .local/issue-tracker/). Plan of record:
.local/issue-tracker/design-archied-setup.md. install.sh still generates its own
config; that is phase 2 and is not claimed here.
2026-09-15 02:52:24 +10:00
sam 355e1c64b2 fix(scheduling): respect configuration ownership 2026-09-14 23:25:09 +10:00
sam a2cca6088e feat(cronevents): adapt the events bus to scheduling.Sink
A scheduled run has no task, no chat turn and no workflow behind it, so its
emitted events are the only trace it leaves -- and the engine's Sink is the
emitter shape of a bus it deliberately does not import. Something has to turn
one into the other; this is that seam.

  - Sink(mode, bus) returns a sink over the bus for "bus", and nil for
    "none"/absent or a nil bus. Nil rather than a no-op sink keeps
    "emission is off" visible to whoever reads the composition, and it is
    the configuration the engine documents as valid: it still runs, it is
    just unobservable.
  - The published event carries the engine's own Kind/Detail/Data and no
    task-scoped identity. A cron run has none, and borrowing the emitting
    daemon's would attach it to an unrelated task's timeline.
  - An unrecognised mode is an error; the loader rejects it first, but a
    hand-built config must not silently disable observability.

TDD: the sink tests were written first and failed on assertions (Sink("bus")
returned nil; an unknown mode was accepted), not on compilation. The
end-to-end test drives a real engine on an injected clock and subscribes to
the bus, so the Emit -> Publish path is proven rather than assumed -- no
sleeps, no wall-clock deadlines.
2026-09-14 10:51:47 +00:00
sam 4d838b9fb1 feat(configuration): translate [scheduling] into scheduling.EngineConfig
The engine needs a fully-resolved configuration, not zero values it has to
second-guess. Add the translator the wiring slice then hands to
internal/app/archied:

  - TranslateScheduling resolves unset tunables from the domain's own
    Default* constants rather than a second copy here, so the two cannot
    drift.
  - A negative tunable is reported as a startup error wrapping
    ErrInvalidInput, matching validateCapture and validatePollInterval.
    Clamping was rejected: it runs something other than what the operator
    wrote, which is how a misconfiguration stays invisible.
  - Events and Clock stay nil. This package owns no bus and no clock --
    attaching them is composition -- and the engine documents a nil sink as
    a valid configuration: it still runs, it is just unobservable.

applySchedulingDefaults and validateScheduling keep defaulting and
validation separate, the split applyDefaults' own doc explains: the load
path applies both, Validate applies only the latter.

TDD: the translator tests were written first and failed on assertions
(Interval = 0s, want 1m0s; negative values accepted silently), not on
compilation.
2026-09-14 10:51:41 +00:00
sam bb1aea0b30 feat(crondelivery): add chat, workflow and routing cron runners
The ticker engine had no work to dispatch. Add the delivery half as a new
infrastructure package with three scheduling.Runner implementations:

  - ChatCourier sends a job's payload text to its target chat.
  - WorkflowTask submits a job as a unit of work.
  - Router dispatches on the job's kind and is the single runner the engine
    is given, so the engine stays unaware that more than one delivery exists.

Nothing here talks to a channel, a broker or a forge. The outbound send is
an injected Courier function and work intake is a narrow TaskSubmitter
interface, so which transport carries a message stays the deployment's
decision rather than the cron's, and the package is testable without a
network.

An unrecognised kind is refused at the gate, not failed: it emits
KindJobError with phase "dispatch" in the engine's own data shape and
returns nil, so a misconfigured job is visible without being reported as a
job that tried and broke. A nil sink still refuses, just unobservably.

Every runner returns the context error on a cancelled run and produces no
side effect, so the engine's bounded shutdown drains rather than waiting
out the per-run timeout.

Tests exercise a real cronstore on a temp path, including the epic's
headline daily-status scenario end to end from a persisted due job through
the router to the delivered message.
2026-09-14 09:54:41 +00:00
sam 08cfe837a9 feat(cronstore): add job kind discriminator and bump schema to 2
Jobs need a discriminator for the delivery router to dispatch on, and
JobSpec had none. Add a top-level Kind field with values "chat" (default
when empty) and "workflow".

The empty value is load-bearing: every job written before this field
existed carries no kind and must keep delivering as a chat message, so an
empty Kind resolves to "chat" rather than being rejected.

DisallowUnknownFields means this additive change must bump schemaVersion,
so it goes 1 -> 2. A version-1 file still loads — Kind reads back empty —
which a test pins, because the alternative is that every existing cron job
stops firing on upgrade.

The store does not interpret the value: an unrecognised kind is persisted
verbatim and refused by the router, which owns the kind-to-runner mapping.
2026-09-14 09:54:41 +00:00
sam c2ebcb8298 test(archied): stop racing state-store startup against a wall clock
TestRunStateStoreAcceptsEnvironmentToken wrapped the whole of RunStateStore --
SQLite schema init and the serve loop -- in a 200ms context deadline, so
whether it passed depended on how fast the disk was. Measured before the fix:
6 failures in 12 consecutive runs. A gate that fails half the time teaches
people to ignore it, and the failure it reported ('store: init schema:
context deadline exceeded') named a time budget, not a defect.

Cancellation is the assertion, so the test now cancels and then asserts:
the call must not return before cancellation (that would mean startup refused
the config, the thing this test exists to catch) and must return within a
generous grace once cancelled. The graces bound 'did startup reject us', not
'machine speed'. Measured after: 12 passes in 12 runs.

Also applies the canonical gofumpt and 'go fix' output to
internal/infrastructure/staterpc/dial.go, cmd/archie-ui/main_test.go and
internal/releaseupdate/check_script_test.go. task check runs gofumpt -w over
the tree, so leaving these unformatted made the gate rewrite unrelated files
mid-run and report dirty state for changes it had made itself.
2026-09-14 08:09:14 +00:00
sam 03afd2e8ad refactor(webui): take configuration off the dashboard server
webui.Server declared Cfg *config.Holder with eight read sites, none of
which ran in the UI process: composition leaves it nil there. The field
survived because the daemon kept a webui.Server it never served, using it
to render the published ConfigView snapshot and to hold the readiness
probes (archie-core-ml30).

Split at the producer. LocalConfigView becomes webui.BuildConfigView, a
pure function over a ConfigViewInput the configuration owner assembles;
the DTO and its schema stay where the UI renders them. The daemon builds
that input from its own state (boot.configViewInput) and publishes the
result. Readiness reads the daemon's Holder, channel manager and chat
contract, and the registry it produces is a daemon field, not a field on
a server with no listener. Boot now owns one Holder instead of seeding a
second and replacing it in buildDaemon; operator retry caps read it too,
so they follow a reload rather than a boot-time snapshot.

Server loses Cfg, ConfigProvenance, LastReload, ConfigOverrides and
SetProvenance. The nil-guarded branches they fed went with them, each
checked first against what the UI process actually serves:

- chat.show_tool_calls and the /api/setup checklist were degraded, not
  dead. ConfigView gains a chat section carrying show_tool_calls, the
  operator name and whether a channel is configured, and both surfaces
  read the projection. The end-to-end suite asserts the checklist renders
  from the published snapshot.
- /api/logs takes its path as a process-local option. The history is on
  the daemon's disk, so a dashboard elsewhere cannot read it by learning
  the path; that route still needs a contract.
- handleChannels drops its config-derived fallback, superseded by the
  status manager, which already carries the descriptions and detail.
- trustForwardedHeaders keeps only the process's own setting, which the
  UI process already sets.
- resolveForge keeps the published-projection path it already had.

ConfigView.Editable moves to handleConfig, decided by whether this
process holds UpdateConfig. It describes the writer, not the document, so
the write contract (archie-core-j28m) makes the page editable by wiring
one field. The write handlers and their seams stay for it.

overlay.Store gains Keys: Snapshot nests dotted keys for decoding, so the
overridden-key list was publishing section names ("budgets") where the
dashboard marks and resets rows by stored key ("budgets.max_steps").

Multi-identity forge links move to archie-core-pv6t: forgeConfigForTask
resolved a task's forge from config.Config, had no reachable caller once
the holder was gone, and belongs in the projection rather than the
rendering package.
2026-09-11 23:57:38 +10:00
sam 9d9c79a22f fix(staterpc): attach the bearer token to State Store streams
The capture batch reads moved onto server-streaming RPCs (StreamCaptures /
StreamUndispatchedCaptures) to get past gRPC's 4 MiB unary cap, but the
client interceptor suite attached the bearer token to unary calls only:
Dial installed WithUnaryInterceptor and nothing for streams, while
TaskGrants.StreamInterceptor requires the administrative token. On every
token-protected (non-loopback) listener -- every container-mode deployment
-- the daemon's binding dispatch and the dashboard's capture inspector got
PermissionDenied from the stream interceptor, and the unary fallback those
reads replaced is no longer taken, so there was no working path.

- Add StreamClientTokenInterceptor, mirroring gatewayrpc's, and install it
  alongside the unary one in Dial, the single client dial path the daemon,
  the dashboard and the agent all use.
- Route agenttransport's State Store dial through staterpc.Dial, deleting
  the duplicate dial/fail-closed logic that installed only the unary
  interceptor -- a second place for this class of bug to hide.
- Regression tests: the grants harness now dials through the production
  Dial so client-side wiring cannot drift again;
  TestCaptureStreamsCarryTheAdminToken reads both list surfaces (5 MiB
  batch) through a token-protected listener;
  TestStateStoreRealProcessTokenProtectedCaptureStream does the same
  against the real binary; TestUpdateRejectsNilTask covers the Update
  guard left untested by the earlier finding fix.
2026-09-11 22:43:34 +10:00
sam a00c578cb7 refactor(ui): sever the archie-ui binary from every daemon runtime package
Completes the objective deletion gate for the UI Service
(archie-core-8cda.5.6): go list -deps ./cmd/archie-ui now links zero
banned packages -- no modernc.org/sqlite, no internal/store, gateway,
channels, memory, secret, agentexec, tools, skill, yaegiutil, curator,
or the workflow engine. The closure shrinks from 68 to 26 archie-core
packages. Each cut is a producer-side move; no consumer-side defensive
shims.

- Store contracts (TaskStore family, value types, sentinels) moved from
  internal/store to internal/domain/storecontract -- the approved contract
  location per state-store-contract rev. 2d, and NOT internal/contracts:
  that tree is buf generate output and tools/proto.sh check deletes
  hand-written files there. internal/store keeps aliases; sentinel
  message strings are byte-identical and remain the wire contract.
- Chat contracts (ChatContract, sessions, turns, streaming, commands)
  moved from internal/gateway to internal/domain/messaging; gateway keeps
  aliases. ToolCallEvent rendering helpers become gateway functions
  (methods cannot live on alias types).
- Task vocabulary (Task, statuses, mid-run Store, Definition) split into
  internal/domain/workflow/task; the pipeline engine stays in package
  workflow with aliases, so daemon-side callers are unchanged.
- overlay.DeniedKeys moved to internal/infrastructure/configuration:
  webui referenced the constant and that dragged the overlay SQLite
  store in.
- webui.Server's concrete runtime handles become webui-owned view
  interfaces with daemon-side bootstrap adapters: channel lifecycle
  (internal/channels/status), MemoryStatus, CuratorStatus, and a
  SkillCatalog seam replacing the direct skill.DefaultRoots/CatalogRoots
  calls. Each degrades to an empty page when unwired.
- config.SecretRef moved into internal/config (config vocabulary);
  internal/secret keeps an alias and Registry.Resolve absorbs the
  zero-value short-circuit.

Docs: state-store-contract rev. 2d relocation record; ui-service-boundary
deletion gate marked satisfied; ARCHITECTURE.md package map rows.
2026-09-10 03:03:33 +10:00
sam 983ddd7c4b refactor(store): move the producer-owned contracts to internal/contracts/store/v1
The deletion gate for the UI Service (archie-core-8cda.5.6) is objective:
go list -deps from cmd/archie-ui must show no SQL/store implementation.
internal/store's hand-written contract surfaces (TaskStore and its
component interfaces, CaptureStore, MappingStore, BindingStore,
BindingDispatcher, BindingTaskCreator, ConfigSnapshotStore) move to
internal/contracts/store/v1 (package storev1), alongside the value types
they carry (CapturedEvent, ConfigSnapshot, WorkflowStat, StageStat,
DayTokens) and the sentinel errors -- whose canonical message strings are
the wire contract and are byte-identical after the move.

internal/store keeps type aliases, so daemon-side callers (archied, the
daemon, staterpc's server side, taskactions) are unaffected. The
UI-facing packages switch to storev1 directly: webui, archieui,
captureintake, gatewayrpc, and staterpc's client/values -- which drops
internal/store and modernc.org/sqlite from the archie-ui binary's import
closure.

overlay.DeniedKeys moves to internal/infrastructure/configuration for the
same reason: webui referenced the constant and that dragged the overlay
package's SQLite store in.

The chat-contract and remaining runtime-handle decoupling continues under
the same bead.
2026-09-10 03:03:33 +10:00
sam d36073528d refactor(archied): cut the dashboard over to the archie-ui process
PRD gate 7 (docs/prds/ui-service-boundary.md): the daemon's in-process
webui.Run listener is deleted in the same change that wires the UI process,
so no fallback or second HTTP authority remains. The daemon's webui.Server
stays only as the configuration snapshot's renderer (archie-core-ymut): it
keeps the config Holder, provenance, reload status and the override list,
and drops the store surfaces, event broadcast, chat/task wiring that only
fed the listener. The bus drain becomes persistence-only -- the store is
the single fan-out point the UI process reads through its event pump.

The dashboard's configuration write path (PATCH /api/config, per-row reset,
per-repo field update) is deleted rather than left as dead policy: the
writes are descoped for the UI process (archie-core-ymut) and no route
reaches them. Editing is config.toml plus reload; the overlay store stays
for reload wiring.
2026-09-10 00:56:02 +10:00
sam 428a7879f6 feat(archieui): mount the capture intake receiver over the State Store
At the cutover (archie-core-8cda.5.4) the UI process is the only listener
serving POST /webhooks/capture/{source}: the receiver is a persistence shim
over the State Store contract, and the daemon's binding-dispatch loop keeps
consuming captures from the same store, so the HTTP front door moves without
moving the owner of work intake. Zero [capture] options fall back to
configuration.DefaultCapture; the arrival announcement persists through
InsertEvent so the event pump delivers it, where the daemon's bus drain
persisted it before.
2026-09-10 00:50:28 +10:00
sam d6b2589448 refactor(archied): move webhook capture intake to the process that owns work intake
The dashboard's POST /webhooks/capture/{source} handler becomes
internal/infrastructure/captureintake.Receiver, mounted by the daemon on
the same bypass mux through webui.Server.CaptureIntake; the dashboard
keeps only the GET /api/captures read and the mapping preview's scan
window. The UI process now mounts no intake route at all instead of one
that answers 503 (archie-core-8cda.5.4).
2026-09-10 00:35:14 +10:00
sam 242e51b3e1 feat(staterpc): carry the dashboard's configuration snapshot
archie-core-ymut decided the configuration page reads a projection the daemon
publishes rather than reaching into a shared config.Holder. This is the
carrier: a single-row store surface plus PutConfigSnapshot/GetConfigSnapshot,
taking the contract to 42 RPCs.

The document is opaque here. Its shape belongs to the daemon that builds it
and the page that renders it, so the store neither parses nor validates it,
and schema names the projection so a reader can refuse one it does not
understand. It is secret-free where it is built: the projection carries an API
key's environment variable name and whether it resolved, never a value.

Both RPCs are administrative. authorizesTaskScopedCall is deny-by-default, so
a container's task-scoped grant can neither rewrite what an operator reads nor
read a projection of the deployment it runs inside; a test pins both.

Nothing publishes or reads it yet -- the daemon's publisher and the UI's
read path land with the rest of the cutover.
2026-09-09 23:35:41 +10:00
sam 6048c8ba91 feat(archied): serve the daemon's own health endpoint
The update watchdog verifies archied's restart, so archied has to be what
answers. It was probing the dashboard's /healthz, which belongs to the
dashboard: switch [web] off and nothing answers, and in the extracted UI
topology that endpoint reports a different process entirely, which would
confirm a release while the daemon it was meant to verify is down.

[health].listen (127.0.0.1:8485, defaulted, always on) serves /healthz,
/health and /health/detailed for the life of the process. Liveness answers
503 until the daemon reaches its run loop: the listener binds before the
subsystems do, so an unconditional 200 would tell the watchdog a half-booted
release came up. Failing to bind is fatal, because a daemon nothing can probe
gets every update rolled back. The State Store's readiness surface now shares
the listener plumbing, keeping its log and error text verbatim.

Closes archie-core-exbz, which asked which of two bad options to take when
the dashboard is off. Neither: the daemon owns its own liveness.

Also deletes TestInstallUpdateDetachesInstallerFromCallbackContext. It has
failed intermittently under load more than once, racing its fake bot server's
multipart parse against the cancellation it induces.
2026-09-09 23:29:11 +10:00
sam fcf64a610d feat(webui): route dashboard task actions through the Gateway contract
The dashboard composed its own taskactions.Service over whatever handles
happened to be set on webui.Server. In the extracted UI process those are
all nil, and each nil silently removes a guarantee: no Cfg means max_retries
stops being enforced, no Issues means a rejected task's forge issue stays
open and the poller re-enqueues it, no Events means operator actions never
reach the timeline, no TaskStopper means Stop cannot interrupt running work.
The handler now asks whoever owns task execution, through
ApplyOperatorTaskAction, and Issues/TaskStopper leave the dashboard entirely.

That path crosses two hops that both flatten errors, so the sentinels the
handler maps to 404/409/503 travel explicitly: a kind beside the message on
the NATS envelope, a gRPC code on the Gateway contract, each restored on
arrival. Without them a task that simply moved on reports as a broken daemon.

The action tests keep running the real service, now behind a local contract
the way the daemon serves it in production, so retry limits, forge closure,
events, archiving and log removal stay covered where they were.
2026-09-09 23:29:11 +10:00
sam 4e641478c2 feat(gateway): give the dashboard operator its own task-action contract
archie-core-8cda.5.4 requires /api/tasks/{id}/action to go through
ChatContract rather than a task-action service the UI process composes
itself. The contract could not carry the request: ApplyTaskAction's identity
is a scope, and the daemon's action service distinguishes a named identity
from a nil one, which is the authenticated operator acting across
identities. Sending "" would not have expressed it either -- that is a real
identity in a single-identity deployment (chatTaskProfiles).

ApplyOperatorTaskAction is that case, additively: a separate RPC, so buf
sees no cardinality change on a shipped field, and no request that can carry
both an identity and operator authority. ChatTaskActor's identity becomes a
pointer end to end, from the Gateway's local adapter through the NATS hop to
taskactions.Service.Apply, which has always taken one.

The conformance test now covers both scopes through the local adapter and
the gRPC hop; the chat tool test pins that a chat action is never unscoped.
No caller passes nil yet -- the dashboard handler switches over with the
rest of the cutover.
2026-09-09 23:29:11 +10:00
sam 694aaeb7cd style: apply gofumpt formatting 2026-09-09 10:08:51 +00:00
sam e3b1a859a8 feat(gateway): flip channel boundary onto messaging.Message
Replaced gateway.Message as the currency at the channel-facing boundary
with the canonical internal/domain/messaging.Message. Channel adapters
now build the record directly (RoleUser, ConversationID, Sender) and the
Router hands it back unchanged, so nothing converts between two shapes in
process. gateway.Message is deleted; the dashboard route that had no home
in the record lives in a new Inbound envelope (Message + transport-only
Page), which reaches the system prompt and is never persisted.

Role is now set at construction instead of derived at the store boundary,
and the assistant reply is a direct messaging.Message (RoleAssistant,
Sender=botUser). The gRPC proto is unchanged: pb.Message still carries no
role, and both sides keep deriving it from the owning session's bot
identity via gateway.RoleForSender (ToStoredMessage/FromStoredMessage are
deleted).

Adds tests that the old shape could not express: Page reaches the system
prompt but not the persisted record, and a channel-built Inbound round-trips
with the Role the channel set.

Refs: archie-core-9g5e
2026-09-09 01:05:36 +10:00
sam 4c9c7cac55 feat(gateway): authenticate the gRPC contract and allow off-loopback listeners
The Gateway had no transport boundary: RunGateway refused any non-loopback
listen address and serveGateway registered no interceptor, so archie-ui was
colocation-only while the State Store already had a token-authenticated
equivalent.

gatewayrpc gains a gateway-token metadata credential with constant-time
comparison and both unary and stream interceptors on each side. Stream
coverage is required here and not in staterpc: the Gateway's Stream RPC is
server-streaming. Dial fails closed on a non-loopback target with no token,
mirroring staterpc.Dial. gatewayServerOpts applies the same rule server-side:
loopback stays insecure, non-loopback requires a token, malformed errors.

The daemon resolves [services.gateway].target_token then GATEWAY_TOKEN;
archie-ui passes the token its config projection already carried, so a
distributed dashboard is now possible.

Closes: archie-core-juqx
2026-09-09 00:27:03 +10:00
sam a3e8718d19 feat(archieui): standalone UI process over remote Gateway and State Store
Add cmd/archie-ui and internal/app/archieui: a second composition root that
serves the dashboard and the compiled SPA against the two contracts the daemon
already dials, so the UI stops needing the daemon's in-process objects.

The composition root lives outside internal/app/archied deliberately. That
package pulls 88 internal packages (daemon, forge, containers, NATS, secrets,
workflow); reusing its boot the way RunGateway and RunStateStore do would make
the PRD's deletion gate unreachable. archieui links 41, and cmd/archie-ui 42.

Configuration ownership follows docs/prds/ui-service-boundary.md: the process
reads the shared file, but only [services.gateway].{target,target_token},
[services.state].{target,target_token} and [web].{listen,
trust_forwarded_headers}, with flags taking precedence. Options has no field
for anything else in that file to land in, and no config.Holder.

compose() sets only the contract-backed and process-local fields. Every daemon
runtime handle stays nil on purpose and its route degrades through the
existing 501/503/empty paths. Captures, CaptureLimiter and BindingDispatcher
are withheld for the duration of the seam: the daemon's dashboard still serves
POST /webhooks/capture/{source}, and two intakes are not permitted.

Readiness is the UI's own registry over its two dependencies via a new bounded
readiness.ContractProbe. The existing GatewayProbe was unusable here: with no
channel manager to inject it reports "no gateway channels configured", i.e.
permanently degraded.

The State Store's fail-closed non-loopback rule and the two dial paths move to
staterpc.Dial/TargetIsLoopback and gatewayrpc.Dial, so the server side and
every client share one implementation instead of three copies.

The Gateway remains loopback-only with no auth interceptor, so this process is
scoped to being colocated with it; filed as archie-core-juqx.

Refs: archie-core-8cda.5.2
2026-09-08 22:54:26 +10:00
sam 89d8dc0e7f feat(messaging): migrate gateway session persistence onto domain types
SessionStore message history now stores/loads domain/messaging.Message:
sender attribution, derived role, and conversation address are canonical
record fields. SQLite gains a role column with open-time backfill for
pre-migration databases. gateway.Message remains the channel-facing
transport; conversion lives in one boundary module. ChatContract,
gatewayrpc proto, and dashboard JSON are unchanged; the RPC client
splits into ChatContract (Client) and SessionStore (StoreClient) views.

Sessions stay SessionContext: UUID keys and platform/bot/title/branch
metadata have no lossless home in Conversation; keyed migration tracked
separately once Agent/user/binding ownership settles.

Refs: archie-core-d9dv
2026-09-08 21:28:19 +10:00
sam f5414a82a1 fix(state-store): task-scope container credentials, stream large capture lists, validate Update, wire dev's state-store (archie-core-8cda.4.7)
Closes six review findings against .4.6 (PR #775):

- daemon.StateStoreGrantIssuer + staterpc.TaskGrants: containers get a
  per-task credential authorized only for their own Update/Transition/
  InsertEvent, never the daemon's administrative token. Issued before
  Acquire, revoked on Release; fails closed if no issuer is wired.
- StreamCaptures/StreamUndispatchedCaptures: new streaming RPCs so a
  batch of large capture bodies can't exceed gRPC's 4MiB unary cap.
  The original unary RPCs are kept, unmodified (deprecated) rather than
  reshaped, so buf breaking stays green for an in-flight rolling deploy.
- Update rejects a nil Task with InvalidArgument instead of panicking in
  the store layer.
- RequireHostGateway only forces on for embedded NATS, so an externally
  reachable NATS/State Store no longer requires a local Docker bridge.
- Client-side token resolution now matches the server's (target_token,
  then STATE_STORE_TOKEN secret/env).
- task dev now runs archie-state-store (dev:state-store) alongside
  archied/archie-gateway/vite; deployments/dev.toml points them at it.
2026-09-07 13:18:44 +10:00
sam cead0e927d test(staterpc): verify State Store end-to-end and preserve context error identity (#775)
* test(state-store): real-process smoke + deadline/sentinel error contract

Add end-to-end verification for archie-core-8cda.4.7, the .4.7 State Store
verification stage against docs/prds/state-store-contract.md (rev. 2c):

- Real-process smoke coverage: build ./cmd/archie-state-store, run it against
  a minimal config on loopback, poll the readiness surface, and drive the
  State Store gRPC contract through staterpc.NewClient exactly as a consumer
  does. Covers the combined task/event/capture view, error-sentinel fidelity
  across the wire, the found=false-not-error convention, single-owner SQLite
  (the binary owns the one archie.db file; the consumer never opens a store
  file), per-call deadline behaviour, restart/recovery (SIGTERM + reopen on
  the same db), and the remote capture/mapping/binding surfaces.

- Fix a real deadline-identity gap in unmapError: a cancelled or
  deadline-exceeded context surfaced by gRPC-Go as a *status.Error was
  re-wrapped into a sanitised internal-style error, breaking
  errors.Is(err, context.Canceled/DeadlineExceeded). The agent's deadlineStore
  bounds each Store call with context.WithTimeout and the workflow consumer
  (workflow.go) uses errors.Is(err, context.DeadlineExceeded) to mark a stage
  interrupted rather than failed, so the re-wrap would wrongly park an
  interrupted task. Unmap Canceled/DeadlineExceeded codes back to the standard
  context sentinels.

- Pin the error-mapping contract in staterpc: context-identity preservation,
  sentinel round-trip fidelity for every store sentinel, and the sanitisation
  rule (an Internal error must not leak raw detail or map to a sentinel).

* test(state-store): assert single-owner SQLite composition (daemon/gateway require target)

The single-owner invariant (docs/prds/state-store-contract.md §12 step 7/8) is
that only archie-state-store opens archie.db; the daemon and gateway resolve
their task-store surface from openStateStoreAdapter, which requires
[services.state].target and opens no local store. This test pins that
composition root so a future change cannot silently reintroduce a local
*store.Store in the daemon or gateway path (dual-store ownership).

* test(state-store): skip real-process smoke tests under -short

The smoke tests build and exec the real archie-state-store binary, which is
slow enough that a -short run (e.g. a focused edit loop) should skip them.
task check (go test ./... -count=1) does not use -short, so they still run in
the full gate.

* test(state-store): fix subprocess log race under -race

The smoke test captured the subprocess's stdout/stderr in a strings.Builder
that the os/exec writer goroutine and the test reader goroutine touched
concurrently, racing under -race. Replace it with a mutex-guarded buffer, the
standard pattern for reading a running subprocess's output.

* test(state-store): satisfy lint (noctx, errorlint) on new tests

- exec.Command -> exec.CommandContext, http.Get -> NewRequestWithContext +
  Client.Do, so the subprocess and readiness polling honour the test context
  (noctx).
- errorlint: compare the raw non-status error via errors.Is rather than != on
  a wrapped error.

* docs(deployments): document State Store readiness verification and single-owner invariant

The deployment runbook described how to launch archie-state-store but not how
to verify it is healthy before starting archied. Document the -ready-addr
readiness surface (/healthz, /health/detailed state_db component) and the
single-owner invariant: one task SQLite file owned by archie-state-store, with
archied/archie-gateway never opening archie.db directly (state-store-contract
§12 step 7/8).

* fix(state-store): preserve context deadline/cancel identity in mapError

The symmetric server-side gap to the unmapError fix: if a store query fails
because the caller's context expires mid-call (§6 StoreTimeout), the handler's
mapError folded context.Canceled/DeadlineExceeded into codes.Internal. The
client would receive a sanitised internal error with no deadline identity, so
the agent's workflow consumer (errors.Is(err, context.DeadlineExceeded)) could
not distinguish an interrupted stage from a failed one.

Map a context cancel/deadline error to its matching gRPC code so unmapError
rehydrates it back to the standard context sentinel, completing the §6/§7
round-trip. Pin both directions with TestMapErrorPreservesContextIdentity.
2026-09-07 05:47:36 +10:00
sam 05529d48d5 refactor(state-store): cut daemon/Gateway over to the remote State Store (archie-core-8cda.4.6) (#774)
* refactor(state-store): delete NATS storerpc; agent store is gRPC-only (archie-core-8cda.4.6)

The agent is fully on the gRPC State Store contract, so the legacy NATS
storerpc path is dead (docs/prds/state-store-contract.md §12 step 4):
- delete internal/storerpc (Server, Client, subjects) and its tests
- drop the storerpc registration from registerTaskRPCServers and the
  now-unused store param
- make the agent transport's State Store URL required and Store() return
  only the gRPC staterpc.Client (no NATS fallback)
- rework agentworker/agent transport tests to back the store with a real
  gRPC State Store server instead of the deleted NATS storerpc server

The agent binary now fails fast when STATE_STORE_URL is absent. Agent store
calls (workflow.Store) go over gRPC to the archie-state-store service.

* refactor(state-store): delete daemon/gateway in-process store ownership (archie-core-8cda.4.6)

The daemon and gateway no longer open archie.db in-process: the single SQLite
file is owned by the standalone archie-state-store process, and both consumers
dial its gRPC State StateStore contract (docs/prds/state-store-contract.md
§12 step 7, no dual-store ownership).

- openStores no longer opens the production task store or seeds b.st; it only
  wires secrets/forge and the gateway conversation store
- openStateStoreAdapter now requires [services.state].target (the old local
  default is deleted) and resolves b.stateStore as the remote *staterpc.Client
- delete the in-process startStateStoreServer (the multiplexed gRPC server and
  its per-task bearer-token registry) from the daemon composition
- RunGateway now resolves the same remote State Store adapter; its session
  SQLite stays Gateway-owned and untouched
- daemon.ConnectedStateStore carries the configured target plus the resolved
  bearer token, which containerEnv injects as STATE_STORE_URL / STATE_STORE_TOKEN
  so archie-agent authenticates to the same remote service
- readiness store probe reads b.stateStore

PRD-consistent choice (noted): with the in-process server gone, per-task token
generation is removed; the daemon/gateway/agent all present the single
[services.state].target_token (or STATE_STORE_TOKEN secret) that the standalone
store validates.

* docs(webui): require [services.state].target in config and deployment templates (archie-core-8cda.4.6)

After the in-process store path is deleted, archied and archie-gateway dial the
standalone archie-state-store gRPC service via [services.state].target and never
open archie.db themselves (docs/prds/state-store-contract.md §12 step 7).

- config.example.toml documents [services.state].target as required, with the
  loopback vs Docker-bridge gateway + target_token rule
- deployment templates set [services.state] per topology: bridge gateway +
  token for container-mode agents, loopback for host-only
- deployments/README.md and systemd-user-service.md describe start commands
  for both topologies and drop the stale "not yet consumed by the daemon" note

* style: gofumpt alignment for State Store daemon literal; appease noctx/staticcheck (archie-core-8cda.4.6)

* docs(state-store): refresh stale in-process references post-cutover (archie-core-8cda.4.6)
2026-09-07 05:06:12 +10:00
sam 576e22b554 feat(state-store): generalize storerpc as the State Store gRPC contract (archie-core-8cda.4.2) (#770)
* feat(state-store): generalize storerpc as the State Store gRPC contract

Implements archie-core-8cda.4.2 against docs/prds/state-store-contract.md
rev. 2c: generate protobuf/gRPC client and server adapters for every
ratified store contract (proto/state/v1/state.proto, 40 RPCs, one
StateStoreService), add internal/infrastructure/staterpc with a bufconn
conformance suite exercising both local and remote adapters, serve the
service in-process (bridge address + mandatory per-task bearer token when
agent containers exist, loopback-only otherwise), and flip archie-agent's
workflow.Store to a long-lived gRPC client when the daemon injects
STATE_STORE_URL/STATE_STORE_TOKEN (falling back to the legacy NATS
storerpc path otherwise -- one agent process is never both).

Also drops the *sql.Tx parameter from store.BindingDispatcher.RecordDispatch
(a required wire-blocker fix: a transaction cannot cross a gRPC boundary,
and production always passed nil).

fix(store): drop RecordDispatch's unusable *sql.Tx parameter
feat(config): add services.state contract-adapter selector

* fix(state-store): apply no-mistakes review decisions

- Drop StreamTokenInterceptor (unused; the State Store service has no
  streaming RPCs and nothing calls it).
- Make StateStoreTokens.Validate compare tokens in constant time
  (crypto/subtle) per the auto-fix hardening.ing finding.
- Amend config.example.toml / config.Services.State doc text so it frames
  [services.state].target as the ratified surface consumed by the upcoming
  standalone archie-state-store binary (.4.3), not active today.
2026-09-07 03:01:33 +10:00
sam 5c0efaceaf refactor(workflow): relocate Task/Status/Source and define workflow.Store (#754)
* refactor(workflow,store): relocate Task/Status/Source and define workflow.Store

Move store.Task, store.Status*/store.Source*, and the 3-method workflow
store interface out of internal/store into internal/domain/workflow as
workflow.Task/workflow.Status/workflow.Source plus a consumer-owned
workflow.Store, superseding store.WorkflowStore. internal/domain/workflow
now imports zero internal/store symbols; internal/store persists the
domain type instead (infrastructure depends on domain), and its Store
satisfies workflow.Store.

Updates every production and test caller of the relocated symbols across
daemon, webui, gateway, agentworker, agenttransport/nats, storerpc,
taskrun, and worktreerpc, and removes TestRecordDispatchViaExplicitTx per
docs/prds/state-store-contract.md (rev. 2c) sections 4 and 12 step 2.

Two workflow-package integration tests that exercise the real *store.Store
move to an external workflow_test package (store_integration_test.go) to
avoid a workflow(test)->store->workflow(prod) import cycle now that store
depends on workflow.

* no-mistakes(document): docs(state-store): mark §4.8 relocation done in state-store-contract
2026-09-07 00:39:26 +10:00