Pure resolution logic combining a workspace's AgentSpec with the
user-level default_agent into a Resolved value carrying Command, Args,
and Env. No I/O — PATH lookup stays in shell.ExecAgent and ctask agents
check, so Resolve is trivially testable and reusable.
BuiltinProfiles enumerates claude and opencode; "custom" is the escape
hatch and requires command. Keep BuiltinProfiles in sync with
workspace.knownAgentTypes and workspace.IsBuiltinAgentType (Task 1).
Replace TaskMeta.Agent (string) with TaskMeta.Agent (AgentSpec) carrying
type/command/args/env. Custom UnmarshalYAML preserves the legacy scalar
form: a built-in name (claude, opencode) maps to that type; any other
scalar maps to type=custom with the scalar as command. A missing agent
field leaves Type empty so the resolver fills in default_agent at launch.
ValidateAgentSpec enforces: known type (claude|opencode|custom),
type=custom requires command, command must be an executable name or
path with no whitespace or shell metacharacters.
Launch-path wiring (Task 3) and the --agent flag rework (Task 4) are
intentionally not part of this commit; cmd/* call sites are patched to
the minimum needed for the build to compile.
Adds the two new metadata fields specified for Phase 1 of v0.6 plus
the validation and defaulting helpers around them.
internal/workspace/metadata.go:
- CurrentMetaSchemaVersion = 1 constant.
- WorkspaceSection struct {Mode string} with omitempty.
- SchemaVersion int and Workspace WorkspaceSection fields added to
TaskMeta at the top of the struct. Both are omitempty so legacy
task.yaml files (no schema_version, no workspace block) round-trip
without acquiring these keys when an unrelated field is updated.
- EffectiveSchemaVersion(meta) — returns 1 for stored-value-0 legacy
workspaces; non-zero stored values are returned verbatim.
- ValidateSchemaVersion(slug, meta) — rejects stored values higher
than CurrentMetaSchemaVersion with the spec-mandated upgrade
message. Accepts 0 (legacy missing).
- ValidateWorkspaceMode(slug, meta) — rejects modes other than ""
and "native". "adopted" is reserved for v0.7.
- ReadMeta now runs both validators after unmarshal. The validation
error includes the workspace slug (derived from task.yaml's slug
field, falling back to the directory basename when the file itself
is corrupt).
internal/workspace/create.go:
- workspace.Create stamps every new meta with
SchemaVersion: CurrentMetaSchemaVersion and Workspace.Mode: "native".
This is the ONLY write site for these fields in v0.6; resume,
archive, restore, and any other path that rewrites task.yaml MUST
NOT backfill them (the "no opportunistic schema writes" invariant).
internal/workspace/schema_test.go:
- 10 tests:
* new meta written by Create contains schema_version: 1 +
workspace.mode: native (both serialization and round-trip)
* legacy meta without these fields loads with stored value 0 / ""
and EffectiveSchemaVersion returns 1
* task.yaml with schema_version: 2 is rejected with upgrade message
* task.yaml with workspace.mode: adopted is rejected
* the no-opportunistic-writes invariant is pinned for both WriteMeta
and WriteMetaLocked: a legacy file rewritten with an updated
UpdatedAt does NOT acquire schema_version or workspace: keys
* ValidateSchemaVersion accepts {0, 1}; ValidateWorkspaceMode
accepts {"", "native"}
Phase 1 foundation. Adds:
- internal/config/configfile.go — strict-key YAML parser for the
global config file. Unknown top-level keys invalidate the entire
file (no partial apply); future schema versions are rejected with
an upgrade message. Platform-appropriate path (XDG_CONFIG_HOME or
~/.config on Unix, %APPDATA% on native Windows).
- internal/config/resolver.go — Resolver / ResolvedSetting /
SettingSource (Builtin, ConfigFileSrc, EnvVar, CLIFlag,
PlatformOverride). Each setting carries provenance plus an
Override chain so callers can render "env var (overrides config
file: X)" lines. session_mode applies the native-Windows
platform override at the resolver layer with the configured
value chained as Override. Exports SetConfigPathForTest and
SetIsNativeWindowsForTest so cross-package tests can isolate
themselves from host config or simulate the override.
- internal/config/config.go — legacy ResolveRoot / ResolveAgent /
ResolveSeedDir / ResolveProjectRoot / ResolveSessionMode now
delegate to LoadResolver so config-file values take effect for
entry commands. ResolveProjectRoot preserves the "" sentinel for
built-in source so SearchRoots and doctor checkProjectRoot keep
their existing fallback semantics. ResolveSessionMode preserves
the v0.5.3 unknown-value stderr warning, distinguishing env-var
and config-file sources in the message.
- Tests: 6 LoadConfigFile cases (missing, basic, partial, unknown
key, future schema, malformed YAML), 3 ConfigFilePath cases
(XDG / ~/.config / %APPDATA%), 11 resolver cases including
layering, override chains, path expansion, platform override,
and SettingSource string rendering.
- Test isolation: vulnerable tests in config_test.go and
config_roots_test.go that asserted Builtin-source defaults now
call SetConfigPathForTest to point at a nonexistent path,
insulating them from developer-host config files. Three cmd
tests that asserted persistent session_mode behavior now call
SetIsNativeWindowsForTest to disable the platform override
(Phase 1 introduces the override; the layering-only behavior
these tests cover is tested separately in resolver_test.go).
No new dependencies (gopkg.in/yaml.v3 was already in go.mod).
No version bump (lands at the end of Phase 3 per the v0.6 spec).
Add a Session block to ctask info output, surfacing the workspace
session lease state derived from SessionStatus. Inserted between Path
and any launch-dir fields so the new content is visually distinct
from both blocks.
Format: state on the header line, then indented Mode / Owner / Attach
/ Note rows aligned at column 14. The Owner line omits the hostname
when it matches the local machine. The Attach hint surfaces only for
active+persistent sessions and uses invocationName() so the suggested
command reflects the user's actual invocation. Malformed leases
render as stale with a single-line diagnostic and no Mode/Owner/Attach
rows so we never display fields parsed from a broken file.
Exposes session.CurrentHostname() so the cmd layer has a single
source of truth for the local-vs-remote hostname check.
Add internal/session.SessionStatus(wsDir) that derives a display-only
view of the workspace session lease. Pure read of .ctask/session.json
with no tmux invocation, no PID liveness, no lock acquisition, and no
mutation of lease state.
States: none | active | stale. Mode defaults to "direct" when a
pre-v0.5.3 lease lacks the field. Malformed leases surface as stale
with a diagnostic so the present-but-broken case stays visible
instead of being silently classified as none.
Reused for ctask info and ctask list in subsequent commits. Lifecycle
code continues to use the existing primitives (ReadLease, IsFresh,
InspectLease).
Three independent v0.5.3 polish items surfaced during manual WSL smoke testing,
bundled into one commit since they're all string/UX touches with no behavior change.
1. v0.4 lease-prompt tightening (`internal/session/{lease,run,run_preflight}.go`,
`cmd/entry.go`): when ctask is about to enter direct mode on a workspace that
already has a live tmux session, the "Continue anyway?" prompt now suggests
`ctask attach <slug>` as the reattach path. Threaded via
`PreflightOpts.ActiveLeaseHint` / `LaunchOpts.ActiveLeaseHint`; computed in
`cmd/entry.go::directModeTmuxHint` (best-effort: silent when no tmux on PATH
or no session for the workspace). Closes the footgun where a user forgot to
`export CTASK_SESSION_MODE=persistent` in a second terminal and hit the v0.4
coexistence prompt without realizing tmux passive-reattach was the intended
path.
2. Invocation-name in user-facing command hints (`cmd/invocation.go` new,
`cmd/{persistent,entry,resume,doctor}.go`): the binary name printed in
bypass / restore / "create one with" suggestions now reflects
`filepath.Base(os.Args[0])` instead of a hard-coded "ctask". Local-build
PowerShell users running `.\ctask.exe` see `ctask.exe new <ws> --direct`,
matching what they need to type. Installed contexts continue to see `ctask`.
Test seam (`invocationNameOverride`) pins the name to "ctask" in unit tests
so substring assertions stay stable across Go test binary names. Descriptive
prose ("ctask persistent mode requires...") and the ssh-remote hint
(`ssh -t <host> ctask <subcmd>`) intentionally keep the literal "ctask" —
they refer to the program identity / remote invocation, not the local
command form. Affected tests: `cmd/{persistent,resume}_test.go` tightened to
check the full `"<binary> <subcmd> <workspace> --direct"` form.
3. Smoke-checklist fixes (`docs/.../2026-05-08-v0.5.3-smoke-test-checklist.md`):
six issues caught during the run -- S2 now exports CTASK_SESSION_MODE in
both terminals (previously only WSL-A had it, which routed WSL-B's
secondary resume through direct mode instead of passive reattach); O3/A2
tmux-ls expectations corrected (tmux doesn't emit a literal "(detached)"
token); P2 expected behavior rewritten (passive reattach detach returns to
prompt immediately -- AttachExisting calls only shell.AttachSession with
no PollSessionEnd, the owner is responsible for finalize); A1 no longer
asks for Ctrl-C in WSL-B; A6 path now uses a glob (was hardcoded to the
checklist's authoring date, broke on v0.5.1 local-time directory naming);
M1 PATH-hide rewritten to `$HOME/.local/bin` only (was `:/bin` which is a
symlink to /usr/bin on usrmerge systems, did not hide tmux) and uses
`command -v` instead of `which` (which is itself in /usr/bin, unreachable
under the minimal PATH); M3/M4 reordered so the no-workspace verification
runs after PATH is restored (was silently failing under minimal PATH);
T1 wording made "substring match" explicit; T2 wording made N/A
unambiguous; section 10 split into 10a-10f, each a separate input, to
work around PSReadLine multi-line paste parsing.
Adds a concise "## Cross-Workspace Context" section to both the
task and project CLAUDE.md seed templates. Teaches the agent to
inspect related workspaces with the new commands before making
changes:
ctask list --all discover all workspaces, including archived
ctask info <workspace> view metadata and status of any workspace
ctask notes <workspace> read another workspace's notes.md
ctask path <workspace> get the filesystem path to inspect files
Closes the v0.5.2 design loop: ctask exposes workspace context
through CLI commands and lets agents consume it themselves. The
seed text is read-only by convention — the section explicitly
asks the agent to treat other workspaces as read-only unless the
user grants modification rights.
Applies to newly created workspaces only. Existing workspaces
keep their current CLAUDE.md (per spec: no retroactive overwrite).
Users with custom seed directories see this only if they update
their seeds.
- justfile: add build-linux, build-windows, build-all (output to dist/)
- .gitignore: cover ctask, ctask-*, dist/
- scripts/install.sh + scripts/uninstall.sh: POSIX equivalents of .ps1
- remove WorkspacePath metadata field (no production readers; legacy
task.yaml files continue to parse silently)
Linux smoke-test on WSL/container pending.
See audit-report.md and v0.5.1-spec.md.
Workspace directory names (YYYY-MM-DD_slug) and the YYYYMMDD-HHMMSS ID
field now use local time so users see their wall-clock date rather
than UTC — the prior behavior caused evening-EST creations to appear
under tomorrow's date for several hours every day. ctask info's
Created/Updated/Archived lines also convert to local for display.
Stored timestamps in task.yaml, session logs, the lease, the manifest,
and the session summary all continue to use UTC. Only user-facing
surfaces change.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Rewrites the built-in project CLAUDE.md template with a new Workspace
Structure section that explains the root-vs-subdir split. File
Placement rules refer to the subdirectory. Git section keeps the
single-repo rule and explicitly names the project subdirectory as an
example of where not to init.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
When CTASK_PROJECT_ROOT is unset, SearchRoots now appends
\$CTASK_ROOT/projects/ so that projects created under the default
category are discoverable from any shell without per-session env var
setup. Dedupe in scanAllRoots prevents double-counting workspaces that
are reachable both via the depth-2 scan under CTASK_ROOT and via the
new explicit search root. Adds a named regression test asserting no
duplicates appear in either ResolveQuery or ListWorkspaces results.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
LaunchOpts gains LaunchDir. session.Run resolves it via
workspace.ResolveLaunch, prints any fallback warning, and passes the
absolute path as the child process's working directory. Security
violations (absolute paths, .. escape) abort the session. The banner
gains a 'project dir: <name>/' line when launch_dir is set.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
config.EnvVars gains a 7th launchDir argument. cmd/new, cmd/resume, and
cmd/open pass ws.Meta.LaunchDir. Child sessions can read CTASK_LAUNCH_DIR
to know which subdirectory ctask launched them into.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ctask new --project now creates an empty subdirectory named after the
final suffixed slug inside the workspace root, and sets meta.LaunchDir
to that slug. Task workspaces are unchanged. Seeds do not target the
subdirectory — the user populates it with their project code and their
own CLAUDE.md.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Resolves a relative launch_dir into the absolute directory the child
process should cd into. Returns an error for absolute paths and paths
that escape the workspace via .. traversal. Returns (wsDir, warning, nil)
on os.IsNotExist or target-is-a-file so the caller prints a warning and
falls back. Non-IsNotExist stat errors (permission, invalid name, I/O)
propagate as real errors rather than being masked as warnings.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adds a child-exit-code guard to handleProvisional so a `ctask new`
workspace is reclaimed only when the agent was actually canceled
before real work (trust prompt rejected, Esc during startup, Ctrl+C
mid-launch — all confirmed empirically as exit code 1). A zero exit
means the user entered the agent and exited cleanly, which is a
legitimate workflow that must preserve the workspace even with an
empty manifest diff — for example when the user wants the workspace
directory established so they can populate context/ before resuming.
The exit code reaches handleProvisional via a new childExitCode
helper that unwraps *exec.ExitError from cmd.Run's return. Non-exit
errors (agent not found, OS-level failure) map to -1 so the
workspace is still cleaned up — the child never actually ran.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Project CLAUDE.md template now includes a Git section stating that the
workspace uses a single git repo at the root and subdirectory git init
is not permitted. docs/commands.md picks up the same guidance under the
--project flag section.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Rewrites scanWorkspaces to handle both category layout
(root/<category>/<workspace>/task.yaml) and flat layout
(root/<workspace>/task.yaml used under CTASK_PROJECT_ROOT).
Adds scanAllRoots to walk multiple roots with absolute-path dedupe.
ResolveQuery, ListWorkspaces, and MostRecentActive now accept []string.
QueryResult gains a Root field so callers can render display paths and
session env vars relative to the originating root.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
When `ctask new` launched the agent or shell and the child exited without
touching any files (e.g. the user canceled at Claude Code's trust prompt),
the workspace was left behind as empty clutter. Now, if the invocation
just created the workspace and the manifest diff is empty (zero added,
modified, deleted), the workspace directory is removed and finalize is
skipped. resume/open/last are unaffected (NewlyCreated defaults to false),
and --no-launch is unaffected (session.Run is never called).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Extracts the cross-type "most recently updated active workspace"
selector that previously lived inline in cmd/last and cmd/delete.
The helper takes only a root path and returns (nil, nil) when
nothing matches, which keeps the call sites trivial.
Eight focused tests cover:
- tasks-only fixture
- projects-only fixture
- project most-recent vs older task
- task most-recent vs older project
- legacy v0.2 workspace (no Type field) winning, treated as task
- newest workspace archived, older active project wins
- empty root returns (nil, nil)
- all archived returns (nil, nil)
A new createTestWorkspaceFull helper takes an explicit UpdatedAt
timestamp so the "which is newest" assertions don't depend on
wall-clock ordering.
cmd/last and cmd/delete are migrated onto the helper in the next
commit.
ListOpts now exposes a Type string field (TypeAny / TypeTask /
TypeProject). TypeAny is the new way to express "both tasks and
projects" in a single ListWorkspaces call -- which the next two
commits will use to consolidate cmd/last and cmd/delete onto a
single helper, and to make 'ctask list' default to showing both
types.
Invalid Type values now return an explicit error from
ListWorkspaces (defensive against typos in callers).
cmd/list, cmd/last, and cmd/delete are migrated to the new field.
External behavior is unchanged in this commit; the cleanup of
ctask list semantics happens in a follow-up commit so the diff
stays reviewable.
ListOpts gains a Projects bool that filters by EffectiveType.
Default behavior (Projects: false) now returns tasks only --
this is a deliberate semantic change that supports the new
'ctask list' (tasks) vs 'ctask list --projects' (projects)
spec.
The change silently regresses two cmd-level callers that scan
for "the most recently updated workspace": cmd/last.go (used by
'ctask last') and cmd/delete.go (used to print the "this was
your most recent workspace" note). Both are fixed by unioning a
tasks-scan with a projects-scan, so 'last' and 'delete' continue
to consider both types.
Test helper createTestWorkspaceTyped allows setting an explicit
type (or "" to simulate a v0.2 workspace with no type field).