harnessed 4.9.1 → 4.10.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 (61) hide show
  1. package/README.md +40 -4
  2. package/bin/harnessed-inject-state.mjs +103 -2
  3. package/dist/cli.mjs +1668 -1400
  4. package/dist/cli.mjs.map +1 -1
  5. package/dist/index.mjs +1 -1
  6. package/dist/index.mjs.map +1 -1
  7. package/package.json +1 -1
  8. package/workflows/auto/SKILL.md +26 -12
  9. package/workflows/auto/SKILL.zh-Hans.md +25 -10
  10. package/workflows/discuss/auto/SKILL.md +15 -12
  11. package/workflows/discuss/auto/SKILL.zh-Hans.md +12 -8
  12. package/workflows/discuss/phase/SKILL.md +15 -12
  13. package/workflows/discuss/phase/SKILL.zh-Hans.md +12 -8
  14. package/workflows/discuss/strategic/SKILL.md +15 -12
  15. package/workflows/discuss/strategic/SKILL.zh-Hans.md +12 -8
  16. package/workflows/discuss/subtask/SKILL.md +15 -12
  17. package/workflows/discuss/subtask/SKILL.zh-Hans.md +12 -8
  18. package/workflows/plan/architecture/SKILL.md +14 -12
  19. package/workflows/plan/architecture/SKILL.zh-Hans.md +11 -8
  20. package/workflows/plan/auto/SKILL.md +26 -12
  21. package/workflows/plan/auto/SKILL.zh-Hans.md +25 -10
  22. package/workflows/plan/phase/SKILL.md +14 -12
  23. package/workflows/plan/phase/SKILL.zh-Hans.md +11 -8
  24. package/workflows/research/SKILL.md +14 -12
  25. package/workflows/research/SKILL.zh-Hans.md +11 -8
  26. package/workflows/retro/SKILL.md +14 -12
  27. package/workflows/retro/SKILL.zh-Hans.md +11 -8
  28. package/workflows/role-prompts.yaml +34 -0
  29. package/workflows/role-prompts.zh-Hans.yaml +33 -0
  30. package/workflows/ship/auto/SKILL.md +29 -0
  31. package/workflows/ship/auto/SKILL.zh-Hans.md +28 -0
  32. package/workflows/ship/preflight/SKILL.md +17 -0
  33. package/workflows/ship/preflight/SKILL.zh-Hans.md +16 -0
  34. package/workflows/task/auto/SKILL.md +26 -12
  35. package/workflows/task/auto/SKILL.zh-Hans.md +25 -10
  36. package/workflows/task/clarify/SKILL.md +15 -12
  37. package/workflows/task/clarify/SKILL.zh-Hans.md +12 -8
  38. package/workflows/task/code/SKILL.md +14 -12
  39. package/workflows/task/code/SKILL.zh-Hans.md +11 -8
  40. package/workflows/task/deliver/SKILL.md +14 -12
  41. package/workflows/task/deliver/SKILL.zh-Hans.md +11 -8
  42. package/workflows/task/test/SKILL.md +14 -12
  43. package/workflows/task/test/SKILL.zh-Hans.md +11 -8
  44. package/workflows/verify/auto/SKILL.md +26 -12
  45. package/workflows/verify/auto/SKILL.zh-Hans.md +25 -10
  46. package/workflows/verify/code-review/SKILL.md +14 -12
  47. package/workflows/verify/code-review/SKILL.zh-Hans.md +11 -8
  48. package/workflows/verify/design/SKILL.md +14 -12
  49. package/workflows/verify/design/SKILL.zh-Hans.md +11 -8
  50. package/workflows/verify/multispec/SKILL.md +14 -12
  51. package/workflows/verify/multispec/SKILL.zh-Hans.md +11 -8
  52. package/workflows/verify/paranoid/SKILL.md +14 -12
  53. package/workflows/verify/paranoid/SKILL.zh-Hans.md +11 -8
  54. package/workflows/verify/progress/SKILL.md +14 -12
  55. package/workflows/verify/progress/SKILL.zh-Hans.md +11 -8
  56. package/workflows/verify/qa/SKILL.md +14 -12
  57. package/workflows/verify/qa/SKILL.zh-Hans.md +11 -8
  58. package/workflows/verify/security/SKILL.md +14 -12
  59. package/workflows/verify/security/SKILL.zh-Hans.md +11 -8
  60. package/workflows/verify/simplify/SKILL.md +14 -12
  61. package/workflows/verify/simplify/SKILL.zh-Hans.md +11 -8
package/dist/cli.mjs CHANGED
@@ -1,17 +1,17 @@
1
1
  #!/usr/bin/env node
2
+ import { existsSync, mkdirSync, renameSync, writeFileSync, readFileSync, readdirSync } from 'fs';
3
+ import { homedir } from 'os';
4
+ import { join, dirname, resolve, sep, relative } from 'path';
2
5
  import { Type } from '@sinclair/typebox';
6
+ import { readFile, readdir, unlink, writeFile, stat, rm, cp, mkdir, rename, appendFile, access } from 'fs/promises';
7
+ import { Value } from '@sinclair/typebox/value';
8
+ import lockfile from 'proper-lockfile';
3
9
  import { parse, LineCounter, parseDocument, isSeq, isScalar } from 'yaml';
4
10
  import { Ajv } from 'ajv';
5
11
  import * as ajvFormatsNs from 'ajv-formats';
6
12
  import { execFileSync, spawnSync, spawn, exec, execFile, execSync } from 'child_process';
7
- import { existsSync, mkdirSync, renameSync, writeFileSync, readFileSync, readdirSync } from 'fs';
8
- import { join, dirname, resolve, sep, relative } from 'path';
9
13
  import { fileURLToPath } from 'url';
10
- import { homedir } from 'os';
11
14
  import { createHash } from 'crypto';
12
- import { readFile, readdir, unlink, writeFile, stat, rm, cp, mkdir, rename, appendFile, access } from 'fs/promises';
13
- import { Value } from '@sinclair/typebox/value';
14
- import lockfile from 'proper-lockfile';
15
15
  import { Parser } from 'expr-eval';
16
16
  import { query } from '@anthropic-ai/claude-agent-sdk';
17
17
  import { promisify } from 'util';
@@ -38,7 +38,7 @@ var init_package = __esm({
38
38
  "package.json"() {
39
39
  package_default = {
40
40
  name: "harnessed",
41
- version: "4.9.1",
41
+ version: "4.10.0",
42
42
  description: "AI coding harness package manager + composition orchestrator",
43
43
  type: "module",
44
44
  license: "Apache-2.0",
@@ -139,1553 +139,1782 @@ var init_package = __esm({
139
139
  };
140
140
  }
141
141
  });
142
-
143
- // src/manifest/errors.ts
144
- function instancePathToKeyPath(instancePath) {
145
- if (!instancePath || instancePath === "/") return [];
146
- return instancePath.split("/").filter(Boolean).map((seg) => {
147
- const n = Number(seg);
148
- return Number.isInteger(n) && String(n) === seg ? n : seg;
149
- });
150
- }
151
- function locateLineFromDoc(doc, lineCounter, instancePath) {
152
- const path = instancePathToKeyPath(instancePath);
153
- let node;
154
- if (path.length === 0) {
155
- node = doc.contents;
156
- } else {
157
- node = doc.getIn(path, true);
158
- }
159
- if (!node || typeof node !== "object") return { line: null, column: null };
160
- const range = node.range;
161
- if (!range) return { line: null, column: null };
162
- const offset = range[0];
163
- const pos = lineCounter.linePos(offset);
164
- return { line: pos.line, column: pos.col };
165
- }
166
- function ajvErrorToFriendly(err2, file, doc, lineCounter) {
167
- let path = err2.instancePath || "/";
168
- const params = err2.params;
169
- if (err2.keyword === "additionalProperties" && params && typeof params.additionalProperty === "string") {
170
- path = `${path}/${params.additionalProperty}`;
171
- } else if (err2.keyword === "required" && params && typeof params.missingProperty === "string") {
172
- path = `${path}/${params.missingProperty}`;
173
- }
174
- let line = null;
175
- let column = null;
176
- if (doc && lineCounter) {
177
- const lookupPath = err2.keyword === "required" ? err2.instancePath || "/" : path;
178
- const loc = locateLineFromDoc(doc, lineCounter, lookupPath);
179
- line = loc.line;
180
- column = loc.column;
181
- }
142
+ function claudeDescriptor(home = homedir()) {
143
+ const claudeHome = join(home, ".claude");
182
144
  return {
183
- file,
184
- path,
185
- message: err2.message ?? "unknown error",
186
- line,
187
- column,
188
- keyword: err2.keyword
145
+ id: "claude",
146
+ homeDir: claudeHome,
147
+ stateRoot: join(claudeHome, "harnessed"),
148
+ settingsPath: join(claudeHome, "settings.json"),
149
+ skillsDir: join(claudeHome, "skills"),
150
+ commandsDir: join(claudeHome, "commands"),
151
+ pluginsRegistry: join(claudeHome, "plugins", "installed_plugins.json"),
152
+ // mcpConfigPath is a SIBLING of `.claude` (`<home>/.claude.json`), based on
153
+ // the same home base — not a child of homeDir.
154
+ mcpConfigPath: join(home, ".claude.json"),
155
+ // claude writes its env keys into JSON settings.json (capability present).
156
+ supportsEnvKeyWrite: true,
157
+ // Claude Code exposes the active session id to Bash-invoked CLI + hooks.
158
+ sessionIdEnv: "CLAUDE_CODE_SESSION_ID"
189
159
  };
190
160
  }
191
- function yamlParseErrorToFriendly(err2, file) {
161
+ function codexDescriptor(home = homedir()) {
162
+ const codexHome = join(home, ".codex");
163
+ const configToml = join(codexHome, "config.toml");
192
164
  return {
193
- file,
194
- path: "/",
195
- message: err2.message,
196
- line: err2.linePos?.[0]?.line ?? null,
197
- column: err2.linePos?.[0]?.col ?? null,
198
- keyword: "yaml-parse"
165
+ id: "codex",
166
+ homeDir: codexHome,
167
+ stateRoot: join(codexHome, "harnessed"),
168
+ settingsPath: configToml,
169
+ // SHARED convention dir, NOT <homeDir>/skills.
170
+ skillsDir: join(home, ".agents", "skills"),
171
+ commandsDir: join(codexHome, "prompts"),
172
+ pluginsRegistry: null,
173
+ mcpConfigPath: configToml,
174
+ supportsEnvKeyWrite: false,
175
+ // No verified codex session-id env → single-session fallback (anti-stale).
176
+ sessionIdEnv: null
199
177
  };
200
178
  }
201
- var init_errors = __esm({
202
- "src/manifest/errors.ts"() {
179
+ function descriptorById(id, home) {
180
+ if (id === "claude") return claudeDescriptor(home);
181
+ if (id === "codex") return codexDescriptor(home);
182
+ return void 0;
183
+ }
184
+ function detectPlatform(home = homedir()) {
185
+ const base = claudeDescriptor(home);
186
+ const override = process.env.HARNESSED_ROOT_OVERRIDE;
187
+ if (override !== void 0 && override !== "") return { ...base, stateRoot: override };
188
+ const envPlatform = process.env.HARNESSED_PLATFORM;
189
+ if (envPlatform !== void 0 && envPlatform !== "") {
190
+ const d = descriptorById(envPlatform, home);
191
+ if (d) return d;
192
+ }
193
+ try {
194
+ const pin = readFileSync(join(base.stateRoot, ".platform"), "utf8").trim();
195
+ const d = descriptorById(pin, home);
196
+ if (d) return d;
197
+ } catch {
198
+ }
199
+ try {
200
+ if (existsSync(base.homeDir)) return base;
201
+ const codex = codexDescriptor(home);
202
+ if (existsSync(codex.homeDir)) return codex;
203
+ } catch {
204
+ }
205
+ return base;
206
+ }
207
+ function getSettingsPath(home) {
208
+ return detectPlatform(home).settingsPath;
209
+ }
210
+ function getSkillsDir(home) {
211
+ return detectPlatform(home).skillsDir;
212
+ }
213
+ function getCommandsDir(home) {
214
+ return detectPlatform(home).commandsDir;
215
+ }
216
+ function getPluginsRegistry(home) {
217
+ return detectPlatform(home).pluginsRegistry;
218
+ }
219
+ function getMcpConfigPath(home) {
220
+ return detectPlatform(home).mcpConfigPath;
221
+ }
222
+ function harnessSkillsDirs(home) {
223
+ const dirs = [claudeDescriptor(home).skillsDir, codexDescriptor(home).skillsDir];
224
+ return [...new Set(dirs)];
225
+ }
226
+ var init_platform = __esm({
227
+ "src/installers/lib/platform.ts"() {
203
228
  }
204
229
  });
205
- var ApiVersion, Kind, SpdxLicense, LicenseSource, Upstream, MetadataSchema;
206
- var init_metadata = __esm({
207
- "src/manifest/schema/metadata.ts"() {
208
- ApiVersion = Type.Literal("harnessed/v1");
209
- Kind = Type.Literal("Manifest");
210
- SpdxLicense = Type.Union([
211
- Type.Literal("MIT"),
212
- Type.Literal("Apache-2.0"),
213
- Type.Literal("BSD-3-Clause"),
214
- Type.Literal("ISC"),
215
- Type.Literal("0BSD"),
216
- Type.Literal("MIT-0"),
217
- Type.Literal("anthropics-official")
218
- ]);
219
- LicenseSource = Type.Union([
220
- Type.Literal("README"),
221
- Type.Literal("registry"),
222
- Type.Literal("none"),
223
- Type.Literal("anthropics-official")
224
- ]);
225
- Upstream = Type.Object(
226
- {
227
- source: Type.String({ minLength: 1 }),
228
- homepage: Type.String({ format: "uri" }),
229
- repository: Type.String({ format: "uri" }),
230
- license: SpdxLicense,
231
- license_source: Type.Optional(LicenseSource),
232
- notice: Type.String({ minLength: 1, maxLength: 500 })
233
- },
234
- { additionalProperties: false }
235
- );
236
- MetadataSchema = Type.Object(
237
- {
238
- name: Type.String({ pattern: "^[a-z0-9][a-z0-9-]*$", minLength: 1 }),
239
- display_name: Type.Optional(Type.String()),
240
- description: Type.String({ minLength: 1, maxLength: 120 }),
241
- upstream: Upstream
242
- },
243
- { additionalProperties: false }
230
+ function getHarnessedRoot() {
231
+ return detectPlatform().stateRoot;
232
+ }
233
+ function harnessedSubdir(name) {
234
+ return join(getHarnessedRoot(), name);
235
+ }
236
+ function harnessedFile(name) {
237
+ return join(getHarnessedRoot(), name);
238
+ }
239
+ function migrateLegacyHarnessedRoot() {
240
+ const legacyRoot = join(homedir(), ".harnessed");
241
+ const newRoot = join(homedir(), ".claude", "harnessed");
242
+ const claudeParent = join(homedir(), ".claude");
243
+ if (!existsSync(legacyRoot)) return;
244
+ if (!existsSync(newRoot)) {
245
+ mkdirSync(claudeParent, { recursive: true });
246
+ renameSync(legacyRoot, newRoot);
247
+ console.error(
248
+ `[harnessed] migrated legacy state directory ${legacyRoot} \u2192 ${newRoot} (v3.0.3 path change)`
244
249
  );
250
+ return;
245
251
  }
246
- });
247
- var HookEvent, CcHookAdd;
248
- var init_ccHookAdd = __esm({
249
- "src/manifest/schema/installMethods/ccHookAdd.ts"() {
250
- HookEvent = Type.Union([
251
- Type.Literal("SessionStart"),
252
- Type.Literal("UserPromptSubmit"),
253
- Type.Literal("PreToolUse"),
254
- Type.Literal("PostToolUse")
255
- ]);
256
- CcHookAdd = Type.Object(
257
- {
258
- method: Type.Literal("cc-hook-add"),
259
- cmd: Type.String({ minLength: 1 }),
260
- // audit-trail (the bash invocation registered)
261
- // cwd/env required by lib/spawn.ts discriminated-union access (sister 6 method
262
- // shape parity — even though cc-hook-add does not spawn, generic spawn helper
263
- // expects these fields on the install union).
264
- cwd: Type.Optional(Type.String()),
265
- env: Type.Optional(Type.Record(Type.String(), Type.String())),
266
- hook_event: HookEvent,
267
- hook_matcher: Type.Optional(Type.String()),
268
- hook_command: Type.String({ minLength: 1 }),
269
- idempotent_check: Type.String({ minLength: 1 })
270
- },
271
- { additionalProperties: false }
252
+ const safetyBak = join(homedir(), ".harnessed.legacy-bak");
253
+ if (existsSync(safetyBak)) {
254
+ console.error(
255
+ `[harnessed] WARN: ${legacyRoot} reappeared after a prior migration (existing bak at ${safetyBak}); leaving in place \u2014 inspect manually if needed`
272
256
  );
257
+ return;
258
+ }
259
+ renameSync(legacyRoot, safetyBak);
260
+ console.error(
261
+ `[harnessed] both ${legacyRoot} and ${newRoot} existed \u2014 legacy directory preserved at ${safetyBak} (review manually if you need data from it; v3.0.3 path change)`
262
+ );
263
+ }
264
+ var init_harnessedRoot = __esm({
265
+ "src/installers/lib/harnessedRoot.ts"() {
266
+ init_platform();
273
267
  }
274
268
  });
275
- var GIT_REF_PATTERN, REPO_PATTERN, CcPluginMarketplace;
276
- var init_ccPluginMarketplace = __esm({
277
- "src/manifest/schema/installMethods/ccPluginMarketplace.ts"() {
278
- GIT_REF_PATTERN = "^([a-f0-9]{7,40}|v?\\d+\\.\\d+\\.\\d+([.-][\\w.-]+)?)$";
279
- REPO_PATTERN = "^[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+$";
280
- CcPluginMarketplace = Type.Object(
281
- {
282
- method: Type.Literal("cc-plugin-marketplace"),
283
- cmd: Type.String({ minLength: 1 }),
284
- cwd: Type.Optional(Type.String()),
285
- env: Type.Optional(Type.Record(Type.String(), Type.String())),
286
- args: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
287
- git_ref: Type.String({ minLength: 1, pattern: GIT_REF_PATTERN }),
288
- idempotent_check: Type.String({ minLength: 1 }),
289
- // ADR 0005 — third-party marketplace structured metadata (optional).
290
- marketplace_source: Type.Optional(
291
- Type.Object(
292
- {
293
- source: Type.Literal("github"),
294
- repo: Type.String({ pattern: REPO_PATTERN, minLength: 3 })
295
- },
296
- { additionalProperties: false }
297
- )
298
- )
299
- },
300
- { additionalProperties: false }
301
- );
269
+ function branchOnSchemaVersion(v, handlers) {
270
+ const isKnownVersion = Object.values(SCHEMA_VERSIONS).includes(v);
271
+ return isKnownVersion ? handlers.v1() : handlers.unknown();
272
+ }
273
+ var SCHEMA_VERSIONS;
274
+ var init_schemaVersion = __esm({
275
+ "src/types/schemaVersion.ts"() {
276
+ SCHEMA_VERSIONS = {
277
+ routingSnapshot: "harnessed.routing-snapshot.v1",
278
+ handoffDoc: "harnessed.handoff-doc.v1",
279
+ phasesYaml: "harnessed.phases-yaml.v1",
280
+ manifestState: "harnessed.manifest-state.v1",
281
+ installerState: "harnessed.installer-state.v1",
282
+ routeDecisionLog: "harnessed.route-decision-log.v1",
283
+ checkpoint: "harnessed.checkpoint.v1",
284
+ currentWorkflow: "harnessed.current-workflow.v1",
285
+ // ← Phase 3.1 W1 T1.1 ADD (D-02 KARPATHY 3-state)
286
+ workflowStore: "harnessed.workflow-store.v1",
287
+ // ← Phase 15 ADD (per-repo multi-workflow store)
288
+ config: "harnessed.config.v1",
289
+ // ← Phase 3.2 W1 T1.1 ADD (D-01 PROBE gstack_prefix store)
290
+ governance: "harnessed.governance.v1",
291
+ // ← Phase 3.2 W1 T1.1 ADD (D-04 PUSH veto status)
292
+ aliases: "harnessed.aliases.v1",
293
+ // ← Phase 3.3 W1 T1.1 ADD (D-01 RICH)
294
+ knownGood: "harnessed.known-good.v1",
295
+ // ← Phase 3.3 W1 T1.1 ADD (D-03 YAML manifest)
296
+ capabilities: "harnessed.capabilities.v1",
297
+ // ← Phase v2.0-2.3 W0 ADD (R20.2 flat yaml capabilities manifest validate)
298
+ judgment: "harnessed.judgment.v1",
299
+ // ← Phase v2.0-2.3 W0 ADD (R20.4 multi-file judgments validate)
300
+ workflow: "harnessed.workflow.v2",
301
+ // ← Phase v2.0-2.4 W0 T2.4.W0.1 ADD (R20.1+R20.2+R20.9 workflow.yaml v2)
302
+ workflow_v3: "harnessed.workflow.v3",
303
+ // ← Phase v3.0-3.3 W0 T3.3.W0.11 ADD (D-09 disciplines_applied + D-05 tools_available + master delegates_to per Pattern A B.1 LOCK)
304
+ discipline: "harnessed.discipline.v1"
305
+ // ← Phase v3.0-3.3 W0 T3.3.W0.11 ADD (D-09 L0 Discipline Substrate, sister judgment.v1 multi-file pattern)
306
+ };
307
+ Type.Union([
308
+ Type.Literal(SCHEMA_VERSIONS.routingSnapshot),
309
+ Type.Literal(SCHEMA_VERSIONS.handoffDoc),
310
+ Type.Literal(SCHEMA_VERSIONS.phasesYaml),
311
+ Type.Literal(SCHEMA_VERSIONS.manifestState),
312
+ Type.Literal(SCHEMA_VERSIONS.installerState),
313
+ Type.Literal(SCHEMA_VERSIONS.routeDecisionLog),
314
+ Type.Literal(SCHEMA_VERSIONS.checkpoint),
315
+ Type.Literal(SCHEMA_VERSIONS.currentWorkflow),
316
+ // ← Phase 3.1 W1 T1.1 ADD
317
+ Type.Literal(SCHEMA_VERSIONS.workflowStore),
318
+ // ← Phase 15 ADD
319
+ Type.Literal(SCHEMA_VERSIONS.config),
320
+ // ← Phase 3.2 W1 T1.1 ADD
321
+ Type.Literal(SCHEMA_VERSIONS.governance),
322
+ // ← Phase 3.2 W1 T1.1 ADD
323
+ Type.Literal(SCHEMA_VERSIONS.aliases),
324
+ // ← Phase 3.3 W1 T1.1 ADD
325
+ Type.Literal(SCHEMA_VERSIONS.knownGood),
326
+ // ← Phase 3.3 W1 T1.1 ADD
327
+ Type.Literal(SCHEMA_VERSIONS.capabilities),
328
+ // ← Phase v2.0-2.3 W0 ADD
329
+ Type.Literal(SCHEMA_VERSIONS.judgment),
330
+ // ← Phase v2.0-2.3 W0 ADD
331
+ Type.Literal(SCHEMA_VERSIONS.workflow),
332
+ // ← Phase v2.0-2.4 W0 T2.4.W0.1 ADD (first .v2 in union)
333
+ Type.Literal(SCHEMA_VERSIONS.workflow_v3),
334
+ // ← Phase v3.0-3.3 W0 T3.3.W0.11 ADD (first .v3 in union)
335
+ Type.Literal(SCHEMA_VERSIONS.discipline)
336
+ // ← Phase v3.0-3.3 W0 T3.3.W0.11 ADD
337
+ ]);
302
338
  }
303
339
  });
304
- var GIT_REF_PATTERN2, GitCloneWithSetup;
305
- var init_gitCloneWithSetup = __esm({
306
- "src/manifest/schema/installMethods/gitCloneWithSetup.ts"() {
307
- GIT_REF_PATTERN2 = "^([a-f0-9]{7,40}|v?\\d+\\.\\d+\\.\\d+([.-][\\w.-]+)?)$";
308
- GitCloneWithSetup = Type.Object(
340
+ async function writeFileAtomic(path, data) {
341
+ const tmp = `${path}.tmp`;
342
+ await writeFile(tmp, data, "utf8");
343
+ await rename(tmp, path);
344
+ }
345
+ function writeFileSyncAtomic(path, data) {
346
+ const tmp = `${path}.tmp`;
347
+ writeFileSync(tmp, data, "utf8");
348
+ renameSync(tmp, path);
349
+ }
350
+ var init_atomicWrite = __esm({
351
+ "src/checkpoint/atomicWrite.ts"() {
352
+ }
353
+ });
354
+ var CheckpointStatus, CheckpointV1;
355
+ var init_checkpoint_v1 = __esm({
356
+ "src/checkpoint/schema/checkpoint.v1.ts"() {
357
+ init_schemaVersion();
358
+ CheckpointStatus = Type.Union([
359
+ Type.Literal("active"),
360
+ Type.Literal("paused"),
361
+ Type.Literal("complete")
362
+ ]);
363
+ CheckpointV1 = Type.Object(
309
364
  {
310
- method: Type.Literal("git-clone-with-setup"),
311
- cmd: Type.String({ minLength: 1 }),
312
- cwd: Type.Optional(Type.String()),
313
- env: Type.Optional(Type.Record(Type.String(), Type.String())),
314
- args: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
315
- git_ref: Type.String({ minLength: 1, pattern: GIT_REF_PATTERN2 }),
316
- idempotent_check: Type.String({ minLength: 1 })
365
+ schemaVersion: Type.Literal(SCHEMA_VERSIONS.checkpoint),
366
+ phase: Type.String({ minLength: 1 }),
367
+ status: CheckpointStatus,
368
+ last_task: Type.String(),
369
+ key_decisions: Type.Array(Type.String()),
370
+ canonical_refs: Type.Array(Type.String()),
371
+ /** D-04 WIRE-IN: optional SDK session_id captured via `sdkSpawn`
372
+ * `onSessionId` callback (CD-4 closure-ready) for future `--resume`. */
373
+ session_id: Type.Optional(Type.String()),
374
+ /** RESEARCH § 1.3 critical constraint — SDK session resume requires cwd
375
+ * match; we capture and validate at restore time. */
376
+ cwd: Type.String({ minLength: 1 }),
377
+ timestamp: Type.String({ minLength: 1 }),
378
+ // ISO-8601 by convention (TypeBox `format` requires Ajv-style format registry; we keep shape-check only — drift caught in writeCheckpoint path)
379
+ archive_path: Type.String({ minLength: 1 })
317
380
  },
318
381
  { additionalProperties: false }
319
382
  );
320
383
  }
321
384
  });
322
- var McpHttpAdd;
323
- var init_mcpHttpAdd = __esm({
324
- "src/manifest/schema/installMethods/mcpHttpAdd.ts"() {
325
- McpHttpAdd = Type.Object(
385
+ var WorkflowStatus, EvidenceRef, SubProgressEntry, CurrentWorkflowV1;
386
+ var init_currentWorkflow_v1 = __esm({
387
+ "src/checkpoint/schema/currentWorkflow.v1.ts"() {
388
+ init_schemaVersion();
389
+ WorkflowStatus = Type.Union([
390
+ Type.Literal("active"),
391
+ Type.Literal("paused"),
392
+ Type.Literal("complete")
393
+ ]);
394
+ EvidenceRef = Type.Object(
395
+ { path: Type.String({ minLength: 1 }), sha256: Type.String({ minLength: 1 }) },
396
+ { additionalProperties: false }
397
+ );
398
+ SubProgressEntry = Type.Object(
326
399
  {
327
- method: Type.Literal("mcp-http-add"),
328
- cmd: Type.String({ minLength: 1 }),
329
- cwd: Type.Optional(Type.String()),
330
- env: Type.Optional(Type.Record(Type.String(), Type.String())),
331
- args: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
332
- npm_version: Type.String({ minLength: 1 }),
333
- idempotent_check: Type.String({ minLength: 1 })
400
+ // flattened sub name, e.g. "task-code".
401
+ sub: Type.String({ minLength: 1 }),
402
+ status: Type.Union([
403
+ Type.Literal("pending"),
404
+ Type.Literal("done"),
405
+ Type.Literal("failed"),
406
+ Type.Literal("skipped"),
407
+ Type.Literal("rejected")
408
+ ]),
409
+ gate_fired: Type.Boolean(),
410
+ // skip reason (from gates plan skip[].reason).
411
+ reason: Type.Optional(Type.String()),
412
+ // D2 (eng-review) — three-state evidence posture, NOT a boolean:
413
+ // 'verified' — artifacts_expected declared AND all present (sha256 recorded)
414
+ // 'none_declared' — leaf declares no artifacts_expected → guard N/A (NOT a pass)
415
+ // 'overridden' — --force used to bypass a missing-artifact block
416
+ evidence_status: Type.Optional(
417
+ Type.Union([
418
+ Type.Literal("verified"),
419
+ Type.Literal("none_declared"),
420
+ Type.Literal("overridden")
421
+ ])
422
+ ),
423
+ evidence: Type.Optional(Type.Array(EvidenceRef)),
424
+ // G6 — failure counter; incremented only on each ->failed transition (drives
425
+ // breakLoop detection). 'rejected' is terminal and does NOT increment it.
426
+ fail_count: Type.Optional(Type.Integer({ minimum: 0 }))
334
427
  },
335
428
  { additionalProperties: false }
336
429
  );
337
- }
338
- });
339
- var McpStdioAdd;
340
- var init_mcpStdioAdd = __esm({
341
- "src/manifest/schema/installMethods/mcpStdioAdd.ts"() {
342
- McpStdioAdd = Type.Object(
430
+ CurrentWorkflowV1 = Type.Object(
343
431
  {
344
- method: Type.Literal("mcp-stdio-add"),
345
- cmd: Type.String({ minLength: 1 }),
346
- cwd: Type.Optional(Type.String()),
347
- env: Type.Optional(Type.Record(Type.String(), Type.String())),
348
- args: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
349
- npm_version: Type.String({ minLength: 1 }),
350
- idempotent_check: Type.String({ minLength: 1 })
432
+ schemaVersion: Type.Literal(SCHEMA_VERSIONS.currentWorkflow),
433
+ phase: Type.String({ minLength: 1 }),
434
+ status: WorkflowStatus,
435
+ last_checkpoint_path: Type.Union([Type.String(), Type.Null()]),
436
+ // ISO-8601 by convention (TypeBox `format` requires Ajv-style registry; shape-check only here, drift surfaces in state.ts writer).
437
+ started_at: Type.String({ minLength: 1 }),
438
+ paused_at: Type.Optional(Type.String({ minLength: 1 })),
439
+ completed_at: Type.Optional(Type.String({ minLength: 1 })),
440
+ // v5.0 Spec 1 (ADR-0033 D1/D3) — additive optional ledger (sole SoT; the
441
+ // checkpoint envelope does NOT carry a copy). Old files without this field
442
+ // still `Value.Check`-pass → no schema version bump; readers use `?? []`.
443
+ sub_progress: Type.Optional(Type.Array(SubProgressEntry)),
444
+ // G1 — verification depth used during the verify phase ('light' | 'full').
445
+ verify_mode: Type.Optional(Type.Union([Type.Literal("light"), Type.Literal("full")])),
446
+ // G2 — when true the next-step contract reports NEXT:auto (skill auto-advances);
447
+ // when false NEXT:manual (pause for the operator). Precedence env > this > default.
448
+ auto_transition: Type.Optional(Type.Boolean()),
449
+ // Phase 14 — compaction digest: cumulative summary of resolved sub-progress
450
+ // entries evicted by `compact`. Additive-optional (NO schemaVersion bump; old
451
+ // files without it still Value.Check-pass). Keeps a readable trace after
452
+ // eviction. G6 invariant: entries with fail_count>0 are never evicted, so the
453
+ // breakLoop signal is never summarized away.
454
+ compacted_summary: Type.Optional(
455
+ Type.Object(
456
+ {
457
+ evicted: Type.Integer({ minimum: 0 }),
458
+ by_status: Type.Record(Type.String(), Type.Integer({ minimum: 0 })),
459
+ last_at: Type.String({ minLength: 1 })
460
+ },
461
+ { additionalProperties: false }
462
+ )
463
+ ),
464
+ // Phase 22 — smart reminders. Additive-optional flags set by `checkpoint
465
+ // complete` (allResolved) and read by the G4 inject twins (booleans only; the
466
+ // bin computes neither git nor thresholds). Old files without them Value.Check-pass
467
+ // → NO schemaVersion bump.
468
+ // ship_ready — there are unshipped commits since the last vX.Y.Z tag (git-derived,
469
+ // recomputed each completion; self-heals to false after a release).
470
+ // ship_commits — commit count since that tag (feeds the SHIP-READY hint text).
471
+ // retro_due — phases_since_retro (store sidecar) has crossed the threshold;
472
+ // cleared by `harnessed retro --done`.
473
+ ship_ready: Type.Optional(Type.Boolean()),
474
+ ship_commits: Type.Optional(Type.Integer({ minimum: 0 })),
475
+ retro_due: Type.Optional(Type.Boolean())
351
476
  },
352
477
  { additionalProperties: false }
353
478
  );
354
479
  }
355
480
  });
356
- var NpmCli;
357
- var init_npmCli = __esm({
358
- "src/manifest/schema/installMethods/npmCli.ts"() {
359
- NpmCli = Type.Object(
360
- {
361
- method: Type.Literal("npm-cli"),
362
- cmd: Type.String({ minLength: 1 }),
363
- cwd: Type.Optional(Type.String()),
364
- env: Type.Optional(Type.Record(Type.String(), Type.String())),
365
- args: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
366
- npm_version: Type.String({ minLength: 1 }),
367
- idempotent_check: Type.String({ minLength: 1 })
368
- },
369
- { additionalProperties: false }
370
- );
481
+
482
+ // src/checkpoint/schema/index.ts
483
+ var init_schema = __esm({
484
+ "src/checkpoint/schema/index.ts"() {
485
+ init_checkpoint_v1();
486
+ init_currentWorkflow_v1();
371
487
  }
372
488
  });
373
- var NpxSkillInstaller;
374
- var init_npxSkillInstaller = __esm({
375
- "src/manifest/schema/installMethods/npxSkillInstaller.ts"() {
376
- NpxSkillInstaller = Type.Object(
377
- {
378
- method: Type.Literal("npx-skill-installer"),
379
- cmd: Type.String({ minLength: 1 }),
380
- cwd: Type.Optional(Type.String()),
381
- env: Type.Optional(Type.Record(Type.String(), Type.String())),
382
- args: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
383
- npm_version: Type.String({ minLength: 1 }),
384
- idempotent_check: Type.String({ minLength: 1 })
385
- },
386
- { additionalProperties: false }
387
- );
388
- }
489
+
490
+ // src/checkpoint/workflowStore.ts
491
+ var workflowStore_exports = {};
492
+ __export(workflowStore_exports, {
493
+ RetroMetaEntry: () => RetroMetaEntry,
494
+ WorkflowStoreV1: () => WorkflowStoreV1,
495
+ activeKey: () => activeKey,
496
+ listWorkflows: () => listWorkflows,
497
+ readStoreRaw: () => readStoreRaw,
498
+ repoKey: () => repoKey,
499
+ writeStoreRaw: () => writeStoreRaw
389
500
  });
390
- var branches, InstallSchema;
391
- var init_installMethods = __esm({
392
- "src/manifest/schema/installMethods/index.ts"() {
393
- init_ccHookAdd();
394
- init_ccPluginMarketplace();
395
- init_gitCloneWithSetup();
396
- init_mcpHttpAdd();
397
- init_mcpStdioAdd();
398
- init_npmCli();
399
- init_npxSkillInstaller();
400
- branches = [
401
- CcPluginMarketplace,
402
- GitCloneWithSetup,
403
- NpxSkillInstaller,
404
- NpmCli,
405
- McpStdioAdd,
406
- McpHttpAdd,
407
- CcHookAdd
408
- ];
409
- InstallSchema = {
410
- type: "object",
411
- discriminator: { propertyName: "method" },
412
- required: ["method"],
413
- properties: {
414
- method: { type: "string" }
415
- },
416
- oneOf: branches
417
- };
418
- Type.Union([...branches]);
501
+ function storePath() {
502
+ return harnessedFile("workflows.json");
503
+ }
504
+ function legacyPath() {
505
+ return harnessedFile("current-workflow.json");
506
+ }
507
+ function emptyStore() {
508
+ return { schemaVersion: SCHEMA_VERSIONS.workflowStore, workflows: {} };
509
+ }
510
+ function repoKey(cwd = process.cwd()) {
511
+ let dir = resolve(cwd);
512
+ for (; ; ) {
513
+ if (existsSync(join(dir, ".git"))) return dir;
514
+ const parent = dirname(dir);
515
+ if (parent === dir) break;
516
+ dir = parent;
419
517
  }
420
- });
421
- var TypeEnum, ComponentType, Verify, Uninstall, Stability, FallbackAction, UpstreamHealth, Platform, Signature, TestedWithVersions, Category, InstallType, DecisionRules, Phase, Triggers, ProvidedUnit, SpecSchema;
422
- var init_spec = __esm({
423
- "src/manifest/schema/spec.ts"() {
424
- init_installMethods();
425
- TypeEnum = Type.Union([
426
- Type.Literal("cc-plugin"),
427
- Type.Literal("cc-skill-pack"),
428
- Type.Literal("mcp-npm"),
429
- Type.Literal("cli-npm"),
430
- // Phase 2.4 W3 T3.1 (D-04 § 3.1 + R2.4.4 + B-22) — 5th type, 1:1 with install_type:'hook'.
431
- // Lifecycle hooks registered to ~/.claude/settings.json (SessionStart / UserPromptSubmit /
432
- // PreToolUse / PostToolUse) via the cc-hook-add install method.
433
- Type.Literal("cc-hook")
434
- ]);
435
- ComponentType = Type.Union([
436
- Type.Literal("command"),
437
- Type.Literal("behavior-rule"),
438
- Type.Literal("mcp-tool"),
439
- Type.Literal("cli-binary")
440
- ]);
441
- Verify = Type.Object(
442
- {
443
- cmd: Type.String({ minLength: 1 }),
444
- timeout_ms: Type.Optional(Type.Integer({ minimum: 100, maximum: 6e4 })),
445
- expected_exit_code: Type.Optional(Type.Integer())
446
- },
447
- { additionalProperties: false }
448
- );
449
- Uninstall = Type.Object(
450
- {
451
- cmd: Type.String({ minLength: 1 }),
452
- cleanup_paths: Type.Optional(Type.Array(Type.String()))
453
- },
454
- { additionalProperties: false }
455
- );
456
- Stability = Type.Union([
457
- Type.Literal("stable"),
458
- Type.Literal("beta"),
459
- Type.Literal("unstable"),
460
- Type.Literal("archived")
461
- ]);
462
- FallbackAction = Type.Union([
463
- Type.Literal("warn"),
464
- Type.Literal("block"),
465
- Type.Literal("use_alternative")
466
- ]);
467
- UpstreamHealth = Type.Object(
468
- {
469
- stability: Stability,
470
- last_check: Type.String({ format: "date" }),
471
- last_known_good_version: Type.String({ minLength: 1 }),
472
- fallback_action: FallbackAction,
473
- alternative: Type.Optional(Type.String())
474
- },
475
- { additionalProperties: false }
476
- );
477
- Platform = Type.Union([Type.Literal("linux"), Type.Literal("darwin"), Type.Literal("win32")]);
478
- Signature = Type.Object(
479
- { sigstore_bundle: Type.String({ format: "uri" }) },
480
- { additionalProperties: false }
481
- );
482
- TestedWithVersions = Type.Object(
518
+ return resolve(cwd);
519
+ }
520
+ function activeKey(cwd = process.cwd()) {
521
+ const base = repoKey(cwd);
522
+ const envName = detectPlatform().sessionIdEnv;
523
+ const sid = envName ? process.env[envName]?.trim() : void 0;
524
+ return sid ? `${base}::${sid}` : base;
525
+ }
526
+ async function readStoreRaw() {
527
+ try {
528
+ const parsed = JSON.parse(await readFile(storePath(), "utf8"));
529
+ if (Value.Check(WorkflowStoreV1, parsed)) return parsed;
530
+ } catch {
531
+ }
532
+ try {
533
+ const legacy = JSON.parse(await readFile(legacyPath(), "utf8"));
534
+ if (Value.Check(CurrentWorkflowV1, legacy)) {
535
+ return {
536
+ schemaVersion: SCHEMA_VERSIONS.workflowStore,
537
+ workflows: { [repoKey()]: legacy }
538
+ };
539
+ }
540
+ } catch {
541
+ }
542
+ return emptyStore();
543
+ }
544
+ async function writeStoreRaw(store) {
545
+ if (!Value.Check(WorkflowStoreV1, store)) {
546
+ const errs = [...Value.Errors(WorkflowStoreV1, store)].map((e) => e.message).join("; ");
547
+ throw new Error(`workflow-store schema validation failed: ${errs}`);
548
+ }
549
+ const p5 = storePath();
550
+ await mkdir(dirname(p5), { recursive: true });
551
+ await writeFileAtomic(p5, JSON.stringify(store, null, 2));
552
+ }
553
+ async function listWorkflows() {
554
+ const store = await readStoreRaw();
555
+ return Object.entries(store.workflows).map(([key, wf]) => ({
556
+ key,
557
+ phase: wf.phase,
558
+ status: wf.status
559
+ }));
560
+ }
561
+ var RetroMetaEntry, WorkflowStoreV1;
562
+ var init_workflowStore = __esm({
563
+ "src/checkpoint/workflowStore.ts"() {
564
+ init_harnessedRoot();
565
+ init_platform();
566
+ init_schemaVersion();
567
+ init_atomicWrite();
568
+ init_currentWorkflow_v1();
569
+ RetroMetaEntry = Type.Object(
483
570
  {
484
- cc_versions: Type.Optional(Type.Array(Type.String())),
485
- node_versions: Type.Optional(Type.Array(Type.String()))
571
+ phases_since_retro: Type.Integer({ minimum: 0 }),
572
+ last_retro_at: Type.Optional(Type.String({ minLength: 1 }))
486
573
  },
487
574
  { additionalProperties: false }
488
575
  );
489
- Category = Type.Union([
490
- Type.Literal("meta"),
491
- Type.Literal("engineering"),
492
- Type.Literal("design"),
493
- Type.Literal("content"),
494
- Type.Literal("testing"),
495
- Type.Literal("search")
496
- ]);
497
- InstallType = Type.Union([
498
- Type.Literal("skill"),
499
- Type.Literal("mcp"),
500
- Type.Literal("npm"),
501
- Type.Literal("git"),
502
- // Phase 2.4 W3 T3.1 (D-04 § 3.1 + R2.4.4 + B-22) — 5th install_type, 1:1 with TypeEnum:'cc-hook'.
503
- Type.Literal("hook")
504
- ]);
505
- DecisionRules = Type.Object(
576
+ WorkflowStoreV1 = Type.Object(
506
577
  {
507
- trigger: Type.Optional(Type.String({ minLength: 1 })),
508
- default_expert: Type.Optional(Type.String({ minLength: 1 })),
509
- arbitration_rule: Type.Optional(Type.String({ minLength: 1 })),
510
- override_signals: Type.Optional(
511
- Type.Array(
512
- Type.Object(
513
- {
514
- phrase: Type.String({ minLength: 1 }),
515
- use: Type.String({ minLength: 1 })
516
- },
517
- { additionalProperties: false }
518
- )
519
- )
520
- ),
521
- // Phase 2.3 W2 T2.5 — CD-3 negative-space hint mirror (B-17 per-manifest hint
522
- // redundant guard layer; SSOT remains routing/decision_rules.yaml — D-04 lead).
523
- // Additive optional; existing manifests unchanged (A7 守恒).
524
- do_not_use_when: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { minItems: 1 })),
525
- if_rejected_use: Type.Optional(Type.String({ minLength: 1 }))
526
- },
527
- { additionalProperties: false }
528
- );
529
- Phase = Type.Union([
530
- Type.Literal("discuss"),
531
- Type.Literal("plan"),
532
- Type.Literal("execute"),
533
- Type.Literal("verify")
534
- ]);
535
- Triggers = Type.Object(
536
- {
537
- complexity_threshold: Type.Optional(Type.Integer({ minimum: 1 })),
538
- tdd_required: Type.Optional(Type.Boolean()),
539
- brainstorming_required: Type.Optional(Type.Boolean())
540
- },
541
- { additionalProperties: false }
542
- );
543
- ProvidedUnit = Type.Object(
544
- {
545
- id: Type.String({ minLength: 1 }),
546
- // routing-addressable, <org>-<repo>-<unit>
547
- component_type: ComponentType
548
- // reuse existing union
549
- },
550
- { additionalProperties: false }
551
- );
552
- SpecSchema = Type.Object(
553
- {
554
- type: TypeEnum,
555
- component_type: ComponentType,
556
- install: Type.Unsafe(InstallSchema),
557
- verify: Verify,
558
- uninstall: Uninstall,
559
- upstream_health: UpstreamHealth,
560
- signed_by: Type.String({ pattern: "^[a-zA-Z0-9-]+$", minLength: 1 }),
561
- signature: Type.Optional(Signature),
562
- platforms: Type.Array(Platform, { minItems: 1, uniqueItems: true }),
563
- tested_with_versions: Type.Optional(TestedWithVersions),
564
- mutually_exclusive_with: Type.Optional(Type.Array(Type.String())),
565
- category: Category,
566
- install_type: InstallType,
567
- decision_rules: Type.Optional(DecisionRules),
568
- // ADR 0009 errata (phase 1.5 T5.5) — mattpocock phase routing schema.
569
- phase: Type.Optional(Phase),
570
- triggers: Type.Optional(Triggers),
571
- // ADR 0010 errata (phase 2.1 T1.3) — bundle-install `provides` field.
572
- provides: Type.Optional(Type.Array(ProvidedUnit, { minItems: 2, uniqueItems: true }))
578
+ schemaVersion: Type.Literal(SCHEMA_VERSIONS.workflowStore),
579
+ workflows: Type.Record(Type.String(), CurrentWorkflowV1),
580
+ // Additive-optional (no schemaVersion bump — old stores Value.Check-pass).
581
+ retro_meta: Type.Optional(Type.Record(Type.String(), RetroMetaEntry))
573
582
  },
574
583
  { additionalProperties: false }
575
584
  );
576
585
  }
577
586
  });
578
- var ManifestBase, matrix, matrixConstraints, ManifestSchema;
579
- var init_schema = __esm({
580
- "src/manifest/schema/index.ts"() {
581
- init_metadata();
582
- init_spec();
583
- ManifestBase = Type.Object(
584
- {
585
- apiVersion: ApiVersion,
586
- kind: Kind,
587
- metadata: MetadataSchema,
588
- spec: SpecSchema
589
- },
590
- { additionalProperties: false }
591
- );
592
- matrix = {
593
- "cc-plugin": ["cc-plugin-marketplace"],
594
- "cc-skill-pack": ["cc-plugin-marketplace", "git-clone-with-setup", "npx-skill-installer"],
595
- "mcp-npm": ["mcp-stdio-add", "mcp-http-add"],
596
- "cli-npm": ["npm-cli"]
587
+
588
+ // src/checkpoint/state.ts
589
+ var state_exports = {};
590
+ __export(state_exports, {
591
+ LockHeldError: () => LockHeldError,
592
+ WorkflowStateError: () => WorkflowStateError,
593
+ activate: () => activate,
594
+ complete: () => complete,
595
+ mutateStore: () => mutateStore,
596
+ mutateSubProgress: () => mutateSubProgress,
597
+ pause: () => pause,
598
+ readCurrentWorkflow: () => readCurrentWorkflow,
599
+ writeCurrentWorkflow: () => writeCurrentWorkflow
600
+ });
601
+ function statePath() {
602
+ return harnessedFile("current-workflow.json");
603
+ }
604
+ function lockTarget() {
605
+ return getHarnessedRoot();
606
+ }
607
+ function lockOpts() {
608
+ return {
609
+ stale: 1e4,
610
+ retries: { retries: 3, factor: 2, minTimeout: 100 },
611
+ lockfilePath: harnessedFile(".lock")
612
+ };
613
+ }
614
+ async function withLock(fn) {
615
+ const target = lockTarget();
616
+ await mkdir(target, { recursive: true });
617
+ let release;
618
+ try {
619
+ release = await lockfile.lock(target, lockOpts());
620
+ } catch (e) {
621
+ if (e.code === "ELOCKED") throw new LockHeldError();
622
+ throw e;
623
+ }
624
+ try {
625
+ return await fn();
626
+ } finally {
627
+ await release?.();
628
+ }
629
+ }
630
+ async function readCurrentWorkflow() {
631
+ const store = await readStoreRaw();
632
+ return store.workflows[activeKey()] ?? store.workflows[repoKey()] ?? null;
633
+ }
634
+ async function writeCurrentWorkflowUnlocked(s) {
635
+ if (!Value.Check(CurrentWorkflowV1, s)) {
636
+ const errs = [...Value.Errors(CurrentWorkflowV1, s)].map((e) => e.message).join("; ");
637
+ throw new WorkflowStateError(`current-workflow schema validation failed: ${errs}`);
638
+ }
639
+ const store = await readStoreRaw();
640
+ store.workflows[activeKey()] = s;
641
+ await writeStoreRaw(store);
642
+ await writeFileAtomic(statePath(), JSON.stringify(s, null, 2));
643
+ }
644
+ async function writeCurrentWorkflow(s) {
645
+ await withLock(() => writeCurrentWorkflowUnlocked(s));
646
+ }
647
+ async function mutateSubProgress(fn) {
648
+ await withLock(async () => {
649
+ const s = await readCurrentWorkflow();
650
+ if (!s) return;
651
+ const next = fn(s.sub_progress ?? []);
652
+ await writeCurrentWorkflowUnlocked({ ...s, sub_progress: next });
653
+ });
654
+ }
655
+ async function mutateStore(fn) {
656
+ await withLock(async () => {
657
+ const store = await readStoreRaw();
658
+ await writeStoreRaw(fn(store));
659
+ });
660
+ }
661
+ async function activate(phase, checkpointPath = null) {
662
+ await writeCurrentWorkflow({
663
+ schemaVersion: SCHEMA_VERSIONS.currentWorkflow,
664
+ phase,
665
+ status: "active",
666
+ last_checkpoint_path: checkpointPath,
667
+ started_at: (/* @__PURE__ */ new Date()).toISOString()
668
+ });
669
+ }
670
+ async function pause() {
671
+ const s = await readCurrentWorkflow();
672
+ if (!s) return;
673
+ await writeCurrentWorkflow({ ...s, status: "paused", paused_at: (/* @__PURE__ */ new Date()).toISOString() });
674
+ }
675
+ async function complete() {
676
+ const s = await readCurrentWorkflow();
677
+ if (!s) return;
678
+ await writeCurrentWorkflow({ ...s, status: "complete", completed_at: (/* @__PURE__ */ new Date()).toISOString() });
679
+ }
680
+ var WorkflowStateError, LockHeldError;
681
+ var init_state = __esm({
682
+ "src/checkpoint/state.ts"() {
683
+ init_harnessedRoot();
684
+ init_schemaVersion();
685
+ init_atomicWrite();
686
+ init_schema();
687
+ init_workflowStore();
688
+ WorkflowStateError = class extends Error {
689
+ constructor(message) {
690
+ super(message);
691
+ this.name = "WorkflowStateError";
692
+ }
597
693
  };
598
- matrixConstraints = Object.entries(matrix).map(([typeValue, allowedMethods]) => ({
599
- if: {
600
- type: "object",
601
- properties: {
602
- spec: {
603
- type: "object",
604
- properties: { type: { const: typeValue } },
605
- required: ["type"]
606
- }
607
- },
608
- required: ["spec"]
609
- },
610
- // biome-ignore lint/suspicious/noThenProperty: JSON Schema `then` keyword (conditional schemas), not a thenable.
611
- then: {
612
- type: "object",
613
- properties: {
614
- spec: {
615
- type: "object",
616
- properties: {
617
- install: {
618
- type: "object",
619
- properties: { method: { enum: allowedMethods } },
620
- required: ["method"]
621
- }
622
- },
623
- required: ["install"]
624
- }
625
- },
626
- required: ["spec"]
694
+ LockHeldError = class _LockHeldError extends Error {
695
+ constructor() {
696
+ super(
697
+ `another harnessed process holds the lock at ${harnessedFile(".lock")} \u2014 wait or kill stale process (try: harnessed status)`
698
+ );
699
+ this.name = "LockHeldError";
700
+ Object.setPrototypeOf(this, _LockHeldError.prototype);
627
701
  }
628
- }));
629
- ManifestSchema = {
630
- ...ManifestBase,
631
- $id: "https://harnessed.dev/schemas/manifest.v1.schema.json",
632
- title: "harnessed Manifest v1",
633
- description: "Per ADR 0001. Strict mode (additionalProperties: false everywhere).",
634
- allOf: matrixConstraints
635
702
  };
636
703
  }
637
704
  });
638
- function lineOf(node, lineCounter) {
639
- if (!node?.range) return null;
640
- const offset = node.range[0];
641
- return lineCounter.linePos(offset).line;
705
+
706
+ // src/checkpoint/planningScan.ts
707
+ var planningScan_exports = {};
708
+ __export(planningScan_exports, {
709
+ scanPlanning: () => scanPlanning
710
+ });
711
+ function scanPlanning(opts = {}) {
712
+ const repoRoot = opts.repoRoot ?? process.cwd();
713
+ const wf = opts.currentWorkflow ?? null;
714
+ return {
715
+ subProgress: wf?.sub_progress ?? [],
716
+ currentPhase: wf?.phase ?? null,
717
+ phases: scanPhases(repoRoot, opts.includeTasks ?? false)
718
+ };
642
719
  }
643
- function checkCmdString(cmd) {
644
- for (const pat of PATTERNS) {
645
- if (pat.test(cmd)) return { label: pat.label, hint: pat.hint };
720
+ function scanPhases(repoRoot, includeTasks) {
721
+ try {
722
+ const phasesDir = join(repoRoot, ".planning", "phases");
723
+ if (!existsSync(phasesDir)) return [];
724
+ const out = [];
725
+ for (const dir of readdirSync(phasesDir)) {
726
+ const m = PHASE_DIR.exec(dir);
727
+ const num = m?.[1];
728
+ if (!num) continue;
729
+ const dirPath = join(phasesDir, dir);
730
+ let entries;
731
+ try {
732
+ entries = readdirSync(dirPath);
733
+ } catch {
734
+ continue;
735
+ }
736
+ let plans = 0;
737
+ let summaries = 0;
738
+ const prefix = `${num}-`;
739
+ for (const f of entries) {
740
+ if (!f.startsWith(prefix)) continue;
741
+ if (f.endsWith("-PLAN.md")) plans++;
742
+ else if (f.endsWith("-SUMMARY.md")) summaries++;
743
+ }
744
+ const complete2 = plans > 0 && summaries >= plans;
745
+ const phase = {
746
+ phase: num,
747
+ name: m?.[2] ?? "",
748
+ plans,
749
+ summaries,
750
+ complete: complete2,
751
+ order: Number.parseFloat(num)
752
+ };
753
+ if (includeTasks && !complete2) phase.tasks = scanTasks(dirPath);
754
+ out.push(phase);
755
+ }
756
+ out.sort((a, b) => a.order - b.order);
757
+ return out;
758
+ } catch {
759
+ return [];
646
760
  }
647
- return null;
648
761
  }
649
- function checkScalarCmd(doc, lineCounter, path, filename) {
650
- const node = doc.getIn(path, true);
651
- if (!node || !isScalar(node)) return null;
652
- const value = node.value;
653
- if (typeof value !== "string") return null;
654
- for (const pat of PATTERNS) {
655
- if (pat.test(value)) {
656
- return {
657
- file: filename,
658
- path: `/${path.join("/")}`,
659
- message: `shell escape detected: '${pat.label}' (${pat.hint}) at ${path.join(".")} \u2014 v0.1 forbids dynamic shell evaluation; v0.2 will use \`requires_secret\` + \`\${secret:KEY}\` for env placeholders`,
660
- line: lineOf(node, lineCounter),
661
- column: null,
662
- keyword: "security"
663
- };
762
+ function scanTasks(dirPath) {
763
+ for (const fname of ["task_plan.md", "progress.md"]) {
764
+ try {
765
+ const p5 = join(dirPath, fname);
766
+ if (!existsSync(p5)) continue;
767
+ const m = /^[ \t]*- \[ \]\s+(.+)$/m.exec(readFileSync(p5, "utf8"));
768
+ const task = m?.[1];
769
+ if (task) return { nextUnchecked: task.trim() };
770
+ } catch {
664
771
  }
665
772
  }
666
- return null;
773
+ return { nextUnchecked: null };
667
774
  }
668
- function checkSecurityViolations(doc, filename, lineCounter) {
669
- const errors = [];
670
- const cmdPaths = [
671
- ["spec", "install", "cmd"],
672
- ["spec", "verify", "cmd"],
673
- ["spec", "uninstall", "cmd"]
674
- ];
675
- for (const p5 of cmdPaths) {
676
- const err2 = checkScalarCmd(doc, lineCounter, p5, filename);
677
- if (err2) errors.push(err2);
678
- }
679
- const cleanupNode = doc.getIn(["spec", "uninstall", "cleanup_paths"], true);
680
- if (cleanupNode && isSeq(cleanupNode)) {
681
- cleanupNode.items.forEach((item, idx) => {
682
- if (!isScalar(item)) return;
683
- const value = item.value;
684
- if (typeof value !== "string") return;
685
- for (const pat of PATTERNS) {
686
- if (pat.test(value)) {
687
- errors.push({
688
- file: filename,
689
- path: `/spec/uninstall/cleanup_paths/${idx}`,
690
- message: `shell escape detected: '${pat.label}' (${pat.hint}) at spec.uninstall.cleanup_paths[${idx}] \u2014 v0.1 forbids dynamic shell evaluation`,
691
- line: lineOf(item, lineCounter),
692
- column: null,
693
- keyword: "security"
694
- });
695
- break;
696
- }
697
- }
698
- });
699
- }
700
- return errors;
701
- }
702
- var PATTERNS;
703
- var init_security = __esm({
704
- "src/manifest/security.ts"() {
705
- PATTERNS = [
706
- {
707
- label: "$(...)",
708
- hint: "POSIX command substitution",
709
- test: (s) => /\$\(/.test(s)
710
- },
711
- {
712
- // biome-ignore lint/suspicious/noTemplateCurlyInString: literal pattern label, not a JS template
713
- label: "${...}",
714
- // biome-ignore lint/suspicious/noTemplateCurlyInString: literal example in user-facing message
715
- hint: "variable expansion (v0.2 will whitelist `${secret:KEY}`)",
716
- test: (s) => /\$\{/.test(s)
717
- },
718
- {
719
- label: "backtick",
720
- hint: "old-style command substitution",
721
- test: (s) => /`/.test(s)
722
- }
723
- ];
775
+ var PHASE_DIR;
776
+ var init_planningScan = __esm({
777
+ "src/checkpoint/planningScan.ts"() {
778
+ PHASE_DIR = /^(\d+(?:\.\d+)?)-(.*)$/;
724
779
  }
725
780
  });
726
- function getValidator() {
727
- if (!_compiled) {
728
- _compiled = ajv.compile(ManifestSchema);
781
+
782
+ // src/checkpoint/ledger.ts
783
+ var ledger_exports = {};
784
+ __export(ledger_exports, {
785
+ markSub: () => markSub,
786
+ nextPending: () => nextPending,
787
+ seedLedger: () => seedLedger
788
+ });
789
+ function seedLedger(plan) {
790
+ const fireEntries = plan.fire.map(
791
+ (f, i) => ({
792
+ // missing order → Infinity so explicitly-ordered subs sort ahead while
793
+ // unordered ones retain relative input order (stabilized by idx).
794
+ order: f.order ?? Number.POSITIVE_INFINITY,
795
+ idx: i,
796
+ entry: { sub: f.sub, status: "pending", gate_fired: true }
797
+ })
798
+ );
799
+ fireEntries.sort((a, b) => a.order - b.order || a.idx - b.idx);
800
+ const skipEntries = plan.skip.map(
801
+ (s) => ({
802
+ sub: s.sub,
803
+ status: "skipped",
804
+ gate_fired: false,
805
+ reason: s.reason
806
+ })
807
+ );
808
+ return [...fireEntries.map((e) => e.entry), ...skipEntries];
809
+ }
810
+ function markSub(entries, sub, status, opts) {
811
+ const idx = entries.findIndex((e) => e.sub === sub);
812
+ if (idx === -1) {
813
+ throw new Error(
814
+ `markSub: sub '${sub}' not found in ledger (${entries.length} entries). It must be seeded before it can be marked.`
815
+ );
729
816
  }
730
- return _compiled;
817
+ const current = entries[idx];
818
+ const updated = { ...current, status };
819
+ if (status === "failed") updated.fail_count = (current.fail_count ?? 0) + 1;
820
+ if (opts?.evidence !== void 0) updated.evidence = opts.evidence;
821
+ if (opts?.evidence_status !== void 0) updated.evidence_status = opts.evidence_status;
822
+ const next = entries.slice();
823
+ next[idx] = updated;
824
+ return next;
731
825
  }
732
- function checkInstallTypeMismatch(manifest, filename) {
733
- const spec = manifest.spec;
734
- const installType = spec.install_type;
735
- const method = spec.install?.method;
736
- if (!installType || !method) return [];
737
- const allowed = INSTALL_TYPE_METHODS[installType];
738
- if (!allowed || allowed.includes(method)) return [];
739
- return [
740
- {
741
- file: filename,
742
- path: "spec.install.method",
743
- message: `install_type '${installType}' is not compatible with install.method '${method}' (ADR 0007 1:N closure \u2014 expected one of: ${allowed.join(", ")})`,
744
- line: null,
745
- column: null,
746
- keyword: "install-type-mismatch"
747
- }
748
- ];
826
+ function nextPending(entries) {
827
+ return entries.find((e) => e.status === "pending")?.sub ?? null;
749
828
  }
750
- function validateManifestFile(yamlSource, filename) {
751
- const lineCounter = new LineCounter();
752
- const doc = parseDocument(yamlSource, { lineCounter });
753
- if (doc.errors.length > 0) {
754
- return {
755
- ok: false,
756
- errors: doc.errors.map((e) => yamlParseErrorToFriendly(e, filename))
757
- };
758
- }
759
- const securityErrors = checkSecurityViolations(doc, filename, lineCounter);
760
- if (securityErrors.length > 0) {
761
- return { ok: false, errors: securityErrors };
829
+ var init_ledger = __esm({
830
+ "src/checkpoint/ledger.ts"() {
762
831
  }
763
- const data = doc.toJS();
764
- const validate = getValidator();
765
- if (!validate(data)) {
766
- const errs = validate.errors ?? [];
832
+ });
833
+
834
+ // src/checkpoint/deriveNext.ts
835
+ function deriveNext(snapshot) {
836
+ const pendingSub = nextPending(snapshot.subProgress);
837
+ if (pendingSub !== null) return { kind: "sub", sub: pendingSub };
838
+ const failed = snapshot.subProgress.find((e) => e.status === "failed" && (e.fail_count ?? 0) > 0);
839
+ if (failed) {
767
840
  return {
768
- ok: false,
769
- errors: errs.map((err2) => ajvErrorToFriendly(err2, filename, doc, lineCounter))
841
+ kind: "blocked",
842
+ unit: failed.sub,
843
+ reason: `sub '${failed.sub}' failed ${failed.fail_count}x \u2014 resolve before advancing`
770
844
  };
771
845
  }
772
- const manifest = data;
773
- const crossFieldErrors = checkInstallTypeMismatch(manifest, filename);
774
- if (crossFieldErrors.length > 0) {
775
- return { ok: false, errors: crossFieldErrors };
846
+ const firstIncomplete = snapshot.phases.find((p5) => !p5.complete);
847
+ if (firstIncomplete) {
848
+ const task = firstIncomplete.tasks?.nextUnchecked;
849
+ if (task) return { kind: "task", phase: firstIncomplete.phase, task };
850
+ return { kind: "phase", phase: firstIncomplete.phase, name: firstIncomplete.name };
776
851
  }
777
- return { ok: true, manifest };
852
+ return { kind: "done" };
778
853
  }
779
- var addFormats, ajv, _compiled, INSTALL_TYPE_METHODS;
780
- var init_validate = __esm({
781
- "src/manifest/validate.ts"() {
782
- init_errors();
783
- init_schema();
784
- init_security();
785
- addFormats = ajvFormatsNs.default;
786
- ajv = addFormats(
787
- new Ajv({
788
- strict: true,
789
- strictSchema: true,
790
- strictTypes: true,
791
- strictRequired: true,
792
- allErrors: true,
793
- discriminator: true,
794
- allowUnionTypes: false
795
- })
796
- );
797
- _compiled = null;
798
- INSTALL_TYPE_METHODS = {
799
- npm: ["npm-cli"],
800
- mcp: ["mcp-stdio-add", "mcp-http-add"],
801
- git: ["git-clone-with-setup"],
802
- skill: ["cc-plugin-marketplace", "npx-skill-installer"]
803
- };
854
+ var init_deriveNext = __esm({
855
+ "src/checkpoint/deriveNext.ts"() {
856
+ init_ledger();
804
857
  }
805
858
  });
806
859
 
807
- // src/cli/lib/origin-check.ts
808
- var origin_check_exports = {};
809
- __export(origin_check_exports, {
810
- checkOrigin: () => checkOrigin
811
- });
812
- function normalizeUrl(s) {
813
- return s.trim().replace(/^(https?:\/\/|git@github\.com:|ssh:\/\/git@github\.com\/)/, "").replace(/\.git$/, "").replace(":", "/").replace(/\/$/, "").toLowerCase();
860
+ // src/checkpoint/forwardStep.ts
861
+ var forwardStep_exports = {};
862
+ __export(forwardStep_exports, {
863
+ describeUnit: () => describeUnit,
864
+ resolveAdvance: () => resolveAdvance,
865
+ resolveForwardStep: () => resolveForwardStep
866
+ });
867
+ function describeUnit(unit) {
868
+ switch (unit.kind) {
869
+ case "phase":
870
+ return `phase ${unit.phase} '${unit.name}'`;
871
+ case "task":
872
+ return `task '${unit.task}' in phase ${unit.phase}`;
873
+ case "sub":
874
+ return `sub '${unit.sub}'`;
875
+ case "blocked":
876
+ return unit.unit;
877
+ case "done":
878
+ return null;
879
+ }
814
880
  }
815
- function checkOrigin(cwd = process.cwd(), opts = {}) {
816
- const allowFork = opts.allowFork ?? true;
817
- let expected = null;
818
- try {
819
- const pkg = JSON.parse(readFileSync(join(cwd, "package.json"), "utf8"));
820
- expected = typeof pkg.repository === "string" ? pkg.repository : pkg.repository?.url ?? null;
821
- } catch {
881
+ function remainingPhases(snapshot) {
882
+ return snapshot.phases.filter((p5) => !p5.complete).length;
883
+ }
884
+ function pluralPhases(n) {
885
+ return `${n} phase${n === 1 ? "" : "s"} remain`;
886
+ }
887
+ function resolveForwardStep(snapshot) {
888
+ const unit = deriveNext(snapshot);
889
+ switch (unit.kind) {
890
+ case "done":
891
+ return {
892
+ next: "done",
893
+ unit,
894
+ exitCode: 2,
895
+ lines: ["NEXT: done"],
896
+ json: { next: "done", unit: null, hint: null }
897
+ };
898
+ case "blocked": {
899
+ const u = describeUnit(unit) ?? unit.unit;
900
+ return {
901
+ next: "blocked",
902
+ unit,
903
+ exitCode: 10,
904
+ lines: ["NEXT: blocked", `UNIT: ${u}`, `HINT: ${unit.reason}`],
905
+ json: { next: "blocked", unit: u, hint: unit.reason }
906
+ };
907
+ }
908
+ default: {
909
+ const u = describeUnit(unit) ?? "";
910
+ const hint = `run /auto (or harnessed advance) to start it \u2014 ${pluralPhases(remainingPhases(snapshot))}`;
911
+ return {
912
+ next: "advance",
913
+ unit,
914
+ exitCode: 0,
915
+ lines: ["NEXT: advance", `UNIT: ${u}`, `HINT: ${hint}`],
916
+ json: { next: "advance", unit: u, hint }
917
+ };
918
+ }
822
919
  }
823
- if (!expected) {
920
+ }
921
+ function detectGate(snapshot, unit) {
922
+ if (unit.kind === "blocked") {
923
+ return { unit: describeUnit(unit) ?? unit.unit, reason: unit.reason, code: 10 };
924
+ }
925
+ if (unit.kind === "phase" || unit.kind === "task") {
926
+ const pointer = snapshot.currentPhase;
927
+ if (pointer != null) {
928
+ const pointerOrder = Number.parseFloat(pointer);
929
+ const derivedOrder = Number.parseFloat(unit.phase);
930
+ if (Number.isFinite(pointerOrder) && Number.isFinite(derivedOrder) && derivedOrder < pointerOrder) {
931
+ return {
932
+ unit: describeUnit(unit) ?? unit.phase,
933
+ reason: `phase ${unit.phase} is incomplete but the workflow pointer ran ahead to ${pointer}`,
934
+ code: 11
935
+ };
936
+ }
937
+ }
938
+ }
939
+ return null;
940
+ }
941
+ function resolveAdvance(snapshot, force = false) {
942
+ const unit = deriveNext(snapshot);
943
+ if (unit.kind === "done") {
824
944
  return {
825
- status: "warn",
826
- detail: "package.json has no repository.url field",
827
- fix: "add `repository` field to package.json"
945
+ next: "done",
946
+ unit,
947
+ exitCode: 2,
948
+ lines: ["ADVANCE: done \u2014 all phases complete"],
949
+ json: { next: "done", unit: null, hint: null }
828
950
  };
829
951
  }
830
- const r = spawnSync("git", ["config", "--get", "remote.origin.url"], {
831
- cwd,
832
- encoding: "utf8"
833
- });
834
- if (r.status !== 0) {
952
+ const gate = detectGate(snapshot, unit);
953
+ if (gate && !force) {
835
954
  return {
836
- status: "warn",
837
- detail: "no git remote origin (detached / non-clone)",
838
- fix: "git remote add origin <expected-url>"
955
+ next: "gate-reject",
956
+ unit,
957
+ exitCode: gate.code,
958
+ lines: [
959
+ `ADVANCE: refused \u2014 ${gate.reason}`,
960
+ `UNFINISHED: ${gate.unit}`,
961
+ "HINT: finish it, or pass --force to override (records an audit note)"
962
+ ],
963
+ json: { next: "gate-reject", unit: gate.unit, hint: gate.reason }
839
964
  };
840
965
  }
841
- const actual = r.stdout.trim();
842
- if (normalizeUrl(actual) === normalizeUrl(expected)) {
843
- return { status: "pass", detail: actual };
966
+ const u = describeUnit(unit) ?? "";
967
+ const cmd = `\u2192 run /auto "${u}"`;
968
+ const lines = [];
969
+ if (gate && force) {
970
+ lines.push(`AUDIT: --force override \u2014 advancing past unfinished ${gate.unit} (${gate.reason})`);
844
971
  }
972
+ lines.push("ADVANCE: advance", `UNIT: ${u}`, cmd);
845
973
  return {
846
- status: allowFork ? "warn" : "fail",
847
- detail: `origin '${actual}' \u2260 expected '${expected}'`,
848
- fix: allowFork ? "verify intentional fork; if not, `git remote set-url origin <expected>`" : "origin URL drift \u2014 possible tamper, `git remote set-url origin <expected>` to restore"
974
+ next: "advance",
975
+ unit,
976
+ exitCode: 0,
977
+ lines,
978
+ json: { next: "advance", unit: u, hint: cmd }
849
979
  };
850
980
  }
851
- var init_origin_check = __esm({
852
- "src/cli/lib/origin-check.ts"() {
981
+ var init_forwardStep = __esm({
982
+ "src/checkpoint/forwardStep.ts"() {
983
+ init_deriveNext();
853
984
  }
854
985
  });
855
- function mapToSupported(raw) {
856
- if (!raw) return "en";
857
- if (/^zh([^a-z]|$)/i.test(raw)) return "zh-Hans";
858
- return "en";
859
- }
860
- function detectLocale() {
861
- const raw = process.env.HARNESSED_LANG || process.env.LC_ALL || process.env.LANG || process.env.LANGUAGE || safeIntlLocale();
862
- return mapToSupported(raw);
986
+
987
+ // src/manifest/errors.ts
988
+ function instancePathToKeyPath(instancePath) {
989
+ if (!instancePath || instancePath === "/") return [];
990
+ return instancePath.split("/").filter(Boolean).map((seg) => {
991
+ const n = Number(seg);
992
+ return Number.isInteger(n) && String(n) === seg ? n : seg;
993
+ });
863
994
  }
864
- function safeIntlLocale() {
865
- try {
866
- return Intl.DateTimeFormat().resolvedOptions().locale;
867
- } catch {
868
- return void 0;
995
+ function locateLineFromDoc(doc, lineCounter, instancePath) {
996
+ const path = instancePathToKeyPath(instancePath);
997
+ let node;
998
+ if (path.length === 0) {
999
+ node = doc.contents;
1000
+ } else {
1001
+ node = doc.getIn(path, true);
869
1002
  }
1003
+ if (!node || typeof node !== "object") return { line: null, column: null };
1004
+ const range = node.range;
1005
+ if (!range) return { line: null, column: null };
1006
+ const offset = range[0];
1007
+ const pos = lineCounter.linePos(offset);
1008
+ return { line: pos.line, column: pos.col };
870
1009
  }
871
- function messagesDir() {
872
- const here = dirname(fileURLToPath(import.meta.url));
873
- const candidates = [resolve(here, "..", "..", "messages"), resolve(here, "..", "messages")];
874
- for (const c of candidates) {
875
- try {
876
- readFileSync(join(c, "en.json"), "utf8");
877
- return c;
878
- } catch {
879
- }
880
- }
881
- return resolve(process.cwd(), "messages");
882
- }
883
- function loadLocale(locale) {
884
- if (cache[locale]) return cache[locale];
885
- const path = join(messagesDir(), `${locale}.json`);
886
- try {
887
- const raw = readFileSync(path, "utf8");
888
- cache[locale] = JSON.parse(raw);
889
- } catch {
890
- cache[locale] = {};
891
- }
892
- return cache[locale];
893
- }
894
- function setLocale(locale) {
895
- if (!locale) return;
896
- const mapped = mapToSupported(locale);
897
- if (SUPPORTED.has(mapped)) currentLocale = mapped;
898
- }
899
- function getLocale() {
900
- if (currentLocale === null) currentLocale = detectLocale();
901
- return currentLocale;
902
- }
903
- function t(key, params) {
904
- const locale = getLocale();
905
- const primary = loadLocale(locale);
906
- let template = primary[key];
907
- if (template === void 0 && locale !== "en") {
908
- template = loadLocale("en")[key];
1010
+ function ajvErrorToFriendly(err2, file, doc, lineCounter) {
1011
+ let path = err2.instancePath || "/";
1012
+ const params = err2.params;
1013
+ if (err2.keyword === "additionalProperties" && params && typeof params.additionalProperty === "string") {
1014
+ path = `${path}/${params.additionalProperty}`;
1015
+ } else if (err2.keyword === "required" && params && typeof params.missingProperty === "string") {
1016
+ path = `${path}/${params.missingProperty}`;
909
1017
  }
910
- if (template === void 0) template = key;
911
- if (!params) return template;
912
- return template.replace(/\{\{(\w+)\}\}/g, (_match, name) => {
913
- const v = params[name];
914
- return v === void 0 ? `{{${name}}}` : String(v);
915
- });
916
- }
917
- var SUPPORTED, currentLocale, cache;
918
- var init_i18n = __esm({
919
- "src/i18n/index.ts"() {
920
- SUPPORTED = /* @__PURE__ */ new Set(["en", "zh-Hans"]);
921
- currentLocale = null;
922
- cache = {};
1018
+ let line = null;
1019
+ let column = null;
1020
+ if (doc && lineCounter) {
1021
+ const lookupPath = err2.keyword === "required" ? err2.instancePath || "/" : path;
1022
+ const loc = locateLineFromDoc(doc, lineCounter, lookupPath);
1023
+ line = loc.line;
1024
+ column = loc.column;
923
1025
  }
924
- });
925
- function claudeDescriptor(home = homedir()) {
926
- const claudeHome = join(home, ".claude");
927
1026
  return {
928
- id: "claude",
929
- homeDir: claudeHome,
930
- stateRoot: join(claudeHome, "harnessed"),
931
- settingsPath: join(claudeHome, "settings.json"),
932
- skillsDir: join(claudeHome, "skills"),
933
- commandsDir: join(claudeHome, "commands"),
934
- pluginsRegistry: join(claudeHome, "plugins", "installed_plugins.json"),
935
- // mcpConfigPath is a SIBLING of `.claude` (`<home>/.claude.json`), based on
936
- // the same home base — not a child of homeDir.
937
- mcpConfigPath: join(home, ".claude.json"),
938
- // claude writes its env keys into JSON settings.json (capability present).
939
- supportsEnvKeyWrite: true,
940
- // Claude Code exposes the active session id to Bash-invoked CLI + hooks.
941
- sessionIdEnv: "CLAUDE_CODE_SESSION_ID"
1027
+ file,
1028
+ path,
1029
+ message: err2.message ?? "unknown error",
1030
+ line,
1031
+ column,
1032
+ keyword: err2.keyword
942
1033
  };
943
1034
  }
944
- function codexDescriptor(home = homedir()) {
945
- const codexHome = join(home, ".codex");
946
- const configToml = join(codexHome, "config.toml");
1035
+ function yamlParseErrorToFriendly(err2, file) {
947
1036
  return {
948
- id: "codex",
949
- homeDir: codexHome,
950
- stateRoot: join(codexHome, "harnessed"),
951
- settingsPath: configToml,
952
- // SHARED convention dir, NOT <homeDir>/skills.
953
- skillsDir: join(home, ".agents", "skills"),
954
- commandsDir: join(codexHome, "prompts"),
955
- pluginsRegistry: null,
956
- mcpConfigPath: configToml,
957
- supportsEnvKeyWrite: false,
958
- // No verified codex session-id env → single-session fallback (anti-stale).
959
- sessionIdEnv: null
1037
+ file,
1038
+ path: "/",
1039
+ message: err2.message,
1040
+ line: err2.linePos?.[0]?.line ?? null,
1041
+ column: err2.linePos?.[0]?.col ?? null,
1042
+ keyword: "yaml-parse"
960
1043
  };
961
1044
  }
962
- function descriptorById(id, home) {
963
- if (id === "claude") return claudeDescriptor(home);
964
- if (id === "codex") return codexDescriptor(home);
965
- return void 0;
966
- }
967
- function detectPlatform(home = homedir()) {
968
- const base = claudeDescriptor(home);
969
- const override = process.env.HARNESSED_ROOT_OVERRIDE;
970
- if (override !== void 0 && override !== "") return { ...base, stateRoot: override };
971
- const envPlatform = process.env.HARNESSED_PLATFORM;
972
- if (envPlatform !== void 0 && envPlatform !== "") {
973
- const d = descriptorById(envPlatform, home);
974
- if (d) return d;
975
- }
976
- try {
977
- const pin = readFileSync(join(base.stateRoot, ".platform"), "utf8").trim();
978
- const d = descriptorById(pin, home);
979
- if (d) return d;
980
- } catch {
981
- }
982
- try {
983
- if (existsSync(base.homeDir)) return base;
984
- const codex = codexDescriptor(home);
985
- if (existsSync(codex.homeDir)) return codex;
986
- } catch {
987
- }
988
- return base;
989
- }
990
- function getSettingsPath(home) {
991
- return detectPlatform(home).settingsPath;
992
- }
993
- function getSkillsDir(home) {
994
- return detectPlatform(home).skillsDir;
995
- }
996
- function getCommandsDir(home) {
997
- return detectPlatform(home).commandsDir;
998
- }
999
- function getPluginsRegistry(home) {
1000
- return detectPlatform(home).pluginsRegistry;
1001
- }
1002
- function getMcpConfigPath(home) {
1003
- return detectPlatform(home).mcpConfigPath;
1004
- }
1005
- function harnessSkillsDirs(home) {
1006
- const dirs = [claudeDescriptor(home).skillsDir, codexDescriptor(home).skillsDir];
1007
- return [...new Set(dirs)];
1008
- }
1009
- var init_platform = __esm({
1010
- "src/installers/lib/platform.ts"() {
1045
+ var init_errors = __esm({
1046
+ "src/manifest/errors.ts"() {
1011
1047
  }
1012
1048
  });
1013
- function getHarnessedRoot() {
1014
- return detectPlatform().stateRoot;
1015
- }
1016
- function harnessedSubdir(name) {
1017
- return join(getHarnessedRoot(), name);
1018
- }
1019
- function harnessedFile(name) {
1020
- return join(getHarnessedRoot(), name);
1021
- }
1022
- function migrateLegacyHarnessedRoot() {
1023
- const legacyRoot = join(homedir(), ".harnessed");
1024
- const newRoot = join(homedir(), ".claude", "harnessed");
1025
- const claudeParent = join(homedir(), ".claude");
1026
- if (!existsSync(legacyRoot)) return;
1027
- if (!existsSync(newRoot)) {
1028
- mkdirSync(claudeParent, { recursive: true });
1029
- renameSync(legacyRoot, newRoot);
1030
- console.error(
1031
- `[harnessed] migrated legacy state directory ${legacyRoot} \u2192 ${newRoot} (v3.0.3 path change)`
1049
+ var ApiVersion, Kind, SpdxLicense, LicenseSource, Upstream, MetadataSchema;
1050
+ var init_metadata = __esm({
1051
+ "src/manifest/schema/metadata.ts"() {
1052
+ ApiVersion = Type.Literal("harnessed/v1");
1053
+ Kind = Type.Literal("Manifest");
1054
+ SpdxLicense = Type.Union([
1055
+ Type.Literal("MIT"),
1056
+ Type.Literal("Apache-2.0"),
1057
+ Type.Literal("BSD-3-Clause"),
1058
+ Type.Literal("ISC"),
1059
+ Type.Literal("0BSD"),
1060
+ Type.Literal("MIT-0"),
1061
+ Type.Literal("anthropics-official")
1062
+ ]);
1063
+ LicenseSource = Type.Union([
1064
+ Type.Literal("README"),
1065
+ Type.Literal("registry"),
1066
+ Type.Literal("none"),
1067
+ Type.Literal("anthropics-official")
1068
+ ]);
1069
+ Upstream = Type.Object(
1070
+ {
1071
+ source: Type.String({ minLength: 1 }),
1072
+ homepage: Type.String({ format: "uri" }),
1073
+ repository: Type.String({ format: "uri" }),
1074
+ license: SpdxLicense,
1075
+ license_source: Type.Optional(LicenseSource),
1076
+ notice: Type.String({ minLength: 1, maxLength: 500 })
1077
+ },
1078
+ { additionalProperties: false }
1032
1079
  );
1033
- return;
1034
- }
1035
- const safetyBak = join(homedir(), ".harnessed.legacy-bak");
1036
- if (existsSync(safetyBak)) {
1037
- console.error(
1038
- `[harnessed] WARN: ${legacyRoot} reappeared after a prior migration (existing bak at ${safetyBak}); leaving in place \u2014 inspect manually if needed`
1080
+ MetadataSchema = Type.Object(
1081
+ {
1082
+ name: Type.String({ pattern: "^[a-z0-9][a-z0-9-]*$", minLength: 1 }),
1083
+ display_name: Type.Optional(Type.String()),
1084
+ description: Type.String({ minLength: 1, maxLength: 120 }),
1085
+ upstream: Upstream
1086
+ },
1087
+ { additionalProperties: false }
1039
1088
  );
1040
- return;
1041
- }
1042
- renameSync(legacyRoot, safetyBak);
1043
- console.error(
1044
- `[harnessed] both ${legacyRoot} and ${newRoot} existed \u2014 legacy directory preserved at ${safetyBak} (review manually if you need data from it; v3.0.3 path change)`
1045
- );
1046
- }
1047
- var init_harnessedRoot = __esm({
1048
- "src/installers/lib/harnessedRoot.ts"() {
1049
- init_platform();
1050
1089
  }
1051
1090
  });
1052
- function getBackupRoot() {
1053
- return harnessedSubdir("backups");
1054
- }
1055
- function mirrorPath(target, scope, backupDir) {
1056
- const root = scope === "HOME" ? HOME_DIR : ".";
1057
- const rel = root ? relative(root, target) : target;
1058
- if (!rel || rel.startsWith("..")) {
1059
- const flat = createHash("sha1").update(target).digest("hex").slice(0, 16);
1060
- return join(backupDir, scope, flat);
1061
- }
1062
- return join(backupDir, scope, rel);
1063
- }
1064
- function detectEol(buf) {
1065
- return buf.includes("\r\n") ? "crlf" : "lf";
1066
- }
1067
- async function backup(plan, ctx) {
1068
- const filename = ctx.manifest.metadata.name;
1069
- const backupId = (/* @__PURE__ */ new Date()).toISOString().replace(/:/g, "-");
1070
- const backupDir = join(getBackupRoot(), backupId);
1071
- try {
1072
- await mkdir(backupDir, { recursive: true });
1073
- } catch (err2) {
1074
- return {
1075
- ok: false,
1076
- error: {
1077
- file: filename,
1078
- path: "/",
1079
- message: `failed to create backup dir ${backupDir}: ${err2.message}`,
1080
- line: null,
1081
- column: null,
1082
- keyword: "backup-mkdir-failed"
1083
- }
1084
- };
1085
- }
1086
- const entries = [];
1087
- for (const file of plan.files) {
1088
- let buf;
1089
- try {
1090
- buf = await readFile(file.target);
1091
- } catch (err2) {
1092
- const code = err2.code;
1093
- if (code === "ENOENT" && file.oldText === "") {
1094
- entries.push({
1095
- target: file.target,
1096
- backup: "",
1097
- // sentinel: no backup written; rollback should unlink target
1098
- sha1: "",
1099
- eol: "lf"
1100
- // moot for non-existent file; default to lf
1101
- });
1102
- continue;
1103
- }
1104
- if (code === "EISDIR") {
1105
- entries.push({ target: file.target, backup: "", sha1: "", eol: "lf" });
1106
- continue;
1107
- }
1108
- return {
1109
- ok: false,
1110
- error: {
1111
- file: filename,
1112
- path: file.target,
1113
- message: `failed to read original file for backup: ${err2.message}`,
1114
- line: null,
1115
- column: null,
1116
- keyword: "backup-read-failed"
1117
- }
1118
- };
1119
- }
1120
- const sha1 = createHash("sha1").update(buf).digest("hex");
1121
- const eol = detectEol(buf);
1122
- const dest = mirrorPath(file.target, file.scope, backupDir);
1123
- try {
1124
- await mkdir(dirname(dest), { recursive: true });
1125
- await writeFile(dest, buf);
1126
- } catch (err2) {
1127
- return {
1128
- ok: false,
1129
- error: {
1130
- file: filename,
1131
- path: dest,
1132
- message: `failed to write backup copy: ${err2.message}`,
1133
- line: null,
1134
- column: null,
1135
- keyword: "backup-write-failed"
1136
- }
1137
- };
1138
- }
1139
- entries.push({ target: file.target, backup: dest, sha1, eol });
1140
- }
1141
- const metadata = {
1142
- installer: filename,
1143
- manifest: filename,
1144
- timestamp: backupId,
1145
- files: entries
1146
- };
1147
- const metadataPath = join(backupDir, "metadata.json");
1148
- try {
1149
- await writeFile(metadataPath, `${JSON.stringify(metadata, null, 2)}
1150
- `, "utf8");
1151
- } catch (err2) {
1152
- return {
1153
- ok: false,
1154
- error: {
1155
- file: filename,
1156
- path: metadataPath,
1157
- message: `failed to write metadata.json: ${err2.message}`,
1158
- line: null,
1159
- column: null,
1160
- keyword: "backup-metadata-failed"
1161
- }
1162
- };
1163
- }
1164
- return { ok: true, backupId, backupDir };
1165
- }
1166
- var HOME_DIR;
1167
- var init_backup = __esm({
1168
- "src/installers/lib/backup.ts"() {
1169
- init_harnessedRoot();
1170
- HOME_DIR = process.env.HOME ?? process.env.USERPROFILE ?? "";
1171
- }
1172
- });
1173
-
1174
- // src/manifest/lib/path-guard.ts
1175
- function checkPathSafe(input) {
1176
- for (const re of PATH_TRAVERSAL_PATTERNS) {
1177
- if (re.test(input)) throw new PathTraversalError();
1178
- }
1179
- }
1180
- var PATH_TRAVERSAL_PATTERNS, PathTraversalError;
1181
- var init_path_guard = __esm({
1182
- "src/manifest/lib/path-guard.ts"() {
1183
- PATH_TRAVERSAL_PATTERNS = [
1184
- /\.\.\//,
1185
- // (1) Unix dot-dot-slash: ../../etc/passwd
1186
- /\.\.\\/,
1187
- // (2) Windows backslash: ..\windows\system32
1188
- // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional null-byte injection detection (R10.4 D-03 OWASP A1 vector 3)
1189
- /\x00/,
1190
- // (3) Null byte injection: path\x00attack
1191
- /%2[eE]%2[eE]/,
1192
- // (4) URL-encoded dot-dot: %2e%2e%2fetc
1193
- /%25[2][eE]%25[2][eE]/
1194
- // (5) Double-encoded: %252e%252e%252f
1195
- ];
1196
- PathTraversalError = class _PathTraversalError extends Error {
1197
- constructor() {
1198
- super("path traversal attempt detected");
1199
- this.name = "PathTraversalError";
1200
- Object.setPrototypeOf(this, _PathTraversalError.prototype);
1201
- }
1202
- };
1091
+ var HookEvent, CcHookAdd;
1092
+ var init_ccHookAdd = __esm({
1093
+ "src/manifest/schema/installMethods/ccHookAdd.ts"() {
1094
+ HookEvent = Type.Union([
1095
+ Type.Literal("SessionStart"),
1096
+ Type.Literal("UserPromptSubmit"),
1097
+ Type.Literal("PreToolUse"),
1098
+ Type.Literal("PostToolUse")
1099
+ ]);
1100
+ CcHookAdd = Type.Object(
1101
+ {
1102
+ method: Type.Literal("cc-hook-add"),
1103
+ cmd: Type.String({ minLength: 1 }),
1104
+ // audit-trail (the bash invocation registered)
1105
+ // cwd/env required by lib/spawn.ts discriminated-union access (sister 6 method
1106
+ // shape parity — even though cc-hook-add does not spawn, generic spawn helper
1107
+ // expects these fields on the install union).
1108
+ cwd: Type.Optional(Type.String()),
1109
+ env: Type.Optional(Type.Record(Type.String(), Type.String())),
1110
+ hook_event: HookEvent,
1111
+ hook_matcher: Type.Optional(Type.String()),
1112
+ hook_command: Type.String({ minLength: 1 }),
1113
+ idempotent_check: Type.String({ minLength: 1 })
1114
+ },
1115
+ { additionalProperties: false }
1116
+ );
1203
1117
  }
1204
1118
  });
1205
-
1206
- // src/checkpoint/ledger.ts
1207
- var ledger_exports = {};
1208
- __export(ledger_exports, {
1209
- markSub: () => markSub,
1210
- nextPending: () => nextPending,
1211
- seedLedger: () => seedLedger
1212
- });
1213
- function seedLedger(plan) {
1214
- const fireEntries = plan.fire.map(
1215
- (f, i) => ({
1216
- // missing order → Infinity so explicitly-ordered subs sort ahead while
1217
- // unordered ones retain relative input order (stabilized by idx).
1218
- order: f.order ?? Number.POSITIVE_INFINITY,
1219
- idx: i,
1220
- entry: { sub: f.sub, status: "pending", gate_fired: true }
1221
- })
1222
- );
1223
- fireEntries.sort((a, b) => a.order - b.order || a.idx - b.idx);
1224
- const skipEntries = plan.skip.map(
1225
- (s) => ({
1226
- sub: s.sub,
1227
- status: "skipped",
1228
- gate_fired: false,
1229
- reason: s.reason
1230
- })
1231
- );
1232
- return [...fireEntries.map((e) => e.entry), ...skipEntries];
1233
- }
1234
- function markSub(entries, sub, status, opts) {
1235
- const idx = entries.findIndex((e) => e.sub === sub);
1236
- if (idx === -1) {
1237
- throw new Error(
1238
- `markSub: sub '${sub}' not found in ledger (${entries.length} entries). It must be seeded before it can be marked.`
1119
+ var GIT_REF_PATTERN, REPO_PATTERN, CcPluginMarketplace;
1120
+ var init_ccPluginMarketplace = __esm({
1121
+ "src/manifest/schema/installMethods/ccPluginMarketplace.ts"() {
1122
+ GIT_REF_PATTERN = "^([a-f0-9]{7,40}|v?\\d+\\.\\d+\\.\\d+([.-][\\w.-]+)?)$";
1123
+ REPO_PATTERN = "^[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+$";
1124
+ CcPluginMarketplace = Type.Object(
1125
+ {
1126
+ method: Type.Literal("cc-plugin-marketplace"),
1127
+ cmd: Type.String({ minLength: 1 }),
1128
+ cwd: Type.Optional(Type.String()),
1129
+ env: Type.Optional(Type.Record(Type.String(), Type.String())),
1130
+ args: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
1131
+ git_ref: Type.String({ minLength: 1, pattern: GIT_REF_PATTERN }),
1132
+ idempotent_check: Type.String({ minLength: 1 }),
1133
+ // ADR 0005 — third-party marketplace structured metadata (optional).
1134
+ marketplace_source: Type.Optional(
1135
+ Type.Object(
1136
+ {
1137
+ source: Type.Literal("github"),
1138
+ repo: Type.String({ pattern: REPO_PATTERN, minLength: 3 })
1139
+ },
1140
+ { additionalProperties: false }
1141
+ )
1142
+ )
1143
+ },
1144
+ { additionalProperties: false }
1239
1145
  );
1240
1146
  }
1241
- const current = entries[idx];
1242
- const updated = { ...current, status };
1243
- if (status === "failed") updated.fail_count = (current.fail_count ?? 0) + 1;
1244
- if (opts?.evidence !== void 0) updated.evidence = opts.evidence;
1245
- if (opts?.evidence_status !== void 0) updated.evidence_status = opts.evidence_status;
1246
- const next = entries.slice();
1247
- next[idx] = updated;
1248
- return next;
1249
- }
1250
- function nextPending(entries) {
1251
- return entries.find((e) => e.status === "pending")?.sub ?? null;
1252
- }
1253
- var init_ledger = __esm({
1254
- "src/checkpoint/ledger.ts"() {
1255
- }
1256
1147
  });
1257
- function branchOnSchemaVersion(v, handlers) {
1258
- const isKnownVersion = Object.values(SCHEMA_VERSIONS).includes(v);
1259
- return isKnownVersion ? handlers.v1() : handlers.unknown();
1260
- }
1261
- var SCHEMA_VERSIONS;
1262
- var init_schemaVersion = __esm({
1263
- "src/types/schemaVersion.ts"() {
1264
- SCHEMA_VERSIONS = {
1265
- routingSnapshot: "harnessed.routing-snapshot.v1",
1266
- handoffDoc: "harnessed.handoff-doc.v1",
1267
- phasesYaml: "harnessed.phases-yaml.v1",
1268
- manifestState: "harnessed.manifest-state.v1",
1269
- installerState: "harnessed.installer-state.v1",
1270
- routeDecisionLog: "harnessed.route-decision-log.v1",
1271
- checkpoint: "harnessed.checkpoint.v1",
1272
- currentWorkflow: "harnessed.current-workflow.v1",
1273
- // ← Phase 3.1 W1 T1.1 ADD (D-02 KARPATHY 3-state)
1274
- workflowStore: "harnessed.workflow-store.v1",
1275
- // ← Phase 15 ADD (per-repo multi-workflow store)
1276
- config: "harnessed.config.v1",
1277
- // ← Phase 3.2 W1 T1.1 ADD (D-01 PROBE gstack_prefix store)
1278
- governance: "harnessed.governance.v1",
1279
- // ← Phase 3.2 W1 T1.1 ADD (D-04 PUSH veto status)
1280
- aliases: "harnessed.aliases.v1",
1281
- // ← Phase 3.3 W1 T1.1 ADD (D-01 RICH)
1282
- knownGood: "harnessed.known-good.v1",
1283
- // ← Phase 3.3 W1 T1.1 ADD (D-03 YAML manifest)
1284
- capabilities: "harnessed.capabilities.v1",
1285
- // ← Phase v2.0-2.3 W0 ADD (R20.2 flat yaml capabilities manifest validate)
1286
- judgment: "harnessed.judgment.v1",
1287
- // ← Phase v2.0-2.3 W0 ADD (R20.4 multi-file judgments validate)
1288
- workflow: "harnessed.workflow.v2",
1289
- // ← Phase v2.0-2.4 W0 T2.4.W0.1 ADD (R20.1+R20.2+R20.9 workflow.yaml v2)
1290
- workflow_v3: "harnessed.workflow.v3",
1291
- // ← Phase v3.0-3.3 W0 T3.3.W0.11 ADD (D-09 disciplines_applied + D-05 tools_available + master delegates_to per Pattern A B.1 LOCK)
1292
- discipline: "harnessed.discipline.v1"
1293
- // ← Phase v3.0-3.3 W0 T3.3.W0.11 ADD (D-09 L0 Discipline Substrate, sister judgment.v1 multi-file pattern)
1294
- };
1295
- Type.Union([
1296
- Type.Literal(SCHEMA_VERSIONS.routingSnapshot),
1297
- Type.Literal(SCHEMA_VERSIONS.handoffDoc),
1298
- Type.Literal(SCHEMA_VERSIONS.phasesYaml),
1299
- Type.Literal(SCHEMA_VERSIONS.manifestState),
1300
- Type.Literal(SCHEMA_VERSIONS.installerState),
1301
- Type.Literal(SCHEMA_VERSIONS.routeDecisionLog),
1302
- Type.Literal(SCHEMA_VERSIONS.checkpoint),
1303
- Type.Literal(SCHEMA_VERSIONS.currentWorkflow),
1304
- // ← Phase 3.1 W1 T1.1 ADD
1305
- Type.Literal(SCHEMA_VERSIONS.workflowStore),
1306
- // ← Phase 15 ADD
1307
- Type.Literal(SCHEMA_VERSIONS.config),
1308
- // ← Phase 3.2 W1 T1.1 ADD
1309
- Type.Literal(SCHEMA_VERSIONS.governance),
1310
- // ← Phase 3.2 W1 T1.1 ADD
1311
- Type.Literal(SCHEMA_VERSIONS.aliases),
1312
- // ← Phase 3.3 W1 T1.1 ADD
1313
- Type.Literal(SCHEMA_VERSIONS.knownGood),
1314
- // ← Phase 3.3 W1 T1.1 ADD
1315
- Type.Literal(SCHEMA_VERSIONS.capabilities),
1316
- // ← Phase v2.0-2.3 W0 ADD
1317
- Type.Literal(SCHEMA_VERSIONS.judgment),
1318
- // ← Phase v2.0-2.3 W0 ADD
1319
- Type.Literal(SCHEMA_VERSIONS.workflow),
1320
- // ← Phase v2.0-2.4 W0 T2.4.W0.1 ADD (first .v2 in union)
1321
- Type.Literal(SCHEMA_VERSIONS.workflow_v3),
1322
- // ← Phase v3.0-3.3 W0 T3.3.W0.11 ADD (first .v3 in union)
1323
- Type.Literal(SCHEMA_VERSIONS.discipline)
1324
- // ← Phase v3.0-3.3 W0 T3.3.W0.11 ADD
1325
- ]);
1148
+ var GIT_REF_PATTERN2, GitCloneWithSetup;
1149
+ var init_gitCloneWithSetup = __esm({
1150
+ "src/manifest/schema/installMethods/gitCloneWithSetup.ts"() {
1151
+ GIT_REF_PATTERN2 = "^([a-f0-9]{7,40}|v?\\d+\\.\\d+\\.\\d+([.-][\\w.-]+)?)$";
1152
+ GitCloneWithSetup = Type.Object(
1153
+ {
1154
+ method: Type.Literal("git-clone-with-setup"),
1155
+ cmd: Type.String({ minLength: 1 }),
1156
+ cwd: Type.Optional(Type.String()),
1157
+ env: Type.Optional(Type.Record(Type.String(), Type.String())),
1158
+ args: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
1159
+ git_ref: Type.String({ minLength: 1, pattern: GIT_REF_PATTERN2 }),
1160
+ idempotent_check: Type.String({ minLength: 1 })
1161
+ },
1162
+ { additionalProperties: false }
1163
+ );
1326
1164
  }
1327
1165
  });
1328
- async function writeFileAtomic(path, data) {
1329
- const tmp = `${path}.tmp`;
1330
- await writeFile(tmp, data, "utf8");
1331
- await rename(tmp, path);
1332
- }
1333
- function writeFileSyncAtomic(path, data) {
1334
- const tmp = `${path}.tmp`;
1335
- writeFileSync(tmp, data, "utf8");
1336
- renameSync(tmp, path);
1337
- }
1338
- var init_atomicWrite = __esm({
1339
- "src/checkpoint/atomicWrite.ts"() {
1166
+ var McpHttpAdd;
1167
+ var init_mcpHttpAdd = __esm({
1168
+ "src/manifest/schema/installMethods/mcpHttpAdd.ts"() {
1169
+ McpHttpAdd = Type.Object(
1170
+ {
1171
+ method: Type.Literal("mcp-http-add"),
1172
+ cmd: Type.String({ minLength: 1 }),
1173
+ cwd: Type.Optional(Type.String()),
1174
+ env: Type.Optional(Type.Record(Type.String(), Type.String())),
1175
+ args: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
1176
+ npm_version: Type.String({ minLength: 1 }),
1177
+ idempotent_check: Type.String({ minLength: 1 })
1178
+ },
1179
+ { additionalProperties: false }
1180
+ );
1340
1181
  }
1341
1182
  });
1342
- var CheckpointStatus, CheckpointV1;
1343
- var init_checkpoint_v1 = __esm({
1344
- "src/checkpoint/schema/checkpoint.v1.ts"() {
1345
- init_schemaVersion();
1346
- CheckpointStatus = Type.Union([
1347
- Type.Literal("active"),
1348
- Type.Literal("paused"),
1349
- Type.Literal("complete")
1350
- ]);
1351
- CheckpointV1 = Type.Object(
1183
+ var McpStdioAdd;
1184
+ var init_mcpStdioAdd = __esm({
1185
+ "src/manifest/schema/installMethods/mcpStdioAdd.ts"() {
1186
+ McpStdioAdd = Type.Object(
1352
1187
  {
1353
- schemaVersion: Type.Literal(SCHEMA_VERSIONS.checkpoint),
1354
- phase: Type.String({ minLength: 1 }),
1355
- status: CheckpointStatus,
1356
- last_task: Type.String(),
1357
- key_decisions: Type.Array(Type.String()),
1358
- canonical_refs: Type.Array(Type.String()),
1359
- /** D-04 WIRE-IN: optional SDK session_id captured via `sdkSpawn`
1360
- * `onSessionId` callback (CD-4 closure-ready) for future `--resume`. */
1361
- session_id: Type.Optional(Type.String()),
1362
- /** RESEARCH § 1.3 critical constraint — SDK session resume requires cwd
1363
- * match; we capture and validate at restore time. */
1364
- cwd: Type.String({ minLength: 1 }),
1365
- timestamp: Type.String({ minLength: 1 }),
1366
- // ISO-8601 by convention (TypeBox `format` requires Ajv-style format registry; we keep shape-check only — drift caught in writeCheckpoint path)
1367
- archive_path: Type.String({ minLength: 1 })
1188
+ method: Type.Literal("mcp-stdio-add"),
1189
+ cmd: Type.String({ minLength: 1 }),
1190
+ cwd: Type.Optional(Type.String()),
1191
+ env: Type.Optional(Type.Record(Type.String(), Type.String())),
1192
+ args: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
1193
+ npm_version: Type.String({ minLength: 1 }),
1194
+ idempotent_check: Type.String({ minLength: 1 })
1368
1195
  },
1369
1196
  { additionalProperties: false }
1370
1197
  );
1371
1198
  }
1372
1199
  });
1373
- var WorkflowStatus, EvidenceRef, SubProgressEntry, CurrentWorkflowV1;
1374
- var init_currentWorkflow_v1 = __esm({
1375
- "src/checkpoint/schema/currentWorkflow.v1.ts"() {
1376
- init_schemaVersion();
1377
- WorkflowStatus = Type.Union([
1378
- Type.Literal("active"),
1379
- Type.Literal("paused"),
1380
- Type.Literal("complete")
1200
+ var NpmCli;
1201
+ var init_npmCli = __esm({
1202
+ "src/manifest/schema/installMethods/npmCli.ts"() {
1203
+ NpmCli = Type.Object(
1204
+ {
1205
+ method: Type.Literal("npm-cli"),
1206
+ cmd: Type.String({ minLength: 1 }),
1207
+ cwd: Type.Optional(Type.String()),
1208
+ env: Type.Optional(Type.Record(Type.String(), Type.String())),
1209
+ args: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
1210
+ npm_version: Type.String({ minLength: 1 }),
1211
+ idempotent_check: Type.String({ minLength: 1 })
1212
+ },
1213
+ { additionalProperties: false }
1214
+ );
1215
+ }
1216
+ });
1217
+ var NpxSkillInstaller;
1218
+ var init_npxSkillInstaller = __esm({
1219
+ "src/manifest/schema/installMethods/npxSkillInstaller.ts"() {
1220
+ NpxSkillInstaller = Type.Object(
1221
+ {
1222
+ method: Type.Literal("npx-skill-installer"),
1223
+ cmd: Type.String({ minLength: 1 }),
1224
+ cwd: Type.Optional(Type.String()),
1225
+ env: Type.Optional(Type.Record(Type.String(), Type.String())),
1226
+ args: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
1227
+ npm_version: Type.String({ minLength: 1 }),
1228
+ idempotent_check: Type.String({ minLength: 1 })
1229
+ },
1230
+ { additionalProperties: false }
1231
+ );
1232
+ }
1233
+ });
1234
+ var branches, InstallSchema;
1235
+ var init_installMethods = __esm({
1236
+ "src/manifest/schema/installMethods/index.ts"() {
1237
+ init_ccHookAdd();
1238
+ init_ccPluginMarketplace();
1239
+ init_gitCloneWithSetup();
1240
+ init_mcpHttpAdd();
1241
+ init_mcpStdioAdd();
1242
+ init_npmCli();
1243
+ init_npxSkillInstaller();
1244
+ branches = [
1245
+ CcPluginMarketplace,
1246
+ GitCloneWithSetup,
1247
+ NpxSkillInstaller,
1248
+ NpmCli,
1249
+ McpStdioAdd,
1250
+ McpHttpAdd,
1251
+ CcHookAdd
1252
+ ];
1253
+ InstallSchema = {
1254
+ type: "object",
1255
+ discriminator: { propertyName: "method" },
1256
+ required: ["method"],
1257
+ properties: {
1258
+ method: { type: "string" }
1259
+ },
1260
+ oneOf: branches
1261
+ };
1262
+ Type.Union([...branches]);
1263
+ }
1264
+ });
1265
+ var TypeEnum, ComponentType, Verify, Uninstall, Stability, FallbackAction, UpstreamHealth, Platform, Signature, TestedWithVersions, Category, InstallType, DecisionRules, Phase, Triggers, ProvidedUnit, SpecSchema;
1266
+ var init_spec = __esm({
1267
+ "src/manifest/schema/spec.ts"() {
1268
+ init_installMethods();
1269
+ TypeEnum = Type.Union([
1270
+ Type.Literal("cc-plugin"),
1271
+ Type.Literal("cc-skill-pack"),
1272
+ Type.Literal("mcp-npm"),
1273
+ Type.Literal("cli-npm"),
1274
+ // Phase 2.4 W3 T3.1 (D-04 § 3.1 + R2.4.4 + B-22) — 5th type, 1:1 with install_type:'hook'.
1275
+ // Lifecycle hooks registered to ~/.claude/settings.json (SessionStart / UserPromptSubmit /
1276
+ // PreToolUse / PostToolUse) via the cc-hook-add install method.
1277
+ Type.Literal("cc-hook")
1278
+ ]);
1279
+ ComponentType = Type.Union([
1280
+ Type.Literal("command"),
1281
+ Type.Literal("behavior-rule"),
1282
+ Type.Literal("mcp-tool"),
1283
+ Type.Literal("cli-binary")
1284
+ ]);
1285
+ Verify = Type.Object(
1286
+ {
1287
+ cmd: Type.String({ minLength: 1 }),
1288
+ timeout_ms: Type.Optional(Type.Integer({ minimum: 100, maximum: 6e4 })),
1289
+ expected_exit_code: Type.Optional(Type.Integer())
1290
+ },
1291
+ { additionalProperties: false }
1292
+ );
1293
+ Uninstall = Type.Object(
1294
+ {
1295
+ cmd: Type.String({ minLength: 1 }),
1296
+ cleanup_paths: Type.Optional(Type.Array(Type.String()))
1297
+ },
1298
+ { additionalProperties: false }
1299
+ );
1300
+ Stability = Type.Union([
1301
+ Type.Literal("stable"),
1302
+ Type.Literal("beta"),
1303
+ Type.Literal("unstable"),
1304
+ Type.Literal("archived")
1305
+ ]);
1306
+ FallbackAction = Type.Union([
1307
+ Type.Literal("warn"),
1308
+ Type.Literal("block"),
1309
+ Type.Literal("use_alternative")
1310
+ ]);
1311
+ UpstreamHealth = Type.Object(
1312
+ {
1313
+ stability: Stability,
1314
+ last_check: Type.String({ format: "date" }),
1315
+ last_known_good_version: Type.String({ minLength: 1 }),
1316
+ fallback_action: FallbackAction,
1317
+ alternative: Type.Optional(Type.String())
1318
+ },
1319
+ { additionalProperties: false }
1320
+ );
1321
+ Platform = Type.Union([Type.Literal("linux"), Type.Literal("darwin"), Type.Literal("win32")]);
1322
+ Signature = Type.Object(
1323
+ { sigstore_bundle: Type.String({ format: "uri" }) },
1324
+ { additionalProperties: false }
1325
+ );
1326
+ TestedWithVersions = Type.Object(
1327
+ {
1328
+ cc_versions: Type.Optional(Type.Array(Type.String())),
1329
+ node_versions: Type.Optional(Type.Array(Type.String()))
1330
+ },
1331
+ { additionalProperties: false }
1332
+ );
1333
+ Category = Type.Union([
1334
+ Type.Literal("meta"),
1335
+ Type.Literal("engineering"),
1336
+ Type.Literal("design"),
1337
+ Type.Literal("content"),
1338
+ Type.Literal("testing"),
1339
+ Type.Literal("search")
1340
+ ]);
1341
+ InstallType = Type.Union([
1342
+ Type.Literal("skill"),
1343
+ Type.Literal("mcp"),
1344
+ Type.Literal("npm"),
1345
+ Type.Literal("git"),
1346
+ // Phase 2.4 W3 T3.1 (D-04 § 3.1 + R2.4.4 + B-22) — 5th install_type, 1:1 with TypeEnum:'cc-hook'.
1347
+ Type.Literal("hook")
1348
+ ]);
1349
+ DecisionRules = Type.Object(
1350
+ {
1351
+ trigger: Type.Optional(Type.String({ minLength: 1 })),
1352
+ default_expert: Type.Optional(Type.String({ minLength: 1 })),
1353
+ arbitration_rule: Type.Optional(Type.String({ minLength: 1 })),
1354
+ override_signals: Type.Optional(
1355
+ Type.Array(
1356
+ Type.Object(
1357
+ {
1358
+ phrase: Type.String({ minLength: 1 }),
1359
+ use: Type.String({ minLength: 1 })
1360
+ },
1361
+ { additionalProperties: false }
1362
+ )
1363
+ )
1364
+ ),
1365
+ // Phase 2.3 W2 T2.5 — CD-3 negative-space hint mirror (B-17 per-manifest hint
1366
+ // redundant guard layer; SSOT remains routing/decision_rules.yaml — D-04 lead).
1367
+ // Additive optional; existing manifests unchanged (A7 守恒).
1368
+ do_not_use_when: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { minItems: 1 })),
1369
+ if_rejected_use: Type.Optional(Type.String({ minLength: 1 }))
1370
+ },
1371
+ { additionalProperties: false }
1372
+ );
1373
+ Phase = Type.Union([
1374
+ Type.Literal("discuss"),
1375
+ Type.Literal("plan"),
1376
+ Type.Literal("execute"),
1377
+ Type.Literal("verify")
1381
1378
  ]);
1382
- EvidenceRef = Type.Object(
1383
- { path: Type.String({ minLength: 1 }), sha256: Type.String({ minLength: 1 }) },
1379
+ Triggers = Type.Object(
1380
+ {
1381
+ complexity_threshold: Type.Optional(Type.Integer({ minimum: 1 })),
1382
+ tdd_required: Type.Optional(Type.Boolean()),
1383
+ brainstorming_required: Type.Optional(Type.Boolean())
1384
+ },
1384
1385
  { additionalProperties: false }
1385
1386
  );
1386
- SubProgressEntry = Type.Object(
1387
+ ProvidedUnit = Type.Object(
1387
1388
  {
1388
- // flattened sub name, e.g. "task-code".
1389
- sub: Type.String({ minLength: 1 }),
1390
- status: Type.Union([
1391
- Type.Literal("pending"),
1392
- Type.Literal("done"),
1393
- Type.Literal("failed"),
1394
- Type.Literal("skipped"),
1395
- Type.Literal("rejected")
1396
- ]),
1397
- gate_fired: Type.Boolean(),
1398
- // skip reason (from gates plan skip[].reason).
1399
- reason: Type.Optional(Type.String()),
1400
- // D2 (eng-review) — three-state evidence posture, NOT a boolean:
1401
- // 'verified' — artifacts_expected declared AND all present (sha256 recorded)
1402
- // 'none_declared' — leaf declares no artifacts_expected → guard N/A (NOT a pass)
1403
- // 'overridden' — --force used to bypass a missing-artifact block
1404
- evidence_status: Type.Optional(
1405
- Type.Union([
1406
- Type.Literal("verified"),
1407
- Type.Literal("none_declared"),
1408
- Type.Literal("overridden")
1409
- ])
1410
- ),
1411
- evidence: Type.Optional(Type.Array(EvidenceRef)),
1412
- // G6 — failure counter; incremented only on each ->failed transition (drives
1413
- // breakLoop detection). 'rejected' is terminal and does NOT increment it.
1414
- fail_count: Type.Optional(Type.Integer({ minimum: 0 }))
1389
+ id: Type.String({ minLength: 1 }),
1390
+ // routing-addressable, <org>-<repo>-<unit>
1391
+ component_type: ComponentType
1392
+ // reuse existing union
1415
1393
  },
1416
1394
  { additionalProperties: false }
1417
1395
  );
1418
- CurrentWorkflowV1 = Type.Object(
1396
+ SpecSchema = Type.Object(
1419
1397
  {
1420
- schemaVersion: Type.Literal(SCHEMA_VERSIONS.currentWorkflow),
1421
- phase: Type.String({ minLength: 1 }),
1422
- status: WorkflowStatus,
1423
- last_checkpoint_path: Type.Union([Type.String(), Type.Null()]),
1424
- // ISO-8601 by convention (TypeBox `format` requires Ajv-style registry; shape-check only here, drift surfaces in state.ts writer).
1425
- started_at: Type.String({ minLength: 1 }),
1426
- paused_at: Type.Optional(Type.String({ minLength: 1 })),
1427
- completed_at: Type.Optional(Type.String({ minLength: 1 })),
1428
- // v5.0 Spec 1 (ADR-0033 D1/D3) — additive optional ledger (sole SoT; the
1429
- // checkpoint envelope does NOT carry a copy). Old files without this field
1430
- // still `Value.Check`-pass → no schema version bump; readers use `?? []`.
1431
- sub_progress: Type.Optional(Type.Array(SubProgressEntry)),
1432
- // G1 — verification depth used during the verify phase ('light' | 'full').
1433
- verify_mode: Type.Optional(Type.Union([Type.Literal("light"), Type.Literal("full")])),
1434
- // G2 — when true the next-step contract reports NEXT:auto (skill auto-advances);
1435
- // when false NEXT:manual (pause for the operator). Precedence env > this > default.
1436
- auto_transition: Type.Optional(Type.Boolean()),
1437
- // Phase 14 — compaction digest: cumulative summary of resolved sub-progress
1438
- // entries evicted by `compact`. Additive-optional (NO schemaVersion bump; old
1439
- // files without it still Value.Check-pass). Keeps a readable trace after
1440
- // eviction. G6 invariant: entries with fail_count>0 are never evicted, so the
1441
- // breakLoop signal is never summarized away.
1442
- compacted_summary: Type.Optional(
1443
- Type.Object(
1444
- {
1445
- evicted: Type.Integer({ minimum: 0 }),
1446
- by_status: Type.Record(Type.String(), Type.Integer({ minimum: 0 })),
1447
- last_at: Type.String({ minLength: 1 })
1448
- },
1449
- { additionalProperties: false }
1450
- )
1451
- ),
1452
- // Phase 22 — smart reminders. Additive-optional flags set by `checkpoint
1453
- // complete` (allResolved) and read by the G4 inject twins (booleans only; the
1454
- // bin computes neither git nor thresholds). Old files without them Value.Check-pass
1455
- // → NO schemaVersion bump.
1456
- // ship_ready — there are unshipped commits since the last vX.Y.Z tag (git-derived,
1457
- // recomputed each completion; self-heals to false after a release).
1458
- // ship_commits — commit count since that tag (feeds the SHIP-READY hint text).
1459
- // retro_due — phases_since_retro (store sidecar) has crossed the threshold;
1460
- // cleared by `harnessed retro --done`.
1461
- ship_ready: Type.Optional(Type.Boolean()),
1462
- ship_commits: Type.Optional(Type.Integer({ minimum: 0 })),
1463
- retro_due: Type.Optional(Type.Boolean())
1398
+ type: TypeEnum,
1399
+ component_type: ComponentType,
1400
+ install: Type.Unsafe(InstallSchema),
1401
+ verify: Verify,
1402
+ uninstall: Uninstall,
1403
+ upstream_health: UpstreamHealth,
1404
+ signed_by: Type.String({ pattern: "^[a-zA-Z0-9-]+$", minLength: 1 }),
1405
+ signature: Type.Optional(Signature),
1406
+ platforms: Type.Array(Platform, { minItems: 1, uniqueItems: true }),
1407
+ tested_with_versions: Type.Optional(TestedWithVersions),
1408
+ mutually_exclusive_with: Type.Optional(Type.Array(Type.String())),
1409
+ category: Category,
1410
+ install_type: InstallType,
1411
+ decision_rules: Type.Optional(DecisionRules),
1412
+ // ADR 0009 errata (phase 1.5 T5.5) — mattpocock phase routing schema.
1413
+ phase: Type.Optional(Phase),
1414
+ triggers: Type.Optional(Triggers),
1415
+ // ADR 0010 errata (phase 2.1 T1.3) — bundle-install `provides` field.
1416
+ provides: Type.Optional(Type.Array(ProvidedUnit, { minItems: 2, uniqueItems: true }))
1464
1417
  },
1465
1418
  { additionalProperties: false }
1466
1419
  );
1467
1420
  }
1468
1421
  });
1469
-
1470
- // src/checkpoint/schema/index.ts
1422
+ var ManifestBase, matrix, matrixConstraints, ManifestSchema;
1471
1423
  var init_schema2 = __esm({
1472
- "src/checkpoint/schema/index.ts"() {
1473
- init_checkpoint_v1();
1474
- init_currentWorkflow_v1();
1424
+ "src/manifest/schema/index.ts"() {
1425
+ init_metadata();
1426
+ init_spec();
1427
+ ManifestBase = Type.Object(
1428
+ {
1429
+ apiVersion: ApiVersion,
1430
+ kind: Kind,
1431
+ metadata: MetadataSchema,
1432
+ spec: SpecSchema
1433
+ },
1434
+ { additionalProperties: false }
1435
+ );
1436
+ matrix = {
1437
+ "cc-plugin": ["cc-plugin-marketplace"],
1438
+ "cc-skill-pack": ["cc-plugin-marketplace", "git-clone-with-setup", "npx-skill-installer"],
1439
+ "mcp-npm": ["mcp-stdio-add", "mcp-http-add"],
1440
+ "cli-npm": ["npm-cli"]
1441
+ };
1442
+ matrixConstraints = Object.entries(matrix).map(([typeValue, allowedMethods]) => ({
1443
+ if: {
1444
+ type: "object",
1445
+ properties: {
1446
+ spec: {
1447
+ type: "object",
1448
+ properties: { type: { const: typeValue } },
1449
+ required: ["type"]
1450
+ }
1451
+ },
1452
+ required: ["spec"]
1453
+ },
1454
+ // biome-ignore lint/suspicious/noThenProperty: JSON Schema `then` keyword (conditional schemas), not a thenable.
1455
+ then: {
1456
+ type: "object",
1457
+ properties: {
1458
+ spec: {
1459
+ type: "object",
1460
+ properties: {
1461
+ install: {
1462
+ type: "object",
1463
+ properties: { method: { enum: allowedMethods } },
1464
+ required: ["method"]
1465
+ }
1466
+ },
1467
+ required: ["install"]
1468
+ }
1469
+ },
1470
+ required: ["spec"]
1471
+ }
1472
+ }));
1473
+ ManifestSchema = {
1474
+ ...ManifestBase,
1475
+ $id: "https://harnessed.dev/schemas/manifest.v1.schema.json",
1476
+ title: "harnessed Manifest v1",
1477
+ description: "Per ADR 0001. Strict mode (additionalProperties: false everywhere).",
1478
+ allOf: matrixConstraints
1479
+ };
1480
+ }
1481
+ });
1482
+ function lineOf(node, lineCounter) {
1483
+ if (!node?.range) return null;
1484
+ const offset = node.range[0];
1485
+ return lineCounter.linePos(offset).line;
1486
+ }
1487
+ function checkCmdString(cmd) {
1488
+ for (const pat of PATTERNS) {
1489
+ if (pat.test(cmd)) return { label: pat.label, hint: pat.hint };
1490
+ }
1491
+ return null;
1492
+ }
1493
+ function checkScalarCmd(doc, lineCounter, path, filename) {
1494
+ const node = doc.getIn(path, true);
1495
+ if (!node || !isScalar(node)) return null;
1496
+ const value = node.value;
1497
+ if (typeof value !== "string") return null;
1498
+ for (const pat of PATTERNS) {
1499
+ if (pat.test(value)) {
1500
+ return {
1501
+ file: filename,
1502
+ path: `/${path.join("/")}`,
1503
+ message: `shell escape detected: '${pat.label}' (${pat.hint}) at ${path.join(".")} \u2014 v0.1 forbids dynamic shell evaluation; v0.2 will use \`requires_secret\` + \`\${secret:KEY}\` for env placeholders`,
1504
+ line: lineOf(node, lineCounter),
1505
+ column: null,
1506
+ keyword: "security"
1507
+ };
1508
+ }
1509
+ }
1510
+ return null;
1511
+ }
1512
+ function checkSecurityViolations(doc, filename, lineCounter) {
1513
+ const errors = [];
1514
+ const cmdPaths = [
1515
+ ["spec", "install", "cmd"],
1516
+ ["spec", "verify", "cmd"],
1517
+ ["spec", "uninstall", "cmd"]
1518
+ ];
1519
+ for (const p5 of cmdPaths) {
1520
+ const err2 = checkScalarCmd(doc, lineCounter, p5, filename);
1521
+ if (err2) errors.push(err2);
1522
+ }
1523
+ const cleanupNode = doc.getIn(["spec", "uninstall", "cleanup_paths"], true);
1524
+ if (cleanupNode && isSeq(cleanupNode)) {
1525
+ cleanupNode.items.forEach((item, idx) => {
1526
+ if (!isScalar(item)) return;
1527
+ const value = item.value;
1528
+ if (typeof value !== "string") return;
1529
+ for (const pat of PATTERNS) {
1530
+ if (pat.test(value)) {
1531
+ errors.push({
1532
+ file: filename,
1533
+ path: `/spec/uninstall/cleanup_paths/${idx}`,
1534
+ message: `shell escape detected: '${pat.label}' (${pat.hint}) at spec.uninstall.cleanup_paths[${idx}] \u2014 v0.1 forbids dynamic shell evaluation`,
1535
+ line: lineOf(item, lineCounter),
1536
+ column: null,
1537
+ keyword: "security"
1538
+ });
1539
+ break;
1540
+ }
1541
+ }
1542
+ });
1543
+ }
1544
+ return errors;
1545
+ }
1546
+ var PATTERNS;
1547
+ var init_security = __esm({
1548
+ "src/manifest/security.ts"() {
1549
+ PATTERNS = [
1550
+ {
1551
+ label: "$(...)",
1552
+ hint: "POSIX command substitution",
1553
+ test: (s) => /\$\(/.test(s)
1554
+ },
1555
+ {
1556
+ // biome-ignore lint/suspicious/noTemplateCurlyInString: literal pattern label, not a JS template
1557
+ label: "${...}",
1558
+ // biome-ignore lint/suspicious/noTemplateCurlyInString: literal example in user-facing message
1559
+ hint: "variable expansion (v0.2 will whitelist `${secret:KEY}`)",
1560
+ test: (s) => /\$\{/.test(s)
1561
+ },
1562
+ {
1563
+ label: "backtick",
1564
+ hint: "old-style command substitution",
1565
+ test: (s) => /`/.test(s)
1566
+ }
1567
+ ];
1475
1568
  }
1476
1569
  });
1477
-
1478
- // src/checkpoint/workflowStore.ts
1479
- var workflowStore_exports = {};
1480
- __export(workflowStore_exports, {
1481
- RetroMetaEntry: () => RetroMetaEntry,
1482
- WorkflowStoreV1: () => WorkflowStoreV1,
1483
- activeKey: () => activeKey,
1484
- listWorkflows: () => listWorkflows,
1485
- readStoreRaw: () => readStoreRaw,
1486
- repoKey: () => repoKey,
1487
- writeStoreRaw: () => writeStoreRaw
1488
- });
1489
- function storePath() {
1490
- return harnessedFile("workflows.json");
1491
- }
1492
- function legacyPath() {
1493
- return harnessedFile("current-workflow.json");
1494
- }
1495
- function emptyStore() {
1496
- return { schemaVersion: SCHEMA_VERSIONS.workflowStore, workflows: {} };
1497
- }
1498
- function repoKey(cwd = process.cwd()) {
1499
- let dir = resolve(cwd);
1500
- for (; ; ) {
1501
- if (existsSync(join(dir, ".git"))) return dir;
1502
- const parent = dirname(dir);
1503
- if (parent === dir) break;
1504
- dir = parent;
1570
+ function getValidator() {
1571
+ if (!_compiled) {
1572
+ _compiled = ajv.compile(ManifestSchema);
1505
1573
  }
1506
- return resolve(cwd);
1574
+ return _compiled;
1507
1575
  }
1508
- function activeKey(cwd = process.cwd()) {
1509
- const base = repoKey(cwd);
1510
- const envName = detectPlatform().sessionIdEnv;
1511
- const sid = envName ? process.env[envName]?.trim() : void 0;
1512
- return sid ? `${base}::${sid}` : base;
1576
+ function checkInstallTypeMismatch(manifest, filename) {
1577
+ const spec = manifest.spec;
1578
+ const installType = spec.install_type;
1579
+ const method = spec.install?.method;
1580
+ if (!installType || !method) return [];
1581
+ const allowed = INSTALL_TYPE_METHODS[installType];
1582
+ if (!allowed || allowed.includes(method)) return [];
1583
+ return [
1584
+ {
1585
+ file: filename,
1586
+ path: "spec.install.method",
1587
+ message: `install_type '${installType}' is not compatible with install.method '${method}' (ADR 0007 1:N closure \u2014 expected one of: ${allowed.join(", ")})`,
1588
+ line: null,
1589
+ column: null,
1590
+ keyword: "install-type-mismatch"
1591
+ }
1592
+ ];
1513
1593
  }
1514
- async function readStoreRaw() {
1515
- try {
1516
- const parsed = JSON.parse(await readFile(storePath(), "utf8"));
1517
- if (Value.Check(WorkflowStoreV1, parsed)) return parsed;
1518
- } catch {
1594
+ function validateManifestFile(yamlSource, filename) {
1595
+ const lineCounter = new LineCounter();
1596
+ const doc = parseDocument(yamlSource, { lineCounter });
1597
+ if (doc.errors.length > 0) {
1598
+ return {
1599
+ ok: false,
1600
+ errors: doc.errors.map((e) => yamlParseErrorToFriendly(e, filename))
1601
+ };
1519
1602
  }
1520
- try {
1521
- const legacy = JSON.parse(await readFile(legacyPath(), "utf8"));
1522
- if (Value.Check(CurrentWorkflowV1, legacy)) {
1523
- return {
1524
- schemaVersion: SCHEMA_VERSIONS.workflowStore,
1525
- workflows: { [repoKey()]: legacy }
1526
- };
1527
- }
1528
- } catch {
1603
+ const securityErrors = checkSecurityViolations(doc, filename, lineCounter);
1604
+ if (securityErrors.length > 0) {
1605
+ return { ok: false, errors: securityErrors };
1529
1606
  }
1530
- return emptyStore();
1531
- }
1532
- async function writeStoreRaw(store) {
1533
- if (!Value.Check(WorkflowStoreV1, store)) {
1534
- const errs = [...Value.Errors(WorkflowStoreV1, store)].map((e) => e.message).join("; ");
1535
- throw new Error(`workflow-store schema validation failed: ${errs}`);
1607
+ const data = doc.toJS();
1608
+ const validate = getValidator();
1609
+ if (!validate(data)) {
1610
+ const errs = validate.errors ?? [];
1611
+ return {
1612
+ ok: false,
1613
+ errors: errs.map((err2) => ajvErrorToFriendly(err2, filename, doc, lineCounter))
1614
+ };
1536
1615
  }
1537
- const p5 = storePath();
1538
- await mkdir(dirname(p5), { recursive: true });
1539
- await writeFileAtomic(p5, JSON.stringify(store, null, 2));
1540
- }
1541
- async function listWorkflows() {
1542
- const store = await readStoreRaw();
1543
- return Object.entries(store.workflows).map(([key, wf]) => ({
1544
- key,
1545
- phase: wf.phase,
1546
- status: wf.status
1547
- }));
1616
+ const manifest = data;
1617
+ const crossFieldErrors = checkInstallTypeMismatch(manifest, filename);
1618
+ if (crossFieldErrors.length > 0) {
1619
+ return { ok: false, errors: crossFieldErrors };
1620
+ }
1621
+ return { ok: true, manifest };
1548
1622
  }
1549
- var RetroMetaEntry, WorkflowStoreV1;
1550
- var init_workflowStore = __esm({
1551
- "src/checkpoint/workflowStore.ts"() {
1552
- init_harnessedRoot();
1553
- init_platform();
1554
- init_schemaVersion();
1555
- init_atomicWrite();
1556
- init_currentWorkflow_v1();
1557
- RetroMetaEntry = Type.Object(
1558
- {
1559
- phases_since_retro: Type.Integer({ minimum: 0 }),
1560
- last_retro_at: Type.Optional(Type.String({ minLength: 1 }))
1561
- },
1562
- { additionalProperties: false }
1563
- );
1564
- WorkflowStoreV1 = Type.Object(
1565
- {
1566
- schemaVersion: Type.Literal(SCHEMA_VERSIONS.workflowStore),
1567
- workflows: Type.Record(Type.String(), CurrentWorkflowV1),
1568
- // Additive-optional (no schemaVersion bump — old stores Value.Check-pass).
1569
- retro_meta: Type.Optional(Type.Record(Type.String(), RetroMetaEntry))
1570
- },
1571
- { additionalProperties: false }
1623
+ var addFormats, ajv, _compiled, INSTALL_TYPE_METHODS;
1624
+ var init_validate = __esm({
1625
+ "src/manifest/validate.ts"() {
1626
+ init_errors();
1627
+ init_schema2();
1628
+ init_security();
1629
+ addFormats = ajvFormatsNs.default;
1630
+ ajv = addFormats(
1631
+ new Ajv({
1632
+ strict: true,
1633
+ strictSchema: true,
1634
+ strictTypes: true,
1635
+ strictRequired: true,
1636
+ allErrors: true,
1637
+ discriminator: true,
1638
+ allowUnionTypes: false
1639
+ })
1572
1640
  );
1641
+ _compiled = null;
1642
+ INSTALL_TYPE_METHODS = {
1643
+ npm: ["npm-cli"],
1644
+ mcp: ["mcp-stdio-add", "mcp-http-add"],
1645
+ git: ["git-clone-with-setup"],
1646
+ skill: ["cc-plugin-marketplace", "npx-skill-installer"]
1647
+ };
1573
1648
  }
1574
1649
  });
1575
1650
 
1576
- // src/checkpoint/state.ts
1577
- var state_exports = {};
1578
- __export(state_exports, {
1579
- LockHeldError: () => LockHeldError,
1580
- WorkflowStateError: () => WorkflowStateError,
1581
- activate: () => activate,
1582
- complete: () => complete,
1583
- mutateStore: () => mutateStore,
1584
- mutateSubProgress: () => mutateSubProgress,
1585
- pause: () => pause,
1586
- readCurrentWorkflow: () => readCurrentWorkflow,
1587
- writeCurrentWorkflow: () => writeCurrentWorkflow
1651
+ // src/cli/lib/origin-check.ts
1652
+ var origin_check_exports = {};
1653
+ __export(origin_check_exports, {
1654
+ checkOrigin: () => checkOrigin
1588
1655
  });
1589
- function statePath() {
1590
- return harnessedFile("current-workflow.json");
1591
- }
1592
- function lockTarget() {
1593
- return getHarnessedRoot();
1656
+ function normalizeUrl(s) {
1657
+ return s.trim().replace(/^(https?:\/\/|git@github\.com:|ssh:\/\/git@github\.com\/)/, "").replace(/\.git$/, "").replace(":", "/").replace(/\/$/, "").toLowerCase();
1594
1658
  }
1595
- function lockOpts() {
1659
+ function checkOrigin(cwd = process.cwd(), opts = {}) {
1660
+ const allowFork = opts.allowFork ?? true;
1661
+ let expected = null;
1662
+ try {
1663
+ const pkg = JSON.parse(readFileSync(join(cwd, "package.json"), "utf8"));
1664
+ expected = typeof pkg.repository === "string" ? pkg.repository : pkg.repository?.url ?? null;
1665
+ } catch {
1666
+ }
1667
+ if (!expected) {
1668
+ return {
1669
+ status: "warn",
1670
+ detail: "package.json has no repository.url field",
1671
+ fix: "add `repository` field to package.json"
1672
+ };
1673
+ }
1674
+ const r = spawnSync("git", ["config", "--get", "remote.origin.url"], {
1675
+ cwd,
1676
+ encoding: "utf8"
1677
+ });
1678
+ if (r.status !== 0) {
1679
+ return {
1680
+ status: "warn",
1681
+ detail: "no git remote origin (detached / non-clone)",
1682
+ fix: "git remote add origin <expected-url>"
1683
+ };
1684
+ }
1685
+ const actual = r.stdout.trim();
1686
+ if (normalizeUrl(actual) === normalizeUrl(expected)) {
1687
+ return { status: "pass", detail: actual };
1688
+ }
1596
1689
  return {
1597
- stale: 1e4,
1598
- retries: { retries: 3, factor: 2, minTimeout: 100 },
1599
- lockfilePath: harnessedFile(".lock")
1690
+ status: allowFork ? "warn" : "fail",
1691
+ detail: `origin '${actual}' \u2260 expected '${expected}'`,
1692
+ fix: allowFork ? "verify intentional fork; if not, `git remote set-url origin <expected>`" : "origin URL drift \u2014 possible tamper, `git remote set-url origin <expected>` to restore"
1600
1693
  };
1601
1694
  }
1602
- async function withLock(fn) {
1603
- const target = lockTarget();
1604
- await mkdir(target, { recursive: true });
1605
- let release;
1606
- try {
1607
- release = await lockfile.lock(target, lockOpts());
1608
- } catch (e) {
1609
- if (e.code === "ELOCKED") throw new LockHeldError();
1610
- throw e;
1695
+ var init_origin_check = __esm({
1696
+ "src/cli/lib/origin-check.ts"() {
1611
1697
  }
1698
+ });
1699
+ function mapToSupported(raw) {
1700
+ if (!raw) return "en";
1701
+ if (/^zh([^a-z]|$)/i.test(raw)) return "zh-Hans";
1702
+ return "en";
1703
+ }
1704
+ function detectLocale() {
1705
+ const raw = process.env.HARNESSED_LANG || process.env.LC_ALL || process.env.LANG || process.env.LANGUAGE || safeIntlLocale();
1706
+ return mapToSupported(raw);
1707
+ }
1708
+ function safeIntlLocale() {
1612
1709
  try {
1613
- return await fn();
1614
- } finally {
1615
- await release?.();
1710
+ return Intl.DateTimeFormat().resolvedOptions().locale;
1711
+ } catch {
1712
+ return void 0;
1616
1713
  }
1617
1714
  }
1618
- async function readCurrentWorkflow() {
1619
- const store = await readStoreRaw();
1620
- return store.workflows[activeKey()] ?? store.workflows[repoKey()] ?? null;
1715
+ function messagesDir() {
1716
+ const here = dirname(fileURLToPath(import.meta.url));
1717
+ const candidates = [resolve(here, "..", "..", "messages"), resolve(here, "..", "messages")];
1718
+ for (const c of candidates) {
1719
+ try {
1720
+ readFileSync(join(c, "en.json"), "utf8");
1721
+ return c;
1722
+ } catch {
1723
+ }
1724
+ }
1725
+ return resolve(process.cwd(), "messages");
1621
1726
  }
1622
- async function writeCurrentWorkflowUnlocked(s) {
1623
- if (!Value.Check(CurrentWorkflowV1, s)) {
1624
- const errs = [...Value.Errors(CurrentWorkflowV1, s)].map((e) => e.message).join("; ");
1625
- throw new WorkflowStateError(`current-workflow schema validation failed: ${errs}`);
1727
+ function loadLocale(locale) {
1728
+ if (cache[locale]) return cache[locale];
1729
+ const path = join(messagesDir(), `${locale}.json`);
1730
+ try {
1731
+ const raw = readFileSync(path, "utf8");
1732
+ cache[locale] = JSON.parse(raw);
1733
+ } catch {
1734
+ cache[locale] = {};
1626
1735
  }
1627
- const store = await readStoreRaw();
1628
- store.workflows[activeKey()] = s;
1629
- await writeStoreRaw(store);
1630
- await writeFileAtomic(statePath(), JSON.stringify(s, null, 2));
1736
+ return cache[locale];
1631
1737
  }
1632
- async function writeCurrentWorkflow(s) {
1633
- await withLock(() => writeCurrentWorkflowUnlocked(s));
1738
+ function setLocale(locale) {
1739
+ if (!locale) return;
1740
+ const mapped = mapToSupported(locale);
1741
+ if (SUPPORTED.has(mapped)) currentLocale = mapped;
1634
1742
  }
1635
- async function mutateSubProgress(fn) {
1636
- await withLock(async () => {
1637
- const s = await readCurrentWorkflow();
1638
- if (!s) return;
1639
- const next = fn(s.sub_progress ?? []);
1640
- await writeCurrentWorkflowUnlocked({ ...s, sub_progress: next });
1641
- });
1743
+ function getLocale() {
1744
+ if (currentLocale === null) currentLocale = detectLocale();
1745
+ return currentLocale;
1642
1746
  }
1643
- async function mutateStore(fn) {
1644
- await withLock(async () => {
1645
- const store = await readStoreRaw();
1646
- await writeStoreRaw(fn(store));
1747
+ function t(key, params) {
1748
+ const locale = getLocale();
1749
+ const primary = loadLocale(locale);
1750
+ let template = primary[key];
1751
+ if (template === void 0 && locale !== "en") {
1752
+ template = loadLocale("en")[key];
1753
+ }
1754
+ if (template === void 0) template = key;
1755
+ if (!params) return template;
1756
+ return template.replace(/\{\{(\w+)\}\}/g, (_match, name) => {
1757
+ const v = params[name];
1758
+ return v === void 0 ? `{{${name}}}` : String(v);
1647
1759
  });
1648
1760
  }
1649
- async function activate(phase, checkpointPath = null) {
1650
- await writeCurrentWorkflow({
1651
- schemaVersion: SCHEMA_VERSIONS.currentWorkflow,
1652
- phase,
1653
- status: "active",
1654
- last_checkpoint_path: checkpointPath,
1655
- started_at: (/* @__PURE__ */ new Date()).toISOString()
1656
- });
1761
+ var SUPPORTED, currentLocale, cache;
1762
+ var init_i18n = __esm({
1763
+ "src/i18n/index.ts"() {
1764
+ SUPPORTED = /* @__PURE__ */ new Set(["en", "zh-Hans"]);
1765
+ currentLocale = null;
1766
+ cache = {};
1767
+ }
1768
+ });
1769
+ function getBackupRoot() {
1770
+ return harnessedSubdir("backups");
1657
1771
  }
1658
- async function pause() {
1659
- const s = await readCurrentWorkflow();
1660
- if (!s) return;
1661
- await writeCurrentWorkflow({ ...s, status: "paused", paused_at: (/* @__PURE__ */ new Date()).toISOString() });
1772
+ function mirrorPath(target, scope, backupDir) {
1773
+ const root = scope === "HOME" ? HOME_DIR : ".";
1774
+ const rel = root ? relative(root, target) : target;
1775
+ if (!rel || rel.startsWith("..")) {
1776
+ const flat = createHash("sha1").update(target).digest("hex").slice(0, 16);
1777
+ return join(backupDir, scope, flat);
1778
+ }
1779
+ return join(backupDir, scope, rel);
1662
1780
  }
1663
- async function complete() {
1664
- const s = await readCurrentWorkflow();
1665
- if (!s) return;
1666
- await writeCurrentWorkflow({ ...s, status: "complete", completed_at: (/* @__PURE__ */ new Date()).toISOString() });
1781
+ function detectEol(buf) {
1782
+ return buf.includes("\r\n") ? "crlf" : "lf";
1667
1783
  }
1668
- var WorkflowStateError, LockHeldError;
1669
- var init_state = __esm({
1670
- "src/checkpoint/state.ts"() {
1671
- init_harnessedRoot();
1672
- init_schemaVersion();
1673
- init_atomicWrite();
1674
- init_schema2();
1675
- init_workflowStore();
1676
- WorkflowStateError = class extends Error {
1677
- constructor(message) {
1678
- super(message);
1679
- this.name = "WorkflowStateError";
1784
+ async function backup(plan, ctx) {
1785
+ const filename = ctx.manifest.metadata.name;
1786
+ const backupId = (/* @__PURE__ */ new Date()).toISOString().replace(/:/g, "-");
1787
+ const backupDir = join(getBackupRoot(), backupId);
1788
+ try {
1789
+ await mkdir(backupDir, { recursive: true });
1790
+ } catch (err2) {
1791
+ return {
1792
+ ok: false,
1793
+ error: {
1794
+ file: filename,
1795
+ path: "/",
1796
+ message: `failed to create backup dir ${backupDir}: ${err2.message}`,
1797
+ line: null,
1798
+ column: null,
1799
+ keyword: "backup-mkdir-failed"
1680
1800
  }
1681
1801
  };
1682
- LockHeldError = class _LockHeldError extends Error {
1802
+ }
1803
+ const entries = [];
1804
+ for (const file of plan.files) {
1805
+ let buf;
1806
+ try {
1807
+ buf = await readFile(file.target);
1808
+ } catch (err2) {
1809
+ const code = err2.code;
1810
+ if (code === "ENOENT" && file.oldText === "") {
1811
+ entries.push({
1812
+ target: file.target,
1813
+ backup: "",
1814
+ // sentinel: no backup written; rollback should unlink target
1815
+ sha1: "",
1816
+ eol: "lf"
1817
+ // moot for non-existent file; default to lf
1818
+ });
1819
+ continue;
1820
+ }
1821
+ if (code === "EISDIR") {
1822
+ entries.push({ target: file.target, backup: "", sha1: "", eol: "lf" });
1823
+ continue;
1824
+ }
1825
+ return {
1826
+ ok: false,
1827
+ error: {
1828
+ file: filename,
1829
+ path: file.target,
1830
+ message: `failed to read original file for backup: ${err2.message}`,
1831
+ line: null,
1832
+ column: null,
1833
+ keyword: "backup-read-failed"
1834
+ }
1835
+ };
1836
+ }
1837
+ const sha1 = createHash("sha1").update(buf).digest("hex");
1838
+ const eol = detectEol(buf);
1839
+ const dest = mirrorPath(file.target, file.scope, backupDir);
1840
+ try {
1841
+ await mkdir(dirname(dest), { recursive: true });
1842
+ await writeFile(dest, buf);
1843
+ } catch (err2) {
1844
+ return {
1845
+ ok: false,
1846
+ error: {
1847
+ file: filename,
1848
+ path: dest,
1849
+ message: `failed to write backup copy: ${err2.message}`,
1850
+ line: null,
1851
+ column: null,
1852
+ keyword: "backup-write-failed"
1853
+ }
1854
+ };
1855
+ }
1856
+ entries.push({ target: file.target, backup: dest, sha1, eol });
1857
+ }
1858
+ const metadata = {
1859
+ installer: filename,
1860
+ manifest: filename,
1861
+ timestamp: backupId,
1862
+ files: entries
1863
+ };
1864
+ const metadataPath = join(backupDir, "metadata.json");
1865
+ try {
1866
+ await writeFile(metadataPath, `${JSON.stringify(metadata, null, 2)}
1867
+ `, "utf8");
1868
+ } catch (err2) {
1869
+ return {
1870
+ ok: false,
1871
+ error: {
1872
+ file: filename,
1873
+ path: metadataPath,
1874
+ message: `failed to write metadata.json: ${err2.message}`,
1875
+ line: null,
1876
+ column: null,
1877
+ keyword: "backup-metadata-failed"
1878
+ }
1879
+ };
1880
+ }
1881
+ return { ok: true, backupId, backupDir };
1882
+ }
1883
+ var HOME_DIR;
1884
+ var init_backup = __esm({
1885
+ "src/installers/lib/backup.ts"() {
1886
+ init_harnessedRoot();
1887
+ HOME_DIR = process.env.HOME ?? process.env.USERPROFILE ?? "";
1888
+ }
1889
+ });
1890
+
1891
+ // src/manifest/lib/path-guard.ts
1892
+ function checkPathSafe(input) {
1893
+ for (const re of PATH_TRAVERSAL_PATTERNS) {
1894
+ if (re.test(input)) throw new PathTraversalError();
1895
+ }
1896
+ }
1897
+ var PATH_TRAVERSAL_PATTERNS, PathTraversalError;
1898
+ var init_path_guard = __esm({
1899
+ "src/manifest/lib/path-guard.ts"() {
1900
+ PATH_TRAVERSAL_PATTERNS = [
1901
+ /\.\.\//,
1902
+ // (1) Unix dot-dot-slash: ../../etc/passwd
1903
+ /\.\.\\/,
1904
+ // (2) Windows backslash: ..\windows\system32
1905
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional null-byte injection detection (R10.4 D-03 OWASP A1 vector 3)
1906
+ /\x00/,
1907
+ // (3) Null byte injection: path\x00attack
1908
+ /%2[eE]%2[eE]/,
1909
+ // (4) URL-encoded dot-dot: %2e%2e%2fetc
1910
+ /%25[2][eE]%25[2][eE]/
1911
+ // (5) Double-encoded: %252e%252e%252f
1912
+ ];
1913
+ PathTraversalError = class _PathTraversalError extends Error {
1683
1914
  constructor() {
1684
- super(
1685
- `another harnessed process holds the lock at ${harnessedFile(".lock")} \u2014 wait or kill stale process (try: harnessed status)`
1686
- );
1687
- this.name = "LockHeldError";
1688
- Object.setPrototypeOf(this, _LockHeldError.prototype);
1915
+ super("path traversal attempt detected");
1916
+ this.name = "PathTraversalError";
1917
+ Object.setPrototypeOf(this, _PathTraversalError.prototype);
1689
1918
  }
1690
1919
  };
1691
1920
  }
@@ -1723,7 +1952,7 @@ var init_template = __esm({
1723
1952
  "src/checkpoint/template.ts"() {
1724
1953
  init_harnessedRoot();
1725
1954
  init_atomicWrite();
1726
- init_schema2();
1955
+ init_schema();
1727
1956
  BUDGET_TOKEN = 1e3;
1728
1957
  CheckpointTooLargeError = class extends Error {
1729
1958
  constructor(message) {
@@ -2223,7 +2452,8 @@ function generateCommandFile(name, prompt, _capabilities, _installedPlugins, _in
2223
2452
  }
2224
2453
  function nameToYamlHintPath(name) {
2225
2454
  if (["auto", "research", "retro"].includes(name)) return `${name}/workflow.yaml`;
2226
- if (["discuss", "plan", "task", "verify"].includes(name)) return `${name}/auto/workflow.yaml`;
2455
+ if (["discuss", "plan", "task", "verify", "ship"].includes(name))
2456
+ return `${name}/auto/workflow.yaml`;
2227
2457
  const dashIdx = name.indexOf("-");
2228
2458
  if (dashIdx > 0) {
2229
2459
  return `${name.slice(0, dashIdx)}/${name.slice(dashIdx + 1)}/workflow.yaml`;
@@ -2233,7 +2463,7 @@ function nameToYamlHintPath(name) {
2233
2463
  function shouldOverwriteFile(content) {
2234
2464
  return HARNESSED_MARKER_RX.test(content) || V3_4_3_SIGNATURE_SUB_RX.test(content) || V3_4_3_SIGNATURE_MASTER_RX.test(content);
2235
2465
  }
2236
- async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabilities, installedPlugins, installedUserSkills, writer, fileExists2 = existsSync, readFileSync13 = (p5) => readFileSync(p5, "utf8")) {
2466
+ async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabilities, installedPlugins, installedUserSkills, writer, fileExists2 = existsSync, readFileSync14 = (p5) => readFileSync(p5, "utf8")) {
2237
2467
  const results = [];
2238
2468
  const aggregatedWarnings = /* @__PURE__ */ new Set();
2239
2469
  for (const name of slashNames) {
@@ -2252,7 +2482,7 @@ async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabiliti
2252
2482
  if (fileExists2(path)) {
2253
2483
  let existing = "";
2254
2484
  try {
2255
- existing = readFileSync13(path);
2485
+ existing = readFileSync14(path);
2256
2486
  } catch {
2257
2487
  existing = "";
2258
2488
  }
@@ -2296,7 +2526,7 @@ var init_generateCommands = __esm({
2296
2526
  "discuss-subtask",
2297
2527
  "task-clarify"
2298
2528
  ]);
2299
- ORCHESTRATOR_COMMANDS = /* @__PURE__ */ new Set(["auto", "plan", "task", "verify"]);
2529
+ ORCHESTRATOR_COMMANDS = /* @__PURE__ */ new Set(["auto", "plan", "task", "verify", "ship"]);
2300
2530
  MARKER = `<!-- harnessed-generated:v3.4.4 -->`;
2301
2531
  LANG_DIRECTIVE = `> **Language**: respond to the user in the language set by \`env.HARNESSED_USER_LANG\` (e.g. \`zh-Hans\` \u2192 \u7B80\u4F53\u4E2D\u6587, \`en\` \u2192 English). If unset, mirror the user's input language. Keep code / commands / identifiers / error messages / URLs verbatim.`;
2302
2532
  HARNESSED_MARKER_RX = /<!--\s*harnessed-generated:v\d+\.\d+\.\d+\s*-->/;
@@ -6702,7 +6932,7 @@ var init_resume = __esm({
6702
6932
  init_schemaVersion();
6703
6933
  init_evidence();
6704
6934
  init_recovery();
6705
- init_schema2();
6935
+ init_schema();
6706
6936
  init_state();
6707
6937
  }
6708
6938
  });
@@ -6838,6 +7068,30 @@ var init_migration_report = __esm({
6838
7068
  // src/cli.ts
6839
7069
  init_package();
6840
7070
 
7071
+ // src/cli/advance.ts
7072
+ function registerAdvance(program2) {
7073
+ program2.command("advance").description(
7074
+ "Advance to the next work unit derived from .planning (gated: refuses to skip an earlier incomplete phase unless --force). Print-only \u2014 emits the command to run."
7075
+ ).option("--json", "emit machine-readable {next, unit, hint} for driver loops").option("--force", "override the advance-gate (records an audit note in the output)").action(async (opts) => {
7076
+ const { readCurrentWorkflow: readCurrentWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
7077
+ const { scanPlanning: scanPlanning2 } = await Promise.resolve().then(() => (init_planningScan(), planningScan_exports));
7078
+ const { resolveAdvance: resolveAdvance2 } = await Promise.resolve().then(() => (init_forwardStep(), forwardStep_exports));
7079
+ const current = await readCurrentWorkflow2();
7080
+ const snapshot = scanPlanning2({
7081
+ repoRoot: process.cwd(),
7082
+ currentWorkflow: current,
7083
+ includeTasks: false
7084
+ });
7085
+ const step = resolveAdvance2(snapshot, opts.force ?? false);
7086
+ if (opts.json) {
7087
+ console.log(JSON.stringify(step.json));
7088
+ } else {
7089
+ for (const line of step.lines) console.log(line);
7090
+ }
7091
+ process.exit(step.exitCode);
7092
+ });
7093
+ }
7094
+
6841
7095
  // src/cli/audit.ts
6842
7096
  init_validate();
6843
7097
 
@@ -7934,7 +8188,7 @@ function registerManifestAdd(program2) {
7934
8188
  // src/cli/next.ts
7935
8189
  function registerNext(program2) {
7936
8190
  program2.command("next").description(
7937
- "Print the deterministic next-step contract (NEXT: auto|manual|done) for the active workflow"
8191
+ "Print the deterministic next-step contract: intra-workflow sub (auto|manual|done) then cross-unit forward continuation (advance|blocked|done), exit 0/2/10"
7938
8192
  ).action(async () => {
7939
8193
  const { readCurrentWorkflow: readCurrentWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
7940
8194
  const { resolveNext: resolveNext2, resolveAutoTransition: resolveAutoTransition2 } = await Promise.resolve().then(() => (init_nextStep(), nextStep_exports));
@@ -7942,10 +8196,23 @@ function registerNext(program2) {
7942
8196
  const ledger = current?.sub_progress ?? [];
7943
8197
  const auto = resolveAutoTransition2(current?.auto_transition);
7944
8198
  const step = resolveNext2(ledger, auto);
7945
- console.log(`NEXT: ${step.next}`);
7946
- if (step.sub) console.log(`SUB: ${step.sub}`);
7947
- if (step.hint) console.log(`HINT: ${step.hint}`);
7948
- process.exit(0);
8199
+ if (step.next !== "done") {
8200
+ console.log(`NEXT: ${step.next}`);
8201
+ if (step.sub) console.log(`SUB: ${step.sub}`);
8202
+ if (step.hint) console.log(`HINT: ${step.hint}`);
8203
+ process.exit(0);
8204
+ return;
8205
+ }
8206
+ const { scanPlanning: scanPlanning2 } = await Promise.resolve().then(() => (init_planningScan(), planningScan_exports));
8207
+ const { resolveForwardStep: resolveForwardStep2 } = await Promise.resolve().then(() => (init_forwardStep(), forwardStep_exports));
8208
+ const snapshot = scanPlanning2({
8209
+ repoRoot: process.cwd(),
8210
+ currentWorkflow: current,
8211
+ includeTasks: false
8212
+ });
8213
+ const fwd = resolveForwardStep2(snapshot);
8214
+ for (const line of fwd.lines) console.log(line);
8215
+ process.exit(fwd.exitCode);
7949
8216
  });
7950
8217
  }
7951
8218
 
@@ -9693,6 +9960,7 @@ registerGates(program);
9693
9960
  registerPrompt(program);
9694
9961
  registerCheckpoint(program);
9695
9962
  registerNext(program);
9963
+ registerAdvance(program);
9696
9964
  registerReject(program);
9697
9965
  registerCompact(program);
9698
9966
  registerWorkflows(program);