agent-trellis 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/adapters/claude-code.js +4 -3
  2. package/dist/adapters/codex.js +4 -3
  3. package/dist/adapters/kimi-code.js +4 -3
  4. package/dist/adapters/kiro.js +5 -4
  5. package/dist/adapters/pi.js +4 -3
  6. package/dist/adapters/piMcp.d.ts +6 -3
  7. package/dist/adapters/piMcp.js +10 -3
  8. package/dist/adapters/zcode.d.ts +12 -1
  9. package/dist/adapters/zcode.js +7 -6
  10. package/dist/cli.js +38 -5
  11. package/dist/commands/doctor.d.ts +9 -1
  12. package/dist/commands/doctor.js +43 -6
  13. package/dist/commands/init.d.ts +6 -0
  14. package/dist/commands/init.js +24 -0
  15. package/dist/commands/mcp.d.ts +44 -1
  16. package/dist/commands/mcp.js +145 -33
  17. package/dist/commands/migrate.d.ts +12 -0
  18. package/dist/commands/migrate.js +8 -4
  19. package/dist/commands/migrateWorkspace.d.ts +40 -0
  20. package/dist/commands/migrateWorkspace.js +197 -0
  21. package/dist/commands/rollback.js +65 -35
  22. package/dist/commands/skill.d.ts +14 -0
  23. package/dist/commands/skill.js +71 -0
  24. package/dist/commands/sync.d.ts +16 -1
  25. package/dist/commands/sync.js +48 -15
  26. package/dist/core/adapter.d.ts +14 -0
  27. package/dist/core/canonical.d.ts +20 -32
  28. package/dist/core/canonical.js +18 -86
  29. package/dist/core/mcpServerDef.d.ts +39 -0
  30. package/dist/core/mcpServerDef.js +93 -0
  31. package/dist/core/types.d.ts +43 -4
  32. package/dist/lib/mcpMigrateRead.d.ts +25 -0
  33. package/dist/lib/mcpMigrateRead.js +9 -2
  34. package/dist/lib/skillProvider.js +18 -5
  35. package/dist/lib/workspace.d.ts +39 -0
  36. package/dist/lib/workspace.js +158 -0
  37. package/dist/lib/workspaceConfig.d.ts +45 -0
  38. package/dist/lib/workspaceConfig.js +98 -0
  39. package/dist/lib/workspaceDoctor.d.ts +44 -0
  40. package/dist/lib/workspaceDoctor.js +94 -0
  41. package/dist/lib/workspaceFiles.d.ts +38 -0
  42. package/dist/lib/workspaceFiles.js +264 -0
  43. package/dist/lib/workspaceMcp.d.ts +57 -0
  44. package/dist/lib/workspaceMcp.js +277 -0
  45. package/dist/lib/workspaceMerge.d.ts +37 -0
  46. package/dist/lib/workspaceMerge.js +98 -0
  47. package/dist/lib/workspaceMigrate.d.ts +118 -0
  48. package/dist/lib/workspaceMigrate.js +423 -0
  49. package/dist/pi-bridge/bundle.js +262 -96
  50. package/docs/architecture.md +111 -49
  51. package/docs/getting-started.md +102 -14
  52. package/docs/mcp-oauth-matrix.md +12 -1
  53. package/docs/overview.zh-CN.md +17 -0
  54. package/docs/research.md +28 -6
  55. package/docs/roadmap.md +17 -5
  56. package/package.json +1 -1
  57. package/docs/implementation-plan.md +0 -341
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Workspace (project-level) canonical layer: discovery of the nearest
3
+ * `.agents/` directory and loading of its `config.json` / `AGENTS.md` /
4
+ * `skills/` into a `WorkspaceLayer` (openspec trellis-workspace-scope,
5
+ * design D1/D2). The shape follows the `.agents` Protocol draft's
6
+ * two-layer model; skills under `.agents/skills/` are additionally read
7
+ * natively by Codex, pi, and Kimi Code, so the canonical directory is
8
+ * itself the deliverable for those agents.
9
+ */
10
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
11
+ import { homedir } from "node:os";
12
+ import { dirname, join, resolve } from "node:path";
13
+ import { oauthClientMetadata } from "../core/types.js";
14
+ import { fromServerDefYaml } from "../core/mcpServerDef.js";
15
+ export const WORKSPACE_DIR_NAME = ".agents";
16
+ /** The only `config.json` schema version this implementation understands. */
17
+ export const WORKSPACE_CONFIG_VERSION = 1;
18
+ const CONFIG_SOURCE_LABEL = ".agents/config.json";
19
+ /**
20
+ * Walk ancestors of `startDir` upward; the first directory containing a
21
+ * `.agents/` directory is the workspace root. The user's home directory
22
+ * itself is never a workspace root (a `~/.agents/` global convention, if
23
+ * one ever exists, is a separate decision), and reaching the filesystem
24
+ * root yields `null` — pure global-only behavior.
25
+ */
26
+ export function findWorkspaceRoot(startDir) {
27
+ const home = resolve(homedir());
28
+ let dir = resolve(startDir);
29
+ while (true) {
30
+ if (dir === home)
31
+ return null;
32
+ const candidate = join(dir, WORKSPACE_DIR_NAME);
33
+ try {
34
+ if (statSync(candidate).isDirectory())
35
+ return dir;
36
+ }
37
+ catch {
38
+ // not present or unreadable — keep walking
39
+ }
40
+ const parent = dirname(dir);
41
+ if (parent === dir)
42
+ return null;
43
+ dir = parent;
44
+ }
45
+ }
46
+ function isTombstone(def) {
47
+ return def.enabled === false && def.transport === undefined;
48
+ }
49
+ /** Load `<workspaceDir>/.agents/` into a `WorkspaceLayer`. Every file is
50
+ * optional; a present-but-invalid `config.json` is a hard error (never a
51
+ * silent misread), with the secrets boundary enforced against `policy`. */
52
+ export function loadWorkspaceLayer(workspaceDir, policy) {
53
+ const layerRoot = join(workspaceDir, WORKSPACE_DIR_NAME);
54
+ const diagnostics = [];
55
+ const layer = { root: workspaceDir, servers: {}, tombstones: [], skills: [], diagnostics };
56
+ const configPath = join(layerRoot, "config.json");
57
+ if (existsSync(configPath)) {
58
+ let parsed;
59
+ try {
60
+ parsed = JSON.parse(readFileSync(configPath, "utf-8"));
61
+ }
62
+ catch (err) {
63
+ throw new Error(`${CONFIG_SOURCE_LABEL}: invalid JSON — ${err.message}`);
64
+ }
65
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
66
+ throw new Error(`${CONFIG_SOURCE_LABEL}: top level must be an object { "version", "mcp" }`);
67
+ }
68
+ const { version, mcp, ...extra } = parsed;
69
+ const configVersion = version === undefined ? WORKSPACE_CONFIG_VERSION : version;
70
+ if (typeof configVersion !== "number" || !Number.isInteger(configVersion) || configVersion < 1) {
71
+ throw new Error(`${CONFIG_SOURCE_LABEL}: "version" must be a positive integer, got ${JSON.stringify(version)}`);
72
+ }
73
+ if (configVersion > WORKSPACE_CONFIG_VERSION) {
74
+ throw new Error(`${CONFIG_SOURCE_LABEL}: schema version ${configVersion} is newer than this Trellis understands (${WORKSPACE_CONFIG_VERSION}) — upgrade Trellis`);
75
+ }
76
+ for (const key of Object.keys(extra)) {
77
+ diagnostics.push(`${CONFIG_SOURCE_LABEL}: unrecognized top-level key "${key}" — ignored`);
78
+ }
79
+ if (mcp !== undefined) {
80
+ if (typeof mcp !== "object" || mcp === null || typeof mcp.servers !== "object" || mcp.servers === null || Array.isArray(mcp.servers)) {
81
+ throw new Error(`${CONFIG_SOURCE_LABEL}: "mcp.servers" must be an object mapping server names to definitions`);
82
+ }
83
+ for (const [name, rawDef] of Object.entries(mcp.servers)) {
84
+ if (typeof rawDef !== "object" || rawDef === null) {
85
+ throw new Error(`${CONFIG_SOURCE_LABEL}: "${name}" must be a server definition object or { "enabled": false }`);
86
+ }
87
+ if (isTombstone(rawDef)) {
88
+ layer.tombstones.push(name);
89
+ continue;
90
+ }
91
+ // enabled:false WITH a transport is tombstone semantics too — it
92
+ // disables the same-ID global entry and renders nothing.
93
+ if (rawDef.enabled === false) {
94
+ layer.tombstones.push(name);
95
+ continue;
96
+ }
97
+ layer.servers[name] = fromServerDefYaml(name, rawDef, CONFIG_SOURCE_LABEL);
98
+ }
99
+ }
100
+ }
101
+ const instructionsPath = join(layerRoot, "AGENTS.md");
102
+ if (existsSync(instructionsPath)) {
103
+ layer.instructionsFile = instructionsPath;
104
+ }
105
+ const skillsRoot = join(layerRoot, "skills");
106
+ let skillEntries = [];
107
+ try {
108
+ skillEntries = readdirSync(skillsRoot);
109
+ }
110
+ catch {
111
+ // no skills/ — optional, same as every other layer file
112
+ }
113
+ for (const name of skillEntries) {
114
+ const dir = join(skillsRoot, name);
115
+ try {
116
+ if (statSync(dir).isDirectory())
117
+ layer.skills.push({ name, dir });
118
+ }
119
+ catch {
120
+ // unreadable/broken entry — skip, not a load failure
121
+ }
122
+ }
123
+ assertWorkspaceSecretsClean(layer.servers, policy);
124
+ return layer;
125
+ }
126
+ /** An exact `${NAME}` value is a reference to the global secret store, not
127
+ * a literal — the only credential-shaped content allowed in a committable
128
+ * project layer (same classification as mcpMigrateRead.ts). */
129
+ const VAR_REF_RE = /^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/;
130
+ /**
131
+ * Load-time secrets boundary for the project layer (workspace-scope spec
132
+ * "Secrets stay global-only"): scans the fields a pasted secret could
133
+ * reach — `env` entries, `staticEnv` values, `headers` values, and OAuth
134
+ * client metadata — and refuses the load, naming the server and field but
135
+ * never echoing the value.
136
+ */
137
+ function assertWorkspaceSecretsClean(servers, policy) {
138
+ const check = (server, field, value) => {
139
+ if (value === undefined || VAR_REF_RE.test(value))
140
+ return;
141
+ for (const pattern of policy.rejectPatterns) {
142
+ if (pattern.test(value)) {
143
+ throw new Error(`${CONFIG_SOURCE_LABEL}: "${server}" ${field} matches a secrets.policy.yaml reject pattern — the project layer is committable and must carry only \${VAR} references; move the value to the global secret store (the offending value is intentionally not printed)`);
144
+ }
145
+ }
146
+ };
147
+ for (const [name, def] of Object.entries(servers)) {
148
+ for (const entry of def.env ?? [])
149
+ check(name, "env", entry);
150
+ for (const [key, value] of Object.entries(def.staticEnv ?? {}))
151
+ check(name, `static_env.${key}`, value);
152
+ for (const [key, value] of Object.entries(def.headers ?? {}))
153
+ check(name, `headers.${key}`, value);
154
+ const meta = oauthClientMetadata(def.auth);
155
+ check(name, "auth.client_id", meta.clientId);
156
+ check(name, "auth.client_secret_env", meta.clientSecretEnv);
157
+ }
158
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Write-side helpers for the workspace layer (trellis-workspace-scope
3
+ * tasks 3.3/3.4): scaffolding `.agents/` (`init --workspace`) and
4
+ * upserting a server into `.agents/config.json` (`mcp add --workspace`).
5
+ *
6
+ * The read side lives in src/lib/workspace.ts (`loadWorkspaceLayer`) —
7
+ * same file, same schema, one validator (via `toServerDefYaml`, so a
8
+ * `McpServerDef` serializes to the exact snake_case shape the loader
9
+ * validates back). Everything written here is committable by design:
10
+ * only `${VAR}` references ever land in `config.json`, never values
11
+ * (the loader refuses literals at read time; these helpers never
12
+ * resolve anything in the first place).
13
+ */
14
+ import type { McpServerDef } from "../core/types.js";
15
+ import { type McpServerDefYaml } from "../core/mcpServerDef.js";
16
+ import type { BackupSession } from "./backup.js";
17
+ export interface WorkspaceConfigJson {
18
+ version?: number;
19
+ mcp?: {
20
+ servers?: Record<string, McpServerDefYaml>;
21
+ };
22
+ [key: string]: unknown;
23
+ }
24
+ export declare function workspaceConfigPath(workspaceRoot: string): string;
25
+ /** `{}` when the file doesn't exist yet (a workspace may carry only
26
+ * skills/AGENTS.md); a clear error naming the file when it exists but
27
+ * doesn't parse — never a raw JSON stack. */
28
+ export declare function readWorkspaceConfigJson(workspaceRoot: string): WorkspaceConfigJson;
29
+ export declare function writeWorkspaceConfigJson(workspaceRoot: string, config: WorkspaceConfigJson, backup?: BackupSession): void;
30
+ /** Insert or replace `mcp.servers.<name>` with the def serialized through
31
+ * the shared YAML/JSON translator. `version` is filled in when absent —
32
+ * an existing file's version (and any unknown keys) is preserved. */
33
+ export declare function upsertWorkspaceServer(workspaceRoot: string, name: string, def: McpServerDef, backup?: BackupSession): void;
34
+ export interface WorkspaceScaffoldFile {
35
+ path: string;
36
+ action: "create" | "already-present";
37
+ }
38
+ /** Exported for `migrate --workspace`: a `.agents/AGENTS.md` holding
39
+ * exactly this template is treated as still-empty scaffolding that an
40
+ * instructions import may replace, not as user content to conflict on. */
41
+ export declare const WORKSPACE_AGENTS_MD_TEMPLATE = "# Project instructions\n\nShared instructions for every agent working in this repository. Trellis\ndelivers this file to agents that don't read `.agents/AGENTS.md`\nnatively (Codex/pi/Kimi do; Kiro gets a steering copy; Claude Code keeps\nits own CLAUDE.md).\n";
42
+ /** Fill-missing-only scaffold of `.agents/`: never overwrites anything
43
+ * that already exists, so re-running is a no-op (idempotent by
44
+ * construction, same posture as global `trellis init`). */
45
+ export declare function scaffoldWorkspace(workspaceRoot: string, write?: boolean): WorkspaceScaffoldFile[];
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Write-side helpers for the workspace layer (trellis-workspace-scope
3
+ * tasks 3.3/3.4): scaffolding `.agents/` (`init --workspace`) and
4
+ * upserting a server into `.agents/config.json` (`mcp add --workspace`).
5
+ *
6
+ * The read side lives in src/lib/workspace.ts (`loadWorkspaceLayer`) —
7
+ * same file, same schema, one validator (via `toServerDefYaml`, so a
8
+ * `McpServerDef` serializes to the exact snake_case shape the loader
9
+ * validates back). Everything written here is committable by design:
10
+ * only `${VAR}` references ever land in `config.json`, never values
11
+ * (the loader refuses literals at read time; these helpers never
12
+ * resolve anything in the first place).
13
+ */
14
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
15
+ import { dirname, join } from "node:path";
16
+ import { toServerDefYaml } from "../core/mcpServerDef.js";
17
+ import { WORKSPACE_CONFIG_VERSION, WORKSPACE_DIR_NAME } from "./workspace.js";
18
+ export function workspaceConfigPath(workspaceRoot) {
19
+ return join(workspaceRoot, WORKSPACE_DIR_NAME, "config.json");
20
+ }
21
+ /** `{}` when the file doesn't exist yet (a workspace may carry only
22
+ * skills/AGENTS.md); a clear error naming the file when it exists but
23
+ * doesn't parse — never a raw JSON stack. */
24
+ export function readWorkspaceConfigJson(workspaceRoot) {
25
+ const path = workspaceConfigPath(workspaceRoot);
26
+ if (!existsSync(path))
27
+ return {};
28
+ try {
29
+ const parsed = JSON.parse(readFileSync(path, "utf-8"));
30
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
31
+ throw new Error("top level must be an object");
32
+ }
33
+ return parsed;
34
+ }
35
+ catch (err) {
36
+ throw new Error(`${path} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`);
37
+ }
38
+ }
39
+ export function writeWorkspaceConfigJson(workspaceRoot, config, backup) {
40
+ const path = workspaceConfigPath(workspaceRoot);
41
+ mkdirSync(dirname(path), { recursive: true });
42
+ const content = `${JSON.stringify(config, null, 2)}\n`;
43
+ if (backup) {
44
+ backup.writeFile(path, content);
45
+ return;
46
+ }
47
+ writeFileSync(path, content);
48
+ }
49
+ /** Insert or replace `mcp.servers.<name>` with the def serialized through
50
+ * the shared YAML/JSON translator. `version` is filled in when absent —
51
+ * an existing file's version (and any unknown keys) is preserved. */
52
+ export function upsertWorkspaceServer(workspaceRoot, name, def, backup) {
53
+ const config = readWorkspaceConfigJson(workspaceRoot);
54
+ const servers = { ...(config.mcp?.servers ?? {}), [name]: toServerDefYaml(def) };
55
+ const next = {
56
+ ...config,
57
+ version: config.version ?? WORKSPACE_CONFIG_VERSION,
58
+ mcp: { ...(config.mcp ?? {}), servers },
59
+ };
60
+ writeWorkspaceConfigJson(workspaceRoot, next, backup);
61
+ }
62
+ /** Exported for `migrate --workspace`: a `.agents/AGENTS.md` holding
63
+ * exactly this template is treated as still-empty scaffolding that an
64
+ * instructions import may replace, not as user content to conflict on. */
65
+ export const WORKSPACE_AGENTS_MD_TEMPLATE = `# Project instructions
66
+
67
+ Shared instructions for every agent working in this repository. Trellis
68
+ delivers this file to agents that don't read \`.agents/AGENTS.md\`
69
+ natively (Codex/pi/Kimi do; Kiro gets a steering copy; Claude Code keeps
70
+ its own CLAUDE.md).
71
+ `;
72
+ /** Fill-missing-only scaffold of `.agents/`: never overwrites anything
73
+ * that already exists, so re-running is a no-op (idempotent by
74
+ * construction, same posture as global `trellis init`). */
75
+ export function scaffoldWorkspace(workspaceRoot, write = true) {
76
+ const agentsDir = join(workspaceRoot, WORKSPACE_DIR_NAME);
77
+ const configPath = workspaceConfigPath(workspaceRoot);
78
+ const skillsDir = join(agentsDir, "skills");
79
+ const agentsMdPath = join(agentsDir, "AGENTS.md");
80
+ if (write) {
81
+ mkdirSync(agentsDir, { recursive: true });
82
+ mkdirSync(skillsDir, { recursive: true });
83
+ }
84
+ const files = [];
85
+ files.push(existsSync(configPath)
86
+ ? { path: configPath, action: "already-present" }
87
+ : { path: configPath, action: "create" });
88
+ if (!existsSync(configPath) && write) {
89
+ writeFileSync(configPath, `${JSON.stringify({ version: WORKSPACE_CONFIG_VERSION, mcp: { servers: {} } }, null, 2)}\n`);
90
+ }
91
+ files.push(existsSync(agentsMdPath)
92
+ ? { path: agentsMdPath, action: "already-present" }
93
+ : { path: agentsMdPath, action: "create" });
94
+ if (!existsSync(agentsMdPath) && write) {
95
+ writeFileSync(agentsMdPath, WORKSPACE_AGENTS_MD_TEMPLATE);
96
+ }
97
+ return files;
98
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Workspace attribution for `trellis doctor` (trellis-workspace-scope
3
+ * task 3.5): given the workspace-merged canonical source, reports which
4
+ * layer each MCP server / skill comes from, what the workspace shadowed
5
+ * or tombstoned, which `${VAR}` references in workspace server defs
6
+ * don't resolve under the current secrets policy, which project-level
7
+ * native config files hold entries Trellis never rendered (the
8
+ * `migrate --workspace` hint), and zcode's reverse-precedence deviation
9
+ * (task 2.5's doctor half). Read-only by construction — it computes
10
+ * from the already-loaded canonical source and file reads only.
11
+ */
12
+ import type { AgentId, CanonicalSource, LayerProvenance } from "../core/types.js";
13
+ export interface WorkspaceLayerEntry {
14
+ name: string;
15
+ layer: LayerProvenance;
16
+ }
17
+ export interface WorkspaceUnmigratedHint {
18
+ agent: AgentId;
19
+ path: string;
20
+ /** Entry names present in the file with no Trellis manifest record. */
21
+ entries: string[];
22
+ }
23
+ export interface WorkspaceDoctorSection {
24
+ root: string;
25
+ mcp: WorkspaceLayerEntry[];
26
+ skills: WorkspaceLayerEntry[];
27
+ /** `mcp:name` / `skill:name` entries the workspace layer overrode. */
28
+ shadowed: string[];
29
+ /** `mcp:name` entries the workspace layer tombstoned (global entry
30
+ * disabled for this project). Subset of `shadowed`. */
31
+ tombstoned: string[];
32
+ /** `${VAR}` references in workspace server defs that resolve to
33
+ * nothing under the current secrets policy. Names only — never
34
+ * values. */
35
+ unresolvedVars: {
36
+ server: string;
37
+ field: string;
38
+ name: string;
39
+ }[];
40
+ unmigrated: WorkspaceUnmigratedHint[];
41
+ /** zcode's user-level-first deviation notices (empty otherwise). */
42
+ precedenceWarnings: string[];
43
+ }
44
+ export declare function collectWorkspaceDoctorSection(canonical: CanonicalSource): WorkspaceDoctorSection | undefined;
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Workspace attribution for `trellis doctor` (trellis-workspace-scope
3
+ * task 3.5): given the workspace-merged canonical source, reports which
4
+ * layer each MCP server / skill comes from, what the workspace shadowed
5
+ * or tombstoned, which `${VAR}` references in workspace server defs
6
+ * don't resolve under the current secrets policy, which project-level
7
+ * native config files hold entries Trellis never rendered (the
8
+ * `migrate --workspace` hint), and zcode's reverse-precedence deviation
9
+ * (task 2.5's doctor half). Read-only by construction — it computes
10
+ * from the already-loaded canonical source and file reads only.
11
+ */
12
+ import { existsSync, readFileSync } from "node:fs";
13
+ import { resolveSecretEnv } from "./secretEnv.js";
14
+ import { loadWorkspaceRendered, workspaceMcpConfigPath, workspacePrecedenceWarnings } from "./workspaceMcp.js";
15
+ const VAR_REF_RE = /^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/;
16
+ function collectVarRefs(canonical) {
17
+ const provenance = canonical.workspace?.mcpProvenance ?? {};
18
+ const refs = [];
19
+ for (const [name, def] of Object.entries(canonical.mcp.servers)) {
20
+ if (provenance[name] !== "workspace")
21
+ continue;
22
+ for (const envName of def.env ?? []) {
23
+ refs.push({ server: name, field: "env", name: envName });
24
+ }
25
+ for (const [key, value] of Object.entries(def.staticEnv ?? {})) {
26
+ const match = VAR_REF_RE.exec(value);
27
+ if (match)
28
+ refs.push({ server: name, field: `static_env.${key}`, name: match[1] });
29
+ }
30
+ for (const [key, value] of Object.entries(def.headers ?? {})) {
31
+ const match = VAR_REF_RE.exec(value);
32
+ if (match)
33
+ refs.push({ server: name, field: `headers.${key}`, name: match[1] });
34
+ }
35
+ }
36
+ return refs;
37
+ }
38
+ /** Entry names a JSON `mcpServers` file / Codex TOML / zcode nested
39
+ * config holds beyond what the in-repo manifest records Trellis
40
+ * rendering. Regex-parses Codex TOML section headers — doctor only
41
+ * needs names for a hint, not a full TOML AST. */
42
+ function unmarkedEntries(agentId, configPath, recorded) {
43
+ if (!existsSync(configPath))
44
+ return [];
45
+ let names = [];
46
+ if (agentId === "codex") {
47
+ const content = readFileSync(configPath, "utf-8");
48
+ const re = /^\[mcp_servers\.([^\]]+)\]\s*$/gm;
49
+ let match;
50
+ while ((match = re.exec(content)) !== null)
51
+ names.push(match[1]);
52
+ }
53
+ else {
54
+ try {
55
+ const parsed = JSON.parse(readFileSync(configPath, "utf-8"));
56
+ const servers = agentId === "zcode"
57
+ ? (parsed.mcp?.servers ?? {})
58
+ : (parsed.mcpServers ?? {});
59
+ names = Object.keys(servers);
60
+ }
61
+ catch {
62
+ return []; // unparsable file is the sync guard's finding, not doctor's
63
+ }
64
+ }
65
+ return names.filter((name) => recorded[name] === undefined);
66
+ }
67
+ export function collectWorkspaceDoctorSection(canonical) {
68
+ const workspace = canonical.workspace;
69
+ if (!workspace)
70
+ return undefined;
71
+ const mcp = Object.keys(canonical.mcp.servers)
72
+ .map((name) => ({ name, layer: workspace.mcpProvenance[name] ?? "global" }))
73
+ .sort((a, b) => a.name.localeCompare(b.name));
74
+ const skills = canonical.skills
75
+ .map((s) => ({ name: s.name, layer: workspace.skillProvenance[s.name] ?? "global" }))
76
+ .sort((a, b) => a.name.localeCompare(b.name));
77
+ // A shadowed mcp entry that no longer exists in the merged source was
78
+ // tombstoned; one still present (with workspace provenance) was
79
+ // overridden.
80
+ const tombstoned = workspace.shadowed.filter((entry) => entry.startsWith("mcp:") && canonical.mcp.servers[entry.slice(4)] === undefined);
81
+ const refs = collectVarRefs(canonical);
82
+ const resolved = resolveSecretEnv([...new Set(refs.map((r) => r.name))], canonical.secretsPolicy);
83
+ const unresolvedVars = refs.filter((r) => resolved[r.name] === undefined);
84
+ const manifest = loadWorkspaceRendered(workspace.root);
85
+ const unmigrated = [];
86
+ for (const agentId of canonical.managedAgents) {
87
+ const configPath = workspaceMcpConfigPath(agentId, workspace.root);
88
+ const entries = unmarkedEntries(agentId, configPath, manifest.mcp?.[agentId] ?? {});
89
+ if (entries.length > 0)
90
+ unmigrated.push({ agent: agentId, path: configPath, entries });
91
+ }
92
+ const precedenceWarnings = canonical.managedAgents.flatMap((id) => workspacePrecedenceWarnings(id, canonical));
93
+ return { root: workspace.root, mcp, skills, shadowed: workspace.shadowed, tombstoned, unresolvedVars, unmigrated, precedenceWarnings };
94
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Workspace (project-level) skills & instructions delivery
3
+ * (trellis-workspace-scope design D4/D5). Unlike global delivery (symlinks
4
+ * into `~/.trellis/`), workspace skills are COPIED into the agent's
5
+ * project-level directory — rendered artifacts must be committable to the
6
+ * repo and usable on filesystems without symlink support.
7
+ *
8
+ * A copy has no symlink-realpath ownership proof, so ownership mirrors the
9
+ * MCP ledger instead: one `.trellis-workspace.json` per destination root
10
+ * maps skill name → { source, sourceDigest, destDigest }. A delivered
11
+ * directory is "ours" only while its current digest still equals the
12
+ * recorded `destDigest`; a hand-edited copy is a conflict, never touched —
13
+ * the same posture mcpOwnership gives bare JSON/TOML keys.
14
+ *
15
+ * Instructions are delivered as marker-headed file copies: root `AGENTS.md`
16
+ * (read natively by Codex, pi, and Kimi Code) and Kiro's
17
+ * `.kiro/steering/trellis-workspace.md`. Claude Code reads `CLAUDE.md`, not
18
+ * `AGENTS.md`, and a repo's `CLAUDE.md` is almost always user-authored —
19
+ * v1 deliberately writes no Claude instructions file (documented
20
+ * limitation; `migrate --workspace` is the path for absorbing one).
21
+ */
22
+ import type { AdapterPlanItem } from "../core/adapter.js";
23
+ import type { AgentId, CanonicalSource } from "../core/types.js";
24
+ import type { BackupSession } from "./backup.js";
25
+ /** Per-destination-root ledger of Trellis-owned workspace copies. */
26
+ export type WorkspaceCopyLedger = Record<string, {
27
+ source: string;
28
+ sourceDigest: string;
29
+ destDigest: string;
30
+ }>;
31
+ /** Exported for `migrate --workspace` (trellis-workspace-scope task 4.x):
32
+ * absorbing a root `AGENTS.md` rewrites it marker-headed in place, which
33
+ * must be byte-identical to what a later sync would render. */
34
+ export declare const INSTRUCTIONS_MARKER = "<!-- generated by trellis from .agents/AGENTS.md \u2014 do not edit; run `trellis sync` to refresh -->";
35
+ export declare function planWorkspaceFiles(agentId: AgentId, canonical: CanonicalSource): AdapterPlanItem[];
36
+ /** Executes a `planWorkspaceFiles` result through the run's backup session
37
+ * and rewrites the copy ledger for every destination root it touched. */
38
+ export declare function applyWorkspaceFiles(agentId: AgentId, canonical: CanonicalSource, items: AdapterPlanItem[], backup: BackupSession): void;