@williambeto/ai-workflow 2.8.0 → 2.8.1

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../node_modules/ajv-formats/src/formats.ts","../../node_modules/ajv-formats/src/limit.ts","../../node_modules/ajv-formats/src/index.ts","../../src/cli/commands/init.ts","../../src/core/install-plan.ts","../../src/core/templates.ts","../../src/core/filesystem.ts","../../src/core/opencode-merge.ts","../../src/core/symlink-layout.ts","../../src/adapters/platforms/claude.ts","../../src/adapters/platforms/codex.ts","../../src/adapters/platforms/antigravity.ts","../../src/cli/commands/doctor.ts","../../src/core/validation/canonical-finalization.ts","../../src/cli/commands/collect-evidence.ts","../../src/core/healing/cli-remediation-executor.ts","../../src/cli/commands/run.ts","../../src/core/sdd/approval-receipt.ts","../../src/core/sdd/workflow-artifacts.ts","../../src/core/sdd/technical-plan-validator.ts","../../src/core/healing/runtime-remediation-executor.ts","../../src/cli/commands/execute.ts","../../src/cli/commands/clean.ts","../../src/cli/index.ts"],"sourcesContent":["import type {Format, FormatDefinition} from \"ajv\"\nimport type {FormatValidator, FormatCompare} from \"ajv/dist/types\"\n\nexport type FormatMode = \"fast\" | \"full\"\n\nexport type FormatName =\n | \"date\"\n | \"time\"\n | \"date-time\"\n | \"iso-time\"\n | \"iso-date-time\"\n | \"duration\"\n | \"uri\"\n | \"uri-reference\"\n | \"uri-template\"\n | \"url\"\n | \"email\"\n | \"hostname\"\n | \"ipv4\"\n | \"ipv6\"\n | \"regex\"\n | \"uuid\"\n | \"json-pointer\"\n | \"json-pointer-uri-fragment\"\n | \"relative-json-pointer\"\n | \"byte\"\n | \"int32\"\n | \"int64\"\n | \"float\"\n | \"double\"\n | \"password\"\n | \"binary\"\n\nexport type DefinedFormats = {\n [key in FormatName]: Format\n}\n\nfunction fmtDef(\n validate: RegExp | FormatValidator<string>,\n compare: FormatCompare<string>\n): FormatDefinition<string> {\n return {validate, compare}\n}\n\nexport const fullFormats: DefinedFormats = {\n // date: http://tools.ietf.org/html/rfc3339#section-5.6\n date: fmtDef(date, compareDate),\n // date-time: http://tools.ietf.org/html/rfc3339#section-5.6\n time: fmtDef(getTime(true), compareTime),\n \"date-time\": fmtDef(getDateTime(true), compareDateTime),\n \"iso-time\": fmtDef(getTime(), compareIsoTime),\n \"iso-date-time\": fmtDef(getDateTime(), compareIsoDateTime),\n // duration: https://tools.ietf.org/html/rfc3339#appendix-A\n duration: /^P(?!$)((\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+S)?)?|(\\d+W)?)$/,\n uri,\n \"uri-reference\":\n /^(?:[a-z][a-z0-9+\\-.]*:)?(?:\\/?\\/(?:(?:[a-z0-9\\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\\.[a-z0-9\\-._~!$&'()*+,;=:]+)\\]|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)|(?:[a-z0-9\\-._~!$&'\"()*+,;=]|%[0-9a-f]{2})*)(?::\\d*)?(?:\\/(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})*)*|\\/(?:(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\\?(?:[a-z0-9\\-._~!$&'\"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\\-._~!$&'\"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,\n // uri-template: https://tools.ietf.org/html/rfc6570\n \"uri-template\":\n /^(?:(?:[^\\x00-\\x20\"'<>%\\\\^`{|}]|%[0-9a-f]{2})|\\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\\*)?)*\\})*$/i,\n // For the source: https://gist.github.com/dperini/729294\n // For test cases: https://mathiasbynens.be/demo/url-regex\n url: /^(?:https?|ftp):\\/\\/(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z0-9\\u{00a1}-\\u{ffff}]+-)*[a-z0-9\\u{00a1}-\\u{ffff}]+)(?:\\.(?:[a-z0-9\\u{00a1}-\\u{ffff}]+-)*[a-z0-9\\u{00a1}-\\u{ffff}]+)*(?:\\.(?:[a-z\\u{00a1}-\\u{ffff}]{2,})))(?::\\d{2,5})?(?:\\/[^\\s]*)?$/iu,\n email:\n /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,\n hostname:\n /^(?=.{1,253}\\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\\.?$/i,\n // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html\n ipv4: /^(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)$/,\n ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))$/i,\n regex,\n // uuid: http://tools.ietf.org/html/rfc4122\n uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,\n // JSON-pointer: https://tools.ietf.org/html/rfc6901\n // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A\n \"json-pointer\": /^(?:\\/(?:[^~/]|~0|~1)*)*$/,\n \"json-pointer-uri-fragment\": /^#(?:\\/(?:[a-z0-9_\\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,\n // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00\n \"relative-json-pointer\": /^(?:0|[1-9][0-9]*)(?:#|(?:\\/(?:[^~/]|~0|~1)*)*)$/,\n // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types\n // byte: https://github.com/miguelmota/is-base64\n byte,\n // signed 32 bit integer\n int32: {type: \"number\", validate: validateInt32},\n // signed 64 bit integer\n int64: {type: \"number\", validate: validateInt64},\n // C-type float\n float: {type: \"number\", validate: validateNumber},\n // C-type double\n double: {type: \"number\", validate: validateNumber},\n // hint to the UI to hide input strings\n password: true,\n // unchecked string payload\n binary: true,\n}\n\nexport const fastFormats: DefinedFormats = {\n ...fullFormats,\n date: fmtDef(/^\\d\\d\\d\\d-[0-1]\\d-[0-3]\\d$/, compareDate),\n time: fmtDef(\n /^(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)$/i,\n compareTime\n ),\n \"date-time\": fmtDef(\n /^\\d\\d\\d\\d-[0-1]\\d-[0-3]\\dt(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)$/i,\n compareDateTime\n ),\n \"iso-time\": fmtDef(\n /^(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)?$/i,\n compareIsoTime\n ),\n \"iso-date-time\": fmtDef(\n /^\\d\\d\\d\\d-[0-1]\\d-[0-3]\\d[t\\s](?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)?$/i,\n compareIsoDateTime\n ),\n // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js\n uri: /^(?:[a-z][a-z0-9+\\-.]*:)(?:\\/?\\/)?[^\\s]*$/i,\n \"uri-reference\": /^(?:(?:[a-z][a-z0-9+\\-.]*:)?\\/?\\/)?(?:[^\\\\\\s#][^\\s#]*)?(?:#[^\\\\\\s]*)?$/i,\n // email (sources from jsen validator):\n // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363\n // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation')\n email:\n /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,\n}\n\nexport const formatNames = Object.keys(fullFormats) as FormatName[]\n\nfunction isLeapYear(year: number): boolean {\n // https://tools.ietf.org/html/rfc3339#appendix-C\n return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)\n}\n\nconst DATE = /^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)$/\nconst DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n\nfunction date(str: string): boolean {\n // full-date from http://tools.ietf.org/html/rfc3339#section-5.6\n const matches: string[] | null = DATE.exec(str)\n if (!matches) return false\n const year: number = +matches[1]\n const month: number = +matches[2]\n const day: number = +matches[3]\n return (\n month >= 1 &&\n month <= 12 &&\n day >= 1 &&\n day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month])\n )\n}\n\nfunction compareDate(d1: string, d2: string): number | undefined {\n if (!(d1 && d2)) return undefined\n if (d1 > d2) return 1\n if (d1 < d2) return -1\n return 0\n}\n\nconst TIME = /^(\\d\\d):(\\d\\d):(\\d\\d(?:\\.\\d+)?)(z|([+-])(\\d\\d)(?::?(\\d\\d))?)?$/i\n\nfunction getTime(strictTimeZone?: boolean): (str: string) => boolean {\n return function time(str: string): boolean {\n const matches: string[] | null = TIME.exec(str)\n if (!matches) return false\n const hr: number = +matches[1]\n const min: number = +matches[2]\n const sec: number = +matches[3]\n const tz: string | undefined = matches[4]\n const tzSign: number = matches[5] === \"-\" ? -1 : 1\n const tzH: number = +(matches[6] || 0)\n const tzM: number = +(matches[7] || 0)\n if (tzH > 23 || tzM > 59 || (strictTimeZone && !tz)) return false\n if (hr <= 23 && min <= 59 && sec < 60) return true\n // leap second\n const utcMin = min - tzM * tzSign\n const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0)\n return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61\n }\n}\n\nfunction compareTime(s1: string, s2: string): number | undefined {\n if (!(s1 && s2)) return undefined\n const t1 = new Date(\"2020-01-01T\" + s1).valueOf()\n const t2 = new Date(\"2020-01-01T\" + s2).valueOf()\n if (!(t1 && t2)) return undefined\n return t1 - t2\n}\n\nfunction compareIsoTime(t1: string, t2: string): number | undefined {\n if (!(t1 && t2)) return undefined\n const a1 = TIME.exec(t1)\n const a2 = TIME.exec(t2)\n if (!(a1 && a2)) return undefined\n t1 = a1[1] + a1[2] + a1[3]\n t2 = a2[1] + a2[2] + a2[3]\n if (t1 > t2) return 1\n if (t1 < t2) return -1\n return 0\n}\n\nconst DATE_TIME_SEPARATOR = /t|\\s/i\nfunction getDateTime(strictTimeZone?: boolean): (str: string) => boolean {\n const time = getTime(strictTimeZone)\n\n return function date_time(str: string): boolean {\n // http://tools.ietf.org/html/rfc3339#section-5.6\n const dateTime: string[] = str.split(DATE_TIME_SEPARATOR)\n return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1])\n }\n}\n\nfunction compareDateTime(dt1: string, dt2: string): number | undefined {\n if (!(dt1 && dt2)) return undefined\n const d1 = new Date(dt1).valueOf()\n const d2 = new Date(dt2).valueOf()\n if (!(d1 && d2)) return undefined\n return d1 - d2\n}\n\nfunction compareIsoDateTime(dt1: string, dt2: string): number | undefined {\n if (!(dt1 && dt2)) return undefined\n const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR)\n const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR)\n const res = compareDate(d1, d2)\n if (res === undefined) return undefined\n return res || compareTime(t1, t2)\n}\n\nconst NOT_URI_FRAGMENT = /\\/|:/\nconst URI =\n /^(?:[a-z][a-z0-9+\\-.]*:)(?:\\/?\\/(?:(?:[a-z0-9\\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\\.[a-z0-9\\-._~!$&'()*+,;=:]+)\\]|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)|(?:[a-z0-9\\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\\d*)?(?:\\/(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\\/(?:(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\\?(?:[a-z0-9\\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i\n\nfunction uri(str: string): boolean {\n // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required \".\"\n return NOT_URI_FRAGMENT.test(str) && URI.test(str)\n}\n\nconst BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm\n\nfunction byte(str: string): boolean {\n BYTE.lastIndex = 0\n return BYTE.test(str)\n}\n\nconst MIN_INT32 = -(2 ** 31)\nconst MAX_INT32 = 2 ** 31 - 1\n\nfunction validateInt32(value: number): boolean {\n return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32\n}\n\nfunction validateInt64(value: number): boolean {\n // JSON and javascript max Int is 2**53, so any int that passes isInteger is valid for Int64\n return Number.isInteger(value)\n}\n\nfunction validateNumber(): boolean {\n return true\n}\n\nconst Z_ANCHOR = /[^\\\\]\\\\Z/\nfunction regex(str: string): boolean {\n if (Z_ANCHOR.test(str)) return false\n try {\n new RegExp(str)\n return true\n } catch (e) {\n return false\n }\n}\n","import type Ajv from \"ajv\"\nimport type {\n Plugin,\n CodeKeywordDefinition,\n KeywordErrorDefinition,\n Code,\n Name,\n ErrorObject,\n} from \"ajv\"\nimport type {AddedFormat} from \"ajv/dist/types\"\nimport type {Rule} from \"ajv/dist/compile/rules\"\nimport {KeywordCxt} from \"ajv\"\nimport {_, str, or, getProperty, operators} from \"ajv/dist/compile/codegen\"\n\ntype Kwd = \"formatMaximum\" | \"formatMinimum\" | \"formatExclusiveMaximum\" | \"formatExclusiveMinimum\"\n\ntype Comparison = \"<=\" | \">=\" | \"<\" | \">\"\n\nconst ops = operators\n\nconst KWDs: {[K in Kwd]: {okStr: Comparison; ok: Code; fail: Code}} = {\n formatMaximum: {okStr: \"<=\", ok: ops.LTE, fail: ops.GT},\n formatMinimum: {okStr: \">=\", ok: ops.GTE, fail: ops.LT},\n formatExclusiveMaximum: {okStr: \"<\", ok: ops.LT, fail: ops.GTE},\n formatExclusiveMinimum: {okStr: \">\", ok: ops.GT, fail: ops.LTE},\n}\n\nexport type LimitFormatError = ErrorObject<Kwd, {limit: string; comparison: Comparison}>\n\nconst error: KeywordErrorDefinition = {\n message: ({keyword, schemaCode}) => str`should be ${KWDs[keyword as Kwd].okStr} ${schemaCode}`,\n params: ({keyword, schemaCode}) =>\n _`{comparison: ${KWDs[keyword as Kwd].okStr}, limit: ${schemaCode}}`,\n}\n\nexport const formatLimitDefinition: CodeKeywordDefinition = {\n keyword: Object.keys(KWDs),\n type: \"string\",\n schemaType: \"string\",\n $data: true,\n error,\n code(cxt) {\n const {gen, data, schemaCode, keyword, it} = cxt\n const {opts, self} = it\n if (!opts.validateFormats) return\n\n const fCxt = new KeywordCxt(it, (self.RULES.all.format as Rule).definition, \"format\")\n if (fCxt.$data) validate$DataFormat()\n else validateFormat()\n\n function validate$DataFormat(): void {\n const fmts = gen.scopeValue(\"formats\", {\n ref: self.formats,\n code: opts.code.formats,\n })\n const fmt = gen.const(\"fmt\", _`${fmts}[${fCxt.schemaCode}]`)\n cxt.fail$data(\n or(\n _`typeof ${fmt} != \"object\"`,\n _`${fmt} instanceof RegExp`,\n _`typeof ${fmt}.compare != \"function\"`,\n compareCode(fmt)\n )\n )\n }\n\n function validateFormat(): void {\n const format = fCxt.schema as string\n const fmtDef: AddedFormat | undefined = self.formats[format]\n if (!fmtDef || fmtDef === true) return\n if (\n typeof fmtDef != \"object\" ||\n fmtDef instanceof RegExp ||\n typeof fmtDef.compare != \"function\"\n ) {\n throw new Error(`\"${keyword}\": format \"${format}\" does not define \"compare\" function`)\n }\n const fmt = gen.scopeValue(\"formats\", {\n key: format,\n ref: fmtDef,\n code: opts.code.formats ? _`${opts.code.formats}${getProperty(format)}` : undefined,\n })\n\n cxt.fail$data(compareCode(fmt))\n }\n\n function compareCode(fmt: Name): Code {\n return _`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword as Kwd].fail} 0`\n }\n },\n dependencies: [\"format\"],\n}\n\nconst formatLimitPlugin: Plugin<undefined> = (ajv: Ajv): Ajv => {\n ajv.addKeyword(formatLimitDefinition)\n return ajv\n}\n\nexport default formatLimitPlugin\n","import {\n DefinedFormats,\n FormatMode,\n FormatName,\n formatNames,\n fastFormats,\n fullFormats,\n} from \"./formats\"\nimport formatLimit from \"./limit\"\nimport type Ajv from \"ajv\"\nimport type {Plugin, Format} from \"ajv\"\nimport {_, Name} from \"ajv/dist/compile/codegen\"\n\nexport {FormatMode, FormatName} from \"./formats\"\nexport {LimitFormatError} from \"./limit\"\nexport interface FormatOptions {\n mode?: FormatMode\n formats?: FormatName[]\n keywords?: boolean\n}\n\nexport type FormatsPluginOptions = FormatName[] | FormatOptions\n\nexport interface FormatsPlugin extends Plugin<FormatsPluginOptions> {\n get: (format: FormatName, mode?: FormatMode) => Format\n}\n\nconst fullName = new Name(\"fullFormats\")\nconst fastName = new Name(\"fastFormats\")\n\nconst formatsPlugin: FormatsPlugin = (\n ajv: Ajv,\n opts: FormatsPluginOptions = {keywords: true}\n): Ajv => {\n if (Array.isArray(opts)) {\n addFormats(ajv, opts, fullFormats, fullName)\n return ajv\n }\n const [formats, exportName] =\n opts.mode === \"fast\" ? [fastFormats, fastName] : [fullFormats, fullName]\n const list = opts.formats || formatNames\n addFormats(ajv, list, formats, exportName)\n if (opts.keywords) formatLimit(ajv)\n return ajv\n}\n\nformatsPlugin.get = (name: FormatName, mode: FormatMode = \"full\"): Format => {\n const formats = mode === \"fast\" ? fastFormats : fullFormats\n const f = formats[name]\n if (!f) throw new Error(`Unknown format \"${name}\"`)\n return f\n}\n\nfunction addFormats(ajv: Ajv, list: FormatName[], fs: DefinedFormats, exportName: Name): void {\n ajv.opts.code.formats ??= _`require(\"ajv-formats/dist/formats\").${exportName}`\n for (const f of list) ajv.addFormat(f, fs[f])\n}\n\nmodule.exports = exports = formatsPlugin\nObject.defineProperty(exports, \"__esModule\", {value: true})\n\nexport default formatsPlugin\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createInstallPlan } from \"../../core/install-plan.js\";\nimport { buildAiWorkflowConfig, getTemplateFiles, isValidProfile } from \"../../core/templates.js\";\nimport { exists, writeFileSafe, readJson } from \"../../core/filesystem.js\";\nimport { createManagedBackup, createManagedPathBackup } from \"../../core/backup.js\";\nimport { mergeOpencodeConfig } from \"../../core/opencode-merge.js\";\nimport { buildSymlinkEntries, isSymlinkTo, setupInternalSymlinks } from \"../../core/symlink-layout.js\";\nimport { ClaudeAdapter, CodexAdapter, AntigravityAdapter } from \"../../adapters/index.js\";\n\nfunction summarize(actions: any[]) {\n const createCount = actions.filter((a) => a.type === \"create\").length;\n const conflictCount = actions.filter((a) => a.type === \"conflict\").length;\n\n return { createCount, conflictCount };\n}\n\nfunction printPlan(actions: any[]) {\n for (const action of actions) {\n console.log(`- ${action.type.padEnd(8)} ${action.relativePath}`);\n }\n}\n\nfunction toIgnoreEntries(linkPath: string): string[] {\n if (linkPath === \"README.workflow.md\") {\n return [linkPath];\n }\n\n const normalized = linkPath.endsWith(\"/\") ? linkPath.slice(0, -1) : linkPath;\n return [normalized, `${normalized}/`];\n}\n\nfunction buildGitignoreBlock(entries: string[]): string {\n const unique = Array.from(new Set(entries));\n const sorted = unique.sort((a, b) => a.localeCompare(b));\n\n return [\n \"# BEGIN AI WORKFLOW KIT\",\n \"# AI Workflow Kit generated files\",\n ...sorted,\n \"# END AI WORKFLOW KIT\"\n ].join(\"\\n\");\n}\n\nasync function upsertGitignoreBlock(cwd: string, entries: string[]): Promise<string> {\n const gitignorePath = path.join(cwd, \".gitignore\");\n const block = buildGitignoreBlock(entries);\n const beginMarker = \"# BEGIN AI WORKFLOW KIT\";\n const endMarker = \"# END AI WORKFLOW KIT\";\n\n const hasGitignore = await exists(gitignorePath);\n if (!hasGitignore) {\n await writeFileSafe(gitignorePath, `${block}\\n`);\n return \"created\";\n }\n\n const current = await fs.readFile(gitignorePath, \"utf8\");\n const beginIndex = current.indexOf(beginMarker);\n const endIndex = current.indexOf(endMarker);\n\n if (beginIndex >= 0 && endIndex > beginIndex) {\n const before = current\n .slice(0, beginIndex)\n .replace(/\\n?# AI Workflow Kit generated files\\n?$/, \"\\n\")\n .replace(/[ \\t]+$/gm, \"\")\n .replace(/\\n*$/, \"\\n\");\n const afterStart = endIndex + endMarker.length;\n const after = current.slice(afterStart).replace(/^\\n*/, \"\\n\");\n const next = `${before}${block}${after}`;\n if (next !== current) {\n await writeFileSafe(gitignorePath, next);\n return \"updated\";\n }\n return \"unchanged\";\n }\n\n const separator = current.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n const next = `${current}${separator}${block}\\n`;\n await writeFileSafe(gitignorePath, next);\n return \"updated\";\n}\n\nasync function injectScripts(cwd: string): Promise<boolean> {\n const pkgPath = path.join(cwd, \"package.json\");\n if (!(await exists(pkgPath))) return false;\n\n try {\n const pkg = await readJson(pkgPath);\n if (!pkg.scripts) pkg.scripts = {};\n\n if (!pkg.scripts.validate) {\n pkg.scripts.validate = \"ai-workflow collect-evidence\";\n await writeFileSafe(pkgPath, `${JSON.stringify(pkg, null, 2)}\\n`);\n return true;\n }\n } catch {\n // Ignore invalid package.json\n }\n return false;\n}\n\nexport interface InitOptions {\n cwd: string;\n yes?: boolean;\n force?: boolean;\n dryRun?: boolean;\n noInstall?: boolean;\n noOverwrite?: boolean;\n claude?: boolean;\n codex?: boolean;\n antigravity?: boolean;\n \"dev-mode\"?: boolean;\n profile?: string;\n}\n\nasync function verifySelfExecutionGuard(cwd: string, devMode?: boolean): Promise<void> {\n if (!devMode) {\n try {\n const pkgPath = path.join(cwd, \"package.json\");\n if (await exists(pkgPath)) {\n const pkg = await readJson(pkgPath);\n if (pkg.name === \"@williambeto/ai-workflow\") {\n console.error(\"\\nFATAL: Cannot run 'ai-workflow init' inside its own development repository.\");\n console.error(\"This would corrupt the development environment. Aborting.\");\n console.error(\"Use the --dev-mode flag if you are developing the kit itself and need to test the init command.\\n\");\n process.exit(1);\n }\n }\n } catch {\n // Ignore if package.json is unreadable. The guard is a safety net.\n }\n }\n}\n\nfunction resolveProfile(profile?: string): string {\n const selectedProfile = profile || \"standard\";\n if (!isValidProfile(selectedProfile)) {\n console.error(`Invalid profile: \"${selectedProfile}\". Valid profiles: standard, full`);\n process.exit(1);\n }\n return selectedProfile;\n}\n\nasync function writeInstallFiles(\n cwd: string,\n actions: any[],\n selectedProfile: string,\n platforms: string[],\n force?: boolean,\n noOverwrite?: boolean,\n backupRoot = \".ai-workflow-backups\"\n): Promise<{ skipped: string[]; backups: string[] }> {\n const skipped: string[] = [];\n const backups: string[] = [];\n\n for (const action of actions) {\n if (action.type === \"conflict\" && (noOverwrite || !force)) {\n skipped.push(action.relativePath);\n continue;\n }\n\n if (action.type === \"conflict\" && force) {\n const backupPath = await createManagedBackup(action.absolutePath, {\n cwd,\n backupRoot,\n maxPerFile: 20\n });\n backups.push(backupPath);\n }\n\n const content =\n action.relativePath === \".ai-workflow/config.json\"\n ? `${JSON.stringify(buildAiWorkflowConfig({ profile: selectedProfile, runtimes: platforms.length > 0 ? platforms : [\"opencode\"] }), null, 2)}\\n`\n : action.content;\n\n await writeFileSafe(action.absolutePath, content || \"\");\n }\n\n return { skipped, backups };\n}\n\nasync function writeSymlinks(\n cwd: string,\n linkEntries: any[],\n force?: boolean,\n backupRoot = \".ai-workflow-backups\"\n): Promise<{ linkBackups: string[]; linkCreated: string[] }> {\n const linkBackups: string[] = [];\n const linkCreated: string[] = [];\n\n for (const { linkPath, targetPath } of linkEntries) {\n const absoluteLinkPath = path.join(cwd, linkPath);\n const absoluteTargetPath = path.join(cwd, targetPath);\n\n if (!(await exists(absoluteTargetPath))) {\n throw new Error(`missing link target: ${targetPath}`);\n }\n\n if (await isSymlinkTo(absoluteLinkPath, absoluteTargetPath)) {\n continue;\n }\n\n if (await exists(absoluteLinkPath)) {\n if (!force) {\n throw new Error(\n `cannot create symlink '${linkPath}' because path already exists. Re-run with --force to backup and replace. If symlink creation fails, see troubleshooting in docs/npm-consumer-quickstart.md.`\n );\n }\n const backupPath = await createManagedPathBackup(absoluteLinkPath, {\n cwd,\n backupRoot,\n maxPerFile: 20\n });\n linkBackups.push(backupPath);\n await fs.rm(absoluteLinkPath, { recursive: true, force: true });\n }\n\n const stat = await fs.lstat(absoluteTargetPath);\n const type = process.platform === \"win32\"\n ? (stat.isDirectory() ? \"junction\" : \"file\")\n : (stat.isDirectory() ? \"dir\" : \"file\");\n const linkTarget = process.platform === \"win32\"\n ? absoluteTargetPath\n : path.relative(path.dirname(absoluteLinkPath), absoluteTargetPath);\n\n try {\n await fs.mkdir(path.dirname(absoluteLinkPath), { recursive: true });\n await fs.symlink(linkTarget, absoluteLinkPath, type);\n } catch (error: any) {\n throw new Error(\n `failed to create symlink '${linkPath}' -> '${targetPath}' (${error.message}). ` +\n \"For Windows, enable Developer Mode or run terminal as Administrator. \" +\n \"For Linux/macOS, verify write permissions in project root.\"\n );\n }\n linkCreated.push(linkPath);\n }\n\n return { linkBackups, linkCreated };\n}\n\nasync function executePlatformMigrations(\n cwd: string,\n installRoot: string,\n platforms: string[],\n claude?: boolean,\n codex?: boolean,\n antigravity?: boolean,\n force?: boolean\n): Promise<void> {\n if (platforms.length === 0) return;\n\n console.log(\"ai-workflow: migrating to native platforms...\");\n const agentsDir = path.join(cwd, installRoot, \"opencode/agents\");\n const skillsDir = path.join(cwd, installRoot, \"opencode/skills\");\n\n const agentFiles = (await fs.readdir(agentsDir).catch(() => []))\n .filter((f) => f.endsWith(\".md\"))\n .map((f) => path.join(agentsDir, f));\n\n if (claude) {\n const adapter = new ClaudeAdapter({ cwd });\n await adapter.deploy(installRoot);\n console.log(\"- claude: deployed AI Workflow Kit agents to CLAUDE.md and .claude/rules/ (native discovery enabled)\");\n }\n\n if (codex) {\n const adapter = new CodexAdapter({ cwd });\n await adapter.deploy(installRoot, force);\n console.log(\"- codex: deployed AI Workflow Kit agents to .agents/, .codex/, and .github/ (native discovery enabled)\");\n }\n\n if (antigravity) {\n const adapter = new AntigravityAdapter({ cwd });\n const skillFolders = await fs.readdir(skillsDir).catch(() => []);\n const skillFiles: string[] = [];\n for (const folder of skillFolders) {\n const skillPath = path.join(skillsDir, folder, \"SKILL.md\");\n if (await exists(skillPath)) {\n skillFiles.push(skillPath);\n }\n }\n\n const allFiles = [...agentFiles, ...skillFiles];\n const transformed = await Promise.all(allFiles.map((f) => adapter.transform(f)));\n await adapter.deploy(transformed, installRoot);\n console.log(`- antigravity: deployed AI Workflow Kit agents to .agents/ (native discovery enabled)`);\n }\n}\n\nfunction printInstallationSummary({\n selectedProfile,\n opencodeResult,\n gitignoreResult,\n scriptInjected,\n linkCreated,\n backups,\n linkBackups,\n skipped,\n noInstall\n}: {\n selectedProfile: string;\n opencodeResult: any;\n gitignoreResult: string;\n scriptInjected: boolean;\n linkCreated: string[];\n backups: string[];\n linkBackups: string[];\n skipped: string[];\n noInstall?: boolean;\n}): void {\n console.log(\"Installation complete.\");\n console.log(`- profile: ${selectedProfile}`);\n console.log(`- opencode.jsonc: ${opencodeResult.reason}`);\n console.log(`- .gitignore: ${gitignoreResult}`);\n console.log(`- scripts: ${scriptInjected ? \"injected 'validate'\" : \"already-up-to-date\"}`);\n console.log(`- symlink layout: ${linkCreated.length > 0 ? `created ${linkCreated.length}` : \"already-up-to-date\"}`);\n\n if (backups.length > 0) {\n console.log(`- backups created: ${backups.length}`);\n for (const filePath of backups) {\n console.log(` ${filePath}`);\n }\n }\n if (linkBackups.length > 0) {\n console.log(`- symlink backups created: ${linkBackups.length}`);\n for (const filePath of linkBackups) {\n console.log(` ${filePath}`);\n }\n }\n if (skipped.length > 0) {\n console.log(`- conflicts skipped: ${skipped.length}`);\n for (const relativePath of skipped) {\n console.log(` ${relativePath}`);\n }\n }\n console.log(`- dependency install: ${noInstall ? \"skipped (--no-install)\" : \"not managed in this step\"}`);\n console.log(\"Next steps:\");\n console.log(\" npx @williambeto/ai-workflow doctor\");\n}\n\nexport async function runInit({\n cwd, yes, force, dryRun, noInstall, noOverwrite, claude, codex, antigravity, \"dev-mode\": devMode, profile\n}: InitOptions): Promise<void> {\n await verifySelfExecutionGuard(cwd, devMode);\n\n const selectedProfile = resolveProfile(profile);\n const installRoot = \".ai-workflow\";\n const backupRoot = \".ai-workflow-backups\";\n\n const platforms: string[] = [];\n if (claude) platforms.push(\"claude\");\n if (codex) platforms.push(\"codex\");\n if (antigravity) platforms.push(\"antigravity\");\n\n console.log(`ai-workflow: initializing in ${cwd}`);\n console.log(`Profile: ${selectedProfile}`);\n if (platforms.length > 0) {\n console.log(`Platforms: ${platforms.join(\", \")}`);\n }\n\n const actions = await createInstallPlan({ cwd, exists, profile: selectedProfile });\n const linkEntries = buildSymlinkEntries({ templateFiles: getTemplateFiles(selectedProfile), installRoot });\n const { createCount, conflictCount } = summarize(actions);\n\n console.log(`Plan: ${createCount} create, ${conflictCount} conflict`);\n printPlan(actions);\n\n if (!yes && conflictCount > 0 && !force && !noOverwrite) {\n throw new Error(\n \"conflicts detected. Re-run with --force to replace managed files or resolve conflicts manually\"\n );\n }\n\n if (dryRun) {\n console.log(\"Dry-run enabled. No files were written.\");\n if (platforms.length > 0) {\n console.log(\"ai-workflow: (dry-run) platform migration would be executed after file writing.\");\n }\n return;\n }\n\n const { skipped, backups } = await writeInstallFiles(cwd, actions, selectedProfile, platforms, force, noOverwrite, backupRoot);\n const { linkBackups, linkCreated } = await writeSymlinks(cwd, linkEntries, force, backupRoot);\n\n await setupInternalSymlinks(cwd, installRoot);\n\n const opencodeResult = await mergeOpencodeConfig(cwd, { force, backupRoot });\n\n const generatedIgnoreEntries = [\n \"node_modules/\",\n \".ai-workflow/\",\n \".ai-workflow-backups/\",\n \"opencode.jsonc.backup.*\",\n \"EVIDENCE.json\",\n \"*.tgz\",\n ...linkEntries.flatMap((entry) => toIgnoreEntries(entry.linkPath))\n ];\n\n if (codex) {\n generatedIgnoreEntries.push(\".agents/\", \".codex/\");\n }\n if (claude) {\n generatedIgnoreEntries.push(\".claude/\");\n }\n if (antigravity) {\n generatedIgnoreEntries.push(\".agents/\");\n }\n\n const gitignoreResult = await upsertGitignoreBlock(cwd, generatedIgnoreEntries);\n const scriptInjected = await injectScripts(cwd);\n\n await executePlatformMigrations(cwd, installRoot, platforms, claude, codex, antigravity, force);\n\n printInstallationSummary({\n selectedProfile,\n opencodeResult,\n gitignoreResult,\n scriptInjected,\n linkCreated,\n backups,\n linkBackups,\n skipped,\n noInstall\n });\n}\n","import path from \"node:path\";\nimport { getTemplateFiles } from \"./templates.js\";\n\nexport interface InstallAction {\n type: \"conflict\" | \"create\";\n relativePath: string;\n absolutePath: string;\n content: string | null;\n}\n\nexport interface CreateInstallPlanOptions {\n cwd: string;\n exists: (filePath: string) => Promise<boolean> | boolean;\n profile?: string;\n}\n\nexport async function createInstallPlan({\n cwd,\n exists,\n profile = \"standard\"\n}: CreateInstallPlanOptions): Promise<InstallAction[]> {\n const actions: InstallAction[] = [];\n const templateFiles = getTemplateFiles(profile);\n const installRoot = \".ai-workflow\";\n\n for (const [relativePath, content] of Object.entries(templateFiles)) {\n if (relativePath === \"opencode.jsonc\") {\n continue;\n }\n\n const installedRelativePath = path.join(installRoot, relativePath);\n const absolutePath = path.join(cwd, installedRelativePath);\n const action = (await exists(absolutePath)) ? \"conflict\" : \"create\";\n actions.push({\n type: action,\n relativePath: installedRelativePath,\n absolutePath,\n content\n });\n }\n\n const configPath = path.join(cwd, \".ai-workflow/config.json\");\n actions.push({\n type: (await exists(configPath)) ? \"conflict\" : \"create\",\n relativePath: \".ai-workflow/config.json\",\n absolutePath: configPath,\n content: null\n });\n\n return actions;\n}\n","import { getFullAgentContent, getFullSkillFiles, discoverPackageFiles, readPackageFile, getPackageVersion } from \"./package-assets.js\";\nimport { getCanonicalAgentName } from \"./identity.js\";\n\nconst COMMON_FILES: Record<string, string> = {\n \"opencode/README.md\": `# OpenCode Setup\\n\\nThis directory is managed by \\`ai-workflow\\` init.\\nAdd agent and command files required by your project workflow.\\n`\n};\n\nconst FULL_PRIMARY_AGENTS: string[] = [\n \"atlas\",\n \"nexus\",\n \"orion\",\n \"astra\",\n \"sage\",\n \"phoenix\"\n];\n\nconst FULL_SKILLS: string[] = [\n \"project-memory\",\n \"optimize-tokens\",\n \"documentation\",\n \"architecture\",\n \"technical-leadership\",\n \"product-discovery\",\n \"product-planning\",\n \"spec-driven-development\",\n \"pr-workflow\",\n \"qa-workflow\",\n \"release-workflow\",\n \"deployment\",\n \"ui-ux-design\",\n \"design-principles\",\n \"frontend-development\",\n \"backend-development\",\n \"full-stack-development\",\n \"refactoring\",\n \"prompt-engineer\"\n];\n\nfunction buildRuntimeFiles({ includeFormalEvidence = false }: { includeFormalEvidence?: boolean } = {}): Record<string, string> {\n const files: Record<string, string> = {};\n\n for (const agent of FULL_PRIMARY_AGENTS) {\n const content = getFullAgentContent(agent);\n if (content === null) {\n throw new Error(`CRITICAL FAILURE: Missing required agent asset: dist-assets/agents/${agent}.md`);\n }\n files[`opencode/agents/${agent}.md`] = content;\n }\n\n for (const skill of FULL_SKILLS) {\n const skillFiles = getFullSkillFiles(skill);\n if (Object.keys(skillFiles).length === 0) {\n continue;\n }\n for (const [relPath, content] of Object.entries(skillFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n if (!files[targetPath]) {\n files[targetPath] = content;\n }\n }\n }\n\n // Copy governance policy into opencode/docs/policies/ so the relative link\n // ../../docs/policies/SKILLS_COMMON_GOVERNANCE.md resolves correctly from\n // opencode/skills/{skill}/SKILL.md for OpenCode and all platform adapters.\n const opencodeGovernancePolicy = readPackageFile(\"dist-assets/docs/policies/SKILLS_COMMON_GOVERNANCE.md\");\n if (opencodeGovernancePolicy !== null) {\n files[\"opencode/docs/policies/SKILLS_COMMON_GOVERNANCE.md\"] = opencodeGovernancePolicy;\n }\n\n const commandFiles = discoverPackageFiles(\"dist-assets/commands\");\n for (const [relPath, content] of Object.entries(commandFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n if (!files[targetPath]) {\n files[targetPath] = content;\n }\n }\n\n const opencodeSkillFiles = discoverPackageFiles(\"dist-assets/skills\");\n for (const [relPath, content] of Object.entries(opencodeSkillFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n if (!files[targetPath]) {\n files[targetPath] = content;\n }\n }\n\n const harnessWorkflowFiles = discoverPackageFiles(\"dist-assets/harness/workflows\");\n for (const [relPath, content] of Object.entries(harnessWorkflowFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"\");\n files[targetPath] = content;\n }\n\n const harnessHandoffFiles = discoverPackageFiles(\"dist-assets/harness/handoffs\");\n for (const [relPath, content] of Object.entries(harnessHandoffFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"\");\n files[targetPath] = content;\n }\n\n const agentsContent = readPackageFile(\"dist-assets/AGENTS.md\");\n if (agentsContent !== null) files[\"AGENTS.md\"] = agentsContent;\n\n const consumerQuickstart = readPackageFile(\"dist-assets/docs/QUICKSTART.md\");\n if (consumerQuickstart !== null) files[\"QUICKSTART.md\"] = consumerQuickstart;\n\n const policyContent = readPackageFile(\"dist-assets/docs/architecture-policy.md\");\n if (policyContent !== null) files[\"opencode/docs/architecture-policy.md\"] = policyContent;\n\n const dpContent = readPackageFile(\"dist-assets/docs/design-patterns-policy.md\");\n if (dpContent !== null) files[\"opencode/docs/design-patterns-policy.md\"] = dpContent;\n\n const visualValidationGuide = readPackageFile(\"dist-assets/docs/visual-validation-guide.md\");\n if (visualValidationGuide !== null) files[\"opencode/docs/visual-validation-guide.md\"] = visualValidationGuide;\n\n const governancePolicies = discoverPackageFiles(\"dist-assets/docs/policies\");\n for (const [relPath, content] of Object.entries(governancePolicies)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n files[targetPath] = content;\n }\n\n const compatibilityDocs = discoverPackageFiles(\"dist-assets/docs/compatibility\");\n for (const [relPath, content] of Object.entries(compatibilityDocs)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n files[targetPath] = content;\n }\n\n const qualityReferenceFiles = discoverPackageFiles(\"dist-assets/docs/references\");\n for (const [relPath, content] of Object.entries(qualityReferenceFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n files[targetPath] = content;\n }\n\n const workflowProfileFiles = discoverPackageFiles(\"dist-assets/docs/profiles\");\n for (const [relPath, content] of Object.entries(workflowProfileFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n files[targetPath] = content;\n }\n\n const templateFiles = discoverPackageFiles(\"dist-assets/templates\");\n for (const [relPath, content] of Object.entries(templateFiles)) {\n if (!includeFormalEvidence && relPath.includes(\"/owner-evidence/\")) continue;\n const targetPath = relPath.replace(/^dist-assets\\//, \"\");\n files[targetPath] = content;\n }\n\n const schemaFiles = discoverPackageFiles(\"dist-assets/schemas\");\n for (const [relPath, content] of Object.entries(schemaFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"\");\n files[targetPath] = content;\n }\n\n return files;\n}\n\nfunction buildExtraFiles(): Record<string, string> {\n const files: Record<string, string> = {};\n const exampleFiles = discoverPackageFiles(\"dist-assets/examples\");\n for (const [relPath, content] of Object.entries(exampleFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"\");\n files[targetPath] = content;\n }\n return files;\n}\n\nconst STANDARD_FILES = buildRuntimeFiles();\nconst FULL_FILES = { ...buildRuntimeFiles({ includeFormalEvidence: true }), ...buildExtraFiles() };\n\nexport const PROFILE_FILES: Record<string, Record<string, string>> = {\n standard: {\n ...COMMON_FILES,\n ...STANDARD_FILES\n },\n full: {\n ...COMMON_FILES,\n ...FULL_FILES\n }\n};\n\nexport function isValidProfile(profile: any): boolean {\n return profile === \"standard\" || profile === \"full\";\n}\n\nexport function getTemplateFiles(profile: string = \"standard\"): Record<string, string> {\n return PROFILE_FILES[profile] ?? PROFILE_FILES.standard;\n}\n\nexport function getManagedBlocks(): string[] {\n return [\n ...FULL_PRIMARY_AGENTS.map((agent) => `opencode.jsonc:agent.${getCanonicalAgentName(agent)}`),\n ...FULL_SKILLS.map((skill) => `opencode.jsonc:agent.${getCanonicalAgentName(skill)}`),\n \"opencode.jsonc:command.atlas\",\n \"opencode.jsonc:command.run\",\n \"opencode.jsonc:command.discover\",\n \"opencode.jsonc:command.spec-create\",\n \"opencode.jsonc:command.spec-review\",\n \"opencode.jsonc:command.spec-implement\",\n \"opencode.jsonc:command.plan\",\n \"opencode.jsonc:command.implement\",\n \"opencode.jsonc:command.validate\",\n \"opencode.jsonc:command.audit\",\n \"opencode.jsonc:command.optimize-tokens\",\n \"opencode.jsonc:command.update-memory\",\n \"opencode.jsonc:command.release\",\n \"opencode.jsonc:command.deploy\"\n ];\n}\n\nexport interface BuildAiWorkflowConfigOptions {\n profile: string;\n runtimes?: string[];\n managedFiles?: any;\n managedLinks?: any[];\n}\n\nexport interface AiWorkflowConfig {\n package: string;\n version: string | null;\n runtime: string;\n profile: string;\n installMode: string;\n generatedAt: string;\n paths: {\n agents: string;\n commands: string;\n skills: string;\n policies: string;\n harness: string;\n schemas: string;\n };\n}\n\nexport function buildAiWorkflowConfig({ profile, runtimes = [\"opencode\"] }: BuildAiWorkflowConfigOptions): AiWorkflowConfig {\n const version = getPackageVersion();\n const now = new Date().toISOString();\n const primaryRuntime = runtimes.join(\"+\");\n\n return {\n package: \"@williambeto/ai-workflow\",\n version,\n runtime: primaryRuntime,\n profile,\n installMode: \"project-local\",\n generatedAt: now,\n paths: {\n agents: \".ai-workflow/opencode/agents\",\n commands: \".ai-workflow/opencode/commands\",\n skills: \".ai-workflow/opencode/skills\",\n policies: \".ai-workflow/opencode/docs/policies\",\n harness: \".ai-workflow/harness\",\n schemas: \".ai-workflow/schemas\"\n }\n };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nexport async function exists(filePath: string): Promise<boolean> {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n}\n\nimport { execSync } from \"node:child_process\";\n\n/**\n * Safe wrapper for writing files that enforces branch guards on protected branches.\n * NOTE: This branch guard only protects write operations performed through this kit wrapper\n * (or the kit's runtime executions). It does not intercept external shell commands or processes.\n */\nexport async function writeFileSafe(filePath: string, content: string): Promise<void> {\n const absolutePath = path.resolve(filePath);\n const repoCwd = path.resolve(process.cwd());\n const relativeToRepo = path.relative(repoCwd, absolutePath).replaceAll(\"\\\\\", \"/\");\n \n // Normalized precise allowlist\n const isOperational = relativeToRepo === \"EVIDENCE.json\" ||\n relativeToRepo.startsWith(\".ai-workflow/\") ||\n relativeToRepo.startsWith(\".ai-workflow\\\\\");\n \n if (!isOperational) {\n let currentBranch = \"\";\n const fileCwd = path.dirname(absolutePath);\n try {\n currentBranch = execSync(\"git branch --show-current\", { cwd: fileCwd, encoding: \"utf8\", stdio: \"pipe\" }).trim();\n } catch {\n // ignore\n }\n const protectedBranches = [\"main\", \"master\"];\n const isInitCommand = process.argv.includes(\"init\");\n if (protectedBranches.includes(currentBranch) && !isInitCommand) {\n if (process.env.AI_WORKFLOW_BYPASS_PROTECTED_BRANCH !== \"true\") {\n throw new Error(\"FAIL_PROTECTED_BRANCH: Direct writes to protected branch are prohibited.\");\n }\n }\n }\n await fs.mkdir(path.dirname(filePath), { recursive: true });\n await fs.writeFile(filePath, content, \"utf8\");\n}\n\nexport async function readJson(filePath: string): Promise<any> {\n const content = await fs.readFile(filePath, \"utf8\");\n return JSON.parse(content);\n}\n\nfunction stripJsonComments(content: string): string {\n let output = \"\";\n let inString = false;\n let quote = \"\";\n let escaped = false;\n let inLineComment = false;\n let inBlockComment = false;\n\n for (let index = 0; index < content.length; index += 1) {\n const char = content[index];\n const next = content[index + 1];\n\n if (inLineComment) {\n if (char === \"\\n\" || char === \"\\r\") {\n inLineComment = false;\n output += char;\n }\n continue;\n }\n\n if (inBlockComment) {\n if (char === \"*\" && next === \"/\") {\n inBlockComment = false;\n index += 1;\n continue;\n }\n if (char === \"\\n\" || char === \"\\r\") {\n output += char;\n }\n continue;\n }\n\n if (inString) {\n output += char;\n if (escaped) {\n escaped = false;\n } else if (char === \"\\\\\") {\n escaped = true;\n } else if (char === quote) {\n inString = false;\n quote = \"\";\n }\n continue;\n }\n\n if (char === '\"' || char === \"'\") {\n inString = true;\n quote = char;\n output += char;\n continue;\n }\n\n if (char === \"/\" && next === \"/\") {\n inLineComment = true;\n index += 1;\n continue;\n }\n\n if (char === \"/\" && next === \"*\") {\n inBlockComment = true;\n index += 1;\n continue;\n }\n\n output += char;\n }\n\n return output;\n}\n\nfunction stripTrailingCommas(content: string): string {\n let output = \"\";\n let inString = false;\n let quote = \"\";\n let escaped = false;\n\n for (let index = 0; index < content.length; index += 1) {\n const char = content[index];\n\n if (inString) {\n output += char;\n if (escaped) {\n escaped = false;\n } else if (char === \"\\\\\") {\n escaped = true;\n } else if (char === quote) {\n inString = false;\n quote = \"\";\n }\n continue;\n }\n\n if (char === '\"' || char === \"'\") {\n inString = true;\n quote = char;\n output += char;\n continue;\n }\n\n if (char === \",\") {\n let nextIndex = index + 1;\n while (/\\s/.test(content[nextIndex] ?? \"\")) {\n nextIndex += 1;\n }\n if (content[nextIndex] === \"}\" || content[nextIndex] === \"]\") {\n continue;\n }\n }\n\n output += char;\n }\n\n return output;\n}\n\nexport async function readJsonc(filePath: string): Promise<any> {\n const content = await fs.readFile(filePath, \"utf8\");\n return JSON.parse(stripTrailingCommas(stripJsonComments(content)));\n}\n","import path from \"node:path\";\nimport { exists, readJsonc, writeFileSafe } from \"./filesystem.js\";\nimport { createManagedBackup } from \"./backup.js\";\nimport { getTemplateFiles } from \"./templates.js\";\n\n/**\n * @file opencode-merge.ts\n * @description Architecture & Registry for OpenCode configuration synthesis (`opencode.jsonc`).\n *\n * ## Architecture Overview\n * This module is responsible for initializing, updating, and merging the project's\n * `opencode.jsonc` file when `aw init` is executed in a consumer repository.\n *\n * ### Core Responsibilities:\n * 1. **Primary Agents Registry (`AGENTS`)**: Defines the 6 core workflow actors (Atlas, Nexus, Orion, Astra, Sage, Phoenix)\n * and maps their instructions to `.ai-workflow/agents/<name>.md`.\n * 2. **Subagents Registry (`SUBAGENTS`)**: Registers domain-specific subagents mapped 1-to-1 with skills installed\n * in `.ai-workflow/skills/<skill>/SKILL.md`. These subagents can be activated by OpenCode runtimes.\n * 3. **Commands Registry (`COMMANDS`)**: Maps slash-commands (e.g. `/atlas`, `/spec-create`, `/validate`) to their respective agent owners.\n * 4. **Safe JSONC Merging**: Merges AIWK configuration blocks into consumer repositories while preserving existing custom user\n * settings in `opencode.jsonc` and managing backups.\n *\n * ### Registering a New Subagent:\n * To add a new subagent to the OpenCode runtime registry:\n * - Ensure a corresponding skill exists in `dist-assets/skills/<skill-name>/SKILL.md`.\n * - Add a new entry to the `SUBAGENTS` object with a PascalCase/Kebab name, a concise `description`, and the matching `skill` directory name.\n * - Note: 5 auxiliary skills (`cyber-security`, `database`, `devops`, `localization`, `performance`) are intentionally excluded\n * from subagent registration as they serve as contextual lenses for existing agents (see `dist-assets/AGENTS.md`).\n */\n\nconst LEGACY_MARKER = \"_aiWorkflowManaged\";\n\ninterface AgentDef {\n description: string;\n}\n\nconst AGENTS: Record<string, AgentDef> = {\n Atlas: { description: \"Router and workflow coordinator for AI Workflow Kit\" },\n Nexus: { description: \"Discovery, requirement, scope, and specification owner\" },\n Orion: { description: \"Planning, PR sequencing, release, and deployment strategy owner\" },\n Astra: { description: \"Implementation owner for incremental, scoped changes\" },\n Sage: { description: \"Audit, validation, evidence, and quality gate owner\" },\n Phoenix: { description: \"Remediation and regression recovery owner\" }\n};\n\ninterface SubagentDef {\n description: string;\n skill: string;\n}\n\nconst SUBAGENTS: Record<string, SubagentDef> = {\n \"Architecture-Specialist\": { description: \"Select the simplest architecture that safely satisfies current requirements\", skill: \"architecture\" },\n \"Backend-Engineer\": { description: \"Support safe PHP/Node/Python backend changes for APIs and persistence\", skill: \"backend-development\" },\n \"Deployment-Specialist\": { description: \"Plan, review, or validate deployment, release, and production-readiness\", skill: \"deployment\" },\n \"Design-Specialist\": { description: \"Apply practical design principles to keep solutions simple and maintainable\", skill: \"design-principles\" },\n \"Docs-Engineer\": { description: \"Write or improve project documentation, READMEs, guides, and prompts\", skill: \"documentation\" },\n \"Frontend-Engineer\": { description: \"Implement or review frontend changes involving UI, state, routing, and accessibility\", skill: \"frontend-development\" },\n \"Frontend-Design-System-Specialist\": { description: \"Enforce CSS/HTML tokens, semantic elements, typography, and premium atmosphere constraints for frontend quality\", skill: \"frontend-design-system\" },\n \"Full-Stack-Engineer\": { description: \"Coordinate frontend and backend changes as one coherent, testable increment\", skill: \"full-stack-development\" },\n \"Token-Economist\": { description: \"Reduce context size while preserving information required for safe execution\", skill: \"optimize-tokens\" },\n \"PR-Manager\": { description: \"Plan, implement, review, or validate small pull requests while preserving scope\", skill: \"pr-workflow\" },\n \"Discovery-Analyst\": { description: \"Clarify ambiguous requests into actionable problem statements and success outcomes\", skill: \"product-discovery\" },\n \"Product-Planner\": { description: \"Turn clarified needs into scoped requirements with acceptance-ready outcomes\", skill: \"product-planning\" },\n \"Memory-Guardian\": { description: \"Manage discoverable project memory for durable decisions and recurring corrections\", skill: \"project-memory\" },\n \"Prompt-Engineer\": { description: \"Expert in creating and refining prompts for AI agents and workflows\", skill: \"prompt-engineer\" },\n \"QA-Engineer\": { description: \"Design, review, or improve tests, acceptance criteria, and validation evidence\", skill: \"qa-workflow\" },\n \"Refactoring-Specialist\": { description: \"Improve code/document structure safely while preserving behavior\", skill: \"refactoring\" },\n \"Release-Specialist\": { description: \"Prepare release readiness decisions with explicit gates and evidence\", skill: \"release-workflow\" },\n \"SDD-Specialist\": { description: \"Convert approved requirements into explicit, testable specification artifacts\", skill: \"spec-driven-development\" },\n \"Technical-Leader\": { description: \"Make technical decisions, review architecture, and identify trade-offs\", skill: \"technical-leadership\" },\n \"UI-UX-Engineer\": { description: \"Improve usability and interface clarity without introducing unnecessary complexity\", skill: \"ui-ux-design\" }\n};\n\ninterface CommandDef {\n description: string;\n agent: string;\n}\n\nconst COMMANDS: Record<string, CommandDef> = {\n atlas: { description: \"Decide safest next step and delegate to the appropriate workflow or agent\", agent: \"Atlas\" },\n run: { description: \"Execute the master orchestration pipeline (Gates, SDD, Implementation, Validation, Healing)\", agent: \"Atlas\" },\n discover: { description: \"Understand the project, gather context, and create initial documentation\", agent: \"Nexus\" },\n \"spec-create\": { description: \"Create a clear specification before implementation\", agent: \"Nexus\" },\n \"spec-review\": { description: \"Review a specification and validate scope, risks, criteria, and gaps\", agent: \"Nexus\" },\n \"spec-implement\": { description: \"Implement an approved specification incrementally\", agent: \"Astra\" },\n plan: { description: \"Plan a task or change, defining steps, risks, and validation\", agent: \"Orion\" },\n implement: { description: \"Implement a small task with defined scope\", agent: \"Astra\" },\n validate: { description: \"Run project validations and collect evidence\", agent: \"Sage\" },\n audit: { description: \"Audit the project, identify issues, and suggest prioritized improvements\", agent: \"Sage\" },\n \"optimize-tokens\": { description: \"Analyze workflow and context usage; suggest reductions without losing quality or evidence\", agent: \"Sage\" },\n \"update-memory\": { description: \"Update durable project memory with relevant decisions, constraints, and reusable context\", agent: \"Nexus\" },\n release: { description: \"Prepare delivery with commit, push, PR/merge readiness, changelog, and evidence\", agent: \"Orion\" },\n deploy: { description: \"Publish the project to the defined environment after validation and release readiness\", agent: \"Orion\" }\n};\n\ninterface ManagedAgentConfig {\n mode: \"primary\" | \"subagent\";\n description: string;\n prompt: string;\n}\n\ninterface ManagedCommandConfig {\n description: string;\n agent: string;\n template: string;\n}\n\ninterface ManagedConfig {\n $schema: string;\n default_agent: string;\n agent: Record<string, ManagedAgentConfig>;\n skills: {\n paths: string[];\n };\n command: Record<string, ManagedCommandConfig>;\n mcp?: Record<string, any>;\n}\n\nfunction buildManagedConfig(): ManagedConfig {\n const agent: Record<string, ManagedAgentConfig> = {};\n for (const [name, def] of Object.entries(AGENTS)) {\n agent[name] = {\n mode: \"primary\",\n description: def.description,\n prompt: `{file:./.ai-workflow/opencode/agents/${name.toLowerCase()}.md}`\n };\n }\n\n for (const [name, def] of Object.entries(SUBAGENTS)) {\n agent[name] = {\n mode: \"subagent\",\n description: def.description,\n prompt: `{file:./.ai-workflow/opencode/skills/${def.skill}/SKILL.md}`\n };\n }\n\n const command: Record<string, ManagedCommandConfig> = {};\n for (const [name, def] of Object.entries(COMMANDS)) {\n command[name] = {\n description: def.description,\n agent: def.agent,\n template: `{file:./.ai-workflow/opencode/commands/${name}.md}`\n };\n }\n\n return {\n $schema: \"https://opencode.ai/config.json\",\n default_agent: \"Atlas\",\n agent,\n skills: {\n paths: [\"./.ai-workflow/opencode/skills\"]\n },\n command\n };\n}\n\nexport interface MergeOpencodeConfigOptions {\n force?: boolean;\n backupRoot?: string;\n}\n\nexport interface MergeOpencodeConfigResult {\n changed: boolean;\n reason: string;\n}\n\nexport async function mergeOpencodeConfig(\n cwd: string,\n { force = false, backupRoot = \".ai-workflow-backups\" }: MergeOpencodeConfigOptions = {}\n): Promise<MergeOpencodeConfigResult> {\n const targetPath = path.join(cwd, \"opencode.jsonc\");\n const managed = buildManagedConfig();\n\n if (!(await exists(targetPath))) {\n await writeFileSafe(targetPath, `${JSON.stringify(managed, null, 2)}\\n`);\n return { changed: true, reason: \"created\" };\n }\n\n let current: any;\n try {\n current = await readJsonc(targetPath);\n } catch {\n if (!force) {\n return { changed: false, reason: \"invalid-json (skipped)\" };\n }\n await createManagedBackup(targetPath, {\n cwd,\n backupRoot,\n maxPerFile: 20\n });\n await writeFileSafe(targetPath, `${JSON.stringify(managed, null, 2)}\\n`);\n return { changed: true, reason: \"invalid-json (replaced with --force)\" };\n }\n\n const { [LEGACY_MARKER]: _legacyManaged, ...currentWithoutLegacy } = current;\n\n const next = {\n ...currentWithoutLegacy,\n $schema: current.$schema ?? managed.$schema,\n ...(managed.mcp\n ? {\n mcp: {\n ...(current.mcp ?? {}),\n ...managed.mcp\n }\n }\n : {}),\n agent: {\n ...(current.agent ?? {}),\n ...managed.agent\n },\n command: {\n ...(current.command ?? {}),\n ...managed.command\n }\n };\n\n const changed = JSON.stringify(current) !== JSON.stringify(next);\n if (!changed) {\n return { changed: false, reason: \"already-up-to-date\" };\n }\n\n await writeFileSafe(targetPath, `${JSON.stringify(next, null, 2)}\\n`);\n return { changed: true, reason: \"merged-managed-sections\" };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nfunction normalize(p: string): string {\n return p.split(path.sep).join(\"/\");\n}\n\n/**\n * For v3.0.0 \"Elite Governance\", we want an ULTRA-CLEAN root.\n * Only \"opencode\" is symlinked to the root (required for OpenCode discovery).\n * All other assets stay inside .ai-workflow/.\n */\nconst LINKABLE_ROOTS = new Set([\n \"opencode\",\n \".agents\",\n \"examples\"\n]);\n\nconst LINKABLE_FILES = new Set<string>([]);\n\nexport interface BuildSymlinkEntriesOptions {\n templateFiles: Record<string, string>;\n installRoot?: string;\n}\n\nexport interface SymlinkEntry {\n linkPath: string;\n targetPath: string;\n}\n\nexport function buildSymlinkEntries({ templateFiles, installRoot = \".ai-workflow\" }: BuildSymlinkEntriesOptions): SymlinkEntry[] {\n const entries = new Map<string, string>();\n\n for (const relativePath of Object.keys(templateFiles)) {\n if (relativePath === \"opencode.jsonc\") continue;\n\n const normalized = normalize(relativePath);\n\n if (LINKABLE_FILES.has(normalized)) {\n entries.set(normalized, `${installRoot}/${normalized}`);\n continue;\n }\n\n // Match composite paths in LINKABLE_ROOTS (e.g., \"docs/policies\")\n for (const rootPath of LINKABLE_ROOTS) {\n if (normalized === rootPath || normalized.startsWith(`${rootPath}/`)) {\n entries.set(rootPath, `${installRoot}/${rootPath}`);\n break;\n }\n }\n }\n\n return Array.from(entries.entries()).map(([linkPath, targetPath]) => ({ linkPath, targetPath }));\n}\n\nexport async function isSymlinkTo(absoluteLinkPath: string, absoluteTargetPath: string): Promise<boolean> {\n try {\n const stat = await fs.lstat(absoluteLinkPath);\n if (!stat.isSymbolicLink()) return false;\n const currentTarget = await fs.readlink(absoluteLinkPath);\n const resolved = path.resolve(path.dirname(absoluteLinkPath), currentTarget);\n return resolved === absoluteTargetPath;\n } catch {\n return false;\n }\n}\n\n/**\n * Internal symlink to satisfy opencode.jsonc paths without polluting the root.\n * Creates .ai-workflow/opencode/skills -> ../.agents/skills\n */\nexport async function setupInternalSymlinks(cwd: string, installRoot: string = \".ai-workflow\"): Promise<void> {\n const skillsLink = path.join(cwd, installRoot, \"opencode/skills\");\n const skillsTarget = path.join(cwd, installRoot, \".agents/skills\");\n\n if (!(await exists(skillsTarget))) return;\n\n try {\n const stat = await fs.lstat(skillsLink).catch(() => null);\n if (stat) {\n if (stat.isSymbolicLink()) {\n const current = await fs.readlink(skillsLink);\n if (current === \"../.agents/skills\") return;\n await fs.unlink(skillsLink);\n } else {\n return; // File exists, skip\n }\n }\n\n const type = process.platform === \"win32\" ? \"junction\" : \"dir\";\n await fs.symlink(\"../.agents/skills\", skillsLink, type);\n } catch {\n // Silent fail for internal symlink\n }\n}\n\nasync function exists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { COMPLETION_STATUS_TEXT } from \"../../core/statuses.js\";\n\n/**\n * Claude Adapter - Transforms OpenCode agents and skills into CLAUDE.md and .claude/rules/.\n */\nexport class ClaudeAdapter {\n cwd: string;\n\n constructor({ cwd }: { cwd: string }) {\n this.cwd = cwd;\n }\n\n /**\n * Transforms an OpenCode agent or skill into a Claude rule with completion contract.\n */\n async transformToRule(filePath: string, type: \"agent\" | \"skill\" = \"agent\"): Promise<{ content: string; name: string }> {\n const content = await fs.readFile(filePath, \"utf8\");\n const fileName = path.basename(filePath, \".md\") === \"SKILL\" \n ? path.basename(path.dirname(filePath)) \n : path.basename(filePath, \".md\");\n \n const ruleName = `${type}-${fileName.toLowerCase()}`;\n \n const hardenedContent = `---\nname: ${ruleName}\ndescription: ${type === \"agent\" ? \"Persona\" : \"Skill\"} rule for ${fileName}\n---\n# ${fileName} ${type === \"agent\" ? \"Persona\" : \"Skill\"}\n\n${content}\n\n## Completion Contract (Mandatory)\nEvery task completion MUST provide the following payload:\n1. **Status**: ${COMPLETION_STATUS_TEXT}\n2. **Scope reviewed**: Brief summary of what was analyzed.\n3. **Findings**: Evidence-based discoveries.\n4. **Files affected**: List of all concrete paths modified or created.\n5. **Validation/evidence**: Commands run and their results.\n6. **Risks/notes**: Any caveats or technical debt introduced.\n7. **Required manager action**: Clear next step for the orchestrator.\n8. **Can manager continue**: [yes/no]\n`;\n\n return {\n content: hardenedContent,\n name: ruleName\n };\n }\n\n /**\n * Deploys agents, skills, and root CLAUDE.md.\n */\n async deploy(installRoot: string = \".ai-workflow\"): Promise<void> {\n const rulesDir = path.join(this.cwd, \".claude/rules\");\n await fs.mkdir(rulesDir, { recursive: true });\n\n const sourceAgentsDir = path.join(this.cwd, installRoot, \"opencode/agents\");\n const sourceSkillsDir = path.join(this.cwd, installRoot, \"opencode/skills\");\n const sourceCommandsDir = path.join(this.cwd, installRoot, \"opencode/commands\");\n\n // 1. Deploy Agents to .claude/rules/agent-*.md\n const agentFiles = await fs.readdir(sourceAgentsDir).catch(() => []);\n for (const file of agentFiles) {\n if (!file.endsWith(\".md\")) continue;\n const transformed = await this.transformToRule(path.join(sourceAgentsDir, file), \"agent\");\n await fs.writeFile(path.join(rulesDir, `${transformed.name}.md`), transformed.content);\n }\n\n // 2. Deploy Skills to .claude/rules/skill-*.md\n const skillFolders = await fs.readdir(sourceSkillsDir).catch(() => []);\n for (const folder of skillFolders) {\n const skillSource = path.join(sourceSkillsDir, folder, \"SKILL.md\");\n if (await this.exists(skillSource)) {\n const transformed = await this.transformToRule(skillSource, \"skill\");\n await fs.writeFile(path.join(rulesDir, `${transformed.name}.md`), transformed.content);\n }\n }\n\n // 3. Create root CLAUDE.md\n await this.deployRootClaudeMd(sourceCommandsDir);\n }\n\n async deployRootClaudeMd(sourceCommandsDir: string): Promise<void> {\n const targetPath = path.join(this.cwd, \"CLAUDE.md\");\n \n // Collect commands to document them in CLAUDE.md\n const commandFiles = await fs.readdir(sourceCommandsDir).catch(() => []);\n let commandsDoc = \"\";\n for (const file of commandFiles) {\n if (!file.endsWith(\".md\")) continue;\n const name = path.basename(file, \".md\");\n commandsDoc += `- \\`ai-workflow run --spec-path=...\\` (Target: ${name})\\n`;\n }\n\n const instructions = `# CLAUDE.md - AI Workflow Kit Governance\n\nThis project uses the **AI Workflow Kit** (OpenCode-first) workflow.\n\n## Mandate: Atlas Authority Protocol\nAll architectural changes must align with the specifications issued by the **Specification Authority** (./specs).\n\n## Common Commands\n${commandsDoc}\n- \\`ai-workflow doctor\\`: Verify installation.\n- \\`ai-workflow collect-evidence\\`: Generate EVIDENCE.json.\n\n## Rules & Personas\nAdhere to the specific rules and personas defined in \\`.claude/rules/\\`. \n- Always follow the **Branch Gate** policy (never work on \\`main\\`).\n- Always follow the **SDD Workflow** (Spec -> Plan -> PR -> Evidence).\n\n## Completion Contract\nEvery task completion MUST follow the payload format defined in the individual rule files.\n`;\n await fs.writeFile(targetPath, instructions);\n }\n\n async exists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n }\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { COMPLETION_STATUS_TEXT } from \"../../core/statuses.js\";\n\n/**\n * Codex Adapter - Transforms OpenCode agents, skills, and commands into Codex-native formats.\n */\nexport class CodexAdapter {\n cwd: string;\n\n constructor({ cwd }: { cwd: string }) {\n this.cwd = cwd;\n }\n\n /**\n * Transforms an OpenCode agent into a Codex prompt with completion contract.\n */\n async transformAgent(filePath: string): Promise<{ content: string; name: string }> {\n const content = await fs.readFile(filePath, \"utf8\");\n const fileName = path.basename(filePath, \".md\");\n \n const hardenedContent = `${content}\n\n## System Directives for Codex\n- **No Conversational Filler**: Output only the requested artifact or analysis. Do not apologize or add filler text.\n- **Explicit Paths**: Always specify the exact, absolute or relative file path before making edits.\n- **Read-Only First**: Do not invent or assume file contents. Always read the workspace first.\n\n## Completion Contract (Mandatory)\nEvery task completion MUST provide the following payload:\n1. **Status**: ${COMPLETION_STATUS_TEXT}\n2. **Scope reviewed**: Brief summary of what was analyzed.\n3. **Findings**: Evidence-based discoveries.\n4. **Files affected**: List of all concrete paths modified or created.\n5. **Validation/evidence**: Commands run and their results.\n6. **Risks/notes**: Any caveats or technical debt introduced.\n7. **Required manager action**: Clear next step for the orchestrator.\n8. **Can manager continue**: [yes/no]\n`;\n\n return {\n content: hardenedContent,\n name: fileName\n };\n }\n\n /**\n * Deploys agents, skills, and commands to Codex-native directories.\n * Mapping:\n * - Agents -> .github/agents/\n * - Skills -> .agents/skills/\n * - Commands -> .codex/prompts/\n */\n async deploy(installRoot: string = \".ai-workflow\", force?: boolean): Promise<void> {\n const sourceAgentsDir = path.join(this.cwd, installRoot, \"opencode/agents\");\n const sourceSkillsDir = path.join(this.cwd, installRoot, \"opencode/skills\");\n const sourceCommandsDir = path.join(this.cwd, installRoot, \"opencode/commands\");\n\n // 1. Deploy Agents to .github/agents/\n const codexAgentsDir = path.join(this.cwd, \".github/agents\");\n await fs.mkdir(codexAgentsDir, { recursive: true });\n \n const agentFiles = await fs.readdir(sourceAgentsDir).catch(() => []);\n for (const file of agentFiles) {\n if (!file.endsWith(\".md\")) continue;\n const transformed = await this.transformAgent(path.join(sourceAgentsDir, file));\n await fs.writeFile(path.join(codexAgentsDir, `${transformed.name}.md`), transformed.content);\n }\n\n // 2. Deploy Skills to .codex/skills/\n const codexSkillsDir = path.join(this.cwd, \".codex/skills\");\n await fs.mkdir(codexSkillsDir, { recursive: true });\n\n const skillFolders = await fs.readdir(sourceSkillsDir).catch(() => []);\n for (const folder of skillFolders) {\n const skillSource = path.join(sourceSkillsDir, folder, \"SKILL.md\");\n if (await this.exists(skillSource)) {\n const targetDir = path.join(codexSkillsDir, folder);\n await fs.mkdir(targetDir, { recursive: true });\n const content = await fs.readFile(skillSource, \"utf8\");\n await fs.writeFile(path.join(targetDir, \"SKILL.md\"), content);\n }\n }\n\n // 3. Deploy Commands to .codex/prompts/\n const codexPromptsDir = path.join(this.cwd, \".codex/prompts\");\n await fs.mkdir(codexPromptsDir, { recursive: true });\n\n const commandFiles = await fs.readdir(sourceCommandsDir).catch(() => []);\n for (const file of commandFiles) {\n if (!file.endsWith(\".md\") && !file.endsWith(\".toml\")) continue;\n // Codex prompts work best as .md\n const targetFileName = file.endsWith(\".toml\") ? `${path.basename(file, \".toml\")}.md` : file;\n const content = await fs.readFile(path.join(sourceCommandsDir, file), \"utf8\");\n await fs.writeFile(path.join(codexPromptsDir, targetFileName), content);\n }\n\n // 4. Copy governance policy into .codex/docs/policies/ so the relative\n // link ../../docs/policies/SKILLS_COMMON_GOVERNANCE.md in each\n // .codex/skills/{skill}/SKILL.md resolves correctly.\n const codexPoliciesDir = path.join(this.cwd, \".codex\", \"docs\", \"policies\");\n await fs.mkdir(codexPoliciesDir, { recursive: true });\n const sourcePoliciesDir = path.join(this.cwd, installRoot, \"opencode\", \"docs\", \"policies\");\n const policyFiles = await fs.readdir(sourcePoliciesDir).catch(() => []);\n for (const file of policyFiles) {\n if (!file.endsWith(\".md\")) continue;\n const policyContent = await fs.readFile(path.join(sourcePoliciesDir, file), \"utf8\");\n await fs.writeFile(path.join(codexPoliciesDir, file), policyContent);\n }\n\n // 5. Create root .github/copilot-instructions.md for maximum Copilot/Codex compatibility\n await this.deployRootCopilotInstructions();\n\n // 6. Create root CODEX.md for explicit global project contract\n await this.deployRootCodexMd(force);\n\n // 7. Create root AGENTS.md for compatibility\n await this.deployRootAgentsMd(force);\n }\n\n async deployRootCopilotInstructions(): Promise<void> {\n const githubDir = path.join(this.cwd, \".github\");\n await fs.mkdir(githubDir, { recursive: true });\n const targetPath = path.join(githubDir, \"copilot-instructions.md\");\n \n const instructions = `# AI Workflow Kit Governance\n\nThis repository uses the **AI Workflow Kit** (OpenCode-first) workflow.\n\n## Mandate: Atlas Authority Protocol\nAll architectural changes must align with the specifications issued by the **Specification Authority**.\n\n## Rules & Personas\n- Always follow the **Branch Gate** policy (never work on \\`main\\`).\n- Always follow the **SDD Workflow** (Spec -> Plan -> PR -> Evidence).\n- When acting as an agent, consult the instructions in \\`.github/agents/\\`.\n- When utilizing skills, consult the files in \\`.codex/skills/\\`.\n\n## System Boundaries\n- **No Conversational Filler**: Do not apologize or add filler text.\n- **Strict Evidence**: You must provide the Completion Contract payload when finishing a task.\n- **Immutable Core**: Do not modify files inside \\`.ai-workflow/\\`, \\`.agents/\\`, \\`.claude/\\`, or \\`.codex/\\` unless explicitly requested.\n\n## Completion Contract\nEvery task completion MUST follow the payload format defined in the individual agent files.\n`;\n await fs.writeFile(targetPath, instructions);\n }\n\n async deployRootCodexMd(force?: boolean): Promise<void> {\n const targetPath = path.join(this.cwd, \"CODEX.md\");\n if (!force && await this.exists(targetPath)) return;\n \n // Check if the template exists\n const templatePath = path.join(this.cwd, \".ai-workflow\", \"templates\", \"CODEX.md.template\");\n if (await this.exists(templatePath)) {\n const content = await fs.readFile(templatePath, \"utf8\");\n await fs.writeFile(targetPath, content);\n return;\n }\n\n // Fallback to copilot instructions\n const instructions = `# AI Workflow Kit Governance\n\nThis repository uses the **AI Workflow Kit** (OpenCode-first) workflow.\n\n## Mandate: Atlas Authority Protocol\nAll architectural changes must align with the specifications issued by the **Specification Authority**.\n\n## Rules & Personas\n- Always follow the **Branch Gate** policy (never work on \\`main\\`).\n- Always follow the **SDD Workflow** (Spec -> Plan -> PR -> Evidence).\n- When acting as an agent, consult the instructions in \\`.github/agents/\\`.\n- When utilizing skills, consult the files in \\`.codex/skills/\\`.\n\n## System Boundaries\n- **No Conversational Filler**: Do not apologize or add filler text.\n- **Strict Evidence**: You must provide the Completion Contract payload when finishing a task.\n- **Immutable Core**: Do not modify files inside \\`.ai-workflow/\\`, \\`.agents/\\`, \\`.claude/\\`, or \\`.codex/\\` unless explicitly requested.\n\n## Completion Contract\nEvery task completion MUST follow the payload format defined in the individual agent files.\n`;\n await fs.writeFile(targetPath, instructions);\n }\n\n async deployRootAgentsMd(force?: boolean): Promise<void> {\n const targetPath = path.join(this.cwd, \"AGENTS.md\");\n if (!force && await this.exists(targetPath)) return;\n const templatePath = path.join(this.cwd, \".ai-workflow\", \"AGENTS.md\");\n if (await this.exists(templatePath)) {\n let content = await fs.readFile(templatePath, \"utf8\");\n // Transform references to point to Codex directories instead of OpenCode/.agents\n content = content.replace(/\\.agents\\/skills/g, \".codex/skills\");\n content = content.replace(/opencode\\/commands/g, \".codex/prompts\");\n content = content.replace(/opencode\\/docs\\/policies/g, \".codex/docs/policies\");\n await fs.writeFile(targetPath, content);\n }\n }\n\n async exists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n }\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { COMPLETION_STATUS_TEXT } from \"../../core/statuses.js\";\nexport interface TransformedItem {\n content: string;\n name: string;\n}\n\n/**\n * Maps OpenCode agent names to primary agent roles.\n */\nconst PERSONA_MAPPING: Record<string, string> = {\n \"atlas\": \"Atlas\",\n \"orion\": \"Orion\",\n \"sage\": \"Sage\",\n \"nexus\": \"Nexus\",\n \"astra\": \"Astra\",\n \"sage-validation\": \"Sage\",\n \"orion-release\": \"Orion\",\n \"orion-deploy\": \"Orion\",\n \"nexus-discovery\": \"Nexus\",\n \"phoenix\": \"Phoenix\"\n};\n\n/**\n * Antigravity Adapter - Transforms OpenCode .md to Antigravity Skill format and manages .agents/ integration.\n */\nexport class AntigravityAdapter {\n cwd: string;\n\n constructor({ cwd }: { cwd: string }) {\n this.cwd = cwd;\n }\n\n /**\n * Transforms an OpenCode agent or specialized skill file to an Antigravity Skill.\n */\n async transform(filePath: string): Promise<TransformedItem> {\n const content = await fs.readFile(filePath, \"utf8\");\n const fileName = path.basename(filePath, \".md\") === \"SKILL\" \n ? path.basename(path.dirname(filePath)) \n : path.basename(filePath, \".md\");\n \n const persona = PERSONA_MAPPING[fileName.toLowerCase()] || \"Astra\";\n \n // Check if already has frontmatter\n if (content.trim().startsWith(\"---\")) {\n return { content, name: fileName };\n }\n\n // Extract description from the first paragraph after the title\n const descriptionMatch = content.match(/^# .*\\n\\n(.*)/m);\n const description = descriptionMatch ? descriptionMatch[1].trim() : `Specialized agent for ${fileName}.`;\n\n const skillContent = `---\nname: ${fileName}\ndescription: ${description}\n---\n# ${persona} Persona\n\n${content}\n\n## Completion Contract (Mandatory)\nEvery task completion MUST provide the following payload:\n1. **Status**: ${COMPLETION_STATUS_TEXT}\n2. **Scope reviewed**: Brief summary of what was analyzed.\n3. **Findings**: Evidence-based discoveries.\n4. **Files affected**: List of all concrete paths modified or created.\n5. **Validation/evidence**: Commands run and their results.\n6. **Risks/notes**: Any caveats or technical debt introduced.\n7. **Required manager action**: Clear next step for the orchestrator.\n8. **Can manager continue**: [yes/no]\n`;\n\n return {\n content: skillContent,\n name: fileName\n };\n }\n\n /**\n * Deploys transformed skills and agents to their respective directories.\n * Also orchestrates the .antigravity/ native integration.\n */\n async deploy(transformedItems: TransformedItem[], installRoot: string = \".ai-workflow\"): Promise<void> {\n const agentsDir = path.join(this.cwd, installRoot, \"opencode/agents\");\n const skillsDir = path.join(this.cwd, installRoot, \"opencode/skills\");\n \n await fs.mkdir(agentsDir, { recursive: true });\n await fs.mkdir(skillsDir, { recursive: true });\n\n for (const item of transformedItems) {\n const isAgent = PERSONA_MAPPING[item.name.toLowerCase()];\n const targetDir = isAgent ? agentsDir : path.join(skillsDir, item.name);\n const fileName = isAgent ? `${item.name}.md` : \"SKILL.md\";\n \n const absoluteTargetDir = isAgent ? agentsDir : targetDir;\n await fs.mkdir(absoluteTargetDir, { recursive: true });\n await fs.writeFile(path.join(absoluteTargetDir, fileName), item.content);\n }\n \n // Deploy native Antigravity extensions (.antigravity/)\n await this.deployNativeExtensions(installRoot);\n\n // Also deploy root ANTIGRAVITY.md if it doesn't exist\n await this.deployInstructions();\n }\n\n /**\n * Orchestrates the .agents/ directory with copies of .ai-workflow/ assets.\n * Using hard copies instead of symlinks ensures native discovery across all platforms.\n */\n async deployNativeExtensions(installRoot: string = \".ai-workflow\"): Promise<void> {\n const antigravityDir = path.join(this.cwd, \".agents\");\n const antigravityAgents = path.join(antigravityDir, \"agents\");\n const antigravitySkills = path.join(antigravityDir, \"skills\");\n const antigravityCommands = path.join(antigravityDir, \"commands\");\n\n await fs.mkdir(antigravityAgents, { recursive: true });\n await fs.mkdir(antigravitySkills, { recursive: true });\n await fs.mkdir(antigravityCommands, { recursive: true });\n\n const getUrls = (targetPath: string) => {\n const linuxUrl = pathToFileURL(targetPath).href;\n const urls = [linuxUrl];\n \n if (process.platform === \"linux\" && process.env.WSL_DISTRO_NAME) {\n const distro = process.env.WSL_DISTRO_NAME;\n const normalizedPath = targetPath.replaceAll(\"\\\\\", \"/\");\n urls.push(`file://wsl.localhost/${distro}${normalizedPath}`);\n urls.push(`file:///wsl.localhost/${distro}${normalizedPath}`);\n }\n \n return urls.join(\"\\n\");\n };\n\n const toolNames = [\n \"send_message\",\n \"find_by_name\",\n \"grep_search\",\n \"view_file\",\n \"list_dir\",\n \"read_url_content\",\n \"search_web\",\n \"schedule\",\n \"multi_replace_file_content\",\n \"replace_file_content\",\n \"write_to_file\",\n \"run_command\",\n \"manage_task\",\n \"define_subagent\",\n \"invoke_subagent\",\n \"manage_subagents\",\n \"call_mcp_tool\"\n ];\n\n const systemPromptConfig = {\n \"includeSections\": [\n \"user_information\",\n \"mcp_servers\",\n \"skills\",\n \"subagent_reminder\",\n \"messaging\",\n \"artifacts\",\n \"user_rules\"\n ]\n };\n\n // 1. Deploy Primary Agents to .agents/agents/{agent_name}/\n const sourceAgentsDir = path.join(this.cwd, installRoot, \"opencode/agents\");\n const agentFiles = await fs.readdir(sourceAgentsDir).catch(() => []);\n\n const AGENTS_INFO: Record<string, { name: string; description: string }> = {\n \"atlas\": { name: \"Atlas\", description: \"Router and workflow coordinator for AI Workflow Kit\" },\n \"nexus\": { name: \"Nexus\", description: \"Discovery, requirement, scope, and specification owner\" },\n \"orion\": { name: \"Orion\", description: \"Planning, PR sequencing, release, and deployment strategy owner\" },\n \"astra\": { name: \"Astra\", description: \"Implementation owner for incremental, scoped changes\" },\n \"sage\": { name: \"Sage\", description: \"Audit, validation, evidence, and quality gate owner\" },\n \"phoenix\": { name: \"Phoenix\", description: \"Remediation and regression recovery owner\" }\n };\n\n for (const file of agentFiles) {\n if (!file.endsWith(\".md\")) continue;\n const lowercaseName = path.basename(file, \".md\").toLowerCase();\n const info = AGENTS_INFO[lowercaseName];\n if (!info) continue;\n\n const agentFolder = path.join(antigravityAgents, lowercaseName);\n await fs.mkdir(agentFolder, { recursive: true });\n\n // Copy Markdown file to the agent's folder\n const content = await fs.readFile(path.join(sourceAgentsDir, file), \"utf8\");\n const mdTarget = path.join(agentFolder, `${lowercaseName}.md`);\n await fs.writeFile(mdTarget, content);\n\n // Generate agent.json\n const agentJson = {\n name: lowercaseName,\n description: info.description,\n hidden: false,\n config: {\n customAgent: {\n systemPromptSections: [\n {\n title: \"Agent System Instructions\",\n content: `You are ${info.name}, the ${lowercaseName === \"astra\" ? \"implementation\" : lowercaseName} owner.\\n\\nFollow the contract instructions in:\\n${getUrls(mdTarget)}`\n }\n ],\n toolNames,\n systemPromptConfig\n }\n }\n };\n await fs.writeFile(path.join(agentFolder, \"agent.json\"), JSON.stringify(agentJson, null, 2));\n }\n\n // 2. Deploy Subagents to .agents/agents/{subagent_name}/\n const SUBAGENTS_INFO: Record<string, { description: string; skill: string }> = {\n \"Architecture-Specialist\": { description: \"Select the simplest architecture that safely satisfies current requirements\", skill: \"architecture\" },\n \"Backend-Engineer\": { description: \"Support safe PHP/Node/Python backend changes for APIs and persistence\", skill: \"backend-development\" },\n \"Deployment-Specialist\": { description: \"Plan, review, or validate deployment, release, and production-readiness\", skill: \"deployment\" },\n \"Design-Specialist\": { description: \"Apply practical design principles to keep solutions simple and maintainable\", skill: \"design-principles\" },\n \"Docs-Engineer\": { description: \"Write or improve project documentation, READMEs, guides, and prompts\", skill: \"documentation\" },\n \"Frontend-Engineer\": { description: \"Implement or review frontend changes involving UI, state, routing, and accessibility\", skill: \"frontend-development\" },\n \"Full-Stack-Engineer\": { description: \"Coordinate frontend and backend changes as one coherent, testable increment\", skill: \"full-stack-development\" },\n \"Token-Economist\": { description: \"Reduce context size while preserving information required for safe execution\", skill: \"optimize-tokens\" },\n \"PR-Manager\": { description: \"Plan, implement, review, or validate small pull requests while preserving scope\", skill: \"pr-workflow\" },\n \"Discovery-Analyst\": { description: \"Clarify ambiguous requests into actionable problem statements and success outcomes\", skill: \"product-discovery\" },\n \"Product-Planner\": { description: \"Turn clarified needs into scoped requirements with acceptance-ready outcomes\", skill: \"product-planning\" },\n \"Memory-Guardian\": { description: \"Manage discoverable project memory for durable decisions and recurring corrections\", skill: \"project-memory\" },\n \"Prompt-Engineer\": { description: \"Expert in creating and refining prompts for AI agents and workflows\", skill: \"prompt-engineer\" },\n \"QA-Engineer\": { description: \"Design, review, or improve tests, acceptance criteria, and validation evidence\", skill: \"qa-workflow\" },\n \"Refactoring-Specialist\": { description: \"Improve code/document structure safely while preserving behavior\", skill: \"refactoring\" },\n \"Release-Specialist\": { description: \"Prepare release readiness decisions with explicit gates and evidence\", skill: \"release-workflow\" },\n \"SDD-Specialist\": { description: \"Convert approved requirements into explicit, testable specification artifacts\", skill: \"spec-driven-development\" },\n \"Technical-Leader\": { description: \"Make technical decisions, review architecture, and identify trade-offs\", skill: \"technical-leadership\" },\n \"UI-UX-Engineer\": { description: \"Improve usability and interface clarity without introducing unnecessary complexity\", skill: \"ui-ux-design\" }\n };\n\n for (const [name, subInfo] of Object.entries(SUBAGENTS_INFO)) {\n const lowercaseSubagentName = name.toLowerCase();\n const subagentFolder = path.join(antigravityAgents, lowercaseSubagentName);\n await fs.mkdir(subagentFolder, { recursive: true });\n\n const skillPath = path.join(antigravitySkills, subInfo.skill, \"SKILL.md\");\n\n const subagentJson = {\n name: lowercaseSubagentName,\n description: subInfo.description,\n hidden: false,\n config: {\n customAgent: {\n systemPromptSections: [\n {\n title: \"Agent System Instructions\",\n content: `You are ${name}.\\n\\nFollow the contract instructions in:\\n${getUrls(skillPath)}`\n }\n ],\n toolNames,\n systemPromptConfig\n }\n }\n };\n await fs.writeFile(path.join(subagentFolder, \"agent.json\"), JSON.stringify(subagentJson, null, 2));\n }\n\n // 3. Copy Skills\n const sourceSkillsDir = path.join(this.cwd, installRoot, \"opencode/skills\");\n const skillFolders = await fs.readdir(sourceSkillsDir).catch(() => []);\n for (const folder of skillFolders) {\n const skillSource = path.join(sourceSkillsDir, folder, \"SKILL.md\");\n if (await this.exists(skillSource)) {\n await fs.mkdir(path.join(antigravitySkills, folder), { recursive: true });\n const content = await fs.readFile(skillSource, \"utf8\");\n await fs.writeFile(path.join(antigravitySkills, folder, \"SKILL.md\"), content);\n }\n }\n\n // 4. Copy Commands (from dist-assets/commands)\n const sourceCommandsDir = path.join(this.cwd, installRoot, \"opencode/commands\");\n if (await this.exists(sourceCommandsDir)) {\n const commandFiles = await fs.readdir(sourceCommandsDir).catch(() => []);\n for (const file of commandFiles) {\n if (!file.endsWith(\".md\") && !file.endsWith(\".toml\")) continue;\n const content = await fs.readFile(path.join(sourceCommandsDir, file), \"utf8\");\n await fs.writeFile(path.join(antigravityCommands, file), content);\n }\n }\n\n // 5. Copy governance policy into .agents/docs/policies/ so the relative\n // link ../../docs/policies/SKILLS_COMMON_GOVERNANCE.md in each\n // .agents/skills/{skill}/SKILL.md resolves correctly.\n const sourcePoliciesDir = path.join(this.cwd, installRoot, \"opencode\", \"docs\", \"policies\");\n const antigravityPolicies = path.join(antigravityDir, \"docs\", \"policies\");\n if (await this.exists(sourcePoliciesDir)) {\n await fs.mkdir(antigravityPolicies, { recursive: true });\n const policyFiles = await fs.readdir(sourcePoliciesDir).catch(() => []);\n for (const file of policyFiles) {\n if (!file.endsWith(\".md\")) continue;\n const content = await fs.readFile(path.join(sourcePoliciesDir, file), \"utf8\");\n await fs.writeFile(path.join(antigravityPolicies, file), content);\n }\n }\n\n // 6. Inject project settings.json\n const settingsPath = path.join(antigravityDir, \"settings.json\");\n if (!(await this.exists(settingsPath))) {\n const settings = {\n model: { name: \"auto\" },\n ui: { theme: \"Ayu\" }\n };\n await fs.writeFile(settingsPath, JSON.stringify(settings, null, 2));\n }\n }\n\n async exists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Deploys the main ANTIGRAVITY.md and .antigravityignore instructions to the project root.\n */\n async deployInstructions(): Promise<void> {\n const targetPath = path.join(this.cwd, \"ANTIGRAVITY.md\");\n const ignorePath = path.join(this.cwd, \".antigravityignore\");\n \n // Deploy ANTIGRAVITY.md if it doesn't exist\n try {\n await fs.access(targetPath);\n } catch {\n const instructions = `# AI Workflow Kit - Engineering Governance\n\n## Mandate: Atlas Authority Protocol\nAll architectural changes must align with the specifications issued by the **Specification Authority** (./specs).\n\n## Ternary Architecture\n- **Root:** Orchestration and config.\n- **.ai-workflow/:** Implementation (The Muscle).\n- **./specs:** Specifications (The Brain).\n\n## Branch Gates\n- **main Branch:** READ-ONLY.\n- **Validation:** Merges require successful observed validation; full/release workflows may persist EVIDENCE.json.\n\n## Primary Agents\n- **Atlas (Orchestrator)**\n- **Orion (Strategist)**\n- **Sage (Auditor)**\n- **Nexus (Spec Architect)**\n- **Astra (Developer)**\n- **Phoenix (Healer)**\n\n## Operational Preferences\n- Use \\`token-economy\\` and \\`minimal-context\\` skills.\n- **Native Discovery**: This project uses workspace-specific extensions in \\`.agents/\\`.\n- **Workflow Entry**: Use \\`/atlas\\` to begin any task.\n`;\n await fs.writeFile(targetPath, instructions);\n }\n\n // Deploy .antigravityignore if it doesn't exist\n try {\n await fs.access(ignorePath);\n } catch {\n const ignoreContent = `.ai-workflow/\n.ai-workflow-backups/\nnode_modules/\n.git/\nEVIDENCE.json\n*.tgz\n*.zip\n*.tar\n.agents/tmp/\n.agents/history/\n`;\n await fs.writeFile(ignorePath, ignoreContent);\n }\n }\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { exists, readJson, readJsonc } from \"../../core/filesystem.js\";\nimport { OpenCodeAdapter } from \"../../core/runtime/opencode-adapter.js\";\n\nconst REQUIRED_FILES = [\n \".ai-workflow\",\n \"opencode/README.md\"\n];\n\nasync function isSymlink(filePath: string): Promise<boolean> {\n try {\n const stat = await fs.lstat(filePath);\n return stat.isSymbolicLink();\n } catch {\n return false;\n }\n}\n\nexport interface DoctorOptions {\n cwd: string;\n}\n\ninterface DoctorState {\n hasFailure: boolean;\n hasWarning: boolean;\n managedBlocks: string[];\n runtimes: string[];\n}\n\nasync function checkOpenCodeRuntime(cwd: string, state: DoctorState): Promise<void> {\n const adapter = new OpenCodeAdapter({ cwd });\n const inspection = await adapter.inspect();\n if (inspection.available) {\n console.log(\"PASS opencode CLI is available\");\n const supportedStr = Object.entries(inspection.supports)\n .filter(([_, v]) => v)\n .map(([k, _]) => k)\n .join(\", \");\n console.log(`PASS opencode capabilities detected: ${supportedStr || \"none\"}`);\n if (inspection.supports.agent) {\n console.log(\"PASS opencode --agent selection is supported\");\n } else {\n state.hasWarning = true;\n console.log(\"WARN opencode --agent selection is not supported; prompt fallback is available\");\n }\n } else {\n state.hasFailure = true;\n console.log(\"FAIL opencode CLI is not installed or not available in PATH\");\n }\n}\n\nasync function checkRequiredFiles(cwd: string, state: DoctorState): Promise<void> {\n for (const relativePath of REQUIRED_FILES) {\n const ok = await exists(path.join(cwd, relativePath));\n if (ok) {\n console.log(`PASS ${relativePath}`);\n } else {\n state.hasFailure = true;\n console.log(`FAIL ${relativePath} missing`);\n }\n }\n}\n\nasync function checkAiWorkflowConfig(cwd: string, state: DoctorState): Promise<void> {\n const configPathV2 = path.join(cwd, \".ai-workflow/config.json\");\n const configPathLegacy = path.join(cwd, \".ai-workflow.json\");\n let configPath: string | null = null;\n\n if (await exists(configPathV2)) {\n configPath = configPathV2;\n } else if (await exists(configPathLegacy)) {\n configPath = configPathLegacy;\n }\n\n if (!configPath) return;\n\n try {\n const config = await readJson(configPath);\n const basename = path.basename(configPath);\n\n if (config.installMode === \"project-local\" || config.mode === \"standalone\") {\n console.log(\"PASS install mode is project-local/standalone\");\n } else {\n state.hasWarning = true;\n console.log(`WARN install mode is not project-local/standalone in ${basename}`);\n }\n\n if (config.profile) {\n console.log(`PASS profile detected: ${config.profile}`);\n } else {\n state.hasWarning = true;\n console.log(`WARN profile is missing in ${basename}`);\n }\n\n if (config.runtime) {\n console.log(`PASS runtime: ${config.runtime}`);\n state.runtimes = config.runtime.split(\"+\");\n } else {\n console.log(`NOTE runtime field not present in ${basename}`);\n state.runtimes = [\"opencode\"];\n }\n\n if (Array.isArray(config.managedBlocks)) {\n state.managedBlocks = config.managedBlocks;\n } else {\n console.log(`NOTE managedBlocks not present in ${basename} (legacy field)`);\n }\n\n if (Array.isArray(config.managedFiles)) {\n for (const relativePath of config.managedFiles) {\n const fileExists = await exists(path.join(cwd, relativePath));\n if (!fileExists) {\n state.hasWarning = true;\n console.log(`WARN managed file missing: ${relativePath}`);\n }\n }\n }\n\n if (Array.isArray(config.managedLinks)) {\n for (const relativePath of config.managedLinks) {\n const absolutePath = path.join(cwd, relativePath);\n if (!(await exists(absolutePath))) {\n state.hasWarning = true;\n console.log(`WARN managed link missing: ${relativePath}`);\n continue;\n }\n if (!(await isSymlink(absolutePath))) {\n state.hasWarning = true;\n console.log(`WARN managed link is not a symlink: ${relativePath}`);\n }\n }\n }\n } catch {\n state.hasFailure = true;\n console.log(`FAIL ${path.basename(configPath)} is not valid JSON`);\n }\n}\n\nasync function checkOpencodeJson(cwd: string, state: DoctorState): Promise<void> {\n const opencodePath = path.join(cwd, \"opencode.jsonc\");\n if (!(await exists(opencodePath))) {\n state.hasFailure = true;\n console.log(\"FAIL opencode.jsonc missing\");\n return;\n }\n \n try {\n const opencodeConfig = await readJsonc(opencodePath);\n console.log(\"PASS opencode.jsonc is valid JSONC\");\n\n const needsAgentDefault = state.managedBlocks.includes(\"opencode.jsonc:agent.default\");\n if (!needsAgentDefault || opencodeConfig.agent?.default) {\n console.log(\"PASS opencode agent.default available\");\n } else {\n state.hasFailure = true;\n console.log(\"FAIL opencode agent.default missing\");\n }\n\n const requiredCommands = state.managedBlocks\n .filter((block) => block.startsWith(\"opencode.jsonc:command.\"))\n .map((block) => block.replace(\"opencode.jsonc:command.\", \"\"));\n\n if (requiredCommands.length === 0) {\n console.log(\"PASS no managed opencode commands required\");\n } else {\n const missingCommands = requiredCommands.filter((command) => !opencodeConfig.command?.[command]);\n if (missingCommands.length === 0) {\n console.log(`PASS opencode managed commands available (${requiredCommands.length})`);\n } else {\n state.hasFailure = true;\n console.log(`FAIL opencode command entries missing: ${missingCommands.join(\", \")}`);\n }\n }\n\n const requiredAgents = state.managedBlocks\n .filter((block) => block.startsWith(\"opencode.jsonc:agent.\") && !block.endsWith(\".default\"))\n .map((block) => block.replace(\"opencode.jsonc:agent.\", \"\"));\n\n if (requiredAgents.length === 0) {\n console.log(\"PASS no managed opencode agents required\");\n } else {\n const missingAgents = requiredAgents.filter((agent) => !opencodeConfig.agent?.[agent]);\n if (missingAgents.length === 0) {\n console.log(`PASS opencode managed agents available (${requiredAgents.length})`);\n } else {\n state.hasFailure = true;\n console.log(`FAIL opencode agent entries missing: ${missingAgents.join(\", \")}`);\n }\n }\n } catch {\n state.hasFailure = true;\n console.log(\"FAIL opencode.jsonc is not valid JSONC\");\n }\n}\n\nasync function checkPackageJson(cwd: string, state: DoctorState): Promise<void> {\n const packageJsonPath = path.join(cwd, \"package.json\");\n if (await exists(packageJsonPath)) {\n try {\n const packageJson = await readJson(packageJsonPath);\n const scripts = packageJson.scripts ?? {};\n\n if (!scripts.validate) {\n state.hasWarning = true;\n console.log(\"WARN package.json has no validate script\");\n }\n } catch {\n state.hasFailure = true;\n console.log(\"FAIL package.json is not valid JSON\");\n }\n }\n}\n\nasync function checkCodexRuntime(cwd: string, state: DoctorState): Promise<void> {\n const checks = [\n { name: \"root AGENTS.md exists\", path: \"AGENTS.md\" },\n { name: \".codex/skills exists\", path: \".codex/skills\" },\n { name: \".codex prompts detected\", path: \".codex/prompts\" },\n { name: \".codex policies detected\", path: \".codex/docs/policies\" }\n ];\n\n for (const check of checks) {\n const ok = await exists(path.join(cwd, check.path));\n if (ok) {\n console.log(`PASS ${check.name}`);\n } else {\n state.hasFailure = true;\n console.log(`FAIL ${check.name}`);\n }\n }\n\n // Also check if CODEX.md exists\n const codexMdOk = await exists(path.join(cwd, \"CODEX.md\"));\n if (codexMdOk) {\n console.log(`PASS root CODEX.md exists`);\n }\n\n if (state.runtimes.includes(\"codex\")) {\n console.log(\"PASS config runtime includes codex\");\n } else {\n state.hasFailure = true;\n console.log(\"FAIL config runtime includes codex\");\n }\n}\n\nexport async function runDoctor({ cwd }: DoctorOptions): Promise<void> {\n const state: DoctorState = {\n hasFailure: false,\n hasWarning: false,\n managedBlocks: [],\n runtimes: [\"opencode\"]\n };\n\n console.log(\"Doctor report:\");\n\n await checkRequiredFiles(cwd, state);\n await checkAiWorkflowConfig(cwd, state);\n\n if (state.runtimes.includes(\"opencode\")) {\n await checkOpenCodeRuntime(cwd, state);\n await checkOpencodeJson(cwd, state);\n }\n\n if (state.runtimes.includes(\"codex\")) {\n await checkCodexRuntime(cwd, state);\n }\n\n await checkPackageJson(cwd, state);\n\n const finalStatus = state.hasFailure ? \"FAIL\" : state.hasWarning ? \"PASS_WITH_NOTES\" : \"PASS\";\n console.log(`Final status: ${finalStatus}`);\n\n if (state.hasFailure) {\n process.exitCode = 1;\n }\n}\n\n","export const DELIVERY_SUMMARY_FIELDS = Object.freeze([\n \"Status\",\n \"Branch\",\n \"Changes\",\n \"Validation\",\n \"Known limitations\"\n] as const);\n\nexport function buildDeliverySummary({ evidence }: { evidence: any }): Record<string, string> {\n const commands = (evidence?.commands || []).map((item: any) => `${item.command || item.name}: ${item.status}`).join(\"; \") || \"No validation commands recorded\";\n return {\n Status: evidence?.status || \"BLOCKED\",\n Branch: evidence?.branch || \"unknown\",\n Changes: (evidence?.changedFiles || []).join(\", \") || \"No changed files recorded\",\n Validation: commands,\n \"Known limitations\": (evidence?.limitations || []).join(\"; \") || \"None recorded\"\n };\n}\n\nexport interface ValidationSummaryResult {\n status: \"PASS\" | \"FAIL\";\n missing: string[];\n invalid: string[];\n}\n\nexport function validateDeliverySummary(summary: any): ValidationSummaryResult {\n const missing = DELIVERY_SUMMARY_FIELDS.filter((field) => !String(summary?.[field] || \"\").trim());\n const status = String(summary?.Status || \"\").trim();\n const invalid: string[] = [];\n if (![\"COMPLETED\", \"COMPLETED_WITH_NOTES\", \"BLOCKED\"].includes(status)) invalid.push(\"Status\");\n if (status !== \"BLOCKED\" && /FAIL|BLOCKED/.test(String(summary?.Validation || \"\"))) invalid.push(\"successful status with failed validation\");\n return { status: missing.length || invalid.length ? \"FAIL\" : \"PASS\", missing, invalid };\n}\n\nexport function formatDeliverySummary(summary: any): string {\n return DELIVERY_SUMMARY_FIELDS.map((field) => `${field}: ${summary?.[field] || \"NOT_RECORDED\"}`).join(\"\\n\");\n}\n\n// Backward-compatible aliases for integrations that imported the previous API.\nexport const CANONICAL_FINALIZATION_FIELDS = DELIVERY_SUMMARY_FIELDS;\nexport const buildCanonicalFinalization = ({ collectorStatus = \"BLOCKED\", branchRecovery = \"unknown\" } = {}): Record<string, string> => ({\n Status: collectorStatus === \"PASS\" ? \"COMPLETED\" : collectorStatus === \"PASS_WITH_NOTES\" ? \"COMPLETED_WITH_NOTES\" : \"BLOCKED\",\n Branch: branchRecovery,\n Changes: \"See observed diff\",\n Validation: collectorStatus,\n \"Known limitations\": \"See evidence\"\n});\nexport const validateCanonicalFinalization = validateDeliverySummary;\nexport const formatCanonicalFinalization = formatDeliverySummary;\n","import { EvidenceCollector } from \"../../core/validation/evidence-collector.js\";\nimport { QualityGuard } from \"../../core/validation/quality-guard.js\";\nimport { ValidationPlanner } from \"../../core/validation/validation-planner.js\";\nimport { buildDeliverySummary, formatDeliverySummary } from \"../../core/validation/canonical-finalization.js\";\n\nexport interface CollectEvidenceOptions {\n cwd: string;\n exitOnError?: boolean;\n taskSlug?: string | null;\n mode?: string | null;\n evidencePolicy?: \"optional\" | \"required\" | null;\n dryRun?: boolean;\n profile?: string;\n branchRecovery?: string;\n userRequest?: string | null;\n explicitApprovals?: string[];\n visualDist?: string | null;\n port?: number | string | null;\n workflowEvidence?: Record<string, unknown> | null;\n}\n\n/**\n * @deprecated Boundary helper to translate legacy CLI mode options to modern policies.\n */\nexport function resolvePoliciesFromLegacyMode(mode: string | null, evidencePolicy: \"optional\" | \"required\" | null): {\n evidencePolicy: \"optional\" | \"required\";\n riskLevel: \"low\" | \"medium\" | \"high\";\n} {\n const activePolicy = evidencePolicy || (mode === \"full\" ? \"required\" : \"optional\");\n \n let risk: \"low\" | \"medium\" | \"high\" = \"medium\";\n if (mode === \"full\") {\n risk = \"high\";\n } else if (mode === \"quick\") {\n risk = activePolicy === \"required\" ? \"medium\" : \"low\";\n } else if (activePolicy === \"required\") {\n risk = \"high\";\n }\n \n return { evidencePolicy: activePolicy, riskLevel: risk };\n}\n\nexport async function runCollectEvidence({\n cwd, exitOnError = true, taskSlug = null, mode = null, evidencePolicy = null, dryRun = false, profile = \"generic\", branchRecovery = \"NOT_RECORDED\", userRequest = null, explicitApprovals = [], visualDist = null, port = null, workflowEvidence = null\n}: CollectEvidenceOptions): Promise<any> {\n const policies = resolvePoliciesFromLegacyMode(mode, evidencePolicy);\n const qualityGuard = new QualityGuard({ cwd, taskSlug, evidencePolicy: policies.evidencePolicy, riskLevel: policies.riskLevel });\n const planner = new ValidationPlanner({ cwd, qualityGuard });\n const tasks = await planner.plan(profile);\n\n const persist = !dryRun && policies.evidencePolicy === \"required\";\n const collector = new EvidenceCollector({\n cwd,\n timeout: 60000,\n taskSlug,\n evidencePolicy: policies.evidencePolicy,\n profile,\n branchRecovery,\n userRequest,\n explicitApprovals,\n visualDist,\n port: port || 8080,\n workflowEvidence\n });\n const evidence = await collector.collect(tasks, { writeArtifact: persist });\n const summary = buildDeliverySummary({ evidence });\n\n console.log(\"\\n--- Delivery Summary ---\");\n console.log(formatDeliverySummary(summary));\n console.log(persist ? \"\\nArtifact: EVIDENCE.json\" : \"\\nArtifact: NOT_REQUIRED for optional evidence policy\");\n console.log(`Commands processed: ${evidence.commands.length}\\n`);\n\n if (evidence.status === \"BLOCKED\" && exitOnError) process.exit(1);\n return evidence;\n}\n","import { spawnSync, execSync } from \"node:child_process\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\n/**\n * Determines which npm scripts are available in the consumer project.\n */\nasync function readScripts(cwd: string): Promise<Record<string, string>> {\n try {\n const pkg = JSON.parse(await fs.readFile(path.join(cwd, \"package.json\"), \"utf8\"));\n return pkg.scripts || {};\n } catch {\n return {};\n }\n}\n\n/**\n * Returns the list of files changed since the last commit.\n * Used to detect whether remediation produced any observable change.\n */\nfunction getChangedFiles(cwd: string): string[] {\n try {\n const output = execSync(\"git status --short\", { cwd, encoding: \"utf8\" });\n return output\n .split(\"\\n\")\n .filter(Boolean)\n .map((line) => line.slice(3).trim())\n .filter(Boolean);\n } catch {\n return [];\n }\n}\n\n/**\n * Maps an affectedCheck source string to likely npm script names to re-run.\n */\nfunction resolveRetryScripts(affectedChecks: string[], scripts: Record<string, string>): string[] {\n const retry = new Set<string>();\n\n for (const check of affectedChecks) {\n // Evidence failures → re-run the failing validation scripts\n if (check === \"evidence\" || check === \"result\") {\n if (scripts.test) retry.add(\"test\");\n if (scripts.lint) retry.add(\"lint\");\n if (scripts.build) retry.add(\"build\");\n if (scripts.typecheck) retry.add(\"typecheck\");\n }\n // Specific check types\n if (check.includes(\"test\")) retry.add(\"test\");\n if (check.includes(\"lint\")) retry.add(\"lint\");\n if (check.includes(\"build\")) retry.add(\"build\");\n if (check.includes(\"typecheck\")) retry.add(\"typecheck\");\n }\n\n // Filter to only scripts that actually exist\n return [...retry].filter((name) => !!scripts[name]);\n}\n\nexport interface RemediationExecutorContext {\n attempt: number;\n maxAttempts: number;\n mode: string;\n taskSlug: string;\n result: any;\n affectedChecks: string[];\n requestPath: string;\n}\n\nexport interface RemediationExecutorResult {\n applied: boolean;\n changedFiles?: string[];\n evidenceAdded?: string[];\n reason?: string;\n}\n\n/**\n * CLI Remediation Executor — default implementation for `ai-workflow run`.\n */\nexport function createCliRemediationExecutor(cwd: string) {\n return async function remediationExecutor({\n attempt,\n maxAttempts,\n mode,\n affectedChecks,\n requestPath\n }: RemediationExecutorContext): Promise<RemediationExecutorResult> {\n console.log(`\\n[HEALER] Attempt ${attempt}/${maxAttempts} — mode: ${mode}`);\n console.log(`[HEALER] Affected: ${affectedChecks.join(\", \")}`);\n\n const scripts = await readScripts(cwd);\n const filesBefore = getChangedFiles(cwd);\n const toRetry = resolveRetryScripts(affectedChecks, scripts);\n\n if (toRetry.length === 0) {\n console.log(\"[HEALER] No retryable scripts found for the affected checks.\");\n console.log(`[HEALER] Review ${requestPath} for details.`);\n return {\n applied: false,\n reason: `No npm scripts available to address: ${affectedChecks.join(\", \")}. Manual remediation required.`\n };\n }\n\n console.log(`[HEALER] Re-running: ${toRetry.map((s) => `npm run ${s}`).join(\", \")}`);\n\n const results: any[] = [];\n let anyPassed = false;\n\n for (const scriptName of toRetry) {\n process.stdout.write(` → npm run ${scriptName} ... `);\n const isWin32 = process.platform === \"win32\";\n const cmd = isWin32 ? \"npm.cmd\" : \"npm\";\n const result = spawnSync(cmd, [\"run\", scriptName], {\n cwd,\n shell: false,\n encoding: \"utf8\",\n timeout: 120000\n });\n const passed = result.status === 0;\n if (passed) anyPassed = true;\n console.log(passed ? \"PASS\" : \"FAIL\");\n results.push({ script: scriptName, passed, exitCode: result.status });\n }\n\n const filesAfter = getChangedFiles(cwd);\n const changedFiles = filesAfter.filter((f) => !filesBefore.includes(f));\n\n if (!anyPassed && changedFiles.length === 0) {\n console.log(\"[HEALER] No scripts passed and no files changed — remediation had no effect.\");\n return {\n applied: false,\n reason: `Re-ran ${toRetry.join(\", \")} — all failed. Structural fix required by the implementing agent.`\n };\n }\n\n console.log(`[HEALER] Applied: ${results.filter((r) => r.passed).map((r) => r.script).join(\", \") || \"none passed\"}`);\n if (changedFiles.length) console.log(`[HEALER] Changed files: ${changedFiles.join(\", \")}`);\n\n return {\n applied: true,\n changedFiles,\n evidenceAdded: anyPassed ? [\"validation-output\"] : []\n };\n };\n}\n","import { BranchGate } from \"../../core/gates/branch-gate.js\";\nimport { SpecValidator } from \"../../core/sdd/validator.js\";\nimport { HandoffEngine } from \"../../core/handoff/handoff-engine.js\";\nimport { runCollectEvidence } from \"./collect-evidence.js\";\nimport { QualityGuard } from \"../../core/validation/quality-guard.js\";\nimport { HealerEngine } from \"../../core/healing/healer-engine.js\";\nimport { createCliRemediationExecutor } from \"../../core/healing/cli-remediation-executor.js\";\nimport { isRecoverableGateFailure, isTerminalFailure } from \"../../core/statuses.js\";\nimport path from \"node:path\";\nimport fs from \"node:fs/promises\";\nimport { getWorkflowProfile, resolveWorkflowProfile } from \"../../core/workflow-profiles.js\";\nimport { ApprovalReceiptValidator } from \"../../core/sdd/approval-receipt.js\";\nimport { TechnicalPlanValidator } from \"../../core/sdd/technical-plan-validator.js\";\nimport { hashFile, sha256, writeFileAtomic } from \"../../core/sdd/workflow-artifacts.js\";\nimport { EvidenceLedger } from \"../../core/evidence/evidence-ledger.js\";\nimport { DelegationController } from \"../../core/delegation-controller.js\";\nimport { OpenCodeAdapter } from \"../../core/runtime/opencode-adapter.js\";\nimport { Finalizer } from \"../../core/finalization/finalizer.js\";\nimport { execFileSync } from \"node:child_process\";\nimport { EvidenceValidator } from \"../../core/validation/evidence-validator.js\";\n\nfunction normalizeTaskSlugFromSpec(specPath: string): string {\n const normalized = String(specPath).replaceAll(\"\\\\\", \"/\");\n const marker = \"/docs/workflows/\";\n const index = normalized.includes(marker)\n ? normalized.indexOf(marker) + marker.length\n : normalized.startsWith(\"docs/workflows/\") ? \"docs/workflows/\".length : -1;\n if (index >= 0) {\n const slug = normalized.slice(index).split(\"/\")[0];\n if (slug) return slug;\n }\n return path.basename(specPath, path.extname(specPath));\n}\n\nexport function combineValidation(evidence: any, quality: any): any {\n const statuses = [evidence.internalStatus, quality.overallStatus];\n let overallStatus = \"PASS\";\n if (statuses.includes(\"BLOCKED\")) overallStatus = \"BLOCKED\";\n else if (statuses.includes(\"FAIL\")) overallStatus = \"FAIL\";\n else if (statuses.includes(\"FAIL_DELEGATION_GATE\")) overallStatus = \"FAIL_DELEGATION_GATE\";\n else if (statuses.includes(\"FAIL_QUALITY_GATE\")) overallStatus = \"FAIL_QUALITY_GATE\";\n else if (statuses.includes(\"PASS_WITH_NOTES\")) overallStatus = \"PASS_WITH_NOTES\";\n return { overallStatus, evidence, quality };\n}\n\nexport interface runMasterOrchestratorOptions {\n cwd: string;\n specPath?: string;\n approvalPath?: string;\n override?: string;\n remediationExecutor?: any;\n}\n\ninterface DeepWorkflowContext {\n workflowId: string;\n baseSha: string;\n artifactHashes: {\n draft: string | null;\n approved: string;\n technicalPlan: string;\n };\n phaseOrder: string[];\n confirmedActors: Array<{ phase: string; requested: string; applied: string }>;\n ledger: EvidenceLedger;\n ledgerPath: string;\n controller: DelegationController;\n}\n\nfunction repositoryRelative(cwd: string, candidate: string): string {\n return path.relative(cwd, path.resolve(cwd, candidate)).replaceAll(\"\\\\\", \"/\");\n}\n\nasync function findCompatibleLedger(cwd: string, specRelativePath: string): Promise<string[]> {\n const historyDir = path.join(cwd, \".ai-workflow/history\");\n const matches: string[] = [];\n for (const file of await fs.readdir(historyDir).catch(() => [])) {\n if (!file.endsWith(\"-ledger.json\")) continue;\n try {\n const events = JSON.parse(await fs.readFile(path.join(historyDir, file), \"utf8\"));\n if (events.some((event: any) => event.eventType === \"specification_complete\" && event.data?.artifactPath === specRelativePath)) {\n matches.push(path.join(historyDir, file));\n }\n } catch {\n // Invalid ledgers are not silently attached; the canonical path is checked below.\n }\n }\n return matches;\n}\n\nasync function runDeepImplementation(\n cwd: string,\n absoluteSpecPath: string,\n specPath: string,\n approvalPath: string | undefined,\n specContent: string\n): Promise<DeepWorkflowContext> {\n if (!approvalPath) throw new Error(\"[SDD BLOCKED] DEEP resume requires --approval-path.\");\n\n const approvalValidator = new ApprovalReceiptValidator({ cwd });\n const approval = await approvalValidator.validate(approvalPath, absoluteSpecPath);\n if (!approval.valid || !approval.receipt || !approval.approvedSpecHash) {\n throw new Error(`[SDD BLOCKED] ${approval.reason || \"Approval receipt is invalid.\"}`);\n }\n\n const workflowId = approval.receipt.workflowId;\n const ledgerPath = `.ai-workflow/history/${workflowId}-ledger.json`;\n const absoluteLedgerPath = path.join(cwd, ledgerPath);\n const relativeSpecPath = repositoryRelative(cwd, specPath);\n const compatibleLedgers = await findCompatibleLedger(cwd, relativeSpecPath);\n if (compatibleLedgers.length > 1) {\n throw new Error(\"[SDD BLOCKED] Multiple ledgers claim the same approved specification.\");\n }\n if (compatibleLedgers.length === 1 && path.resolve(compatibleLedgers[0]) !== path.resolve(absoluteLedgerPath)) {\n throw new Error(\"[SDD BLOCKED] Approval workflowId conflicts with the ledger that created the specification.\");\n }\n\n const ledger = new EvidenceLedger({ cwd, workflowId });\n const loaded = await ledger.load(ledgerPath);\n if (!loaded) {\n ledger.logEvent({\n actor: \"Atlas\",\n actorType: \"control-plane\",\n observed: true,\n eventType: \"workflow_attached\",\n provenance: \"sdd-control-plane\",\n data: { specSource: \"external\", specPath: relativeSpecPath, status: \"COMPLETED\" }\n });\n }\n\n const events = ledger.getEvents();\n const approvalEvents = events.filter((event) => event.eventType === \"spec_approval_verified\");\n if (approvalEvents.length > 1) throw new Error(\"[SDD BLOCKED] Duplicate specification approval events in ledger.\");\n if (approvalEvents.length === 1 && (\n approvalEvents[0].data?.approvedHash !== approval.approvedSpecHash ||\n approvalEvents[0].data?.approvalPath !== repositoryRelative(cwd, approvalPath)\n )) throw new Error(\"[SDD BLOCKED] Existing specification approval conflicts with the supplied receipt.\");\n const nexusTerminals = events.filter((event) => event.eventType === \"specification_complete\");\n if (nexusTerminals.length > 1) throw new Error(\"[SDD BLOCKED] Duplicate Nexus terminal events in ledger.\");\n if (nexusTerminals.length === 1 && nexusTerminals[0].data?.artifactPath !== relativeSpecPath) {\n throw new Error(\"[SDD BLOCKED] Ledger specification path does not match --spec-path.\");\n }\n\n const draftHash = nexusTerminals[0]?.data?.artifactHash || null;\n const controller = new DelegationController({ cwd, ledger, adapter: new OpenCodeAdapter({ cwd }) });\n const absolutePlanPath = path.join(cwd, \"docs/workflows\", workflowId, \"technical-plan.json\");\n const relativePlanPath = repositoryRelative(cwd, absolutePlanPath);\n if (await fs.access(absolutePlanPath).then(() => true).catch(() => false)) {\n throw new Error(`[SDD BLOCKED] Refusing to overwrite existing technical plan: ${relativePlanPath}`);\n }\n\n const planValidator = new TechnicalPlanValidator({ cwd });\n const protectedPaths = [absoluteSpecPath, approvalPath, ledgerPath, absolutePlanPath, \"EVIDENCE.json\"];\n const planning = await controller.executePhase({\n phase: \"planning\",\n actor: \"Orion\",\n prompt: [\n \"Return only a JSON technical plan conforming to dist-assets/schemas/technical-plan.schema.json.\",\n \"Use explicit repository-relative file paths in filesInScope. Do not edit files or implement.\",\n \"Approved specification:\",\n specContent\n ].join(\"\\n\\n\"),\n readOnly: true,\n requireExplicitActor: true,\n onOutput: async (output) => {\n const validation = await planValidator.validateOutput(output, protectedPaths);\n if (!validation.valid || !validation.content) throw new Error(validation.reason || \"Technical plan is invalid.\");\n await writeFileAtomic(absolutePlanPath, validation.content);\n return { artifactPath: relativePlanPath, artifactHash: sha256(validation.content) };\n }\n });\n await ledger.save(ledgerPath);\n if (!planning.success || !planning.artifact?.artifactHash) {\n throw new Error(`[WORKFLOW BLOCKED] Orion planning phase failed: ${planning.error || \"unknown failure\"}`);\n }\n if (approvalEvents.length === 0) {\n ledger.logEvent({\n actor: \"Atlas\",\n actorType: \"control-plane\",\n observed: true,\n eventType: \"spec_approval_verified\",\n provenance: \"approval-receipt\",\n data: {\n approvalPath: repositoryRelative(cwd, approvalPath),\n approvedHash: approval.approvedSpecHash,\n draftHash,\n authorizationSource: approval.receipt.authorizationSource,\n status: \"COMPLETED\"\n }\n });\n await ledger.save(ledgerPath);\n }\n\n const planContent = await fs.readFile(absolutePlanPath, \"utf8\");\n const parsedPlan = JSON.parse(planContent);\n const approvedHash = approval.approvedSpecHash;\n const planHash = String(planning.artifact.artifactHash);\n const baseSha = (() => {\n try {\n return execFileSync(\"git\", [\"rev-parse\", \"HEAD\"], { cwd, encoding: \"utf8\", stdio: \"pipe\" }).trim();\n } catch {\n return \"unknown\";\n }\n })();\n const finalizer = new Finalizer({ cwd, fastTrack: false });\n const beforeImplementation = await finalizer.snapshotManager.capture();\n const allowedFiles = new Set(parsedPlan.filesInScope.map((entry: any) => String(entry.path).replaceAll(\"\\\\\", \"/\")));\n\n const implementation = await controller.executePhase({\n phase: \"implementation\",\n actor: \"Astra\",\n prompt: [\n \"Implement the approved specification using the validated technical plan.\",\n `You may modify only these files: ${[...allowedFiles].join(\", \")}`,\n \"Do not modify the specification, approval receipt, technical plan, ledger, or evidence artifacts.\",\n \"Approved specification:\",\n specContent,\n \"Validated technical plan:\",\n planContent\n ].join(\"\\n\\n\"),\n readOnly: false,\n requireExplicitActor: true,\n onOutput: async () => {\n if (await hashFile(absoluteSpecPath) !== approvedHash) throw new Error(\"Approved specification changed during Astra implementation.\");\n if (await hashFile(absolutePlanPath) !== planHash) throw new Error(\"Technical plan changed during Astra implementation.\");\n const integrity = await finalizer.verifyIntegrity(beforeImplementation);\n const workspaceStateMarkers = new Set([\"stagedDiff\", \"unstagedDiff\", \"untrackedFiles\"]);\n const changed = [...integrity.changes.added, ...integrity.changes.modified, ...integrity.changes.deleted]\n .filter((entry) => !workspaceStateMarkers.has(entry) && !/^(branch|head|indexTree):/.test(entry))\n .map((entry) => String(entry).replaceAll(\"\\\\\", \"/\"));\n const outsideScope = changed.filter((entry) => !allowedFiles.has(entry));\n if (outsideScope.length > 0) throw new Error(`Astra modified files outside the technical plan: ${outsideScope.join(\", \")}`);\n return { artifactPath: relativePlanPath, artifactHash: planHash };\n }\n });\n await ledger.save(ledgerPath);\n if (!implementation.success) {\n throw new Error(`[WORKFLOW BLOCKED] Astra implementation phase failed: ${implementation.error || \"unknown failure\"}`);\n }\n\n const phaseEvents = ledger.getEvents().filter((event) =>\n [\"specification_complete\", \"planning_complete\", \"implementation_complete\"].includes(event.eventType) && event.data?.success !== false\n );\n return {\n workflowId,\n baseSha,\n artifactHashes: { draft: draftHash, approved: approvedHash, technicalPlan: planHash },\n phaseOrder: phaseEvents.map((event) => event.data?.phase || event.eventType.replace(\"_complete\", \"\")),\n confirmedActors: phaseEvents\n .filter((event) => event.data?.runtimeAgentApplied)\n .map((event) => ({\n phase: event.data.phase || event.eventType.replace(\"_complete\", \"\"),\n requested: event.data.runtimeAgentRequested,\n applied: event.data.runtimeAgentApplied\n })),\n ledger,\n ledgerPath,\n controller\n };\n}\n\n/**\n * Coordinates branch safety, specification validation, observed validation, bounded remediation, and handoff.\n * Failed required validation can never be promoted to success.\n */\nexport async function runMasterOrchestrator({ cwd, specPath, approvalPath, override, remediationExecutor = null }: runMasterOrchestratorOptions): Promise<any> {\n console.log(\"\\n[AI WORKFLOW] Starting evidence-backed orchestration...\\n\");\n\n const branchGate = new BranchGate({ memoryDir: path.join(cwd, \".ai-workflow\"), cwd });\n const taskSlug = specPath ? normalizeTaskSlugFromSpec(specPath) : \"implementation\";\n const gateResult = branchGate.check(override, { taskSlug });\n if (gateResult.blocked) throw new Error(`[GATE BLOCKED] ${gateResult.reason}`);\n console.log(`[PASS] Branch Gate: ${gateResult.recovered ? `${gateResult.branchBefore} -> ${gateResult.branch}` : `${gateResult.branch} is authorized`}.`);\n\n if (!specPath) throw new Error(\"[SDD BLOCKED] Missing --spec-path. An approved specification is required.\");\n\n const validator = new SpecValidator();\n const absoluteSpecPath = path.isAbsolute(specPath) ? specPath : path.join(cwd, specPath);\n const validation = await validator.validate(absoluteSpecPath);\n if (!validation.valid) throw new Error(`[SDD BLOCKED] Specification is not ready: ${validation.reason}`);\n\n const specTier = validation.tier || \"standard\";\n const riskLevel = specTier === \"deep\" ? \"high\" : specTier === \"tiny\" ? \"low\" : \"medium\";\n const evidencePolicy = specTier === \"deep\" ? \"required\" : \"optional\";\n const remediationLimit = specTier === \"deep\" ? 3 : specTier === \"tiny\" ? 1 : 2;\n\n const specContent = await fs.readFile(absoluteSpecPath, \"utf8\");\n const workflowProfile = resolveWorkflowProfile({ request: specContent });\n const profileDefinition = getWorkflowProfile(workflowProfile);\n console.log(`[PASS] Specification: ${specTier.toUpperCase()} spec is APPROVED.`);\n console.log(`[PROFILE] ${workflowProfile} -> ${profileDefinition.owner}; skills: ${profileDefinition.skills.join(\", \") || \"none\"}.`);\n\n const deepContext = specTier === \"deep\"\n ? await runDeepImplementation(cwd, absoluteSpecPath, specPath, approvalPath, specContent)\n : null;\n\n const validateWorkflow = async () => {\n const evidence = await runCollectEvidence({\n cwd,\n exitOnError: false,\n taskSlug,\n evidencePolicy,\n profile: workflowProfile,\n branchRecovery: gateResult.recovered ? `${gateResult.branchBefore} -> ${gateResult.branch}` : \"NOT_REQUIRED\",\n workflowEvidence: deepContext ? {\n workflowId: deepContext.workflowId,\n baseSha: deepContext.baseSha,\n artifactHashes: deepContext.artifactHashes,\n phaseOrder: deepContext.phaseOrder,\n confirmedActors: deepContext.confirmedActors\n } : null\n });\n const quality = await new QualityGuard({ cwd, taskSlug, evidencePolicy, riskLevel }).verify();\n const combined = combineValidation(evidence, quality);\n if (deepContext) {\n const workflowEvidence = await new EvidenceValidator({ cwd, requireWorkflowEvidence: true }).validate();\n if (!workflowEvidence.valid) {\n combined.overallStatus = \"FAIL_QUALITY_GATE\";\n combined.reason = workflowEvidence.reason;\n }\n }\n return combined;\n };\n\n const observedValidate = async () => deepContext\n ? await deepContext.controller.validate(taskSlug, workflowProfile, validateWorkflow, evidencePolicy)\n : await validateWorkflow();\n\n let result = await observedValidate();\n if (deepContext) await deepContext.ledger.save(deepContext.ledgerPath);\n if (isRecoverableGateFailure(result.overallStatus)) {\n console.log(`\\n[REMEDIATION REQUIRED] ${result.overallStatus}. Starting bounded remediation (limit: ${remediationLimit}).`);\n // Use the provided executor (programmatic API) or fall back to the default CLI executor.\n // The CLI executor re-runs failed npm scripts; it does not modify source code.\n const executor = typeof remediationExecutor === \"function\"\n ? remediationExecutor\n : createCliRemediationExecutor(cwd);\n const healer = new HealerEngine({ cwd, remediationLimit, taskSlug });\n result = await healer.run({ initialResult: result, validate: observedValidate, remediate: executor });\n if (deepContext) await deepContext.ledger.save(deepContext.ledgerPath);\n }\n\n if (isTerminalFailure(result.overallStatus)) {\n throw new Error(`[WORKFLOW BLOCKED] ${result.overallStatus}: ${result.reason || \"Validation could not be resolved safely.\"}`);\n }\n if (isRecoverableGateFailure(result.overallStatus)) {\n throw new Error(`[WORKFLOW BLOCKED] Unresolved gate status after remediation: ${result.overallStatus}`);\n }\n\n console.log(\"\\n--- Final Handoff ---\");\n const handoffEngine = new HandoffEngine({ cwd });\n const handoffPath = await handoffEngine.generate({\n taskId: path.basename(specPath, \".md\"),\n status: result.overallStatus,\n specPaths: [specPath],\n evidence: result.evidence,\n nextActions: `Profile ${workflowProfile}. Observed validation completed. Ready for review or explicitly approved release actions.`\n });\n\n console.log(`\\n[AI WORKFLOW COMPLETE] ${result.overallStatus}`);\n if (result.remediation?.attempts) console.log(`Remediation attempts: ${result.remediation.attempts}`);\n console.log(`Handoff Packet: ${path.relative(cwd, handoffPath)}\\n`);\n return { ...result, workflowProfile, workflowId: deepContext?.workflowId || null };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport Ajv from \"ajv\";\nimport addFormats from \"ajv-formats\";\nimport { hashFile } from \"./workflow-artifacts.js\";\nimport { getPackageRoot } from \"../package-assets.js\";\n\nexport interface ApprovalReceipt {\n workflowId: string;\n approvedSpecHash: string;\n approvedBy: string;\n approvedAt: string;\n authorizationSource: string;\n}\n\nexport interface ApprovalValidationResult {\n valid: boolean;\n reason?: string;\n receipt?: ApprovalReceipt;\n approvedSpecHash?: string;\n}\n\nexport class ApprovalReceiptValidator {\n cwd: string;\n\n constructor({ cwd = process.cwd() }: { cwd?: string } = {}) {\n this.cwd = path.resolve(cwd);\n }\n\n async validate(receiptPath: string, specPath: string, expectedWorkflowId?: string): Promise<ApprovalValidationResult> {\n const absoluteReceiptPath = path.resolve(this.cwd, receiptPath);\n if (absoluteReceiptPath !== this.cwd && !absoluteReceiptPath.startsWith(`${this.cwd}${path.sep}`)) {\n return { valid: false, reason: \"Approval receipt must be inside the repository.\" };\n }\n\n try {\n const stat = await fs.lstat(absoluteReceiptPath);\n if (!stat.isFile() || stat.isSymbolicLink()) {\n return { valid: false, reason: \"Approval receipt must be a regular, non-symlink file.\" };\n }\n } catch {\n return { valid: false, reason: `Approval receipt not found: ${receiptPath}` };\n }\n\n let receipt: ApprovalReceipt;\n try {\n receipt = JSON.parse(await fs.readFile(absoluteReceiptPath, \"utf8\"));\n const root = getPackageRoot();\n const schema = JSON.parse(await fs.readFile(path.join(root, \"dist-assets/schemas/approval-receipt.schema.json\"), \"utf8\"));\n const ajv = new Ajv({ allErrors: true });\n addFormats(ajv);\n const validateSchema = ajv.compile(schema);\n if (!validateSchema(receipt)) {\n const errors = (validateSchema.errors || []).map((error) => `${error.instancePath} ${error.message}`).join(\", \");\n return { valid: false, reason: `Approval receipt schema violation: ${errors}` };\n }\n } catch (error: any) {\n return { valid: false, reason: `Approval receipt validation failed: ${error.message}` };\n }\n\n if (expectedWorkflowId && receipt.workflowId !== expectedWorkflowId) {\n return { valid: false, reason: `Approval receipt workflowId '${receipt.workflowId}' does not match '${expectedWorkflowId}'.` };\n }\n\n const approvedSpecHash = await hashFile(specPath);\n if (receipt.approvedSpecHash !== approvedSpecHash) {\n return { valid: false, reason: \"Approval receipt hash does not match the approved specification bytes.\" };\n }\n\n return { valid: true, receipt, approvedSpecHash };\n }\n}\n","import { createHash } from \"node:crypto\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nexport function sha256(content: string | Buffer): string {\n return createHash(\"sha256\").update(content).digest(\"hex\");\n}\n\nexport async function hashFile(filePath: string): Promise<string> {\n return sha256(await fs.readFile(filePath));\n}\n\nexport async function writeFileAtomic(filePath: string, content: string): Promise<void> {\n await fs.mkdir(path.dirname(filePath), { recursive: true });\n const temporaryPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;\n try {\n await fs.writeFile(temporaryPath, content, { encoding: \"utf8\", flag: \"wx\" });\n await fs.rename(temporaryPath, filePath);\n } catch (error) {\n await fs.rm(temporaryPath, { force: true }).catch(() => {});\n throw error;\n }\n}\n\nexport function stripMarkdownFence(content: string): string {\n const trimmed = content.trim();\n const match = trimmed.match(/^```(?:markdown|md|json)?\\s*\\n([\\s\\S]*?)\\n```$/i);\n return (match ? match[1] : trimmed).trim() + \"\\n\";\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport Ajv from \"ajv\";\nimport { stripMarkdownFence } from \"./workflow-artifacts.js\";\nimport { getPackageRoot } from \"../package-assets.js\";\n\nexport interface TechnicalPlanFile {\n path: string;\n reason: string;\n}\n\nexport interface TechnicalPlan {\n title: string;\n architectureSummary: string;\n filesInScope: TechnicalPlanFile[];\n filesOutOfScope: TechnicalPlanFile[];\n implementationSteps: string[];\n dependencies: string[];\n risks: string[];\n tradeoffs: string[];\n validationPlan: string[];\n rollbackPlan: string[];\n}\n\nexport interface TechnicalPlanValidationResult {\n valid: boolean;\n reason?: string;\n plan?: TechnicalPlan;\n content?: string;\n}\n\nfunction isContained(root: string, candidate: string): boolean {\n return candidate === root || candidate.startsWith(`${root}${path.sep}`);\n}\n\nexport class TechnicalPlanValidator {\n cwd: string;\n\n constructor({ cwd = process.cwd() }: { cwd?: string } = {}) {\n this.cwd = path.resolve(cwd);\n }\n\n private async validateScopedPath(candidate: string, forbiddenPaths: Set<string>): Promise<string | null> {\n if (path.isAbsolute(candidate)) return `Absolute path is not allowed: '${candidate}'.`;\n const normalized = candidate.replaceAll(\"\\\\\", \"/\");\n if (!normalized || normalized.split(\"/\").some((part) => part === \"\" || part === \".\" || part === \"..\")) {\n return `Path must be normalized without empty, '.' or '..' segments: '${candidate}'.`;\n }\n if (normalized === \".git\" || normalized.startsWith(\".git/\") || normalized === \".ai-workflow\" || normalized.startsWith(\".ai-workflow/\")) {\n return `Workflow control path is out of implementation scope: '${candidate}'.`;\n }\n const conflictsWithProtectedPath = [...forbiddenPaths].some((protectedPath) =>\n normalized === protectedPath ||\n normalized.startsWith(`${protectedPath}/`) ||\n protectedPath.startsWith(`${normalized}/`)\n );\n if (normalized === \"EVIDENCE.json\" || conflictsWithProtectedPath) {\n return `Protected workflow artifact is out of implementation scope: '${candidate}'.`;\n }\n\n const absolute = path.resolve(this.cwd, normalized);\n if (!isContained(this.cwd, absolute)) return `Path escapes repository: '${candidate}'.`;\n\n let cursor = this.cwd;\n for (const part of normalized.split(\"/\")) {\n cursor = path.join(cursor, part);\n try {\n const stat = await fs.lstat(cursor);\n if (cursor === absolute && stat.isDirectory()) {\n return `filesInScope must name explicit files, not a directory: '${candidate}'.`;\n }\n if (stat.isSymbolicLink()) {\n const resolved = await fs.realpath(cursor);\n if (!isContained(this.cwd, resolved)) return `Symlink escapes repository: '${candidate}'.`;\n cursor = resolved;\n }\n } catch (error: any) {\n if (error.code !== \"ENOENT\") return `Cannot inspect scoped path '${candidate}': ${error.message}`;\n break;\n }\n }\n return null;\n }\n\n async validateOutput(output: string, protectedPaths: string[] = []): Promise<TechnicalPlanValidationResult> {\n let plan: TechnicalPlan;\n try {\n plan = JSON.parse(stripMarkdownFence(output));\n } catch (error: any) {\n return { valid: false, reason: `Technical plan is not valid JSON: ${error.message}` };\n }\n\n try {\n const schema = JSON.parse(await fs.readFile(path.join(getPackageRoot(), \"dist-assets/schemas/technical-plan.schema.json\"), \"utf8\"));\n const validateSchema = new Ajv({ allErrors: true }).compile(schema);\n if (!validateSchema(plan)) {\n const errors = (validateSchema.errors || []).map((error) => `${error.instancePath} ${error.message}`).join(\", \");\n return { valid: false, reason: `Technical plan schema violation: ${errors}` };\n }\n } catch (error: any) {\n return { valid: false, reason: `Technical plan schema validation failed: ${error.message}` };\n }\n\n if (plan.filesInScope.length === 0) {\n return { valid: false, reason: \"Technical plan filesInScope must not be empty.\" };\n }\n\n const forbidden = new Set(protectedPaths.map((entry) => path.relative(this.cwd, path.resolve(this.cwd, entry)).replaceAll(\"\\\\\", \"/\")));\n for (const entry of plan.filesInScope) {\n const reason = await this.validateScopedPath(entry.path, forbidden);\n if (reason) return { valid: false, reason };\n }\n\n const content = `${JSON.stringify(plan, null, 2)}\\n`;\n return { valid: true, plan, content };\n }\n}\n","import { OpenCodeAdapter } from \"../runtime/opencode-adapter.js\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { execSync } from \"node:child_process\";\nimport { EvidenceLedger } from \"../evidence/evidence-ledger.js\";\n\nexport function createRuntimeRemediationExecutor(cwd: string, ledger: EvidenceLedger | null = null) {\n const adapter = new OpenCodeAdapter({ cwd });\n\n function getChangedFiles(): string[] {\n try {\n const output = execSync(\"git status --short\", { cwd, encoding: \"utf8\" });\n return output\n .split(\"\\n\")\n .filter(Boolean)\n .map((line) => line.slice(3).trim())\n .filter(Boolean);\n } catch {\n return [];\n }\n }\n\n return async function runtimeRemediationExecutor({\n attempt,\n maxAttempts,\n mode,\n affectedChecks,\n requestPath,\n result\n }: {\n attempt: number;\n maxAttempts: number;\n mode: string;\n affectedChecks: string[];\n requestPath: string;\n result: any;\n }): Promise<{ applied: boolean; changedFiles?: string[]; evidenceAdded?: string[]; reason?: string }> {\n console.log(`\\n[HEALER] Running Runtime/Phoenix Structural Remediation [Attempt ${attempt}/${maxAttempts}]`);\n console.log(`[HEALER] Affected checks: ${affectedChecks.join(\", \")}`);\n\n if (ledger) {\n ledger.logEvent({\n actor: \"Phoenix\",\n actorType: \"runtime-agent\",\n observed: true,\n runtime: \"opencode\",\n eventType: \"remediation_start\",\n provenance: \"opencode-adapter\",\n data: {\n attempt,\n affectedChecks,\n event: \"remediation.started\"\n }\n });\n }\n\n let requestContent: any = {};\n try {\n requestContent = JSON.parse(await fs.readFile(requestPath, \"utf8\"));\n } catch {\n // ignore/fallback\n }\n\n const filesBefore = getChangedFiles();\n const fileContentsBefore: Record<string, string | null> = {};\n for (const file of filesBefore) {\n try {\n fileContentsBefore[file] = await fs.readFile(path.join(cwd, file), \"utf8\");\n } catch {\n fileContentsBefore[file] = null;\n }\n }\n \n // Extract concrete command outputs for failing checks\n const failedCommands = (result?.evidence?.commands || [])\n .filter((cmd: any) => [\"FAIL\", \"BLOCKED\"].includes(cmd.status));\n \n let concreteOutput = \"\";\n if (failedCommands.length > 0) {\n concreteOutput = failedCommands.map((cmd: any) => {\n return `Command: ${cmd.name} (${Array.isArray(cmd.command) ? cmd.command.join(\" \") : cmd.command})\nExit Code: ${cmd.exitCode}\nOutput:\n${cmd.output}`;\n }).join(\"\\n\\n\");\n } else {\n concreteOutput = JSON.stringify(result?.quality || result || {}, null, 2);\n }\n\n const promptMsg = `We are in remediation mode (attempt ${attempt}/${maxAttempts}).\nThe following validation checks have failed:\n${affectedChecks.join(\", \")}\n\nDetails of the failure:\n\\`\\`\\`\n${concreteOutput}\n\\`\\`\\`\n\nPlease inspect the code, identify the root cause of these failures (e.g. failing tests, syntax issues, build errors), and write a correction to the relevant files in the workspace to make the tests/validations pass.`;\n\n console.log(`[HEALER] Sending structural healing request to Phoenix agent...`);\n const runResult = await adapter.execute(promptMsg, {\n agent: \"Phoenix\"\n });\n\n const filesAfter = getChangedFiles();\n const changedFiles: string[] = [];\n for (const file of filesAfter) {\n if (!filesBefore.includes(file)) {\n changedFiles.push(file);\n } else {\n try {\n const contentAfter = await fs.readFile(path.join(cwd, file), \"utf8\");\n if (contentAfter !== fileContentsBefore[file]) {\n changedFiles.push(file);\n }\n } catch {\n if (fileContentsBefore[file] !== null) {\n changedFiles.push(file);\n }\n }\n }\n }\n const success = runResult.success && changedFiles.length > 0;\n\n if (!runResult.success) {\n console.log(`[HEALER] Phoenix remediation failed: ${runResult.error || \"Unknown error\"}`);\n return {\n applied: false,\n reason: `Phoenix runtime execution failed: ${runResult.error || \"Unknown error\"}`\n };\n }\n\n if (changedFiles.length === 0) {\n console.log(`[HEALER] Phoenix execution succeeded but no files were modified.`);\n return {\n applied: false,\n reason: \"Phoenix runtime executed but did not modify any files in the workspace.\"\n };\n }\n\n console.log(`[HEALER] Phoenix successfully executed remediation commands.`);\n console.log(`[HEALER] Files modified: ${changedFiles.join(\", \")}`);\n\n return {\n applied: true,\n changedFiles,\n evidenceAdded: [\"phoenix-healing-run\"]\n };\n };\n}\n","import { RequestClassifier, RequestClassifierResult } from \"../../core/request-classifier.js\";\nimport { ExecutionPlanner, ExecutionPlan } from \"../../core/execution-planner.js\";\nimport { WorkflowStateMachine } from \"../../core/workflow-state-machine.js\";\nimport { BranchGate } from \"../../core/gates/branch-gate.js\";\nimport { EvidenceLedger } from \"../../core/evidence/evidence-ledger.js\";\nimport { DelegationController } from \"../../core/delegation-controller.js\";\nimport { OpenCodeAdapter } from \"../../core/runtime/opencode-adapter.js\";\nimport { runCollectEvidence } from \"./collect-evidence.js\";\nimport { QualityGuard } from \"../../core/validation/quality-guard.js\";\nimport { HandoffEngine } from \"../../core/handoff/handoff-engine.js\";\nimport { HealerEngine } from \"../../core/healing/healer-engine.js\";\nimport { createRuntimeRemediationExecutor } from \"../../core/healing/runtime-remediation-executor.js\";\nimport { isRecoverableGateFailure, isTerminalFailure } from \"../../core/statuses.js\";\nimport { Finalizer } from \"../../core/finalization/finalizer.js\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { execSync } from \"node:child_process\";\nimport { SpecValidator } from \"../../core/sdd/validator.js\";\nimport { sha256, stripMarkdownFence, writeFileAtomic } from \"../../core/sdd/workflow-artifacts.js\";\n\n/** Snapshot of workspace state before/after read-only execution. */\ninterface ReadOnlyWorkspaceState {\n snapshot: { files: Record<string, { sha256: string }> };\n head: string;\n branch: string;\n indexTree: string;\n porcelainStatus: string;\n}\n\n/** Combined result from evidence collection and quality guard. */\ninterface ValidationResult {\n overallStatus: string;\n evidence: Record<string, unknown>;\n quality: Record<string, unknown>;\n}\n\n/** Result returned by BranchGate.check(). */\ninterface BranchGateResult {\n blocked: boolean;\n reason: string;\n branch: string;\n branchBefore: string;\n recovered: boolean;\n}\n\nasync function captureReadOnlyState(cwd: string, fastTrack = false) {\n const finalizer = new Finalizer({ cwd, fastTrack });\n const snapshot = await finalizer.snapshotManager.capture();\n \n const execGit = (args: string) => {\n try {\n return execSync(`git ${args}`, { cwd, encoding: \"utf8\", stdio: \"pipe\" }).trim();\n } catch {\n return \"\";\n }\n };\n\n const head = execGit(\"rev-parse HEAD\");\n const branch = execGit(\"rev-parse --abbrev-ref HEAD\");\n const indexTree = execGit(\"write-tree\");\n const porcelainStatus = execGit(\"status --porcelain\");\n\n return {\n snapshot,\n head,\n branch,\n indexTree,\n porcelainStatus\n };\n}\n\nfunction compareReadOnlyState(before: ReadOnlyWorkspaceState, after: ReadOnlyWorkspaceState) {\n const violations: string[] = [];\n\n // 1. Compare branch\n if (before.branch !== after.branch) {\n violations.push(`Branch changed from '${before.branch}' to '${after.branch}'`);\n }\n\n // 2. Compare HEAD\n if (before.head !== after.head) {\n violations.push(`Git HEAD changed from '${before.head}' to '${after.head}' (commit or reset made inside read-only task)`);\n }\n\n // 3. Compare index tree\n if (before.indexTree !== after.indexTree) {\n violations.push(`Git index tree changed from '${before.indexTree}' to '${after.indexTree}'`);\n }\n\n // 4. Compare porcelain status\n if (before.porcelainStatus !== after.porcelainStatus) {\n violations.push(`Git status changed. Before:\\n${before.porcelainStatus}\\nAfter:\\n${after.porcelainStatus}`);\n }\n\n // 5. Compare workspace files (SHA-256 hashes)\n const beforeFiles = before.snapshot.files || {};\n const afterFiles = after.snapshot.files || {};\n\n for (const [file, info] of Object.entries(afterFiles)) {\n const prevInfo = beforeFiles[file];\n if (!prevInfo) {\n violations.push(`File added: ${file}`);\n } else if (prevInfo.sha256 !== (info as any).sha256) {\n violations.push(`File content modified: ${file}`);\n }\n }\n for (const file of Object.keys(beforeFiles)) {\n if (!afterFiles[file]) {\n violations.push(`File deleted: ${file}`);\n }\n }\n\n return violations;\n}\n\nfunction slugify(text: string): string {\n return text\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 32) || \"task\";\n}\n\nfunction combineValidation(evidence: Record<string, unknown>, quality: Record<string, unknown>): ValidationResult {\n const statuses = [evidence.internalStatus, quality.overallStatus];\n let overallStatus = \"PASS\";\n if (statuses.includes(\"BLOCKED\")) overallStatus = \"BLOCKED\";\n else if (statuses.includes(\"FAIL\")) overallStatus = \"FAIL\";\n else if (statuses.includes(\"FAIL_DELEGATION_GATE\")) overallStatus = \"FAIL_DELEGATION_GATE\";\n else if (statuses.includes(\"FAIL_QUALITY_GATE\")) overallStatus = \"FAIL_QUALITY_GATE\";\n else if (statuses.includes(\"PASS_WITH_NOTES\")) overallStatus = \"PASS_WITH_NOTES\";\n return { overallStatus, evidence, quality };\n}\n\nexport interface ExecuteOptions {\n cwd: string;\n naturalRequest: string;\n taskSlug?: string;\n}\n\n/**\n * classifyAndPlanExecution - Intake analysis and contract formulation.\n */\nasync function classifyAndPlanExecution(\n naturalRequest: string,\n cwd: string,\n taskSlug: string,\n delegationController: DelegationController,\n stateMachine: WorkflowStateMachine\n): Promise<{ plan: ExecutionPlan; classification: RequestClassifierResult }> {\n const classifier = new RequestClassifier();\n const classification = classifier.classify(naturalRequest, { cwd });\n console.log(`[CLASSIFIED] Intent: ${classification.intent}, Mode: ${classification.mode}, Profile: ${classification.profile}`);\n stateMachine.transitionTo(\"CLASSIFIED\");\n\n await delegationController.route(naturalRequest, classification);\n\n const routingDecision = classification.routingDecision || {};\n if (routingDecision.permissionDecision === \"blocked\") {\n stateMachine.transitionTo(\"BLOCKED\");\n throw new Error(`[ROUTE BLOCKED] ${routingDecision.reason}`);\n }\n if (routingDecision.permissionDecision === \"rerouted\") {\n console.log(`[REROUTED] ${routingDecision.reason}`);\n }\n\n const planner = new ExecutionPlanner({ cwd });\n const plan = planner.plan(classification, taskSlug);\n console.log(`[PLANNED] Owner: ${plan.owner}, Remediation limit: ${plan.remediationLimit}`);\n stateMachine.transitionTo(\"PLANNED\");\n\n return { plan, classification };\n}\n\n/**\n * runBranchGate - Authorizes changes within the branch lifecycle.\n */\nfunction runBranchGate(plan: ExecutionPlan, taskSlug: string, cwd: string, stateMachine: WorkflowStateMachine, branchGate: BranchGate): BranchGateResult {\n const gateResult = branchGate.check(\"\", {\n taskSlug,\n readOnly: !plan.branchNeeded\n });\n\n if (gateResult.blocked) {\n stateMachine.transitionTo(\"BLOCKED\");\n throw new Error(`[GATE BLOCKED] ${gateResult.reason}`);\n }\n console.log(`[PASS] Branch Gate: ${gateResult.recovered ? `${gateResult.branchBefore} -> ${gateResult.branch}` : `${gateResult.branch} is authorized`}.`);\n stateMachine.transitionTo(\"BRANCH_READY\");\n return gateResult;\n}\n\n/**\n * createSpecIfRequired - Implements Spec-Driven Development gate.\n */\nasync function createSpecIfRequired(plan: ExecutionPlan, classification: RequestClassifierResult, taskSlug: string, cwd: string): Promise<void> {\n if (plan.specPath) {\n const fullSpecPath = path.join(cwd, plan.specPath);\n const specExists = await fs.access(fullSpecPath).then(() => true).catch(() => false);\n if (!specExists) {\n await fs.mkdir(path.dirname(fullSpecPath), { recursive: true });\n const specTemplatePath = path.join(cwd, \".ai-workflow/templates/specs/standard.md\");\n const templateContent = await fs.readFile(specTemplatePath, \"utf8\").catch(() => {\n return `# [STANDARD] Specification: ${classification.request}\\n\\n## Metadata\\n\\n- ID: SPEC-${taskSlug}\\n- Author: Spec-Engineer\\n- Status: DRAFT\\n- Date: ${new Date().toISOString().split(\"T\")[0]}\\n\\n## Functional Requirements\\n\\n- ${classification.request}\\n\\n## Technical Implementation Plan\\n\\n### Files to Create/Modify\\n\\n- \\`src/index.js\\`\\n\\n## Acceptance Criteria\\n\\n- [ ] Implemented successfully\\n\\n## Testing Strategy\\n\\n- [ ] Behavior tests pass`;\n });\n await fs.writeFile(fullSpecPath, templateContent);\n console.log(`[EXECUTE] Created DRAFT specification template at: ${plan.specPath}`);\n }\n }\n}\n\nasync function runDeepSpecificationCheckpoint(\n plan: ExecutionPlan,\n classification: RequestClassifierResult,\n taskSlug: string,\n cwd: string,\n delegationController: DelegationController,\n stateMachine: WorkflowStateMachine\n): Promise<any> {\n if (!plan.specPath) throw new Error(\"[SDD BLOCKED] Required specification path was not planned.\");\n const absoluteSpecPath = path.resolve(cwd, plan.specPath);\n const relativeSpecPath = path.relative(cwd, absoluteSpecPath).replaceAll(\"\\\\\", \"/\");\n if (relativeSpecPath.startsWith(\"../\") || path.isAbsolute(relativeSpecPath)) {\n throw new Error(\"[SDD BLOCKED] Planned specification path escapes the repository.\");\n }\n if (await fs.access(absoluteSpecPath).then(() => true).catch(() => false)) {\n throw new Error(`[SDD BLOCKED] Refusing to overwrite existing specification: ${relativeSpecPath}`);\n }\n\n const approvalPath = `.ai-workflow/approvals/${taskSlug}.json`;\n const validator = new SpecValidator();\n stateMachine.transitionTo(\"DELEGATED\");\n\n const prompt = [\n \"Produce only the complete Markdown for a [DEEP] specification.\",\n \"The Metadata Status must be exactly DRAFT. Include concrete acceptance criteria as unchecked checkboxes.\",\n \"Do not approve the specification, create a receipt, edit files, or implement code.\",\n `Workflow ID: ${taskSlug}`,\n `Request: ${classification.request}`\n ].join(\"\\n\");\n\n const phaseResult = await delegationController.executePhase({\n phase: \"specification\",\n actor: \"Nexus\",\n prompt,\n readOnly: true,\n requireExplicitActor: true,\n onOutput: async (output) => {\n const content = stripMarkdownFence(output);\n const validation = validator.validateDraftContent(content);\n if (!validation.valid) throw new Error(`Nexus DRAFT rejected: ${validation.reason}`);\n await writeFileAtomic(absoluteSpecPath, content);\n return { artifactPath: relativeSpecPath, artifactHash: sha256(content), draftHash: sha256(content) };\n }\n });\n\n if (!phaseResult.success) {\n stateMachine.transitionTo(\"BLOCKED\");\n throw new Error(`[SDD BLOCKED] Nexus specification phase failed: ${phaseResult.error || \"unknown failure\"}`);\n }\n\n const draftHash = String(phaseResult.artifact?.artifactHash || \"\");\n delegationController.ledger?.logEvent({\n actor: \"Atlas\",\n actorType: \"control-plane\",\n observed: true,\n eventType: \"approval_checkpoint\",\n provenance: \"sdd-control-plane\",\n data: {\n specSource: \"nexus\",\n specPath: relativeSpecPath,\n approvalPath,\n draftHash,\n approvedHash: null,\n planHash: null,\n status: \"BLOCKED\",\n reason: \"SDD APPROVAL REQUIRED\"\n }\n });\n stateMachine.transitionTo(\"BLOCKED\");\n\n const resumeCommand = `aw run --spec-path=${relativeSpecPath} --approval-path=${approvalPath}`;\n console.log(`\\n[BLOCKED] SDD APPROVAL REQUIRED`);\n console.log(`Specification: ${relativeSpecPath}`);\n console.log(`Resume: ${resumeCommand}\\n`);\n return {\n overallStatus: \"BLOCKED\",\n reason: \"SDD APPROVAL REQUIRED\",\n checkpoint: \"approval\",\n exitCode: 2,\n workflowId: taskSlug,\n specPath: relativeSpecPath,\n approvalPath,\n draftHash,\n resumeCommand,\n stateHistory: stateMachine.getHistory()\n };\n}\n\n/**\n * runImplementation - Delegations to the implementation engine.\n */\nasync function runImplementation(\n plan: ExecutionPlan,\n classification: RequestClassifierResult,\n delegationController: DelegationController,\n stateMachine: WorkflowStateMachine,\n fastTrack: boolean = false\n): Promise<any> {\n stateMachine.transitionTo(\"DELEGATED\");\n stateMachine.transitionTo(\"IMPLEMENTING\");\n\n let promptMsg = classification.request;\n if (plan.specPath) {\n promptMsg = `Please review and fill in the specification file at: ${plan.specPath}. Make sure to change the Status field to 'APPROVED' in the Metadata section, and then implement the behavior described.`;\n }\n\n const runResult = await delegationController.implement(promptMsg, plan.owner, { readOnly: !plan.branchNeeded, fastTrack });\n\n if (!runResult.success) {\n console.error(`[EXECUTE] OpenCode adapter execution reported failure: ${runResult.error || \"Unknown error\"}`);\n stateMachine.transitionTo(\"BLOCKED\");\n throw new Error(`[WORKFLOW BLOCKED] OpenCode runtime execution failed: ${runResult.error || \"Unknown error\"}`);\n }\n return runResult;\n}\n\n/**\n * runReadOnlyConfinementCheck - Asserts read-only execution constraints.\n */\nasync function runReadOnlyConfinementCheck(readOnlyStateBefore: ReadOnlyWorkspaceState, cwd: string, stateMachine: WorkflowStateMachine, fastTrack = false): Promise<void> {\n const readOnlyStateAfter = await captureReadOnlyState(cwd, fastTrack);\n const violations = compareReadOnlyState(readOnlyStateBefore, readOnlyStateAfter);\n if (violations.length > 0) {\n console.error(`[EXECUTE] Read-only confinement violation detected:`);\n for (const v of violations) {\n console.error(` - ${v}`);\n }\n stateMachine.transitionTo(\"BLOCKED\");\n throw new Error(`[WORKFLOW BLOCKED] Read-only confinement violation: files were written/modified, index or commits modified: \\n${violations.join(\"\\n\")}`);\n }\n}\n\n/**\n * runValidation - Resolves evidence validation contracts.\n */\nasync function runValidation(\n plan: ExecutionPlan,\n taskSlug: string,\n cwd: string,\n gateResult: BranchGateResult,\n naturalRequest: string,\n delegationController: DelegationController,\n stateMachine: WorkflowStateMachine\n): Promise<{ result: ValidationResult; validateWorkflow: () => Promise<ValidationResult> }> {\n stateMachine.transitionTo(\"VALIDATING\");\n\n const validateWorkflow = async () => {\n const evidence = await runCollectEvidence({\n cwd,\n exitOnError: false,\n taskSlug,\n evidencePolicy: plan.evidencePolicy,\n profile: plan.profile,\n branchRecovery: gateResult.recovered ? `${gateResult.branchBefore} -> ${gateResult.branch}` : \"NOT_REQUIRED\",\n userRequest: naturalRequest,\n explicitApprovals: process.env.AI_WORKFLOW_APPROVALS ? process.env.AI_WORKFLOW_APPROVALS.split(\",\").map(a => a.trim()) : []\n });\n const quality = await new QualityGuard({\n cwd,\n taskSlug,\n evidencePolicy: plan.evidencePolicy,\n riskLevel: plan.riskLevel\n }).verify();\n return combineValidation(evidence, quality);\n };\n\n const result = await delegationController.validate(taskSlug, plan.profile, validateWorkflow, plan.evidencePolicy);\n return { result, validateWorkflow };\n}\n\n/**\n * runBoundedRemediation - Heals gate violations.\n */\nasync function runBoundedRemediation(\n plan: any,\n taskSlug: string,\n cwd: string,\n initialResult: any,\n validateWorkflow: () => Promise<any>,\n ledger: EvidenceLedger,\n delegationController: DelegationController,\n stateMachine: WorkflowStateMachine,\n checkBranchSafety: () => void,\n updateSnapshot: () => Promise<void>\n): Promise<any> {\n if (!isRecoverableGateFailure(initialResult.overallStatus)) {\n return initialResult;\n }\n\n console.log(`\\n[REMEDIATION REQUIRED] ${initialResult.overallStatus}. Starting bounded remediation (limit: ${plan.remediationLimit}).`);\n const executor = createRuntimeRemediationExecutor(cwd, ledger);\n const healer = new HealerEngine({\n cwd,\n remediationLimit: plan.remediationLimit,\n taskSlug,\n ledger\n });\n\n return await healer.run({\n initialResult,\n validate: async () => {\n stateMachine.transitionTo(\"REVALIDATING\");\n return await delegationController.validate(taskSlug, plan.profile, validateWorkflow, plan.evidencePolicy);\n },\n remediate: async (remedCtx) => {\n stateMachine.transitionTo(\"REMEDIATING\");\n const remRes = await executor(remedCtx as any);\n if (remRes.applied) {\n checkBranchSafety();\n await updateSnapshot();\n }\n return remRes;\n }\n });\n}\n\n/**\n * runFinalizerStabilization - Verifies integrity and fidelity.\n */\nasync function runFinalizerStabilization(\n plan: any,\n taskSlug: string,\n cwd: string,\n initialResult: any,\n validateWorkflow: () => Promise<any>,\n delegationController: DelegationController,\n finalizer: Finalizer,\n lastWriteSnapshotRef: { current: any },\n checkBranchSafety: () => void\n): Promise<{ result: any; integrity: any }> {\n let integrity = await finalizer.verifyIntegrity(lastWriteSnapshotRef.current);\n let revalidationCount = 0;\n const maxRevalidations = 2;\n let result = initialResult;\n\n while (!integrity.valid && revalidationCount < maxRevalidations) {\n console.log(`\\n[FINALIZER WARNING] Workspace mutated during validation! Re-running validation to stabilize.`);\n console.log(`Changes detected:`, integrity.changes);\n\n checkBranchSafety();\n\n lastWriteSnapshotRef.current = await finalizer.snapshotManager.capture();\n revalidationCount++;\n\n result = await delegationController.validate(taskSlug, plan.profile, validateWorkflow, plan.evidencePolicy);\n\n checkBranchSafety();\n\n integrity = await finalizer.verifyIntegrity(lastWriteSnapshotRef.current);\n }\n\n return { result, integrity };\n}\n\n/**\n * generateFinalHandoff - Generates Handoff report.\n */\nasync function generateFinalHandoff(plan: ExecutionPlan, taskSlug: string, cwd: string, finalState: string, evidence: Record<string, unknown> | null): Promise<string> {\n console.log(\"\\n--- Final Handoff ---\");\n const handoffEngine = new HandoffEngine({ cwd });\n const handoffPath = await handoffEngine.generate({\n taskId: taskSlug,\n status: finalState,\n specPaths: plan.specPath ? [plan.specPath] : [],\n evidence,\n nextActions: `Profile ${plan.profile}. Observed execution completed with status ${finalState}.`\n });\n\n console.log(`\\n[AI WORKFLOW COMPLETE] ${finalState}`);\n console.log(`Handoff Packet: ${path.relative(cwd, handoffPath)}\\n`);\n return handoffPath;\n}\n\nasync function runFastTrackValidation(cwd: string, result: any, checkBranchSafety: () => void): Promise<string> {\n console.log(`\\n--- [FAST-TRACK] Running Lightweight Validation Gates ---`);\n checkBranchSafety();\n \n const changedFiles = result.evidence?.changedFiles || [];\n console.log(`[FAST-TRACK] Changed files detected:`, changedFiles);\n \n const evidencePath = path.join(cwd, \"EVIDENCE.json\");\n const hasEvidence = await fs.access(evidencePath).then(() => true).catch(() => false);\n \n if (hasEvidence) {\n const { EvidenceValidator } = await import(\"../../core/validation/evidence-validator.js\");\n const isTest = process.env.NODE_ENV === \"test\" || process.env.VITEST === \"true\";\n const evidenceValidator = new EvidenceValidator({ cwd, skipFileCheck: isTest, skipGitCheck: isTest });\n const valResult = await evidenceValidator.validate();\n if (!valResult.valid) {\n console.error(`\\n[FAST-TRACK BLOCKED] EVIDENCE.json validation failed: ${valResult.reason}`);\n return \"FAIL_QUALITY_GATE\";\n }\n }\n return result.overallStatus;\n}\n\nasync function runFidelityValidation(naturalRequest: string, result: any, finalizer: Finalizer): Promise<string> {\n const fidelityResult = await finalizer.verifyFidelity({\n userRequest: naturalRequest,\n projectContext: result.evidence?.deliveryDecision?.projectContext || null,\n deliveryDecision: result.evidence?.deliveryDecision || null,\n changedFiles: result.evidence?.changedFiles || [],\n evidence: result.evidence || null,\n explicitApprovals: process.env.AI_WORKFLOW_APPROVALS ? process.env.AI_WORKFLOW_APPROVALS.split(\",\").map(a => a.trim()) : []\n });\n \n if (!fidelityResult.passed) {\n console.log(`\\n[FINALIZER BLOCKED] BLOCKED: Artifact fidelity check failed!`);\n console.log(`Reason: ${fidelityResult.reason}`);\n return \"FAIL_QUALITY_GATE\";\n }\n return result.overallStatus;\n}\n\nfunction computeFinalState(finalStatus: string): string {\n if (finalStatus === \"PASS\") return \"COMPLETED\";\n if (finalStatus === \"PASS_WITH_NOTES\") return \"COMPLETED_WITH_NOTES\";\n return \"BLOCKED\";\n}\n\nasync function executeReadOnlyWorkflow(\n cwd: string,\n stateMachine: WorkflowStateMachine,\n readOnlyStateBefore: ReadOnlyWorkspaceState,\n fastTrack: boolean\n): Promise<any> {\n await runReadOnlyConfinementCheck(readOnlyStateBefore, cwd, stateMachine, fastTrack);\n\n stateMachine.transitionTo(\"IMPLEMENTED\");\n stateMachine.transitionTo(\"VALIDATING\");\n stateMachine.transitionTo(\"COMPLETED\");\n\n console.log(\"\\n--- Final Handoff ---\");\n console.log(`\\n[AI WORKFLOW COMPLETE] COMPLETED`);\n console.log(`Handoff Packet: [IN-MEMORY] (No handoff file written in read-only mode)\\n`);\n\n return {\n overallStatus: \"PASS\",\n evidence: {\n internalStatus: \"PASS\",\n commandsRun: []\n },\n quality: {\n overallStatus: \"PASS\"\n },\n stateHistory: stateMachine.getHistory()\n };\n}\n\n/**\n * runExecute - Coordinators natural request execution.\n */\nexport async function runExecute({ cwd, naturalRequest, taskSlug: taskSlugOverride }: ExecuteOptions): Promise<any> {\n if (!naturalRequest || !naturalRequest.trim()) {\n throw new Error(\"Missing request. Please provide a natural request string via positional arguments or --request flag.\");\n }\n\n const taskSlug = taskSlugOverride || slugify(naturalRequest);\n console.log(`\\n[AI WORKFLOW] Executing natural request intake [slug: ${taskSlug}]...\\n`);\n\n const ledger = new EvidenceLedger({ cwd, workflowId: taskSlug });\n const delegationController = new DelegationController({ cwd, ledger, adapter: new OpenCodeAdapter({ cwd }) });\n\n let plan: ExecutionPlan | null = null;\n try {\n const stateMachine = new WorkflowStateMachine();\n\n const { plan: planObj, classification } = await classifyAndPlanExecution(naturalRequest, cwd, taskSlug, delegationController, stateMachine);\n plan = planObj;\n const fastTrack = plan.riskLevel === \"low\" && (!plan.branchNeeded || plan.evidencePolicy === \"optional\");\n\n const branchGate = new BranchGate({ memoryDir: path.join(cwd, \".ai-workflow\"), cwd });\n const gateResult = runBranchGate(plan, taskSlug, cwd, stateMachine, branchGate);\n\n const checkBranchSafety = () => {\n if (!planObj.branchNeeded) return;\n const currentBranch = branchGate.getCurrentBranch();\n if (branchGate.protectedBranches.includes(currentBranch)) {\n stateMachine.transitionTo(\"BLOCKED\");\n throw new Error(`[WORKFLOW BLOCKED] Security violation: current branch is protected '${currentBranch}'!`);\n }\n };\n\n if (classification.specPolicy === \"required\") {\n return await runDeepSpecificationCheckpoint(plan, classification, taskSlug, cwd, delegationController, stateMachine);\n }\n\n await createSpecIfRequired(plan, classification, taskSlug, cwd);\n\n let readOnlyStateBefore: ReadOnlyWorkspaceState | null = null;\n if (!plan.branchNeeded) {\n readOnlyStateBefore = await captureReadOnlyState(cwd, fastTrack);\n }\n\n await runImplementation(plan, classification, delegationController, stateMachine, fastTrack);\n\n if (!plan.branchNeeded && readOnlyStateBefore) {\n return await executeReadOnlyWorkflow(cwd, stateMachine, readOnlyStateBefore, fastTrack);\n }\n\n stateMachine.transitionTo(\"IMPLEMENTED\");\n checkBranchSafety();\n\n const finalizer = new Finalizer({ cwd, fastTrack });\n const snapshotRef = { current: await finalizer.snapshotManager.capture() };\n\n const { result: valResult, validateWorkflow } = await runValidation(plan, taskSlug, cwd, gateResult, naturalRequest, delegationController, stateMachine);\n let result = valResult;\n\n result = await runBoundedRemediation(\n plan,\n taskSlug,\n cwd,\n result,\n validateWorkflow,\n ledger,\n delegationController,\n stateMachine,\n checkBranchSafety,\n async () => {\n snapshotRef.current = await finalizer.snapshotManager.capture();\n }\n );\n\n if (isTerminalFailure(result.overallStatus)) {\n stateMachine.transitionTo(\"BLOCKED\");\n throw new Error(`[WORKFLOW BLOCKED] ${result.overallStatus}: Validation could not be resolved safely.`);\n }\n\n checkBranchSafety();\n\n let integrity = { valid: true, changes: { added: [], modified: [], deleted: [] } };\n if (!fastTrack) {\n const stab = await runFinalizerStabilization(\n plan,\n taskSlug,\n cwd,\n result,\n validateWorkflow,\n delegationController,\n finalizer,\n snapshotRef,\n checkBranchSafety\n );\n result = stab.result;\n integrity = stab.integrity;\n }\n\n let finalStatus = result.overallStatus;\n \n if (fastTrack) {\n finalStatus = await runFastTrackValidation(cwd, result, checkBranchSafety);\n } else if (!integrity.valid) {\n console.log(`\\n[FINALIZER BLOCKED] BLOCKED: workspace did not stabilize`);\n console.log(`Final changes detected:`, integrity.changes);\n finalStatus = \"FAIL_QUALITY_GATE\";\n } else {\n finalStatus = await runFidelityValidation(naturalRequest, result, finalizer);\n }\n\n const finalState = computeFinalState(finalStatus);\n stateMachine.transitionTo(finalState);\n\n await generateFinalHandoff(plan, taskSlug, cwd, finalState, result.evidence);\n\n return { ...result, overallStatus: finalStatus, stateHistory: stateMachine.getHistory() };\n } finally {\n if (plan && !plan.branchNeeded) {\n console.log(`\\n[READ-ONLY LEDGER] (In-Memory/Stdout)\\n${JSON.stringify(ledger.getEvents(), null, 2)}\\n`);\n } else {\n try {\n await ledger.save(`.ai-workflow/history/${taskSlug}-ledger.json`);\n } catch (err) {\n if (plan?.riskLevel === \"high\") throw err;\n }\n }\n }\n}\n","import { existsSync, rmSync, lstatSync, unlinkSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport readline from \"node:readline\";\n\ninterface CleanOptions {\n cwd: string;\n yes?: boolean;\n dryRun?: boolean;\n purgeAgents?: boolean;\n}\n\nfunction askConfirmation(question: string): Promise<string> {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n return new Promise((resolve) => {\n rl.question(question, (answer) => {\n rl.close();\n resolve(answer.trim().toLowerCase());\n });\n });\n}\n\nfunction isSymlink(filePath: string): boolean {\n try {\n return lstatSync(filePath).isSymbolicLink();\n } catch (_) {\n return false;\n }\n}\n\nexport async function runClean({ cwd, yes = false, dryRun = false, purgeAgents = false }: CleanOptions): Promise<void> {\n const targets = [\n \".ai-workflow\",\n \"opencode.jsonc\",\n \".workflow-state.json\",\n \"opencode\"\n ];\n\n const hasAgents = existsSync(join(cwd, \".agents\"));\n\n // Check what actually exists\n const existingTargets = targets\n .map(name => join(cwd, name))\n .filter(path => existsSync(path) || isSymlink(path));\n\n if (existingTargets.length === 0 && (!hasAgents || !purgeAgents)) {\n console.log(\"No AI Workflow configuration or files found in the current project.\");\n return;\n }\n\n console.log(\"\\n[AI WORKFLOW] De-initialization\");\n console.log(\"===============================\");\n\n if (dryRun) {\n console.log(\"[DRY RUN] The following items would be deleted:\");\n existingTargets.forEach(path => console.log(` - ${path}`));\n if (hasAgents && purgeAgents) {\n console.log(` - ${join(cwd, \".agents\")} (customizations folder)`);\n } else if (hasAgents) {\n console.log(` - NOTE: ${join(cwd, \".agents\")} exists but will NOT be deleted (run with --purge-agents to delete)`);\n }\n return;\n }\n\n // Interactive prompts if --yes / -y is not passed\n if (!yes) {\n if (!process.stdin.isTTY) {\n console.log(\"Error: Non-interactive terminal detected. Run with --yes to bypass confirmation.\");\n if (process.env.NODE_ENV === \"test\") {\n // Allow tests to bypass TTY block if they mock/stub process.stdin\n } else {\n process.exit(1);\n }\n }\n\n const confirmDeinit = await askConfirmation(\"Are you sure you want to de-initialize AI Workflow from the project? [y/N] \");\n if (confirmDeinit !== \"y\" && confirmDeinit !== \"yes\") {\n console.log(\"Aborted.\");\n return;\n }\n\n if (hasAgents && !purgeAgents) {\n const confirmPurge = await askConfirmation(\"A custom '.agents' folder was detected. Do you want to purge it (this deletes custom prompts/rules/skills)? [y/N] \");\n if (confirmPurge === \"y\" || confirmPurge === \"yes\") {\n purgeAgents = true;\n }\n }\n }\n\n // Add .agents if requested and exists\n if (purgeAgents && hasAgents) {\n existingTargets.push(join(cwd, \".agents\"));\n }\n\n console.log(\"\\nRemoving files...\");\n for (const target of existingTargets) {\n try {\n if (isSymlink(target)) {\n unlinkSync(target);\n console.log(`Deleted symlink: ${target}`);\n } else {\n rmSync(target, { recursive: true, force: true });\n console.log(`Deleted directory/file: ${target}`);\n }\n } catch (error: any) {\n console.error(`Failed to delete ${target}: ${error.message}`);\n }\n }\n\n console.log(\"\\nAI Workflow has been successfully removed from this project.\");\n}\n","import { getPackageVersion } from \"../core/package-assets.js\";\nimport { runInit } from \"./commands/init.js\";\nimport { runDoctor } from \"./commands/doctor.js\";\nimport { runCollectEvidence } from \"./commands/collect-evidence.js\";\nimport { runMasterOrchestrator } from \"./commands/run.js\";\nimport { runExecute } from \"./commands/execute.js\";\nimport { runClean } from \"./commands/clean.js\";\n\nfunction printHelp() {\n console.log(`ai-workflow\n\nUsage:\n ai-workflow execute \"<request>\" [--task=<slug>] [--request=\"<request>\"]\n ai-workflow run --spec-path=<path> [--approval-path=<path>]\n ai-workflow init [--yes] [--force] [--dry-run] [--no-install] [--no-overwrite] [--claude] [--codex] [--antigravity] [--profile=<profile>]\n ai-workflow validate [--a11y] [--visual-dist=<path>] [--port=<port>]\n ai-workflow collect-evidence [--task=<slug>] [--evidence-policy=<optional|required>] [--mode=<quick|standard|full>] [--dry-run] [--visual-dist=<path>] [--port=<port>]\n ai-workflow doctor\n ai-workflow clean [--yes] [--dry-run] [--purge-agents]\n ai-workflow lint skills\n ai-workflow skill create <name> [--description=\"<desc>\"] [--dry-run] [--force]\n\nCommands:\n execute Orchestrate execution of a natural request through the state machine\n run Proportionate orchestrator with branch safety, validation, and bounded remediation\n init Install AI workflow defaults (OpenCode). --profile=standard (default) or --profile=full (adds examples)\n collect-evidence Run observed project validation; persists EVIDENCE.json under required evidence policy\n doctor Verify local ai-workflow installation\n clean De-initialize and remove AI Workflow files and symlinks from the project\n lint Run specialized linters (e.g. lint skills)\n skill Manage AI workflow skills (e.g. create)\n`);\n}\n\ninterface ParsedFlags {\n yes: boolean;\n force: boolean;\n dryRun: boolean;\n noInstall: boolean;\n noOverwrite: boolean;\n claude: boolean;\n codex: boolean;\n antigravity: boolean;\n \"dev-mode\": boolean;\n specPath?: string;\n approvalPath?: string;\n profile?: string;\n taskSlug?: string;\n mode?: string;\n evidencePolicy?: \"optional\" | \"required\";\n request?: string;\n visualDist?: string;\n port?: string;\n a11y: boolean;\n purgeAgents?: boolean;\n}\n\nfunction parseFlags(args: string[]): ParsedFlags {\n const specPathArg = args.find((arg) => arg.startsWith(\"--spec-path=\"));\n const approvalPathArg = args.find((arg) => arg.startsWith(\"--approval-path=\"));\n const profileEqArg = args.find((arg) => arg.startsWith(\"--profile=\"));\n const taskArg = args.find((arg) => arg.startsWith(\"--task=\"));\n const modeArg = args.find((arg) => arg.startsWith(\"--mode=\"));\n const evidencePolicyArg = args.find((arg) => arg.startsWith(\"--evidence-policy=\"));\n const requestArg = args.find((arg) => arg.startsWith(\"--request=\"));\n const visualDistArg = args.find((arg) => arg.startsWith(\"--visual-dist=\"));\n const portArg = args.find((arg) => arg.startsWith(\"--port=\"));\n const profileIdx = args.indexOf(\"--profile\");\n const profileVal = profileEqArg\n ? profileEqArg.replace(\"--profile=\", \"\")\n : profileIdx >= 0 && profileIdx + 1 < args.length && !args[profileIdx + 1].startsWith(\"--\")\n ? args[profileIdx + 1]\n : undefined;\n\n return {\n yes: args.includes(\"--yes\"),\n force: args.includes(\"--force\"),\n dryRun: args.includes(\"--dry-run\"),\n noInstall: args.includes(\"--no-install\"),\n noOverwrite: args.includes(\"--no-overwrite\"),\n claude: args.includes(\"--claude\"),\n codex: args.includes(\"--codex\"),\n antigravity: args.includes(\"--antigravity\"),\n \"dev-mode\": args.includes(\"--dev-mode\"),\n specPath: specPathArg ? specPathArg.replace(\"--spec-path=\", \"\") : undefined,\n approvalPath: approvalPathArg ? approvalPathArg.replace(\"--approval-path=\", \"\") : undefined,\n profile: profileVal || undefined,\n taskSlug: taskArg ? taskArg.replace(\"--task=\", \"\") : undefined,\n mode: modeArg ? modeArg.replace(\"--mode=\", \"\") : undefined,\n evidencePolicy: evidencePolicyArg ? (evidencePolicyArg.replace(\"--evidence-policy=\", \"\") as any) : undefined,\n request: requestArg ? requestArg.replace(\"--request=\", \"\") : undefined,\n visualDist: visualDistArg ? visualDistArg.replace(\"--visual-dist=\", \"\") : undefined,\n port: portArg ? portArg.replace(\"--port=\", \"\") : undefined,\n a11y: args.includes(\"--a11y\"),\n purgeAgents: args.includes(\"--purge-agents\") || args.includes(\"--purge\")\n };\n}\n\ntype CommandHandler = (args: string[], flags: ParsedFlags) => Promise<void>;\n\nconst commandMap: Record<string, CommandHandler> = {\n execute: async (args, flags) => {\n const positionals = args.filter((arg) => !arg.startsWith(\"-\"));\n const request = flags.request || positionals.join(\" \");\n const result = await runExecute({\n cwd: process.cwd(),\n naturalRequest: request,\n taskSlug: flags.taskSlug\n });\n if (result && (result.overallStatus === \"FAIL_QUALITY_GATE\" || result.overallStatus === \"BLOCKED\" || result.overallStatus === \"FAIL\")) {\n process.exitCode = result.exitCode === 2 ? 2 : 1;\n }\n },\n run: async (_, flags) => {\n await runMasterOrchestrator({\n cwd: process.cwd(),\n ...flags\n });\n },\n init: async (_, flags) => {\n await runInit({\n cwd: process.cwd(),\n ...flags\n });\n },\n \"collect-evidence\": async (_, flags) => {\n if (flags.mode && ![\"quick\", \"standard\", \"full\"].includes(flags.mode)) {\n throw new Error(\"--mode must be quick, standard, or full\");\n }\n await runCollectEvidence({ \n cwd: process.cwd(), \n taskSlug: flags.taskSlug, \n mode: flags.mode, \n evidencePolicy: flags.evidencePolicy,\n dryRun: flags.dryRun,\n visualDist: flags.visualDist,\n port: flags.port\n });\n },\n validate: async (_, flags) => {\n const { runValidate } = await import(\"./commands/validate.js\");\n await runValidate({\n cwd: process.cwd(),\n taskSlug: flags.taskSlug,\n a11y: flags.a11y,\n visualDist: flags.visualDist,\n port: flags.port\n });\n },\n doctor: async () => {\n await runDoctor({ cwd: process.cwd() });\n },\n clean: async (_, flags) => {\n await runClean({\n cwd: process.cwd(),\n ...flags\n });\n },\n lint: async (args) => {\n if (args[0] === \"skills\") {\n const { runLinter } = await import(\"../linting/skill-frontmatter-linter.js\");\n const { errors, filesScanned } = runLinter(process.cwd());\n\n console.log(`Scanned ${filesScanned} skill files.`);\n\n if (errors.length > 0) {\n console.error(`\\\\nFound ${errors.length} frontmatter issues:`);\n for (const err of errors) {\n console.error(`- ${err.filePath}: ${err.message}`);\n }\n process.exit(1);\n } else {\n console.log(\"All skills passed frontmatter linting.\");\n }\n } else {\n console.error(\"Unknown lint target. Supported: skills\");\n process.exit(1);\n }\n },\n skill: async (args) => {\n if (args[0] === \"create\") {\n const { parseSkillCreateArgs, runSkillCreate } = await import(\"./commands/skill.js\");\n const createOptions = parseSkillCreateArgs(args.slice(1));\n await runSkillCreate({\n cwd: process.cwd(),\n ...createOptions\n });\n } else {\n console.error(\"Unknown skill command. Supported: create\");\n process.exit(1);\n }\n }\n};\n\nexport async function runCli(args: string[]): Promise<void> {\n const [command] = args;\n\n if (command === \"--version\" || command === \"-v\") {\n console.log(getPackageVersion() || \"unknown\");\n return;\n }\n\n if (!command || command === \"--help\" || command === \"-h\") {\n printHelp();\n return;\n }\n\n const handler = commandMap[command];\n if (handler) {\n const argsSlice = args.slice(1);\n const flags = parseFlags(argsSlice);\n await handler(argsSlice, flags);\n return;\n }\n\n throw new Error(`unknown command: ${command}`);\n}\n\nrunCli(process.argv.slice(2)).catch((error) => {\n console.error(`ai-workflow error: ${error.message}`);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,aAAS,OACP,UACA,SAA8B;AAE9B,aAAO,EAAC,UAAU,QAAO;IAC3B;AAEa,YAAA,cAA8B;;MAEzC,MAAM,OAAO,MAAM,WAAW;;MAE9B,MAAM,OAAO,QAAQ,IAAI,GAAG,WAAW;MACvC,aAAa,OAAO,YAAY,IAAI,GAAG,eAAe;MACtD,YAAY,OAAO,QAAO,GAAI,cAAc;MAC5C,iBAAiB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KAAK,MAAM,CAAC,CAAC;AACxD,YAAM,eAAe;AAAA,QACnB,KAAK,QAAQ,IAAI;AAAA,QACjB,GAAG;AAAA,MACL,CAAC;AAAA,IACH,OAAO;AACL,cAAQ,MAAM,0CAA0C;AACxD,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF;AACF;AAEA,eAAsB,OAAO,MAA+B;AAC1D,QAAM,CAAC,OAAO,IAAI;AAElB,MAAI,YAAY,eAAe,YAAY,MAAM;AAC/C,YAAQ,IAAI,kBAAkB,KAAK,SAAS;AAC5C;AAAA,EACF;AAEA,MAAI,CAAC,WAAW,YAAY,YAAY,YAAY,MAAM;AACxD,cAAU;AACV;AAAA,EACF;AAEA,QAAM,UAAU,WAAW,OAAO;AAClC,MAAI,SAAS;AACX,UAAM,YAAY,KAAK,MAAM,CAAC;AAC9B,UAAM,QAAQ,WAAW,SAAS;AAClC,UAAM,QAAQ,WAAW,KAAK;AAC9B;AAAA,EACF;AAEA,QAAM,IAAI,MAAM,oBAAoB,OAAO,EAAE;AAC/C;AAEA,OAAO,QAAQ,KAAK,MAAM,CAAC,CAAC,EAAE,MAAM,CAAC,UAAU;AAC7C,UAAQ,MAAM,sBAAsB,MAAM,OAAO,EAAE;AACnD,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["addFormats","fs","fs","path","exists","path","path","path","fs","path","exists","fs","path","fs","path","fs","path","fs","path","fs","path","fs","path","path","fs","next","fs","path","fs","path","execSync","fs","path","path","fs","fs","path","fs","path","path","fs","Ajv","addFormats","import_ajv","fs","path","path","fs","Ajv","path","fs","fs","path","execSync","getChangedFiles","fs","path","execSync","execSync","combineValidation","path","fs","EvidenceValidator","isSymlink","path"]}
1
+ {"version":3,"sources":["../../node_modules/ajv-formats/src/formats.ts","../../node_modules/ajv-formats/src/limit.ts","../../node_modules/ajv-formats/src/index.ts","../../src/cli/commands/init.ts","../../src/core/install-plan.ts","../../src/core/templates.ts","../../src/core/filesystem.ts","../../src/core/opencode-merge.ts","../../src/core/symlink-layout.ts","../../src/adapters/platforms/claude.ts","../../src/adapters/platforms/codex.ts","../../src/adapters/platforms/antigravity.ts","../../src/cli/commands/doctor.ts","../../src/core/validation/canonical-finalization.ts","../../src/cli/commands/collect-evidence.ts","../../src/core/healing/cli-remediation-executor.ts","../../src/cli/commands/run.ts","../../src/core/sdd/approval-receipt.ts","../../src/core/sdd/workflow-artifacts.ts","../../src/core/sdd/technical-plan-validator.ts","../../src/core/healing/runtime-remediation-executor.ts","../../src/cli/commands/execute.ts","../../src/cli/commands/clean.ts","../../src/cli/index.ts"],"sourcesContent":["import type {Format, FormatDefinition} from \"ajv\"\nimport type {FormatValidator, FormatCompare} from \"ajv/dist/types\"\n\nexport type FormatMode = \"fast\" | \"full\"\n\nexport type FormatName =\n | \"date\"\n | \"time\"\n | \"date-time\"\n | \"iso-time\"\n | \"iso-date-time\"\n | \"duration\"\n | \"uri\"\n | \"uri-reference\"\n | \"uri-template\"\n | \"url\"\n | \"email\"\n | \"hostname\"\n | \"ipv4\"\n | \"ipv6\"\n | \"regex\"\n | \"uuid\"\n | \"json-pointer\"\n | \"json-pointer-uri-fragment\"\n | \"relative-json-pointer\"\n | \"byte\"\n | \"int32\"\n | \"int64\"\n | \"float\"\n | \"double\"\n | \"password\"\n | \"binary\"\n\nexport type DefinedFormats = {\n [key in FormatName]: Format\n}\n\nfunction fmtDef(\n validate: RegExp | FormatValidator<string>,\n compare: FormatCompare<string>\n): FormatDefinition<string> {\n return {validate, compare}\n}\n\nexport const fullFormats: DefinedFormats = {\n // date: http://tools.ietf.org/html/rfc3339#section-5.6\n date: fmtDef(date, compareDate),\n // date-time: http://tools.ietf.org/html/rfc3339#section-5.6\n time: fmtDef(getTime(true), compareTime),\n \"date-time\": fmtDef(getDateTime(true), compareDateTime),\n \"iso-time\": fmtDef(getTime(), compareIsoTime),\n \"iso-date-time\": fmtDef(getDateTime(), compareIsoDateTime),\n // duration: https://tools.ietf.org/html/rfc3339#appendix-A\n duration: /^P(?!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:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'\"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\\?(?:[a-z0-9\\-._~!$&'\"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\\-._~!$&'\"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,\n // uri-template: https://tools.ietf.org/html/rfc6570\n \"uri-template\":\n /^(?:(?:[^\\x00-\\x20\"'<>%\\\\^`{|}]|%[0-9a-f]{2})|\\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\\*)?)*\\})*$/i,\n // For the source: https://gist.github.com/dperini/729294\n // For test cases: https://mathiasbynens.be/demo/url-regex\n url: /^(?:https?|ftp):\\/\\/(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z0-9\\u{00a1}-\\u{ffff}]+-)*[a-z0-9\\u{00a1}-\\u{ffff}]+)(?:\\.(?:[a-z0-9\\u{00a1}-\\u{ffff}]+-)*[a-z0-9\\u{00a1}-\\u{ffff}]+)*(?:\\.(?:[a-z\\u{00a1}-\\u{ffff}]{2,})))(?::\\d{2,5})?(?:\\/[^\\s]*)?$/iu,\n email:\n /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,\n hostname:\n /^(?=.{1,253}\\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\\.?$/i,\n // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html\n ipv4: /^(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)$/,\n ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))$/i,\n regex,\n // uuid: http://tools.ietf.org/html/rfc4122\n uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,\n // JSON-pointer: https://tools.ietf.org/html/rfc6901\n // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A\n \"json-pointer\": /^(?:\\/(?:[^~/]|~0|~1)*)*$/,\n \"json-pointer-uri-fragment\": /^#(?:\\/(?:[a-z0-9_\\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,\n // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00\n \"relative-json-pointer\": /^(?:0|[1-9][0-9]*)(?:#|(?:\\/(?:[^~/]|~0|~1)*)*)$/,\n // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types\n // byte: https://github.com/miguelmota/is-base64\n byte,\n // signed 32 bit integer\n int32: {type: \"number\", validate: validateInt32},\n // signed 64 bit integer\n int64: {type: \"number\", validate: validateInt64},\n // C-type float\n float: {type: \"number\", validate: validateNumber},\n // C-type double\n double: {type: \"number\", validate: validateNumber},\n // hint to the UI to hide input strings\n password: true,\n // unchecked string payload\n binary: true,\n}\n\nexport const fastFormats: DefinedFormats = {\n ...fullFormats,\n date: fmtDef(/^\\d\\d\\d\\d-[0-1]\\d-[0-3]\\d$/, compareDate),\n time: fmtDef(\n /^(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)$/i,\n compareTime\n ),\n \"date-time\": fmtDef(\n /^\\d\\d\\d\\d-[0-1]\\d-[0-3]\\dt(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)$/i,\n compareDateTime\n ),\n \"iso-time\": fmtDef(\n /^(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)?$/i,\n compareIsoTime\n ),\n \"iso-date-time\": fmtDef(\n /^\\d\\d\\d\\d-[0-1]\\d-[0-3]\\d[t\\s](?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)?$/i,\n compareIsoDateTime\n ),\n // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js\n uri: /^(?:[a-z][a-z0-9+\\-.]*:)(?:\\/?\\/)?[^\\s]*$/i,\n \"uri-reference\": /^(?:(?:[a-z][a-z0-9+\\-.]*:)?\\/?\\/)?(?:[^\\\\\\s#][^\\s#]*)?(?:#[^\\\\\\s]*)?$/i,\n // email (sources from jsen validator):\n // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363\n // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation')\n email:\n /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,\n}\n\nexport const formatNames = Object.keys(fullFormats) as FormatName[]\n\nfunction isLeapYear(year: number): boolean {\n // https://tools.ietf.org/html/rfc3339#appendix-C\n return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)\n}\n\nconst DATE = /^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)$/\nconst DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n\nfunction date(str: string): boolean {\n // full-date from http://tools.ietf.org/html/rfc3339#section-5.6\n const matches: string[] | null = DATE.exec(str)\n if (!matches) return false\n const year: number = +matches[1]\n const month: number = +matches[2]\n const day: number = +matches[3]\n return (\n month >= 1 &&\n month <= 12 &&\n day >= 1 &&\n day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month])\n )\n}\n\nfunction compareDate(d1: string, d2: string): number | undefined {\n if (!(d1 && d2)) return undefined\n if (d1 > d2) return 1\n if (d1 < d2) return -1\n return 0\n}\n\nconst TIME = /^(\\d\\d):(\\d\\d):(\\d\\d(?:\\.\\d+)?)(z|([+-])(\\d\\d)(?::?(\\d\\d))?)?$/i\n\nfunction getTime(strictTimeZone?: boolean): (str: string) => boolean {\n return function time(str: string): boolean {\n const matches: string[] | null = TIME.exec(str)\n if (!matches) return false\n const hr: number = +matches[1]\n const min: number = +matches[2]\n const sec: number = +matches[3]\n const tz: string | undefined = matches[4]\n const tzSign: number = matches[5] === \"-\" ? -1 : 1\n const tzH: number = +(matches[6] || 0)\n const tzM: number = +(matches[7] || 0)\n if (tzH > 23 || tzM > 59 || (strictTimeZone && !tz)) return false\n if (hr <= 23 && min <= 59 && sec < 60) return true\n // leap second\n const utcMin = min - tzM * tzSign\n const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0)\n return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61\n }\n}\n\nfunction compareTime(s1: string, s2: string): number | undefined {\n if (!(s1 && s2)) return undefined\n const t1 = new Date(\"2020-01-01T\" + s1).valueOf()\n const t2 = new Date(\"2020-01-01T\" + s2).valueOf()\n if (!(t1 && t2)) return undefined\n return t1 - t2\n}\n\nfunction compareIsoTime(t1: string, t2: string): number | undefined {\n if (!(t1 && t2)) return undefined\n const a1 = TIME.exec(t1)\n const a2 = TIME.exec(t2)\n if (!(a1 && a2)) return undefined\n t1 = a1[1] + a1[2] + a1[3]\n t2 = a2[1] + a2[2] + a2[3]\n if (t1 > t2) return 1\n if (t1 < t2) return -1\n return 0\n}\n\nconst DATE_TIME_SEPARATOR = /t|\\s/i\nfunction getDateTime(strictTimeZone?: boolean): (str: string) => boolean {\n const time = getTime(strictTimeZone)\n\n return function date_time(str: string): boolean {\n // http://tools.ietf.org/html/rfc3339#section-5.6\n const dateTime: string[] = str.split(DATE_TIME_SEPARATOR)\n return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1])\n }\n}\n\nfunction compareDateTime(dt1: string, dt2: string): number | undefined {\n if (!(dt1 && dt2)) return undefined\n const d1 = new Date(dt1).valueOf()\n const d2 = new Date(dt2).valueOf()\n if (!(d1 && d2)) return undefined\n return d1 - d2\n}\n\nfunction compareIsoDateTime(dt1: string, dt2: string): number | undefined {\n if (!(dt1 && dt2)) return undefined\n const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR)\n const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR)\n const res = compareDate(d1, d2)\n if (res === undefined) return undefined\n return res || compareTime(t1, t2)\n}\n\nconst NOT_URI_FRAGMENT = /\\/|:/\nconst URI =\n /^(?:[a-z][a-z0-9+\\-.]*:)(?:\\/?\\/(?:(?:[a-z0-9\\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\\.[a-z0-9\\-._~!$&'()*+,;=:]+)\\]|(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)|(?:[a-z0-9\\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\\d*)?(?:\\/(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\\/(?:(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\\/(?:[a-z0-9\\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\\?(?:[a-z0-9\\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i\n\nfunction uri(str: string): boolean {\n // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required \".\"\n return NOT_URI_FRAGMENT.test(str) && URI.test(str)\n}\n\nconst BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm\n\nfunction byte(str: string): boolean {\n BYTE.lastIndex = 0\n return BYTE.test(str)\n}\n\nconst MIN_INT32 = -(2 ** 31)\nconst MAX_INT32 = 2 ** 31 - 1\n\nfunction validateInt32(value: number): boolean {\n return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32\n}\n\nfunction validateInt64(value: number): boolean {\n // JSON and javascript max Int is 2**53, so any int that passes isInteger is valid for Int64\n return Number.isInteger(value)\n}\n\nfunction validateNumber(): boolean {\n return true\n}\n\nconst Z_ANCHOR = /[^\\\\]\\\\Z/\nfunction regex(str: string): boolean {\n if (Z_ANCHOR.test(str)) return false\n try {\n new RegExp(str)\n return true\n } catch (e) {\n return false\n }\n}\n","import type Ajv from \"ajv\"\nimport type {\n Plugin,\n CodeKeywordDefinition,\n KeywordErrorDefinition,\n Code,\n Name,\n ErrorObject,\n} from \"ajv\"\nimport type {AddedFormat} from \"ajv/dist/types\"\nimport type {Rule} from \"ajv/dist/compile/rules\"\nimport {KeywordCxt} from \"ajv\"\nimport {_, str, or, getProperty, operators} from \"ajv/dist/compile/codegen\"\n\ntype Kwd = \"formatMaximum\" | \"formatMinimum\" | \"formatExclusiveMaximum\" | \"formatExclusiveMinimum\"\n\ntype Comparison = \"<=\" | \">=\" | \"<\" | \">\"\n\nconst ops = operators\n\nconst KWDs: {[K in Kwd]: {okStr: Comparison; ok: Code; fail: Code}} = {\n formatMaximum: {okStr: \"<=\", ok: ops.LTE, fail: ops.GT},\n formatMinimum: {okStr: \">=\", ok: ops.GTE, fail: ops.LT},\n formatExclusiveMaximum: {okStr: \"<\", ok: ops.LT, fail: ops.GTE},\n formatExclusiveMinimum: {okStr: \">\", ok: ops.GT, fail: ops.LTE},\n}\n\nexport type LimitFormatError = ErrorObject<Kwd, {limit: string; comparison: Comparison}>\n\nconst error: KeywordErrorDefinition = {\n message: ({keyword, schemaCode}) => str`should be ${KWDs[keyword as Kwd].okStr} ${schemaCode}`,\n params: ({keyword, schemaCode}) =>\n _`{comparison: ${KWDs[keyword as Kwd].okStr}, limit: ${schemaCode}}`,\n}\n\nexport const formatLimitDefinition: CodeKeywordDefinition = {\n keyword: Object.keys(KWDs),\n type: \"string\",\n schemaType: \"string\",\n $data: true,\n error,\n code(cxt) {\n const {gen, data, schemaCode, keyword, it} = cxt\n const {opts, self} = it\n if (!opts.validateFormats) return\n\n const fCxt = new KeywordCxt(it, (self.RULES.all.format as Rule).definition, \"format\")\n if (fCxt.$data) validate$DataFormat()\n else validateFormat()\n\n function validate$DataFormat(): void {\n const fmts = gen.scopeValue(\"formats\", {\n ref: self.formats,\n code: opts.code.formats,\n })\n const fmt = gen.const(\"fmt\", _`${fmts}[${fCxt.schemaCode}]`)\n cxt.fail$data(\n or(\n _`typeof ${fmt} != \"object\"`,\n _`${fmt} instanceof RegExp`,\n _`typeof ${fmt}.compare != \"function\"`,\n compareCode(fmt)\n )\n )\n }\n\n function validateFormat(): void {\n const format = fCxt.schema as string\n const fmtDef: AddedFormat | undefined = self.formats[format]\n if (!fmtDef || fmtDef === true) return\n if (\n typeof fmtDef != \"object\" ||\n fmtDef instanceof RegExp ||\n typeof fmtDef.compare != \"function\"\n ) {\n throw new Error(`\"${keyword}\": format \"${format}\" does not define \"compare\" function`)\n }\n const fmt = gen.scopeValue(\"formats\", {\n key: format,\n ref: fmtDef,\n code: opts.code.formats ? _`${opts.code.formats}${getProperty(format)}` : undefined,\n })\n\n cxt.fail$data(compareCode(fmt))\n }\n\n function compareCode(fmt: Name): Code {\n return _`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword as Kwd].fail} 0`\n }\n },\n dependencies: [\"format\"],\n}\n\nconst formatLimitPlugin: Plugin<undefined> = (ajv: Ajv): Ajv => {\n ajv.addKeyword(formatLimitDefinition)\n return ajv\n}\n\nexport default formatLimitPlugin\n","import {\n DefinedFormats,\n FormatMode,\n FormatName,\n formatNames,\n fastFormats,\n fullFormats,\n} from \"./formats\"\nimport formatLimit from \"./limit\"\nimport type Ajv from \"ajv\"\nimport type {Plugin, Format} from \"ajv\"\nimport {_, Name} from \"ajv/dist/compile/codegen\"\n\nexport {FormatMode, FormatName} from \"./formats\"\nexport {LimitFormatError} from \"./limit\"\nexport interface FormatOptions {\n mode?: FormatMode\n formats?: FormatName[]\n keywords?: boolean\n}\n\nexport type FormatsPluginOptions = FormatName[] | FormatOptions\n\nexport interface FormatsPlugin extends Plugin<FormatsPluginOptions> {\n get: (format: FormatName, mode?: FormatMode) => Format\n}\n\nconst fullName = new Name(\"fullFormats\")\nconst fastName = new Name(\"fastFormats\")\n\nconst formatsPlugin: FormatsPlugin = (\n ajv: Ajv,\n opts: FormatsPluginOptions = {keywords: true}\n): Ajv => {\n if (Array.isArray(opts)) {\n addFormats(ajv, opts, fullFormats, fullName)\n return ajv\n }\n const [formats, exportName] =\n opts.mode === \"fast\" ? [fastFormats, fastName] : [fullFormats, fullName]\n const list = opts.formats || formatNames\n addFormats(ajv, list, formats, exportName)\n if (opts.keywords) formatLimit(ajv)\n return ajv\n}\n\nformatsPlugin.get = (name: FormatName, mode: FormatMode = \"full\"): Format => {\n const formats = mode === \"fast\" ? fastFormats : fullFormats\n const f = formats[name]\n if (!f) throw new Error(`Unknown format \"${name}\"`)\n return f\n}\n\nfunction addFormats(ajv: Ajv, list: FormatName[], fs: DefinedFormats, exportName: Name): void {\n ajv.opts.code.formats ??= _`require(\"ajv-formats/dist/formats\").${exportName}`\n for (const f of list) ajv.addFormat(f, fs[f])\n}\n\nmodule.exports = exports = formatsPlugin\nObject.defineProperty(exports, \"__esModule\", {value: true})\n\nexport default formatsPlugin\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createInstallPlan } from \"../../core/install-plan.js\";\nimport { buildAiWorkflowConfig, getTemplateFiles, isValidProfile } from \"../../core/templates.js\";\nimport { exists, writeFileSafe, readJson } from \"../../core/filesystem.js\";\nimport { createManagedBackup, createManagedPathBackup } from \"../../core/backup.js\";\nimport { mergeOpencodeConfig } from \"../../core/opencode-merge.js\";\nimport { buildSymlinkEntries, isSymlinkTo, setupInternalSymlinks } from \"../../core/symlink-layout.js\";\nimport { ClaudeAdapter, CodexAdapter, AntigravityAdapter } from \"../../adapters/index.js\";\n\nfunction summarize(actions: any[]) {\n const createCount = actions.filter((a) => a.type === \"create\").length;\n const conflictCount = actions.filter((a) => a.type === \"conflict\").length;\n\n return { createCount, conflictCount };\n}\n\nfunction printPlan(actions: any[]) {\n for (const action of actions) {\n console.log(`- ${action.type.padEnd(8)} ${action.relativePath}`);\n }\n}\n\nfunction toIgnoreEntries(linkPath: string): string[] {\n if (linkPath === \"README.workflow.md\") {\n return [linkPath];\n }\n\n const normalized = linkPath.endsWith(\"/\") ? linkPath.slice(0, -1) : linkPath;\n return [normalized, `${normalized}/`];\n}\n\nfunction buildGitignoreBlock(entries: string[]): string {\n const unique = Array.from(new Set(entries));\n const sorted = unique.sort((a, b) => a.localeCompare(b));\n\n return [\n \"# BEGIN AI WORKFLOW KIT\",\n \"# AI Workflow Kit generated files\",\n ...sorted,\n \"# END AI WORKFLOW KIT\"\n ].join(\"\\n\");\n}\n\nasync function upsertGitignoreBlock(cwd: string, entries: string[]): Promise<string> {\n const gitignorePath = path.join(cwd, \".gitignore\");\n const block = buildGitignoreBlock(entries);\n const beginMarker = \"# BEGIN AI WORKFLOW KIT\";\n const endMarker = \"# END AI WORKFLOW KIT\";\n\n const hasGitignore = await exists(gitignorePath);\n if (!hasGitignore) {\n await writeFileSafe(gitignorePath, `${block}\\n`);\n return \"created\";\n }\n\n const current = await fs.readFile(gitignorePath, \"utf8\");\n const beginIndex = current.indexOf(beginMarker);\n const endIndex = current.indexOf(endMarker);\n\n if (beginIndex >= 0 && endIndex > beginIndex) {\n const before = current\n .slice(0, beginIndex)\n .replace(/\\n?# AI Workflow Kit generated files\\n?$/, \"\\n\")\n .replace(/[ \\t]+$/gm, \"\")\n .replace(/\\n*$/, \"\\n\");\n const afterStart = endIndex + endMarker.length;\n const after = current.slice(afterStart).replace(/^\\n*/, \"\\n\");\n const next = `${before}${block}${after}`;\n if (next !== current) {\n await writeFileSafe(gitignorePath, next);\n return \"updated\";\n }\n return \"unchanged\";\n }\n\n const separator = current.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n const next = `${current}${separator}${block}\\n`;\n await writeFileSafe(gitignorePath, next);\n return \"updated\";\n}\n\nasync function injectScripts(cwd: string): Promise<boolean> {\n const pkgPath = path.join(cwd, \"package.json\");\n if (!(await exists(pkgPath))) return false;\n\n try {\n const pkg = await readJson(pkgPath);\n if (!pkg.scripts) pkg.scripts = {};\n\n if (!pkg.scripts.validate) {\n pkg.scripts.validate = \"ai-workflow collect-evidence\";\n await writeFileSafe(pkgPath, `${JSON.stringify(pkg, null, 2)}\\n`);\n return true;\n }\n } catch {\n // Ignore invalid package.json\n }\n return false;\n}\n\nexport interface InitOptions {\n cwd: string;\n yes?: boolean;\n force?: boolean;\n dryRun?: boolean;\n noInstall?: boolean;\n noOverwrite?: boolean;\n claude?: boolean;\n codex?: boolean;\n antigravity?: boolean;\n \"dev-mode\"?: boolean;\n profile?: string;\n}\n\nasync function verifySelfExecutionGuard(cwd: string, devMode?: boolean): Promise<void> {\n if (!devMode) {\n try {\n const pkgPath = path.join(cwd, \"package.json\");\n if (await exists(pkgPath)) {\n const pkg = await readJson(pkgPath);\n if (pkg.name === \"@williambeto/ai-workflow\") {\n console.error(\"\\nFATAL: Cannot run 'ai-workflow init' inside its own development repository.\");\n console.error(\"This would corrupt the development environment. Aborting.\");\n console.error(\"Use the --dev-mode flag if you are developing the kit itself and need to test the init command.\\n\");\n process.exit(1);\n }\n }\n } catch {\n // Ignore if package.json is unreadable. The guard is a safety net.\n }\n }\n}\n\nfunction resolveProfile(profile?: string): string {\n const selectedProfile = profile || \"standard\";\n if (!isValidProfile(selectedProfile)) {\n console.error(`Invalid profile: \"${selectedProfile}\". Valid profiles: standard, full`);\n process.exit(1);\n }\n return selectedProfile;\n}\n\nasync function writeInstallFiles(\n cwd: string,\n actions: any[],\n selectedProfile: string,\n platforms: string[],\n force?: boolean,\n noOverwrite?: boolean,\n backupRoot = \".ai-workflow-backups\"\n): Promise<{ skipped: string[]; backups: string[] }> {\n const skipped: string[] = [];\n const backups: string[] = [];\n\n for (const action of actions) {\n if (action.type === \"conflict\" && (noOverwrite || !force)) {\n skipped.push(action.relativePath);\n continue;\n }\n\n if (action.type === \"conflict\" && force) {\n const backupPath = await createManagedBackup(action.absolutePath, {\n cwd,\n backupRoot,\n maxPerFile: 20\n });\n backups.push(backupPath);\n }\n\n const content =\n action.relativePath === \".ai-workflow/config.json\"\n ? `${JSON.stringify(buildAiWorkflowConfig({ profile: selectedProfile, runtimes: platforms.length > 0 ? platforms : [\"opencode\"] }), null, 2)}\\n`\n : action.content;\n\n await writeFileSafe(action.absolutePath, content || \"\");\n }\n\n return { skipped, backups };\n}\n\nasync function writeSymlinks(\n cwd: string,\n linkEntries: any[],\n force?: boolean,\n backupRoot = \".ai-workflow-backups\"\n): Promise<{ linkBackups: string[]; linkCreated: string[] }> {\n const linkBackups: string[] = [];\n const linkCreated: string[] = [];\n\n for (const { linkPath, targetPath } of linkEntries) {\n const absoluteLinkPath = path.join(cwd, linkPath);\n const absoluteTargetPath = path.join(cwd, targetPath);\n\n if (!(await exists(absoluteTargetPath))) {\n throw new Error(`missing link target: ${targetPath}`);\n }\n\n if (await isSymlinkTo(absoluteLinkPath, absoluteTargetPath)) {\n continue;\n }\n\n if (await exists(absoluteLinkPath)) {\n if (!force) {\n throw new Error(\n `cannot create symlink '${linkPath}' because path already exists. Re-run with --force to backup and replace. If symlink creation fails, see troubleshooting in docs/npm-consumer-quickstart.md.`\n );\n }\n const backupPath = await createManagedPathBackup(absoluteLinkPath, {\n cwd,\n backupRoot,\n maxPerFile: 20\n });\n linkBackups.push(backupPath);\n await fs.rm(absoluteLinkPath, { recursive: true, force: true });\n }\n\n const stat = await fs.lstat(absoluteTargetPath);\n const type = process.platform === \"win32\"\n ? (stat.isDirectory() ? \"junction\" : \"file\")\n : (stat.isDirectory() ? \"dir\" : \"file\");\n const linkTarget = process.platform === \"win32\"\n ? absoluteTargetPath\n : path.relative(path.dirname(absoluteLinkPath), absoluteTargetPath);\n\n try {\n await fs.mkdir(path.dirname(absoluteLinkPath), { recursive: true });\n await fs.symlink(linkTarget, absoluteLinkPath, type);\n } catch (error: any) {\n throw new Error(\n `failed to create symlink '${linkPath}' -> '${targetPath}' (${error.message}). ` +\n \"For Windows, enable Developer Mode or run terminal as Administrator. \" +\n \"For Linux/macOS, verify write permissions in project root.\"\n );\n }\n linkCreated.push(linkPath);\n }\n\n return { linkBackups, linkCreated };\n}\n\nasync function executePlatformMigrations(\n cwd: string,\n installRoot: string,\n platforms: string[],\n claude?: boolean,\n codex?: boolean,\n antigravity?: boolean,\n force?: boolean\n): Promise<void> {\n if (platforms.length === 0) return;\n\n console.log(\"ai-workflow: migrating to native platforms...\");\n const agentsDir = path.join(cwd, installRoot, \"opencode/agents\");\n const skillsDir = path.join(cwd, installRoot, \"opencode/skills\");\n\n const agentFiles = (await fs.readdir(agentsDir).catch(() => []))\n .filter((f) => f.endsWith(\".md\"))\n .map((f) => path.join(agentsDir, f));\n\n if (claude) {\n const adapter = new ClaudeAdapter({ cwd });\n await adapter.deploy(installRoot);\n console.log(\"- claude: deployed AI Workflow Kit agents to CLAUDE.md and .claude/rules/ (native discovery enabled)\");\n }\n\n if (codex) {\n const adapter = new CodexAdapter({ cwd });\n await adapter.deploy(installRoot, force);\n console.log(\"- codex: deployed AI Workflow Kit agents to .agents/, .codex/, and .github/ (native discovery enabled)\");\n }\n\n if (antigravity) {\n const adapter = new AntigravityAdapter({ cwd });\n const skillFolders = await fs.readdir(skillsDir).catch(() => []);\n const skillFiles: string[] = [];\n for (const folder of skillFolders) {\n const skillPath = path.join(skillsDir, folder, \"SKILL.md\");\n if (await exists(skillPath)) {\n skillFiles.push(skillPath);\n }\n }\n\n const allFiles = [...agentFiles, ...skillFiles];\n const transformed = await Promise.all(allFiles.map((f) => adapter.transform(f)));\n await adapter.deploy(transformed, installRoot);\n console.log(`- antigravity: deployed AI Workflow Kit agents to .agents/ (native discovery enabled)`);\n }\n}\n\nfunction printInstallationSummary({\n selectedProfile,\n opencodeResult,\n gitignoreResult,\n scriptInjected,\n linkCreated,\n backups,\n linkBackups,\n skipped,\n noInstall\n}: {\n selectedProfile: string;\n opencodeResult: any;\n gitignoreResult: string;\n scriptInjected: boolean;\n linkCreated: string[];\n backups: string[];\n linkBackups: string[];\n skipped: string[];\n noInstall?: boolean;\n}): void {\n console.log(\"Installation complete.\");\n console.log(`- profile: ${selectedProfile}`);\n console.log(`- opencode.jsonc: ${opencodeResult.reason}`);\n console.log(`- .gitignore: ${gitignoreResult}`);\n console.log(`- scripts: ${scriptInjected ? \"injected 'validate'\" : \"already-up-to-date\"}`);\n console.log(`- symlink layout: ${linkCreated.length > 0 ? `created ${linkCreated.length}` : \"already-up-to-date\"}`);\n\n if (backups.length > 0) {\n console.log(`- backups created: ${backups.length}`);\n for (const filePath of backups) {\n console.log(` ${filePath}`);\n }\n }\n if (linkBackups.length > 0) {\n console.log(`- symlink backups created: ${linkBackups.length}`);\n for (const filePath of linkBackups) {\n console.log(` ${filePath}`);\n }\n }\n if (skipped.length > 0) {\n console.log(`- conflicts skipped: ${skipped.length}`);\n for (const relativePath of skipped) {\n console.log(` ${relativePath}`);\n }\n }\n console.log(`- dependency install: ${noInstall ? \"skipped (--no-install)\" : \"not managed in this step\"}`);\n console.log(\"Next steps:\");\n console.log(\" npx @williambeto/ai-workflow doctor\");\n}\n\nexport async function runInit({\n cwd, yes, force, dryRun, noInstall, noOverwrite, claude, codex, antigravity, \"dev-mode\": devMode, profile\n}: InitOptions): Promise<void> {\n await verifySelfExecutionGuard(cwd, devMode);\n\n const selectedProfile = resolveProfile(profile);\n const installRoot = \".ai-workflow\";\n const backupRoot = \".ai-workflow-backups\";\n\n const platforms: string[] = [];\n if (claude) platforms.push(\"claude\");\n if (codex) platforms.push(\"codex\");\n if (antigravity) platforms.push(\"antigravity\");\n\n console.log(`ai-workflow: initializing in ${cwd}`);\n console.log(`Profile: ${selectedProfile}`);\n if (platforms.length > 0) {\n console.log(`Platforms: ${platforms.join(\", \")}`);\n }\n\n const actions = await createInstallPlan({ cwd, exists, profile: selectedProfile });\n const linkEntries = buildSymlinkEntries({ templateFiles: getTemplateFiles(selectedProfile), installRoot });\n const { createCount, conflictCount } = summarize(actions);\n\n console.log(`Plan: ${createCount} create, ${conflictCount} conflict`);\n printPlan(actions);\n\n if (!yes && conflictCount > 0 && !force && !noOverwrite) {\n throw new Error(\n \"conflicts detected. Re-run with --force to replace managed files or resolve conflicts manually\"\n );\n }\n\n if (dryRun) {\n console.log(\"Dry-run enabled. No files were written.\");\n if (platforms.length > 0) {\n console.log(\"ai-workflow: (dry-run) platform migration would be executed after file writing.\");\n }\n return;\n }\n\n const { skipped, backups } = await writeInstallFiles(cwd, actions, selectedProfile, platforms, force, noOverwrite, backupRoot);\n const { linkBackups, linkCreated } = await writeSymlinks(cwd, linkEntries, force, backupRoot);\n\n await setupInternalSymlinks(cwd, installRoot);\n\n const opencodeResult = await mergeOpencodeConfig(cwd, { force, backupRoot });\n\n const generatedIgnoreEntries = [\n \"node_modules/\",\n \".ai-workflow/\",\n \".ai-workflow-backups/\",\n \"opencode.jsonc.backup.*\",\n \"EVIDENCE.json\",\n \"*.tgz\",\n ...linkEntries.flatMap((entry) => toIgnoreEntries(entry.linkPath))\n ];\n\n if (codex) {\n generatedIgnoreEntries.push(\".agents/\", \".codex/\");\n }\n if (claude) {\n generatedIgnoreEntries.push(\".claude/\");\n }\n if (antigravity) {\n generatedIgnoreEntries.push(\".agents/\");\n }\n\n const gitignoreResult = await upsertGitignoreBlock(cwd, generatedIgnoreEntries);\n const scriptInjected = await injectScripts(cwd);\n\n await executePlatformMigrations(cwd, installRoot, platforms, claude, codex, antigravity, force);\n\n printInstallationSummary({\n selectedProfile,\n opencodeResult,\n gitignoreResult,\n scriptInjected,\n linkCreated,\n backups,\n linkBackups,\n skipped,\n noInstall\n });\n}\n","import path from \"node:path\";\nimport { getTemplateFiles } from \"./templates.js\";\n\nexport interface InstallAction {\n type: \"conflict\" | \"create\";\n relativePath: string;\n absolutePath: string;\n content: string | null;\n}\n\nexport interface CreateInstallPlanOptions {\n cwd: string;\n exists: (filePath: string) => Promise<boolean> | boolean;\n profile?: string;\n}\n\nexport async function createInstallPlan({\n cwd,\n exists,\n profile = \"standard\"\n}: CreateInstallPlanOptions): Promise<InstallAction[]> {\n const actions: InstallAction[] = [];\n const templateFiles = getTemplateFiles(profile);\n const installRoot = \".ai-workflow\";\n\n for (const [relativePath, content] of Object.entries(templateFiles)) {\n if (relativePath === \"opencode.jsonc\") {\n continue;\n }\n\n const installedRelativePath = path.join(installRoot, relativePath);\n const absolutePath = path.join(cwd, installedRelativePath);\n const action = (await exists(absolutePath)) ? \"conflict\" : \"create\";\n actions.push({\n type: action,\n relativePath: installedRelativePath,\n absolutePath,\n content\n });\n }\n\n const configPath = path.join(cwd, \".ai-workflow/config.json\");\n actions.push({\n type: (await exists(configPath)) ? \"conflict\" : \"create\",\n relativePath: \".ai-workflow/config.json\",\n absolutePath: configPath,\n content: null\n });\n\n return actions;\n}\n","import { getFullAgentContent, getFullSkillFiles, discoverPackageFiles, readPackageFile, getPackageVersion } from \"./package-assets.js\";\nimport { getCanonicalAgentName } from \"./identity.js\";\n\nconst COMMON_FILES: Record<string, string> = {\n \"opencode/README.md\": `# OpenCode Setup\\n\\nThis directory is managed by \\`ai-workflow\\` init.\\nAdd agent and command files required by your project workflow.\\n`\n};\n\nconst FULL_PRIMARY_AGENTS: string[] = [\n \"atlas\",\n \"nexus\",\n \"orion\",\n \"astra\",\n \"sage\",\n \"phoenix\"\n];\n\nconst FULL_SKILLS: string[] = [\n \"project-memory\",\n \"optimize-tokens\",\n \"documentation\",\n \"architecture\",\n \"technical-leadership\",\n \"product-discovery\",\n \"product-planning\",\n \"spec-driven-development\",\n \"pr-workflow\",\n \"qa-workflow\",\n \"release-workflow\",\n \"deployment\",\n \"ui-ux-design\",\n \"design-principles\",\n \"frontend-development\",\n \"backend-development\",\n \"full-stack-development\",\n \"refactoring\",\n \"prompt-engineer\"\n];\n\nfunction buildRuntimeFiles({ includeFormalEvidence = false }: { includeFormalEvidence?: boolean } = {}): Record<string, string> {\n const files: Record<string, string> = {};\n\n for (const agent of FULL_PRIMARY_AGENTS) {\n const content = getFullAgentContent(agent);\n if (content === null) {\n throw new Error(`CRITICAL FAILURE: Missing required agent asset: dist-assets/agents/${agent}.md`);\n }\n files[`opencode/agents/${agent}.md`] = content;\n }\n\n for (const skill of FULL_SKILLS) {\n const skillFiles = getFullSkillFiles(skill);\n if (Object.keys(skillFiles).length === 0) {\n continue;\n }\n for (const [relPath, content] of Object.entries(skillFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n if (!files[targetPath]) {\n files[targetPath] = content;\n }\n }\n }\n\n // Copy governance policy into opencode/docs/policies/ so the relative link\n // ../../docs/policies/SKILLS_COMMON_GOVERNANCE.md resolves correctly from\n // opencode/skills/{skill}/SKILL.md for OpenCode and all platform adapters.\n const opencodeGovernancePolicy = readPackageFile(\"dist-assets/docs/policies/SKILLS_COMMON_GOVERNANCE.md\");\n if (opencodeGovernancePolicy !== null) {\n files[\"opencode/docs/policies/SKILLS_COMMON_GOVERNANCE.md\"] = opencodeGovernancePolicy;\n }\n\n const commandFiles = discoverPackageFiles(\"dist-assets/commands\");\n for (const [relPath, content] of Object.entries(commandFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n if (!files[targetPath]) {\n files[targetPath] = content;\n }\n }\n\n const opencodeSkillFiles = discoverPackageFiles(\"dist-assets/skills\");\n for (const [relPath, content] of Object.entries(opencodeSkillFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n if (!files[targetPath]) {\n files[targetPath] = content;\n }\n }\n\n const harnessWorkflowFiles = discoverPackageFiles(\"dist-assets/harness/workflows\");\n for (const [relPath, content] of Object.entries(harnessWorkflowFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"\");\n files[targetPath] = content;\n }\n\n const harnessHandoffFiles = discoverPackageFiles(\"dist-assets/harness/handoffs\");\n for (const [relPath, content] of Object.entries(harnessHandoffFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"\");\n files[targetPath] = content;\n }\n\n const agentsContent = readPackageFile(\"dist-assets/AGENTS.md\");\n if (agentsContent !== null) files[\"AGENTS.md\"] = agentsContent;\n\n const consumerQuickstart = readPackageFile(\"dist-assets/docs/QUICKSTART.md\");\n if (consumerQuickstart !== null) files[\"QUICKSTART.md\"] = consumerQuickstart;\n\n const policyContent = readPackageFile(\"dist-assets/docs/architecture-policy.md\");\n if (policyContent !== null) files[\"opencode/docs/architecture-policy.md\"] = policyContent;\n\n const dpContent = readPackageFile(\"dist-assets/docs/design-patterns-policy.md\");\n if (dpContent !== null) files[\"opencode/docs/design-patterns-policy.md\"] = dpContent;\n\n const visualValidationGuide = readPackageFile(\"dist-assets/docs/visual-validation-guide.md\");\n if (visualValidationGuide !== null) files[\"opencode/docs/visual-validation-guide.md\"] = visualValidationGuide;\n\n const governancePolicies = discoverPackageFiles(\"dist-assets/docs/policies\");\n for (const [relPath, content] of Object.entries(governancePolicies)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n files[targetPath] = content;\n }\n\n const compatibilityDocs = discoverPackageFiles(\"dist-assets/docs/compatibility\");\n for (const [relPath, content] of Object.entries(compatibilityDocs)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n files[targetPath] = content;\n }\n\n const qualityReferenceFiles = discoverPackageFiles(\"dist-assets/docs/references\");\n for (const [relPath, content] of Object.entries(qualityReferenceFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n files[targetPath] = content;\n }\n\n const workflowProfileFiles = discoverPackageFiles(\"dist-assets/docs/profiles\");\n for (const [relPath, content] of Object.entries(workflowProfileFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"opencode/\");\n files[targetPath] = content;\n }\n\n const templateFiles = discoverPackageFiles(\"dist-assets/templates\");\n for (const [relPath, content] of Object.entries(templateFiles)) {\n if (!includeFormalEvidence && relPath.includes(\"/owner-evidence/\")) continue;\n const targetPath = relPath.replace(/^dist-assets\\//, \"\");\n files[targetPath] = content;\n }\n\n const schemaFiles = discoverPackageFiles(\"dist-assets/schemas\");\n for (const [relPath, content] of Object.entries(schemaFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"\");\n files[targetPath] = content;\n }\n\n return files;\n}\n\nfunction buildExtraFiles(): Record<string, string> {\n const files: Record<string, string> = {};\n const exampleFiles = discoverPackageFiles(\"dist-assets/examples\");\n for (const [relPath, content] of Object.entries(exampleFiles)) {\n const targetPath = relPath.replace(/^dist-assets\\//, \"\");\n files[targetPath] = content;\n }\n return files;\n}\n\nconst STANDARD_FILES = buildRuntimeFiles();\nconst FULL_FILES = { ...buildRuntimeFiles({ includeFormalEvidence: true }), ...buildExtraFiles() };\n\nexport const PROFILE_FILES: Record<string, Record<string, string>> = {\n standard: {\n ...COMMON_FILES,\n ...STANDARD_FILES\n },\n full: {\n ...COMMON_FILES,\n ...FULL_FILES\n }\n};\n\nexport function isValidProfile(profile: any): boolean {\n return profile === \"standard\" || profile === \"full\";\n}\n\nexport function getTemplateFiles(profile: string = \"standard\"): Record<string, string> {\n return PROFILE_FILES[profile] ?? PROFILE_FILES.standard;\n}\n\nexport function getManagedBlocks(): string[] {\n return [\n ...FULL_PRIMARY_AGENTS.map((agent) => `opencode.jsonc:agent.${getCanonicalAgentName(agent)}`),\n ...FULL_SKILLS.map((skill) => `opencode.jsonc:agent.${getCanonicalAgentName(skill)}`),\n \"opencode.jsonc:command.atlas\",\n \"opencode.jsonc:command.run\",\n \"opencode.jsonc:command.discover\",\n \"opencode.jsonc:command.spec-create\",\n \"opencode.jsonc:command.spec-review\",\n \"opencode.jsonc:command.spec-implement\",\n \"opencode.jsonc:command.plan\",\n \"opencode.jsonc:command.implement\",\n \"opencode.jsonc:command.validate\",\n \"opencode.jsonc:command.audit\",\n \"opencode.jsonc:command.optimize-tokens\",\n \"opencode.jsonc:command.update-memory\",\n \"opencode.jsonc:command.release\",\n \"opencode.jsonc:command.deploy\"\n ];\n}\n\nexport interface BuildAiWorkflowConfigOptions {\n profile: string;\n runtimes?: string[];\n managedFiles?: any;\n managedLinks?: any[];\n}\n\nexport interface AiWorkflowConfig {\n package: string;\n version: string | null;\n runtime: string;\n profile: string;\n installMode: string;\n generatedAt: string;\n paths: {\n agents: string;\n commands: string;\n skills: string;\n policies: string;\n harness: string;\n schemas: string;\n };\n}\n\nexport function buildAiWorkflowConfig({ profile, runtimes = [\"opencode\"] }: BuildAiWorkflowConfigOptions): AiWorkflowConfig {\n const version = getPackageVersion();\n const now = new Date().toISOString();\n const primaryRuntime = runtimes.join(\"+\");\n\n return {\n package: \"@williambeto/ai-workflow\",\n version,\n runtime: primaryRuntime,\n profile,\n installMode: \"project-local\",\n generatedAt: now,\n paths: {\n agents: \".ai-workflow/opencode/agents\",\n commands: \".ai-workflow/opencode/commands\",\n skills: \".ai-workflow/opencode/skills\",\n policies: \".ai-workflow/opencode/docs/policies\",\n harness: \".ai-workflow/harness\",\n schemas: \".ai-workflow/schemas\"\n }\n };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nexport async function exists(filePath: string): Promise<boolean> {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n}\n\nimport { execSync } from \"node:child_process\";\n\n/**\n * Safe wrapper for writing files that enforces branch guards on protected branches.\n * NOTE: This branch guard only protects write operations performed through this kit wrapper\n * (or the kit's runtime executions). It does not intercept external shell commands or processes.\n */\nexport async function writeFileSafe(filePath: string, content: string): Promise<void> {\n const absolutePath = path.resolve(filePath);\n const repoCwd = path.resolve(process.cwd());\n const relativeToRepo = path.relative(repoCwd, absolutePath).replaceAll(\"\\\\\", \"/\");\n \n // Normalized precise allowlist\n const isOperational = relativeToRepo === \"EVIDENCE.json\" ||\n relativeToRepo.startsWith(\".ai-workflow/\") ||\n relativeToRepo.startsWith(\".ai-workflow\\\\\");\n \n if (!isOperational) {\n let currentBranch = \"\";\n const fileCwd = path.dirname(absolutePath);\n try {\n currentBranch = execSync(\"git branch --show-current\", { cwd: fileCwd, encoding: \"utf8\", stdio: \"pipe\" }).trim();\n } catch {\n // ignore\n }\n const protectedBranches = [\"main\", \"master\"];\n const isInitCommand = process.argv.includes(\"init\");\n if (protectedBranches.includes(currentBranch) && !isInitCommand) {\n if (process.env.AI_WORKFLOW_BYPASS_PROTECTED_BRANCH !== \"true\") {\n throw new Error(\"FAIL_PROTECTED_BRANCH: Direct writes to protected branch are prohibited.\");\n }\n }\n }\n await fs.mkdir(path.dirname(filePath), { recursive: true });\n await fs.writeFile(filePath, content, \"utf8\");\n}\n\nexport async function readJson(filePath: string): Promise<any> {\n const content = await fs.readFile(filePath, \"utf8\");\n return JSON.parse(content);\n}\n\nfunction stripJsonComments(content: string): string {\n let output = \"\";\n let inString = false;\n let quote = \"\";\n let escaped = false;\n let inLineComment = false;\n let inBlockComment = false;\n\n for (let index = 0; index < content.length; index += 1) {\n const char = content[index];\n const next = content[index + 1];\n\n if (inLineComment) {\n if (char === \"\\n\" || char === \"\\r\") {\n inLineComment = false;\n output += char;\n }\n continue;\n }\n\n if (inBlockComment) {\n if (char === \"*\" && next === \"/\") {\n inBlockComment = false;\n index += 1;\n continue;\n }\n if (char === \"\\n\" || char === \"\\r\") {\n output += char;\n }\n continue;\n }\n\n if (inString) {\n output += char;\n if (escaped) {\n escaped = false;\n } else if (char === \"\\\\\") {\n escaped = true;\n } else if (char === quote) {\n inString = false;\n quote = \"\";\n }\n continue;\n }\n\n if (char === '\"' || char === \"'\") {\n inString = true;\n quote = char;\n output += char;\n continue;\n }\n\n if (char === \"/\" && next === \"/\") {\n inLineComment = true;\n index += 1;\n continue;\n }\n\n if (char === \"/\" && next === \"*\") {\n inBlockComment = true;\n index += 1;\n continue;\n }\n\n output += char;\n }\n\n return output;\n}\n\nfunction stripTrailingCommas(content: string): string {\n let output = \"\";\n let inString = false;\n let quote = \"\";\n let escaped = false;\n\n for (let index = 0; index < content.length; index += 1) {\n const char = content[index];\n\n if (inString) {\n output += char;\n if (escaped) {\n escaped = false;\n } else if (char === \"\\\\\") {\n escaped = true;\n } else if (char === quote) {\n inString = false;\n quote = \"\";\n }\n continue;\n }\n\n if (char === '\"' || char === \"'\") {\n inString = true;\n quote = char;\n output += char;\n continue;\n }\n\n if (char === \",\") {\n let nextIndex = index + 1;\n while (/\\s/.test(content[nextIndex] ?? \"\")) {\n nextIndex += 1;\n }\n if (content[nextIndex] === \"}\" || content[nextIndex] === \"]\") {\n continue;\n }\n }\n\n output += char;\n }\n\n return output;\n}\n\nexport async function readJsonc(filePath: string): Promise<any> {\n const content = await fs.readFile(filePath, \"utf8\");\n return JSON.parse(stripTrailingCommas(stripJsonComments(content)));\n}\n","import path from \"node:path\";\nimport { exists, readJsonc, writeFileSafe } from \"./filesystem.js\";\nimport { createManagedBackup } from \"./backup.js\";\nimport { getTemplateFiles } from \"./templates.js\";\n\n/**\n * @file opencode-merge.ts\n * @description Architecture & Registry for OpenCode configuration synthesis (`opencode.jsonc`).\n *\n * ## Architecture Overview\n * This module is responsible for initializing, updating, and merging the project's\n * `opencode.jsonc` file when `aw init` is executed in a consumer repository.\n *\n * ### Core Responsibilities:\n * 1. **Primary Agents Registry (`AGENTS`)**: Defines the 6 core workflow actors (Atlas, Nexus, Orion, Astra, Sage, Phoenix)\n * and maps their instructions to `.ai-workflow/agents/<name>.md`.\n * 2. **Subagents Registry (`SUBAGENTS`)**: Registers domain-specific subagents mapped 1-to-1 with skills installed\n * in `.ai-workflow/skills/<skill>/SKILL.md`. These subagents can be activated by OpenCode runtimes.\n * 3. **Commands Registry (`COMMANDS`)**: Maps slash-commands (e.g. `/atlas`, `/spec-create`, `/validate`) to their respective agent owners.\n * 4. **Safe JSONC Merging**: Merges AIWK configuration blocks into consumer repositories while preserving existing custom user\n * settings in `opencode.jsonc` and managing backups.\n *\n * ### Registering a New Subagent:\n * To add a new subagent to the OpenCode runtime registry:\n * - Ensure a corresponding skill exists in `dist-assets/skills/<skill-name>/SKILL.md`.\n * - Add a new entry to the `SUBAGENTS` object with a PascalCase/Kebab name, a concise `description`, and the matching `skill` directory name.\n * - Note: 5 auxiliary skills (`cyber-security`, `database`, `devops`, `localization`, `performance`) are intentionally excluded\n * from subagent registration as they serve as contextual lenses for existing agents (see `dist-assets/AGENTS.md`).\n */\n\nconst LEGACY_MARKER = \"_aiWorkflowManaged\";\n\ninterface AgentDef {\n description: string;\n mode: \"primary\" | \"all\";\n}\n\nconst AGENTS: Record<string, AgentDef> = {\n Atlas: { description: \"Router and workflow coordinator for AI Workflow Kit\", mode: \"primary\" },\n Nexus: { description: \"Discovery, requirement, scope, and specification owner\", mode: \"all\" },\n Orion: { description: \"Planning, PR sequencing, release, and deployment strategy owner\", mode: \"all\" },\n Astra: { description: \"Implementation owner for incremental, scoped workspace changes\", mode: \"all\" },\n Sage: { description: \"Audit, validation, evidence, and quality gate owner\", mode: \"all\" },\n Phoenix: { description: \"Bounded remediation and regression recovery owner\", mode: \"all\" }\n};\n\ninterface SubagentDef {\n description: string;\n skill: string;\n}\n\nconst SUBAGENTS: Record<string, SubagentDef> = {\n \"Architecture-Specialist\": { description: \"Capability only: advise on the simplest safe architecture for current requirements\", skill: \"architecture\" },\n \"Backend-Engineer\": { description: \"Capability only: advise on PHP, Node, or Python APIs and persistence\", skill: \"backend-development\" },\n \"Deployment-Specialist\": { description: \"Capability only: analyze deployment, release, and production readiness\", skill: \"deployment\" },\n \"Design-Specialist\": { description: \"Capability only: advise on simple and maintainable design principles\", skill: \"design-principles\" },\n \"Docs-Engineer\": { description: \"Capability only: advise on documentation, READMEs, guides, and prompts\", skill: \"documentation\" },\n \"Frontend-Engineer\": { description: \"Capability only: advise on UI, state, routing, and accessibility\", skill: \"frontend-development\" },\n \"Frontend-Design-System-Specialist\": { description: \"Capability only: review CSS and HTML tokens, semantics, typography, and visual quality\", skill: \"frontend-design-system\" },\n \"Full-Stack-Engineer\": { description: \"Capability only: analyze frontend and backend integration as one testable increment\", skill: \"full-stack-development\" },\n \"Token-Economist\": { description: \"Capability only: analyze context size while preserving safe execution information\", skill: \"optimize-tokens\" },\n \"PR-Manager\": { description: \"Capability only: plan or review small pull requests while preserving scope\", skill: \"pr-workflow\" },\n \"Discovery-Analyst\": { description: \"Capability only: clarify ambiguous requests into actionable outcomes\", skill: \"product-discovery\" },\n \"Product-Planner\": { description: \"Capability only: shape clarified needs into scoped requirements\", skill: \"product-planning\" },\n \"Memory-Guardian\": { description: \"Capability only: advise on durable project decisions and recurring corrections\", skill: \"project-memory\" },\n \"Prompt-Engineer\": { description: \"Capability only: advise on prompts for agents and workflows\", skill: \"prompt-engineer\" },\n \"QA-Engineer\": { description: \"Capability only: design or review tests, acceptance criteria, and validation evidence\", skill: \"qa-workflow\" },\n \"Refactoring-Specialist\": { description: \"Capability only: review structure and behavior-preserving simplifications\", skill: \"refactoring\" },\n \"Release-Specialist\": { description: \"Capability only: analyze release readiness with explicit gates and evidence\", skill: \"release-workflow\" },\n \"SDD-Specialist\": { description: \"Capability only: shape approved requirements into testable specifications\", skill: \"spec-driven-development\" },\n \"Technical-Leader\": { description: \"Capability only: analyze technical decisions, architecture, and trade-offs\", skill: \"technical-leadership\" },\n \"UI-UX-Engineer\": { description: \"Capability only: review usability and interface clarity\", skill: \"ui-ux-design\" }\n};\n\ninterface CommandDef {\n description: string;\n agent: string;\n}\n\nconst COMMANDS: Record<string, CommandDef> = {\n atlas: { description: \"Decide safest next step and delegate to the appropriate workflow or agent\", agent: \"Atlas\" },\n run: { description: \"Execute the master orchestration pipeline (Gates, SDD, Implementation, Validation, Healing)\", agent: \"Atlas\" },\n discover: { description: \"Understand the project, gather context, and create initial documentation\", agent: \"Nexus\" },\n \"spec-create\": { description: \"Create a clear specification before implementation\", agent: \"Nexus\" },\n \"spec-review\": { description: \"Review a specification and validate scope, risks, criteria, and gaps\", agent: \"Nexus\" },\n \"spec-implement\": { description: \"Implement an approved specification incrementally\", agent: \"Astra\" },\n plan: { description: \"Plan a task or change, defining steps, risks, and validation\", agent: \"Orion\" },\n implement: { description: \"Implement a small task with defined scope\", agent: \"Astra\" },\n validate: { description: \"Run project validations and collect evidence\", agent: \"Sage\" },\n audit: { description: \"Audit the project, identify issues, and suggest prioritized improvements\", agent: \"Sage\" },\n \"optimize-tokens\": { description: \"Analyze workflow and context usage; suggest reductions without losing quality or evidence\", agent: \"Sage\" },\n \"update-memory\": { description: \"Update durable project memory with relevant decisions, constraints, and reusable context\", agent: \"Nexus\" },\n release: { description: \"Prepare delivery with commit, push, PR/merge readiness, changelog, and evidence\", agent: \"Orion\" },\n deploy: { description: \"Publish the project to the defined environment after validation and release readiness\", agent: \"Orion\" }\n};\n\ninterface ManagedAgentConfig {\n mode: \"primary\" | \"subagent\" | \"all\";\n description: string;\n prompt: string;\n permission?: {\n edit?: \"allow\" | \"ask\" | \"deny\";\n bash?: \"allow\" | \"ask\" | \"deny\";\n task?: Record<string, \"allow\" | \"ask\" | \"deny\">;\n };\n}\n\ninterface ManagedCommandConfig {\n description: string;\n agent: string;\n template: string;\n}\n\ninterface ManagedConfig {\n $schema: string;\n default_agent: string;\n agent: Record<string, ManagedAgentConfig>;\n skills: {\n paths: string[];\n };\n command: Record<string, ManagedCommandConfig>;\n mcp?: Record<string, any>;\n}\n\nfunction buildManagedConfig(): ManagedConfig {\n const agent: Record<string, ManagedAgentConfig> = {};\n const coreTaskPermissions = Object.fromEntries([\n [\"*\", \"deny\"],\n ...Object.keys(AGENTS).filter((name) => name !== \"Atlas\").map((name) => [name, \"allow\"])\n ]) as Record<string, \"allow\" | \"deny\">;\n const capabilityTaskPermissions = Object.fromEntries([\n [\"*\", \"deny\"],\n ...Object.keys(SUBAGENTS).map((name) => [name, \"allow\"])\n ]) as Record<string, \"allow\" | \"deny\">;\n\n for (const [name, def] of Object.entries(AGENTS)) {\n agent[name] = {\n mode: def.mode,\n description: def.description,\n prompt: `{file:./.ai-workflow/opencode/agents/${name.toLowerCase()}.md}`,\n permission: {\n ...(name === \"Atlas\" ? { edit: \"deny\" as const, bash: \"ask\" as const } : {}),\n ...(name === \"Astra\" ? { edit: \"allow\" as const } : {}),\n task: name === \"Atlas\" ? coreTaskPermissions : capabilityTaskPermissions\n }\n };\n }\n\n for (const [name, def] of Object.entries(SUBAGENTS)) {\n agent[name] = {\n mode: \"subagent\",\n description: def.description,\n prompt: `{file:./.ai-workflow/opencode/skills/${def.skill}/SKILL.md}`,\n permission: {\n edit: \"deny\",\n bash: \"ask\",\n task: { \"*\": \"deny\" }\n }\n };\n }\n\n const command: Record<string, ManagedCommandConfig> = {};\n for (const [name, def] of Object.entries(COMMANDS)) {\n command[name] = {\n description: def.description,\n agent: def.agent,\n template: `{file:./.ai-workflow/opencode/commands/${name}.md}`\n };\n }\n\n return {\n $schema: \"https://opencode.ai/config.json\",\n default_agent: \"Atlas\",\n agent,\n skills: {\n paths: [\"./.ai-workflow/opencode/skills\"]\n },\n command\n };\n}\n\nexport interface MergeOpencodeConfigOptions {\n force?: boolean;\n backupRoot?: string;\n}\n\nexport interface MergeOpencodeConfigResult {\n changed: boolean;\n reason: string;\n}\n\nexport async function mergeOpencodeConfig(\n cwd: string,\n { force = false, backupRoot = \".ai-workflow-backups\" }: MergeOpencodeConfigOptions = {}\n): Promise<MergeOpencodeConfigResult> {\n const targetPath = path.join(cwd, \"opencode.jsonc\");\n const managed = buildManagedConfig();\n\n if (!(await exists(targetPath))) {\n await writeFileSafe(targetPath, `${JSON.stringify(managed, null, 2)}\\n`);\n return { changed: true, reason: \"created\" };\n }\n\n let current: any;\n try {\n current = await readJsonc(targetPath);\n } catch {\n if (!force) {\n return { changed: false, reason: \"invalid-json (skipped)\" };\n }\n await createManagedBackup(targetPath, {\n cwd,\n backupRoot,\n maxPerFile: 20\n });\n await writeFileSafe(targetPath, `${JSON.stringify(managed, null, 2)}\\n`);\n return { changed: true, reason: \"invalid-json (replaced with --force)\" };\n }\n\n const { [LEGACY_MARKER]: _legacyManaged, ...currentWithoutLegacy } = current;\n\n const next = {\n ...currentWithoutLegacy,\n $schema: current.$schema ?? managed.$schema,\n ...(managed.mcp\n ? {\n mcp: {\n ...(current.mcp ?? {}),\n ...managed.mcp\n }\n }\n : {}),\n agent: {\n ...(current.agent ?? {}),\n ...managed.agent\n },\n command: {\n ...(current.command ?? {}),\n ...managed.command\n }\n };\n\n const changed = JSON.stringify(current) !== JSON.stringify(next);\n if (!changed) {\n return { changed: false, reason: \"already-up-to-date\" };\n }\n\n await writeFileSafe(targetPath, `${JSON.stringify(next, null, 2)}\\n`);\n return { changed: true, reason: \"merged-managed-sections\" };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nfunction normalize(p: string): string {\n return p.split(path.sep).join(\"/\");\n}\n\n/**\n * For v3.0.0 \"Elite Governance\", we want an ULTRA-CLEAN root.\n * Only \"opencode\" is symlinked to the root (required for OpenCode discovery).\n * All other assets stay inside .ai-workflow/.\n */\nconst LINKABLE_ROOTS = new Set([\n \"opencode\",\n \".agents\",\n \"examples\"\n]);\n\nconst LINKABLE_FILES = new Set<string>([]);\n\nexport interface BuildSymlinkEntriesOptions {\n templateFiles: Record<string, string>;\n installRoot?: string;\n}\n\nexport interface SymlinkEntry {\n linkPath: string;\n targetPath: string;\n}\n\nexport function buildSymlinkEntries({ templateFiles, installRoot = \".ai-workflow\" }: BuildSymlinkEntriesOptions): SymlinkEntry[] {\n const entries = new Map<string, string>();\n\n for (const relativePath of Object.keys(templateFiles)) {\n if (relativePath === \"opencode.jsonc\") continue;\n\n const normalized = normalize(relativePath);\n\n if (LINKABLE_FILES.has(normalized)) {\n entries.set(normalized, `${installRoot}/${normalized}`);\n continue;\n }\n\n // Match composite paths in LINKABLE_ROOTS (e.g., \"docs/policies\")\n for (const rootPath of LINKABLE_ROOTS) {\n if (normalized === rootPath || normalized.startsWith(`${rootPath}/`)) {\n entries.set(rootPath, `${installRoot}/${rootPath}`);\n break;\n }\n }\n }\n\n return Array.from(entries.entries()).map(([linkPath, targetPath]) => ({ linkPath, targetPath }));\n}\n\nexport async function isSymlinkTo(absoluteLinkPath: string, absoluteTargetPath: string): Promise<boolean> {\n try {\n const stat = await fs.lstat(absoluteLinkPath);\n if (!stat.isSymbolicLink()) return false;\n const currentTarget = await fs.readlink(absoluteLinkPath);\n const resolved = path.resolve(path.dirname(absoluteLinkPath), currentTarget);\n return resolved === absoluteTargetPath;\n } catch {\n return false;\n }\n}\n\n/**\n * Internal symlink to satisfy opencode.jsonc paths without polluting the root.\n * Creates .ai-workflow/opencode/skills -> ../.agents/skills\n */\nexport async function setupInternalSymlinks(cwd: string, installRoot: string = \".ai-workflow\"): Promise<void> {\n const skillsLink = path.join(cwd, installRoot, \"opencode/skills\");\n const skillsTarget = path.join(cwd, installRoot, \".agents/skills\");\n\n if (!(await exists(skillsTarget))) return;\n\n try {\n const stat = await fs.lstat(skillsLink).catch(() => null);\n if (stat) {\n if (stat.isSymbolicLink()) {\n const current = await fs.readlink(skillsLink);\n if (current === \"../.agents/skills\") return;\n await fs.unlink(skillsLink);\n } else {\n return; // File exists, skip\n }\n }\n\n const type = process.platform === \"win32\" ? \"junction\" : \"dir\";\n await fs.symlink(\"../.agents/skills\", skillsLink, type);\n } catch {\n // Silent fail for internal symlink\n }\n}\n\nasync function exists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { COMPLETION_STATUS_TEXT } from \"../../core/statuses.js\";\n\n/**\n * Claude Adapter - Transforms OpenCode agents and skills into CLAUDE.md and .claude/rules/.\n */\nexport class ClaudeAdapter {\n cwd: string;\n\n constructor({ cwd }: { cwd: string }) {\n this.cwd = cwd;\n }\n\n /**\n * Transforms an OpenCode agent or skill into a Claude rule with completion contract.\n */\n async transformToRule(filePath: string, type: \"agent\" | \"skill\" = \"agent\"): Promise<{ content: string; name: string }> {\n const content = await fs.readFile(filePath, \"utf8\");\n const fileName = path.basename(filePath, \".md\") === \"SKILL\" \n ? path.basename(path.dirname(filePath)) \n : path.basename(filePath, \".md\");\n \n const ruleName = `${type}-${fileName.toLowerCase()}`;\n \n const hardenedContent = `---\nname: ${ruleName}\ndescription: ${type === \"agent\" ? \"Persona\" : \"Skill\"} rule for ${fileName}\n---\n# ${fileName} ${type === \"agent\" ? \"Persona\" : \"Skill\"}\n\n${content}\n\n## Completion Contract (Mandatory)\nEvery task completion MUST provide the following payload:\n1. **Status**: ${COMPLETION_STATUS_TEXT}\n2. **Scope reviewed**: Brief summary of what was analyzed.\n3. **Findings**: Evidence-based discoveries.\n4. **Files affected**: List of all concrete paths modified or created.\n5. **Validation/evidence**: Commands run and their results.\n6. **Risks/notes**: Any caveats or technical debt introduced.\n7. **Required manager action**: Clear next step for the orchestrator.\n8. **Can manager continue**: [yes/no]\n`;\n\n return {\n content: hardenedContent,\n name: ruleName\n };\n }\n\n /**\n * Deploys agents, skills, and root CLAUDE.md.\n */\n async deploy(installRoot: string = \".ai-workflow\"): Promise<void> {\n const rulesDir = path.join(this.cwd, \".claude/rules\");\n await fs.mkdir(rulesDir, { recursive: true });\n\n const sourceAgentsDir = path.join(this.cwd, installRoot, \"opencode/agents\");\n const sourceSkillsDir = path.join(this.cwd, installRoot, \"opencode/skills\");\n const sourceCommandsDir = path.join(this.cwd, installRoot, \"opencode/commands\");\n\n // 1. Deploy Agents to .claude/rules/agent-*.md\n const agentFiles = await fs.readdir(sourceAgentsDir).catch(() => []);\n for (const file of agentFiles) {\n if (!file.endsWith(\".md\")) continue;\n const transformed = await this.transformToRule(path.join(sourceAgentsDir, file), \"agent\");\n await fs.writeFile(path.join(rulesDir, `${transformed.name}.md`), transformed.content);\n }\n\n // 2. Deploy Skills to .claude/rules/skill-*.md\n const skillFolders = await fs.readdir(sourceSkillsDir).catch(() => []);\n for (const folder of skillFolders) {\n const skillSource = path.join(sourceSkillsDir, folder, \"SKILL.md\");\n if (await this.exists(skillSource)) {\n const transformed = await this.transformToRule(skillSource, \"skill\");\n await fs.writeFile(path.join(rulesDir, `${transformed.name}.md`), transformed.content);\n }\n }\n\n // 3. Create root CLAUDE.md\n await this.deployRootClaudeMd(sourceCommandsDir);\n }\n\n async deployRootClaudeMd(sourceCommandsDir: string): Promise<void> {\n const targetPath = path.join(this.cwd, \"CLAUDE.md\");\n \n // Collect commands to document them in CLAUDE.md\n const commandFiles = await fs.readdir(sourceCommandsDir).catch(() => []);\n let commandsDoc = \"\";\n for (const file of commandFiles) {\n if (!file.endsWith(\".md\")) continue;\n const name = path.basename(file, \".md\");\n commandsDoc += `- \\`ai-workflow run --spec-path=...\\` (Target: ${name})\\n`;\n }\n\n const instructions = `# CLAUDE.md - AI Workflow Kit Governance\n\nThis project uses the **AI Workflow Kit** (OpenCode-first) workflow.\n\n## Mandate: Atlas Authority Protocol\nAll architectural changes must align with the specifications issued by the **Specification Authority** (./specs).\n\n## Common Commands\n${commandsDoc}\n- \\`ai-workflow doctor\\`: Verify installation.\n- \\`ai-workflow collect-evidence\\`: Generate EVIDENCE.json.\n\n## Rules & Personas\nAdhere to the specific rules and personas defined in \\`.claude/rules/\\`. \n- Always follow the **Branch Gate** policy (never work on \\`main\\`).\n- Always follow the **SDD Workflow** (Spec -> Plan -> PR -> Evidence).\n\n## Completion Contract\nEvery task completion MUST follow the payload format defined in the individual rule files.\n`;\n await fs.writeFile(targetPath, instructions);\n }\n\n async exists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n }\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { COMPLETION_STATUS_TEXT } from \"../../core/statuses.js\";\n\n/**\n * Codex Adapter - Transforms OpenCode agents, skills, and commands into Codex-native formats.\n */\nexport class CodexAdapter {\n cwd: string;\n\n constructor({ cwd }: { cwd: string }) {\n this.cwd = cwd;\n }\n\n /**\n * Transforms an OpenCode agent into a Codex prompt with completion contract.\n */\n async transformAgent(filePath: string): Promise<{ content: string; name: string }> {\n const content = await fs.readFile(filePath, \"utf8\");\n const fileName = path.basename(filePath, \".md\");\n \n const hardenedContent = `${content}\n\n## System Directives for Codex\n- **No Conversational Filler**: Output only the requested artifact or analysis. Do not apologize or add filler text.\n- **Explicit Paths**: Always specify the exact, absolute or relative file path before making edits.\n- **Read-Only First**: Do not invent or assume file contents. Always read the workspace first.\n\n## Completion Contract (Mandatory)\nEvery task completion MUST provide the following payload:\n1. **Status**: ${COMPLETION_STATUS_TEXT}\n2. **Scope reviewed**: Brief summary of what was analyzed.\n3. **Findings**: Evidence-based discoveries.\n4. **Files affected**: List of all concrete paths modified or created.\n5. **Validation/evidence**: Commands run and their results.\n6. **Risks/notes**: Any caveats or technical debt introduced.\n7. **Required manager action**: Clear next step for the orchestrator.\n8. **Can manager continue**: [yes/no]\n`;\n\n return {\n content: hardenedContent,\n name: fileName\n };\n }\n\n /**\n * Deploys agents, skills, and commands to Codex-native directories.\n * Mapping:\n * - Agents -> .github/agents/\n * - Skills -> .agents/skills/\n * - Commands -> .codex/prompts/\n */\n async deploy(installRoot: string = \".ai-workflow\", force?: boolean): Promise<void> {\n const sourceAgentsDir = path.join(this.cwd, installRoot, \"opencode/agents\");\n const sourceSkillsDir = path.join(this.cwd, installRoot, \"opencode/skills\");\n const sourceCommandsDir = path.join(this.cwd, installRoot, \"opencode/commands\");\n\n // 1. Deploy Agents to .github/agents/\n const codexAgentsDir = path.join(this.cwd, \".github/agents\");\n await fs.mkdir(codexAgentsDir, { recursive: true });\n \n const agentFiles = await fs.readdir(sourceAgentsDir).catch(() => []);\n for (const file of agentFiles) {\n if (!file.endsWith(\".md\")) continue;\n const transformed = await this.transformAgent(path.join(sourceAgentsDir, file));\n await fs.writeFile(path.join(codexAgentsDir, `${transformed.name}.md`), transformed.content);\n }\n\n // 2. Deploy Skills to .codex/skills/\n const codexSkillsDir = path.join(this.cwd, \".codex/skills\");\n await fs.mkdir(codexSkillsDir, { recursive: true });\n\n const skillFolders = await fs.readdir(sourceSkillsDir).catch(() => []);\n for (const folder of skillFolders) {\n const skillSource = path.join(sourceSkillsDir, folder, \"SKILL.md\");\n if (await this.exists(skillSource)) {\n const targetDir = path.join(codexSkillsDir, folder);\n await fs.mkdir(targetDir, { recursive: true });\n const content = await fs.readFile(skillSource, \"utf8\");\n await fs.writeFile(path.join(targetDir, \"SKILL.md\"), content);\n }\n }\n\n // 3. Deploy Commands to .codex/prompts/\n const codexPromptsDir = path.join(this.cwd, \".codex/prompts\");\n await fs.mkdir(codexPromptsDir, { recursive: true });\n\n const commandFiles = await fs.readdir(sourceCommandsDir).catch(() => []);\n for (const file of commandFiles) {\n if (!file.endsWith(\".md\") && !file.endsWith(\".toml\")) continue;\n // Codex prompts work best as .md\n const targetFileName = file.endsWith(\".toml\") ? `${path.basename(file, \".toml\")}.md` : file;\n const content = await fs.readFile(path.join(sourceCommandsDir, file), \"utf8\");\n await fs.writeFile(path.join(codexPromptsDir, targetFileName), content);\n }\n\n // 4. Copy governance policy into .codex/docs/policies/ so the relative\n // link ../../docs/policies/SKILLS_COMMON_GOVERNANCE.md in each\n // .codex/skills/{skill}/SKILL.md resolves correctly.\n const codexPoliciesDir = path.join(this.cwd, \".codex\", \"docs\", \"policies\");\n await fs.mkdir(codexPoliciesDir, { recursive: true });\n const sourcePoliciesDir = path.join(this.cwd, installRoot, \"opencode\", \"docs\", \"policies\");\n const policyFiles = await fs.readdir(sourcePoliciesDir).catch(() => []);\n for (const file of policyFiles) {\n if (!file.endsWith(\".md\")) continue;\n const policyContent = await fs.readFile(path.join(sourcePoliciesDir, file), \"utf8\");\n await fs.writeFile(path.join(codexPoliciesDir, file), policyContent);\n }\n\n // 5. Create root .github/copilot-instructions.md for maximum Copilot/Codex compatibility\n await this.deployRootCopilotInstructions();\n\n // 6. Create root CODEX.md for explicit global project contract\n await this.deployRootCodexMd(force);\n\n // 7. Create root AGENTS.md for compatibility\n await this.deployRootAgentsMd(force);\n }\n\n async deployRootCopilotInstructions(): Promise<void> {\n const githubDir = path.join(this.cwd, \".github\");\n await fs.mkdir(githubDir, { recursive: true });\n const targetPath = path.join(githubDir, \"copilot-instructions.md\");\n \n const instructions = `# AI Workflow Kit Governance\n\nThis repository uses the **AI Workflow Kit** (OpenCode-first) workflow.\n\n## Mandate: Atlas Authority Protocol\nAll architectural changes must align with the specifications issued by the **Specification Authority**.\n\n## Rules & Personas\n- Always follow the **Branch Gate** policy (never work on \\`main\\`).\n- Always follow the **SDD Workflow** (Spec -> Plan -> PR -> Evidence).\n- When acting as an agent, consult the instructions in \\`.github/agents/\\`.\n- When utilizing skills, consult the files in \\`.codex/skills/\\`.\n\n## System Boundaries\n- **No Conversational Filler**: Do not apologize or add filler text.\n- **Strict Evidence**: You must provide the Completion Contract payload when finishing a task.\n- **Immutable Core**: Do not modify files inside \\`.ai-workflow/\\`, \\`.agents/\\`, \\`.claude/\\`, or \\`.codex/\\` unless explicitly requested.\n\n## Completion Contract\nEvery task completion MUST follow the payload format defined in the individual agent files.\n`;\n await fs.writeFile(targetPath, instructions);\n }\n\n async deployRootCodexMd(force?: boolean): Promise<void> {\n const targetPath = path.join(this.cwd, \"CODEX.md\");\n if (!force && await this.exists(targetPath)) return;\n \n // Check if the template exists\n const templatePath = path.join(this.cwd, \".ai-workflow\", \"templates\", \"CODEX.md.template\");\n if (await this.exists(templatePath)) {\n const content = await fs.readFile(templatePath, \"utf8\");\n await fs.writeFile(targetPath, content);\n return;\n }\n\n // Fallback to copilot instructions\n const instructions = `# AI Workflow Kit Governance\n\nThis repository uses the **AI Workflow Kit** (OpenCode-first) workflow.\n\n## Mandate: Atlas Authority Protocol\nAll architectural changes must align with the specifications issued by the **Specification Authority**.\n\n## Rules & Personas\n- Always follow the **Branch Gate** policy (never work on \\`main\\`).\n- Always follow the **SDD Workflow** (Spec -> Plan -> PR -> Evidence).\n- When acting as an agent, consult the instructions in \\`.github/agents/\\`.\n- When utilizing skills, consult the files in \\`.codex/skills/\\`.\n\n## System Boundaries\n- **No Conversational Filler**: Do not apologize or add filler text.\n- **Strict Evidence**: You must provide the Completion Contract payload when finishing a task.\n- **Immutable Core**: Do not modify files inside \\`.ai-workflow/\\`, \\`.agents/\\`, \\`.claude/\\`, or \\`.codex/\\` unless explicitly requested.\n\n## Completion Contract\nEvery task completion MUST follow the payload format defined in the individual agent files.\n`;\n await fs.writeFile(targetPath, instructions);\n }\n\n async deployRootAgentsMd(force?: boolean): Promise<void> {\n const targetPath = path.join(this.cwd, \"AGENTS.md\");\n if (!force && await this.exists(targetPath)) return;\n const templatePath = path.join(this.cwd, \".ai-workflow\", \"AGENTS.md\");\n if (await this.exists(templatePath)) {\n let content = await fs.readFile(templatePath, \"utf8\");\n // Transform references to point to Codex directories instead of OpenCode/.agents\n content = content.replace(/\\.agents\\/skills/g, \".codex/skills\");\n content = content.replace(/opencode\\/commands/g, \".codex/prompts\");\n content = content.replace(/opencode\\/docs\\/policies/g, \".codex/docs/policies\");\n await fs.writeFile(targetPath, content);\n }\n }\n\n async exists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n }\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { COMPLETION_STATUS_TEXT } from \"../../core/statuses.js\";\nexport interface TransformedItem {\n content: string;\n name: string;\n}\n\n/**\n * Maps OpenCode agent names to primary agent roles.\n */\nconst PERSONA_MAPPING: Record<string, string> = {\n \"atlas\": \"Atlas\",\n \"orion\": \"Orion\",\n \"sage\": \"Sage\",\n \"nexus\": \"Nexus\",\n \"astra\": \"Astra\",\n \"sage-validation\": \"Sage\",\n \"orion-release\": \"Orion\",\n \"orion-deploy\": \"Orion\",\n \"nexus-discovery\": \"Nexus\",\n \"phoenix\": \"Phoenix\"\n};\n\n/**\n * Antigravity Adapter - Transforms OpenCode .md to Antigravity Skill format and manages .agents/ integration.\n */\nexport class AntigravityAdapter {\n cwd: string;\n\n constructor({ cwd }: { cwd: string }) {\n this.cwd = cwd;\n }\n\n /**\n * Transforms an OpenCode agent or specialized skill file to an Antigravity Skill.\n */\n async transform(filePath: string): Promise<TransformedItem> {\n const content = await fs.readFile(filePath, \"utf8\");\n const fileName = path.basename(filePath, \".md\") === \"SKILL\" \n ? path.basename(path.dirname(filePath)) \n : path.basename(filePath, \".md\");\n \n const persona = PERSONA_MAPPING[fileName.toLowerCase()] || \"Astra\";\n \n // Check if already has frontmatter\n if (content.trim().startsWith(\"---\")) {\n return { content, name: fileName };\n }\n\n // Extract description from the first paragraph after the title\n const descriptionMatch = content.match(/^# .*\\n\\n(.*)/m);\n const description = descriptionMatch ? descriptionMatch[1].trim() : `Specialized agent for ${fileName}.`;\n\n const skillContent = `---\nname: ${fileName}\ndescription: ${description}\n---\n# ${persona} Persona\n\n${content}\n\n## Completion Contract (Mandatory)\nEvery task completion MUST provide the following payload:\n1. **Status**: ${COMPLETION_STATUS_TEXT}\n2. **Scope reviewed**: Brief summary of what was analyzed.\n3. **Findings**: Evidence-based discoveries.\n4. **Files affected**: List of all concrete paths modified or created.\n5. **Validation/evidence**: Commands run and their results.\n6. **Risks/notes**: Any caveats or technical debt introduced.\n7. **Required manager action**: Clear next step for the orchestrator.\n8. **Can manager continue**: [yes/no]\n`;\n\n return {\n content: skillContent,\n name: fileName\n };\n }\n\n /**\n * Deploys transformed skills and agents to their respective directories.\n * Also orchestrates the .antigravity/ native integration.\n */\n async deploy(transformedItems: TransformedItem[], installRoot: string = \".ai-workflow\"): Promise<void> {\n const agentsDir = path.join(this.cwd, installRoot, \"opencode/agents\");\n const skillsDir = path.join(this.cwd, installRoot, \"opencode/skills\");\n \n await fs.mkdir(agentsDir, { recursive: true });\n await fs.mkdir(skillsDir, { recursive: true });\n\n for (const item of transformedItems) {\n const isAgent = PERSONA_MAPPING[item.name.toLowerCase()];\n const targetDir = isAgent ? agentsDir : path.join(skillsDir, item.name);\n const fileName = isAgent ? `${item.name}.md` : \"SKILL.md\";\n \n const absoluteTargetDir = isAgent ? agentsDir : targetDir;\n await fs.mkdir(absoluteTargetDir, { recursive: true });\n await fs.writeFile(path.join(absoluteTargetDir, fileName), item.content);\n }\n \n // Deploy native Antigravity extensions (.antigravity/)\n await this.deployNativeExtensions(installRoot);\n\n // Also deploy root ANTIGRAVITY.md if it doesn't exist\n await this.deployInstructions();\n }\n\n /**\n * Orchestrates the .agents/ directory with copies of .ai-workflow/ assets.\n * Using hard copies instead of symlinks ensures native discovery across all platforms.\n */\n async deployNativeExtensions(installRoot: string = \".ai-workflow\"): Promise<void> {\n const antigravityDir = path.join(this.cwd, \".agents\");\n const antigravityAgents = path.join(antigravityDir, \"agents\");\n const antigravitySkills = path.join(antigravityDir, \"skills\");\n const antigravityCommands = path.join(antigravityDir, \"commands\");\n\n await fs.mkdir(antigravityAgents, { recursive: true });\n await fs.mkdir(antigravitySkills, { recursive: true });\n await fs.mkdir(antigravityCommands, { recursive: true });\n\n const getUrls = (targetPath: string) => {\n const linuxUrl = pathToFileURL(targetPath).href;\n const urls = [linuxUrl];\n \n if (process.platform === \"linux\" && process.env.WSL_DISTRO_NAME) {\n const distro = process.env.WSL_DISTRO_NAME;\n const normalizedPath = targetPath.replaceAll(\"\\\\\", \"/\");\n urls.push(`file://wsl.localhost/${distro}${normalizedPath}`);\n urls.push(`file:///wsl.localhost/${distro}${normalizedPath}`);\n }\n \n return urls.join(\"\\n\");\n };\n\n const toolNames = [\n \"send_message\",\n \"find_by_name\",\n \"grep_search\",\n \"view_file\",\n \"list_dir\",\n \"read_url_content\",\n \"search_web\",\n \"schedule\",\n \"multi_replace_file_content\",\n \"replace_file_content\",\n \"write_to_file\",\n \"run_command\",\n \"manage_task\",\n \"define_subagent\",\n \"invoke_subagent\",\n \"manage_subagents\",\n \"call_mcp_tool\"\n ];\n\n const systemPromptConfig = {\n \"includeSections\": [\n \"user_information\",\n \"mcp_servers\",\n \"skills\",\n \"subagent_reminder\",\n \"messaging\",\n \"artifacts\",\n \"user_rules\"\n ]\n };\n\n // 1. Deploy Primary Agents to .agents/agents/{agent_name}/\n const sourceAgentsDir = path.join(this.cwd, installRoot, \"opencode/agents\");\n const agentFiles = await fs.readdir(sourceAgentsDir).catch(() => []);\n\n const AGENTS_INFO: Record<string, { name: string; description: string }> = {\n \"atlas\": { name: \"Atlas\", description: \"Router and workflow coordinator for AI Workflow Kit\" },\n \"nexus\": { name: \"Nexus\", description: \"Discovery, requirement, scope, and specification owner\" },\n \"orion\": { name: \"Orion\", description: \"Planning, PR sequencing, release, and deployment strategy owner\" },\n \"astra\": { name: \"Astra\", description: \"Implementation owner for incremental, scoped changes\" },\n \"sage\": { name: \"Sage\", description: \"Audit, validation, evidence, and quality gate owner\" },\n \"phoenix\": { name: \"Phoenix\", description: \"Remediation and regression recovery owner\" }\n };\n\n for (const file of agentFiles) {\n if (!file.endsWith(\".md\")) continue;\n const lowercaseName = path.basename(file, \".md\").toLowerCase();\n const info = AGENTS_INFO[lowercaseName];\n if (!info) continue;\n\n const agentFolder = path.join(antigravityAgents, lowercaseName);\n await fs.mkdir(agentFolder, { recursive: true });\n\n // Copy Markdown file to the agent's folder\n const content = await fs.readFile(path.join(sourceAgentsDir, file), \"utf8\");\n const mdTarget = path.join(agentFolder, `${lowercaseName}.md`);\n await fs.writeFile(mdTarget, content);\n\n // Generate agent.json\n const agentJson = {\n name: lowercaseName,\n description: info.description,\n hidden: false,\n config: {\n customAgent: {\n systemPromptSections: [\n {\n title: \"Agent System Instructions\",\n content: `You are ${info.name}, the ${lowercaseName === \"astra\" ? \"implementation\" : lowercaseName} owner.\\n\\nFollow the contract instructions in:\\n${getUrls(mdTarget)}`\n }\n ],\n toolNames,\n systemPromptConfig\n }\n }\n };\n await fs.writeFile(path.join(agentFolder, \"agent.json\"), JSON.stringify(agentJson, null, 2));\n }\n\n // 2. Deploy Subagents to .agents/agents/{subagent_name}/\n const SUBAGENTS_INFO: Record<string, { description: string; skill: string }> = {\n \"Architecture-Specialist\": { description: \"Select the simplest architecture that safely satisfies current requirements\", skill: \"architecture\" },\n \"Backend-Engineer\": { description: \"Support safe PHP/Node/Python backend changes for APIs and persistence\", skill: \"backend-development\" },\n \"Deployment-Specialist\": { description: \"Plan, review, or validate deployment, release, and production-readiness\", skill: \"deployment\" },\n \"Design-Specialist\": { description: \"Apply practical design principles to keep solutions simple and maintainable\", skill: \"design-principles\" },\n \"Docs-Engineer\": { description: \"Write or improve project documentation, READMEs, guides, and prompts\", skill: \"documentation\" },\n \"Frontend-Engineer\": { description: \"Implement or review frontend changes involving UI, state, routing, and accessibility\", skill: \"frontend-development\" },\n \"Full-Stack-Engineer\": { description: \"Coordinate frontend and backend changes as one coherent, testable increment\", skill: \"full-stack-development\" },\n \"Token-Economist\": { description: \"Reduce context size while preserving information required for safe execution\", skill: \"optimize-tokens\" },\n \"PR-Manager\": { description: \"Plan, implement, review, or validate small pull requests while preserving scope\", skill: \"pr-workflow\" },\n \"Discovery-Analyst\": { description: \"Clarify ambiguous requests into actionable problem statements and success outcomes\", skill: \"product-discovery\" },\n \"Product-Planner\": { description: \"Turn clarified needs into scoped requirements with acceptance-ready outcomes\", skill: \"product-planning\" },\n \"Memory-Guardian\": { description: \"Manage discoverable project memory for durable decisions and recurring corrections\", skill: \"project-memory\" },\n \"Prompt-Engineer\": { description: \"Expert in creating and refining prompts for AI agents and workflows\", skill: \"prompt-engineer\" },\n \"QA-Engineer\": { description: \"Design, review, or improve tests, acceptance criteria, and validation evidence\", skill: \"qa-workflow\" },\n \"Refactoring-Specialist\": { description: \"Improve code/document structure safely while preserving behavior\", skill: \"refactoring\" },\n \"Release-Specialist\": { description: \"Prepare release readiness decisions with explicit gates and evidence\", skill: \"release-workflow\" },\n \"SDD-Specialist\": { description: \"Convert approved requirements into explicit, testable specification artifacts\", skill: \"spec-driven-development\" },\n \"Technical-Leader\": { description: \"Make technical decisions, review architecture, and identify trade-offs\", skill: \"technical-leadership\" },\n \"UI-UX-Engineer\": { description: \"Improve usability and interface clarity without introducing unnecessary complexity\", skill: \"ui-ux-design\" }\n };\n\n for (const [name, subInfo] of Object.entries(SUBAGENTS_INFO)) {\n const lowercaseSubagentName = name.toLowerCase();\n const subagentFolder = path.join(antigravityAgents, lowercaseSubagentName);\n await fs.mkdir(subagentFolder, { recursive: true });\n\n const skillPath = path.join(antigravitySkills, subInfo.skill, \"SKILL.md\");\n\n const subagentJson = {\n name: lowercaseSubagentName,\n description: subInfo.description,\n hidden: false,\n config: {\n customAgent: {\n systemPromptSections: [\n {\n title: \"Agent System Instructions\",\n content: `You are ${name}.\\n\\nFollow the contract instructions in:\\n${getUrls(skillPath)}`\n }\n ],\n toolNames,\n systemPromptConfig\n }\n }\n };\n await fs.writeFile(path.join(subagentFolder, \"agent.json\"), JSON.stringify(subagentJson, null, 2));\n }\n\n // 3. Copy Skills\n const sourceSkillsDir = path.join(this.cwd, installRoot, \"opencode/skills\");\n const skillFolders = await fs.readdir(sourceSkillsDir).catch(() => []);\n for (const folder of skillFolders) {\n const skillSource = path.join(sourceSkillsDir, folder, \"SKILL.md\");\n if (await this.exists(skillSource)) {\n await fs.mkdir(path.join(antigravitySkills, folder), { recursive: true });\n const content = await fs.readFile(skillSource, \"utf8\");\n await fs.writeFile(path.join(antigravitySkills, folder, \"SKILL.md\"), content);\n }\n }\n\n // 4. Copy Commands (from dist-assets/commands)\n const sourceCommandsDir = path.join(this.cwd, installRoot, \"opencode/commands\");\n if (await this.exists(sourceCommandsDir)) {\n const commandFiles = await fs.readdir(sourceCommandsDir).catch(() => []);\n for (const file of commandFiles) {\n if (!file.endsWith(\".md\") && !file.endsWith(\".toml\")) continue;\n const content = await fs.readFile(path.join(sourceCommandsDir, file), \"utf8\");\n await fs.writeFile(path.join(antigravityCommands, file), content);\n }\n }\n\n // 5. Copy governance policy into .agents/docs/policies/ so the relative\n // link ../../docs/policies/SKILLS_COMMON_GOVERNANCE.md in each\n // .agents/skills/{skill}/SKILL.md resolves correctly.\n const sourcePoliciesDir = path.join(this.cwd, installRoot, \"opencode\", \"docs\", \"policies\");\n const antigravityPolicies = path.join(antigravityDir, \"docs\", \"policies\");\n if (await this.exists(sourcePoliciesDir)) {\n await fs.mkdir(antigravityPolicies, { recursive: true });\n const policyFiles = await fs.readdir(sourcePoliciesDir).catch(() => []);\n for (const file of policyFiles) {\n if (!file.endsWith(\".md\")) continue;\n const content = await fs.readFile(path.join(sourcePoliciesDir, file), \"utf8\");\n await fs.writeFile(path.join(antigravityPolicies, file), content);\n }\n }\n\n // 6. Inject project settings.json\n const settingsPath = path.join(antigravityDir, \"settings.json\");\n if (!(await this.exists(settingsPath))) {\n const settings = {\n model: { name: \"auto\" },\n ui: { theme: \"Ayu\" }\n };\n await fs.writeFile(settingsPath, JSON.stringify(settings, null, 2));\n }\n }\n\n async exists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Deploys the main ANTIGRAVITY.md and .antigravityignore instructions to the project root.\n */\n async deployInstructions(): Promise<void> {\n const targetPath = path.join(this.cwd, \"ANTIGRAVITY.md\");\n const ignorePath = path.join(this.cwd, \".antigravityignore\");\n \n // Deploy ANTIGRAVITY.md if it doesn't exist\n try {\n await fs.access(targetPath);\n } catch {\n const instructions = `# AI Workflow Kit - Engineering Governance\n\n## Mandate: Atlas Authority Protocol\nAll architectural changes must align with the specifications issued by the **Specification Authority** (./specs).\n\n## Ternary Architecture\n- **Root:** Orchestration and config.\n- **.ai-workflow/:** Implementation (The Muscle).\n- **./specs:** Specifications (The Brain).\n\n## Branch Gates\n- **main Branch:** READ-ONLY.\n- **Validation:** Merges require successful observed validation; full/release workflows may persist EVIDENCE.json.\n\n## Primary Agents\n- **Atlas (Orchestrator)**\n- **Orion (Strategist)**\n- **Sage (Auditor)**\n- **Nexus (Spec Architect)**\n- **Astra (Developer)**\n- **Phoenix (Healer)**\n\n## Operational Preferences\n- Use \\`token-economy\\` and \\`minimal-context\\` skills.\n- **Native Discovery**: This project uses workspace-specific extensions in \\`.agents/\\`.\n- **Workflow Entry**: Use \\`/atlas\\` to begin any task.\n`;\n await fs.writeFile(targetPath, instructions);\n }\n\n // Deploy .antigravityignore if it doesn't exist\n try {\n await fs.access(ignorePath);\n } catch {\n const ignoreContent = `.ai-workflow/\n.ai-workflow-backups/\nnode_modules/\n.git/\nEVIDENCE.json\n*.tgz\n*.zip\n*.tar\n.agents/tmp/\n.agents/history/\n`;\n await fs.writeFile(ignorePath, ignoreContent);\n }\n }\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { exists, readJson, readJsonc } from \"../../core/filesystem.js\";\nimport { OpenCodeAdapter } from \"../../core/runtime/opencode-adapter.js\";\n\nconst REQUIRED_FILES = [\n \".ai-workflow\",\n \"opencode/README.md\"\n];\n\nasync function isSymlink(filePath: string): Promise<boolean> {\n try {\n const stat = await fs.lstat(filePath);\n return stat.isSymbolicLink();\n } catch {\n return false;\n }\n}\n\nexport interface DoctorOptions {\n cwd: string;\n}\n\ninterface DoctorState {\n hasFailure: boolean;\n hasWarning: boolean;\n managedBlocks: string[];\n runtimes: string[];\n}\n\nasync function checkOpenCodeRuntime(cwd: string, state: DoctorState): Promise<void> {\n const adapter = new OpenCodeAdapter({ cwd });\n const inspection = await adapter.inspect();\n if (inspection.available) {\n console.log(\"PASS opencode CLI is available\");\n const supportedStr = Object.entries(inspection.supports)\n .filter(([_, v]) => v)\n .map(([k, _]) => k)\n .join(\", \");\n console.log(`PASS opencode capabilities detected: ${supportedStr || \"none\"}`);\n if (inspection.supports.agent) {\n console.log(\"PASS opencode --agent selection is supported\");\n } else {\n state.hasWarning = true;\n console.log(\"WARN opencode --agent selection is not supported; prompt fallback is available\");\n }\n } else {\n state.hasFailure = true;\n console.log(\"FAIL opencode CLI is not installed or not available in PATH\");\n }\n}\n\nasync function checkRequiredFiles(cwd: string, state: DoctorState): Promise<void> {\n for (const relativePath of REQUIRED_FILES) {\n const ok = await exists(path.join(cwd, relativePath));\n if (ok) {\n console.log(`PASS ${relativePath}`);\n } else {\n state.hasFailure = true;\n console.log(`FAIL ${relativePath} missing`);\n }\n }\n}\n\nasync function checkAiWorkflowConfig(cwd: string, state: DoctorState): Promise<void> {\n const configPathV2 = path.join(cwd, \".ai-workflow/config.json\");\n const configPathLegacy = path.join(cwd, \".ai-workflow.json\");\n let configPath: string | null = null;\n\n if (await exists(configPathV2)) {\n configPath = configPathV2;\n } else if (await exists(configPathLegacy)) {\n configPath = configPathLegacy;\n }\n\n if (!configPath) return;\n\n try {\n const config = await readJson(configPath);\n const basename = path.basename(configPath);\n\n if (config.installMode === \"project-local\" || config.mode === \"standalone\") {\n console.log(\"PASS install mode is project-local/standalone\");\n } else {\n state.hasWarning = true;\n console.log(`WARN install mode is not project-local/standalone in ${basename}`);\n }\n\n if (config.profile) {\n console.log(`PASS profile detected: ${config.profile}`);\n } else {\n state.hasWarning = true;\n console.log(`WARN profile is missing in ${basename}`);\n }\n\n if (config.runtime) {\n console.log(`PASS runtime: ${config.runtime}`);\n state.runtimes = config.runtime.split(\"+\");\n } else {\n console.log(`NOTE runtime field not present in ${basename}`);\n state.runtimes = [\"opencode\"];\n }\n\n if (Array.isArray(config.managedBlocks)) {\n state.managedBlocks = config.managedBlocks;\n } else {\n console.log(`NOTE managedBlocks not present in ${basename} (legacy field)`);\n }\n\n if (Array.isArray(config.managedFiles)) {\n for (const relativePath of config.managedFiles) {\n const fileExists = await exists(path.join(cwd, relativePath));\n if (!fileExists) {\n state.hasWarning = true;\n console.log(`WARN managed file missing: ${relativePath}`);\n }\n }\n }\n\n if (Array.isArray(config.managedLinks)) {\n for (const relativePath of config.managedLinks) {\n const absolutePath = path.join(cwd, relativePath);\n if (!(await exists(absolutePath))) {\n state.hasWarning = true;\n console.log(`WARN managed link missing: ${relativePath}`);\n continue;\n }\n if (!(await isSymlink(absolutePath))) {\n state.hasWarning = true;\n console.log(`WARN managed link is not a symlink: ${relativePath}`);\n }\n }\n }\n } catch {\n state.hasFailure = true;\n console.log(`FAIL ${path.basename(configPath)} is not valid JSON`);\n }\n}\n\nasync function checkOpencodeJson(cwd: string, state: DoctorState): Promise<void> {\n const opencodePath = path.join(cwd, \"opencode.jsonc\");\n if (!(await exists(opencodePath))) {\n state.hasFailure = true;\n console.log(\"FAIL opencode.jsonc missing\");\n return;\n }\n \n try {\n const opencodeConfig = await readJsonc(opencodePath);\n console.log(\"PASS opencode.jsonc is valid JSONC\");\n\n const needsAgentDefault = state.managedBlocks.includes(\"opencode.jsonc:agent.default\");\n if (!needsAgentDefault || opencodeConfig.agent?.default) {\n console.log(\"PASS opencode agent.default available\");\n } else {\n state.hasFailure = true;\n console.log(\"FAIL opencode agent.default missing\");\n }\n\n const requiredCommands = state.managedBlocks\n .filter((block) => block.startsWith(\"opencode.jsonc:command.\"))\n .map((block) => block.replace(\"opencode.jsonc:command.\", \"\"));\n\n if (requiredCommands.length === 0) {\n console.log(\"PASS no managed opencode commands required\");\n } else {\n const missingCommands = requiredCommands.filter((command) => !opencodeConfig.command?.[command]);\n if (missingCommands.length === 0) {\n console.log(`PASS opencode managed commands available (${requiredCommands.length})`);\n } else {\n state.hasFailure = true;\n console.log(`FAIL opencode command entries missing: ${missingCommands.join(\", \")}`);\n }\n }\n\n const requiredAgents = state.managedBlocks\n .filter((block) => block.startsWith(\"opencode.jsonc:agent.\") && !block.endsWith(\".default\"))\n .map((block) => block.replace(\"opencode.jsonc:agent.\", \"\"));\n\n if (requiredAgents.length === 0) {\n console.log(\"PASS no managed opencode agents required\");\n } else {\n const missingAgents = requiredAgents.filter((agent) => !opencodeConfig.agent?.[agent]);\n if (missingAgents.length === 0) {\n console.log(`PASS opencode managed agents available (${requiredAgents.length})`);\n } else {\n state.hasFailure = true;\n console.log(`FAIL opencode agent entries missing: ${missingAgents.join(\", \")}`);\n }\n }\n } catch {\n state.hasFailure = true;\n console.log(\"FAIL opencode.jsonc is not valid JSONC\");\n }\n}\n\nasync function checkPackageJson(cwd: string, state: DoctorState): Promise<void> {\n const packageJsonPath = path.join(cwd, \"package.json\");\n if (await exists(packageJsonPath)) {\n try {\n const packageJson = await readJson(packageJsonPath);\n const scripts = packageJson.scripts ?? {};\n\n if (!scripts.validate) {\n state.hasWarning = true;\n console.log(\"WARN package.json has no validate script\");\n }\n } catch {\n state.hasFailure = true;\n console.log(\"FAIL package.json is not valid JSON\");\n }\n }\n}\n\nasync function checkCodexRuntime(cwd: string, state: DoctorState): Promise<void> {\n const checks = [\n { name: \"root AGENTS.md exists\", path: \"AGENTS.md\" },\n { name: \".codex/skills exists\", path: \".codex/skills\" },\n { name: \".codex prompts detected\", path: \".codex/prompts\" },\n { name: \".codex policies detected\", path: \".codex/docs/policies\" }\n ];\n\n for (const check of checks) {\n const ok = await exists(path.join(cwd, check.path));\n if (ok) {\n console.log(`PASS ${check.name}`);\n } else {\n state.hasFailure = true;\n console.log(`FAIL ${check.name}`);\n }\n }\n\n // Also check if CODEX.md exists\n const codexMdOk = await exists(path.join(cwd, \"CODEX.md\"));\n if (codexMdOk) {\n console.log(`PASS root CODEX.md exists`);\n }\n\n if (state.runtimes.includes(\"codex\")) {\n console.log(\"PASS config runtime includes codex\");\n } else {\n state.hasFailure = true;\n console.log(\"FAIL config runtime includes codex\");\n }\n}\n\nexport async function runDoctor({ cwd }: DoctorOptions): Promise<void> {\n const state: DoctorState = {\n hasFailure: false,\n hasWarning: false,\n managedBlocks: [],\n runtimes: [\"opencode\"]\n };\n\n console.log(\"Doctor report:\");\n\n await checkRequiredFiles(cwd, state);\n await checkAiWorkflowConfig(cwd, state);\n\n if (state.runtimes.includes(\"opencode\")) {\n await checkOpenCodeRuntime(cwd, state);\n await checkOpencodeJson(cwd, state);\n }\n\n if (state.runtimes.includes(\"codex\")) {\n await checkCodexRuntime(cwd, state);\n }\n\n await checkPackageJson(cwd, state);\n\n const finalStatus = state.hasFailure ? \"FAIL\" : state.hasWarning ? \"PASS_WITH_NOTES\" : \"PASS\";\n console.log(`Final status: ${finalStatus}`);\n\n if (state.hasFailure) {\n process.exitCode = 1;\n }\n}\n\n","export const DELIVERY_SUMMARY_FIELDS = Object.freeze([\n \"Status\",\n \"Branch\",\n \"Changes\",\n \"Validation\",\n \"Known limitations\"\n] as const);\n\nexport function buildDeliverySummary({ evidence }: { evidence: any }): Record<string, string> {\n const commands = (evidence?.commands || []).map((item: any) => `${item.command || item.name}: ${item.status}`).join(\"; \") || \"No validation commands recorded\";\n return {\n Status: evidence?.status || \"BLOCKED\",\n Branch: evidence?.branch || \"unknown\",\n Changes: (evidence?.deliveryChangedFiles || evidence?.changedFiles || []).join(\", \") || \"No changed files recorded\",\n Validation: commands,\n \"Known limitations\": (evidence?.limitations || []).join(\"; \") || \"None recorded\"\n };\n}\n\nexport interface ValidationSummaryResult {\n status: \"PASS\" | \"FAIL\";\n missing: string[];\n invalid: string[];\n}\n\nexport function validateDeliverySummary(summary: any): ValidationSummaryResult {\n const missing = DELIVERY_SUMMARY_FIELDS.filter((field) => !String(summary?.[field] || \"\").trim());\n const status = String(summary?.Status || \"\").trim();\n const invalid: string[] = [];\n if (![\"COMPLETED\", \"COMPLETED_WITH_NOTES\", \"BLOCKED\"].includes(status)) invalid.push(\"Status\");\n if (status !== \"BLOCKED\" && /FAIL|BLOCKED/.test(String(summary?.Validation || \"\"))) invalid.push(\"successful status with failed validation\");\n if (status !== \"BLOCKED\" && /No validation commands recorded/i.test(String(summary?.Validation || \"\"))) {\n invalid.push(\"successful status without validation evidence\");\n }\n if (status === \"BLOCKED\") {\n const diagnostic = String(summary?.[\"Known limitations\"] || \"\").trim();\n if (!/Gate:/i.test(diagnostic) || !/Observed:/i.test(diagnostic) || !/Expected:/i.test(diagnostic) || !/Next action:/i.test(diagnostic)) {\n invalid.push(\"blocked status without a structured diagnostic\");\n }\n }\n return { status: missing.length || invalid.length ? \"FAIL\" : \"PASS\", missing, invalid };\n}\n\nexport function formatDeliverySummary(summary: any): string {\n return DELIVERY_SUMMARY_FIELDS.map((field) => `${field}: ${summary?.[field] || \"NOT_RECORDED\"}`).join(\"\\n\");\n}\n\n// Backward-compatible aliases for integrations that imported the previous API.\nexport const CANONICAL_FINALIZATION_FIELDS = DELIVERY_SUMMARY_FIELDS;\nexport const buildCanonicalFinalization = ({ collectorStatus = \"BLOCKED\", branchRecovery = \"unknown\" } = {}): Record<string, string> => ({\n Status: collectorStatus === \"PASS\" ? \"COMPLETED\" : collectorStatus === \"PASS_WITH_NOTES\" ? \"COMPLETED_WITH_NOTES\" : \"BLOCKED\",\n Branch: branchRecovery,\n Changes: \"See observed diff\",\n Validation: collectorStatus,\n \"Known limitations\": \"See evidence\"\n});\nexport const validateCanonicalFinalization = validateDeliverySummary;\nexport const formatCanonicalFinalization = formatDeliverySummary;\n","import { EvidenceCollector } from \"../../core/validation/evidence-collector.js\";\nimport { QualityGuard } from \"../../core/validation/quality-guard.js\";\nimport { ValidationPlanner } from \"../../core/validation/validation-planner.js\";\nimport { buildDeliverySummary, formatDeliverySummary } from \"../../core/validation/canonical-finalization.js\";\n\nexport interface CollectEvidenceOptions {\n cwd: string;\n exitOnError?: boolean;\n taskSlug?: string | null;\n mode?: string | null;\n evidencePolicy?: \"optional\" | \"required\" | null;\n dryRun?: boolean;\n profile?: string;\n branchRecovery?: string;\n userRequest?: string | null;\n explicitApprovals?: string[];\n visualDist?: string | null;\n port?: number | string | null;\n workflowEvidence?: Record<string, unknown> | null;\n claimedOutcome?: \"CHANGED\" | \"ALREADY_SATISFIED\" | null;\n deliveryChangedFiles?: string[] | null;\n deliveryAddedFiles?: string[] | null;\n deliveryDeletedFiles?: string[] | null;\n}\n\n/**\n * @deprecated Boundary helper to translate legacy CLI mode options to modern policies.\n */\nexport function resolvePoliciesFromLegacyMode(mode: string | null, evidencePolicy: \"optional\" | \"required\" | null): {\n evidencePolicy: \"optional\" | \"required\";\n riskLevel: \"low\" | \"medium\" | \"high\";\n} {\n const activePolicy = evidencePolicy || (mode === \"full\" ? \"required\" : \"optional\");\n \n let risk: \"low\" | \"medium\" | \"high\" = \"medium\";\n if (mode === \"full\") {\n risk = \"high\";\n } else if (mode === \"quick\") {\n risk = activePolicy === \"required\" ? \"medium\" : \"low\";\n } else if (activePolicy === \"required\") {\n risk = \"high\";\n }\n \n return { evidencePolicy: activePolicy, riskLevel: risk };\n}\n\nexport async function runCollectEvidence({\n cwd, exitOnError = true, taskSlug = null, mode = null, evidencePolicy = null, dryRun = false, profile = \"generic\", branchRecovery = \"NOT_RECORDED\", userRequest = null, explicitApprovals = [], visualDist = null, port = null, workflowEvidence = null, claimedOutcome = null, deliveryChangedFiles = null, deliveryAddedFiles = null, deliveryDeletedFiles = null\n}: CollectEvidenceOptions): Promise<any> {\n if (process.env.AI_WORKFLOW_FINALIZATION_OWNER === \"execute\") {\n console.log(\"[FINALIZATION DEFERRED] Parent ai-workflow execute process owns canonical finalization.\");\n return { status: \"DEFERRED_TO_ORCHESTRATOR\", internalStatus: \"DEFERRED\", commands: [] };\n }\n const policies = resolvePoliciesFromLegacyMode(mode, evidencePolicy);\n const workspaceGuard = new QualityGuard({ cwd, taskSlug, evidencePolicy: policies.evidencePolicy, riskLevel: policies.riskLevel });\n const observedDeliveryFiles = deliveryChangedFiles ?? workspaceGuard.getChangedFiles();\n const qualityGuard = new QualityGuard({\n cwd,\n taskSlug,\n evidencePolicy: policies.evidencePolicy,\n riskLevel: policies.riskLevel,\n scopedChangedFiles: observedDeliveryFiles\n });\n const planner = new ValidationPlanner({ cwd, qualityGuard });\n const tasks = await planner.plan(profile, {\n requireObservedValidation: claimedOutcome === \"ALREADY_SATISFIED\" && observedDeliveryFiles.length === 0\n });\n const docs = observedDeliveryFiles.filter((file) => /(^|\\/)(docs?|readme|changelog)|\\.md$/i.test(file));\n if (tasks.length === 0 && docs.length > 0 && docs.length === observedDeliveryFiles.length) {\n tasks.push({\n name: \"docs-integrity\",\n command: [\"aiwk\", \"internal\", \"docs-integrity\"],\n kind: \"lint\",\n internal: \"document-integrity\",\n files: docs\n } as any);\n }\n\n const persist = !dryRun && policies.evidencePolicy === \"required\";\n const collector = new EvidenceCollector({\n cwd,\n timeout: 60000,\n taskSlug,\n evidencePolicy: policies.evidencePolicy,\n profile,\n branchRecovery,\n userRequest,\n explicitApprovals,\n visualDist,\n port: port || 8080,\n workflowEvidence,\n claimedOutcome,\n deliveryChangedFiles: observedDeliveryFiles,\n deliveryAddedFiles,\n deliveryDeletedFiles,\n riskLevel: policies.riskLevel\n });\n const evidence = await collector.collect(tasks, { writeArtifact: persist });\n const summary = buildDeliverySummary({ evidence });\n\n console.log(\"\\n--- Delivery Summary ---\");\n console.log(formatDeliverySummary(summary));\n console.log(persist ? \"\\nArtifact: EVIDENCE.json\" : \"\\nArtifact: NOT_REQUIRED for optional evidence policy\");\n console.log(`Commands processed: ${evidence.commands.length}\\n`);\n\n if (evidence.status === \"BLOCKED\" && exitOnError) process.exit(1);\n return evidence;\n}\n","import { spawnSync, execSync } from \"node:child_process\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\n/**\n * Determines which npm scripts are available in the consumer project.\n */\nasync function readScripts(cwd: string): Promise<Record<string, string>> {\n try {\n const pkg = JSON.parse(await fs.readFile(path.join(cwd, \"package.json\"), \"utf8\"));\n return pkg.scripts || {};\n } catch {\n return {};\n }\n}\n\n/**\n * Returns the list of files changed since the last commit.\n * Used to detect whether remediation produced any observable change.\n */\nfunction getChangedFiles(cwd: string): string[] {\n try {\n const output = execSync(\"git status --short\", { cwd, encoding: \"utf8\" });\n return output\n .split(\"\\n\")\n .filter(Boolean)\n .map((line) => line.slice(3).trim())\n .filter(Boolean);\n } catch {\n return [];\n }\n}\n\n/**\n * Maps an affectedCheck source string to likely npm script names to re-run.\n */\nfunction resolveRetryScripts(affectedChecks: string[], scripts: Record<string, string>): string[] {\n const retry = new Set<string>();\n\n for (const check of affectedChecks) {\n // Evidence failures → re-run the failing validation scripts\n if (check === \"evidence\" || check === \"result\") {\n if (scripts.test) retry.add(\"test\");\n if (scripts.lint) retry.add(\"lint\");\n if (scripts.build) retry.add(\"build\");\n if (scripts.typecheck) retry.add(\"typecheck\");\n }\n // Specific check types\n if (check.includes(\"test\")) retry.add(\"test\");\n if (check.includes(\"lint\")) retry.add(\"lint\");\n if (check.includes(\"build\")) retry.add(\"build\");\n if (check.includes(\"typecheck\")) retry.add(\"typecheck\");\n }\n\n // Filter to only scripts that actually exist\n return [...retry].filter((name) => !!scripts[name]);\n}\n\nexport interface RemediationExecutorContext {\n attempt: number;\n maxAttempts: number;\n mode: string;\n taskSlug: string;\n result: any;\n affectedChecks: string[];\n requestPath: string;\n}\n\nexport interface RemediationExecutorResult {\n applied: boolean;\n changedFiles?: string[];\n evidenceAdded?: string[];\n reason?: string;\n}\n\n/**\n * CLI Remediation Executor — default implementation for `ai-workflow run`.\n */\nexport function createCliRemediationExecutor(cwd: string) {\n return async function remediationExecutor({\n attempt,\n maxAttempts,\n mode,\n affectedChecks,\n requestPath\n }: RemediationExecutorContext): Promise<RemediationExecutorResult> {\n console.log(`\\n[HEALER] Attempt ${attempt}/${maxAttempts} — mode: ${mode}`);\n console.log(`[HEALER] Affected: ${affectedChecks.join(\", \")}`);\n\n const scripts = await readScripts(cwd);\n const filesBefore = getChangedFiles(cwd);\n const toRetry = resolveRetryScripts(affectedChecks, scripts);\n\n if (toRetry.length === 0) {\n console.log(\"[HEALER] No retryable scripts found for the affected checks.\");\n console.log(`[HEALER] Review ${requestPath} for details.`);\n return {\n applied: false,\n reason: `No npm scripts available to address: ${affectedChecks.join(\", \")}. Manual remediation required.`\n };\n }\n\n console.log(`[HEALER] Re-running: ${toRetry.map((s) => `npm run ${s}`).join(\", \")}`);\n\n const results: any[] = [];\n let anyPassed = false;\n\n for (const scriptName of toRetry) {\n process.stdout.write(` → npm run ${scriptName} ... `);\n const isWin32 = process.platform === \"win32\";\n const cmd = isWin32 ? \"npm.cmd\" : \"npm\";\n const result = spawnSync(cmd, [\"run\", scriptName], {\n cwd,\n shell: false,\n encoding: \"utf8\",\n timeout: 120000\n });\n const passed = result.status === 0;\n if (passed) anyPassed = true;\n console.log(passed ? \"PASS\" : \"FAIL\");\n results.push({ script: scriptName, passed, exitCode: result.status });\n }\n\n const filesAfter = getChangedFiles(cwd);\n const changedFiles = filesAfter.filter((f) => !filesBefore.includes(f));\n\n if (!anyPassed && changedFiles.length === 0) {\n console.log(\"[HEALER] No scripts passed and no files changed — remediation had no effect.\");\n return {\n applied: false,\n reason: `Re-ran ${toRetry.join(\", \")} — all failed. Structural fix required by the implementing agent.`\n };\n }\n\n console.log(`[HEALER] Applied: ${results.filter((r) => r.passed).map((r) => r.script).join(\", \") || \"none passed\"}`);\n if (changedFiles.length) console.log(`[HEALER] Changed files: ${changedFiles.join(\", \")}`);\n\n return {\n applied: true,\n changedFiles,\n evidenceAdded: anyPassed ? [\"validation-output\"] : []\n };\n };\n}\n","import { BranchGate } from \"../../core/gates/branch-gate.js\";\nimport { SpecValidator } from \"../../core/sdd/validator.js\";\nimport { HandoffEngine } from \"../../core/handoff/handoff-engine.js\";\nimport { runCollectEvidence } from \"./collect-evidence.js\";\nimport { QualityGuard } from \"../../core/validation/quality-guard.js\";\nimport { HealerEngine } from \"../../core/healing/healer-engine.js\";\nimport { createCliRemediationExecutor } from \"../../core/healing/cli-remediation-executor.js\";\nimport { isRecoverableGateFailure, isTerminalFailure } from \"../../core/statuses.js\";\nimport path from \"node:path\";\nimport fs from \"node:fs/promises\";\nimport { getWorkflowProfile, resolveWorkflowProfile } from \"../../core/workflow-profiles.js\";\nimport { ApprovalReceiptValidator } from \"../../core/sdd/approval-receipt.js\";\nimport { TechnicalPlanValidator } from \"../../core/sdd/technical-plan-validator.js\";\nimport { hashFile, sha256, writeFileAtomic } from \"../../core/sdd/workflow-artifacts.js\";\nimport { EvidenceLedger } from \"../../core/evidence/evidence-ledger.js\";\nimport { DelegationController } from \"../../core/delegation-controller.js\";\nimport { OpenCodeAdapter } from \"../../core/runtime/opencode-adapter.js\";\nimport { Finalizer } from \"../../core/finalization/finalizer.js\";\nimport { execFileSync } from \"node:child_process\";\nimport { EvidenceValidator } from \"../../core/validation/evidence-validator.js\";\n\nfunction normalizeTaskSlugFromSpec(specPath: string): string {\n const normalized = String(specPath).replaceAll(\"\\\\\", \"/\");\n const marker = \"/docs/workflows/\";\n const index = normalized.includes(marker)\n ? normalized.indexOf(marker) + marker.length\n : normalized.startsWith(\"docs/workflows/\") ? \"docs/workflows/\".length : -1;\n if (index >= 0) {\n const slug = normalized.slice(index).split(\"/\")[0];\n if (slug) return slug;\n }\n return path.basename(specPath, path.extname(specPath));\n}\n\nexport function combineValidation(evidence: any, quality: any): any {\n const statuses = [evidence.internalStatus, quality.overallStatus];\n let overallStatus = \"PASS\";\n if (statuses.includes(\"BLOCKED\")) overallStatus = \"BLOCKED\";\n else if (statuses.includes(\"FAIL\")) overallStatus = \"FAIL\";\n else if (statuses.includes(\"FAIL_DELEGATION_GATE\")) overallStatus = \"FAIL_DELEGATION_GATE\";\n else if (statuses.includes(\"FAIL_QUALITY_GATE\")) overallStatus = \"FAIL_QUALITY_GATE\";\n else if (statuses.includes(\"PASS_WITH_NOTES\")) overallStatus = \"PASS_WITH_NOTES\";\n return { overallStatus, evidence, quality };\n}\n\nexport interface runMasterOrchestratorOptions {\n cwd: string;\n specPath?: string;\n approvalPath?: string;\n override?: string;\n remediationExecutor?: any;\n}\n\ninterface DeepWorkflowContext {\n workflowId: string;\n baseSha: string;\n artifactHashes: {\n draft: string | null;\n approved: string;\n technicalPlan: string;\n };\n phaseOrder: string[];\n confirmedActors: Array<{ phase: string; requested: string; applied: string }>;\n ledger: EvidenceLedger;\n ledgerPath: string;\n controller: DelegationController;\n}\n\nfunction repositoryRelative(cwd: string, candidate: string): string {\n return path.relative(cwd, path.resolve(cwd, candidate)).replaceAll(\"\\\\\", \"/\");\n}\n\nasync function findCompatibleLedger(cwd: string, specRelativePath: string): Promise<string[]> {\n const historyDir = path.join(cwd, \".ai-workflow/history\");\n const matches: string[] = [];\n for (const file of await fs.readdir(historyDir).catch(() => [])) {\n if (!file.endsWith(\"-ledger.json\")) continue;\n try {\n const events = JSON.parse(await fs.readFile(path.join(historyDir, file), \"utf8\"));\n if (events.some((event: any) => event.eventType === \"specification_complete\" && event.data?.artifactPath === specRelativePath)) {\n matches.push(path.join(historyDir, file));\n }\n } catch {\n // Invalid ledgers are not silently attached; the canonical path is checked below.\n }\n }\n return matches;\n}\n\nasync function runDeepImplementation(\n cwd: string,\n absoluteSpecPath: string,\n specPath: string,\n approvalPath: string | undefined,\n specContent: string\n): Promise<DeepWorkflowContext> {\n if (!approvalPath) throw new Error(\"[SDD BLOCKED] DEEP resume requires --approval-path.\");\n\n const approvalValidator = new ApprovalReceiptValidator({ cwd });\n const approval = await approvalValidator.validate(approvalPath, absoluteSpecPath);\n if (!approval.valid || !approval.receipt || !approval.approvedSpecHash) {\n throw new Error(`[SDD BLOCKED] ${approval.reason || \"Approval receipt is invalid.\"}`);\n }\n\n const workflowId = approval.receipt.workflowId;\n const ledgerPath = `.ai-workflow/history/${workflowId}-ledger.json`;\n const absoluteLedgerPath = path.join(cwd, ledgerPath);\n const relativeSpecPath = repositoryRelative(cwd, specPath);\n const compatibleLedgers = await findCompatibleLedger(cwd, relativeSpecPath);\n if (compatibleLedgers.length > 1) {\n throw new Error(\"[SDD BLOCKED] Multiple ledgers claim the same approved specification.\");\n }\n if (compatibleLedgers.length === 1 && path.resolve(compatibleLedgers[0]) !== path.resolve(absoluteLedgerPath)) {\n throw new Error(\"[SDD BLOCKED] Approval workflowId conflicts with the ledger that created the specification.\");\n }\n\n const ledger = new EvidenceLedger({ cwd, workflowId });\n const loaded = await ledger.load(ledgerPath);\n if (!loaded) {\n ledger.logEvent({\n actor: \"Atlas\",\n actorType: \"control-plane\",\n observed: true,\n eventType: \"workflow_attached\",\n provenance: \"sdd-control-plane\",\n data: { specSource: \"external\", specPath: relativeSpecPath, status: \"COMPLETED\" }\n });\n }\n\n const events = ledger.getEvents();\n const approvalEvents = events.filter((event) => event.eventType === \"spec_approval_verified\");\n if (approvalEvents.length > 1) throw new Error(\"[SDD BLOCKED] Duplicate specification approval events in ledger.\");\n if (approvalEvents.length === 1 && (\n approvalEvents[0].data?.approvedHash !== approval.approvedSpecHash ||\n approvalEvents[0].data?.approvalPath !== repositoryRelative(cwd, approvalPath)\n )) throw new Error(\"[SDD BLOCKED] Existing specification approval conflicts with the supplied receipt.\");\n const nexusTerminals = events.filter((event) => event.eventType === \"specification_complete\");\n if (nexusTerminals.length > 1) throw new Error(\"[SDD BLOCKED] Duplicate Nexus terminal events in ledger.\");\n if (nexusTerminals.length === 1 && nexusTerminals[0].data?.artifactPath !== relativeSpecPath) {\n throw new Error(\"[SDD BLOCKED] Ledger specification path does not match --spec-path.\");\n }\n\n const draftHash = nexusTerminals[0]?.data?.artifactHash || null;\n const controller = new DelegationController({ cwd, ledger, adapter: new OpenCodeAdapter({ cwd }) });\n const absolutePlanPath = path.join(cwd, \"docs/workflows\", workflowId, \"technical-plan.json\");\n const relativePlanPath = repositoryRelative(cwd, absolutePlanPath);\n if (await fs.access(absolutePlanPath).then(() => true).catch(() => false)) {\n throw new Error(`[SDD BLOCKED] Refusing to overwrite existing technical plan: ${relativePlanPath}`);\n }\n\n const planValidator = new TechnicalPlanValidator({ cwd });\n const protectedPaths = [absoluteSpecPath, approvalPath, ledgerPath, absolutePlanPath, \"EVIDENCE.json\"];\n const planning = await controller.executePhase({\n phase: \"planning\",\n actor: \"Orion\",\n prompt: [\n \"Return only a JSON technical plan conforming to dist-assets/schemas/technical-plan.schema.json.\",\n \"Use explicit repository-relative file paths in filesInScope. Do not edit files or implement.\",\n \"Approved specification:\",\n specContent\n ].join(\"\\n\\n\"),\n readOnly: true,\n requireExplicitActor: true,\n onOutput: async (output) => {\n const validation = await planValidator.validateOutput(output, protectedPaths);\n if (!validation.valid || !validation.content) throw new Error(validation.reason || \"Technical plan is invalid.\");\n await writeFileAtomic(absolutePlanPath, validation.content);\n return { artifactPath: relativePlanPath, artifactHash: sha256(validation.content) };\n }\n });\n await ledger.save(ledgerPath);\n if (!planning.success || !planning.artifact?.artifactHash) {\n throw new Error(`[WORKFLOW BLOCKED] Orion planning phase failed: ${planning.error || \"unknown failure\"}`);\n }\n if (approvalEvents.length === 0) {\n ledger.logEvent({\n actor: \"Atlas\",\n actorType: \"control-plane\",\n observed: true,\n eventType: \"spec_approval_verified\",\n provenance: \"approval-receipt\",\n data: {\n approvalPath: repositoryRelative(cwd, approvalPath),\n approvedHash: approval.approvedSpecHash,\n draftHash,\n authorizationSource: approval.receipt.authorizationSource,\n status: \"COMPLETED\"\n }\n });\n await ledger.save(ledgerPath);\n }\n\n const planContent = await fs.readFile(absolutePlanPath, \"utf8\");\n const parsedPlan = JSON.parse(planContent);\n const approvedHash = approval.approvedSpecHash;\n const planHash = String(planning.artifact.artifactHash);\n const baseSha = (() => {\n try {\n return execFileSync(\"git\", [\"rev-parse\", \"HEAD\"], { cwd, encoding: \"utf8\", stdio: \"pipe\" }).trim();\n } catch {\n return \"unknown\";\n }\n })();\n const finalizer = new Finalizer({ cwd, fastTrack: false });\n const beforeImplementation = await finalizer.snapshotManager.capture();\n const allowedFiles = new Set(parsedPlan.filesInScope.map((entry: any) => String(entry.path).replaceAll(\"\\\\\", \"/\")));\n\n const implementation = await controller.executePhase({\n phase: \"implementation\",\n actor: \"Astra\",\n prompt: [\n \"Implement the approved specification using the validated technical plan.\",\n `You may modify only these files: ${[...allowedFiles].join(\", \")}`,\n \"Do not modify the specification, approval receipt, technical plan, ledger, or evidence artifacts.\",\n \"Approved specification:\",\n specContent,\n \"Validated technical plan:\",\n planContent\n ].join(\"\\n\\n\"),\n readOnly: false,\n requireExplicitActor: true,\n onOutput: async () => {\n if (await hashFile(absoluteSpecPath) !== approvedHash) throw new Error(\"Approved specification changed during Astra implementation.\");\n if (await hashFile(absolutePlanPath) !== planHash) throw new Error(\"Technical plan changed during Astra implementation.\");\n const integrity = await finalizer.verifyIntegrity(beforeImplementation);\n const workspaceStateMarkers = new Set([\"stagedDiff\", \"unstagedDiff\", \"untrackedFiles\"]);\n const changed = [...integrity.changes.added, ...integrity.changes.modified, ...integrity.changes.deleted]\n .filter((entry) => !workspaceStateMarkers.has(entry) && !/^(branch|head|indexTree):/.test(entry))\n .map((entry) => String(entry).replaceAll(\"\\\\\", \"/\"));\n const outsideScope = changed.filter((entry) => !allowedFiles.has(entry));\n if (outsideScope.length > 0) throw new Error(`Astra modified files outside the technical plan: ${outsideScope.join(\", \")}`);\n return { artifactPath: relativePlanPath, artifactHash: planHash };\n }\n });\n await ledger.save(ledgerPath);\n if (!implementation.success) {\n throw new Error(`[WORKFLOW BLOCKED] Astra implementation phase failed: ${implementation.error || \"unknown failure\"}`);\n }\n\n const phaseEvents = ledger.getEvents().filter((event) =>\n [\"specification_complete\", \"planning_complete\", \"implementation_complete\"].includes(event.eventType) && event.data?.success !== false\n );\n return {\n workflowId,\n baseSha,\n artifactHashes: { draft: draftHash, approved: approvedHash, technicalPlan: planHash },\n phaseOrder: phaseEvents.map((event) => event.data?.phase || event.eventType.replace(\"_complete\", \"\")),\n confirmedActors: phaseEvents\n .filter((event) => event.data?.runtimeAgentApplied)\n .map((event) => ({\n phase: event.data.phase || event.eventType.replace(\"_complete\", \"\"),\n requested: event.data.runtimeAgentRequested,\n applied: event.data.runtimeAgentApplied\n })),\n ledger,\n ledgerPath,\n controller\n };\n}\n\n/**\n * Coordinates branch safety, specification validation, observed validation, bounded remediation, and handoff.\n * Failed required validation can never be promoted to success.\n */\nexport async function runMasterOrchestrator({ cwd, specPath, approvalPath, override, remediationExecutor = null }: runMasterOrchestratorOptions): Promise<any> {\n if (process.env.AI_WORKFLOW_FINALIZATION_OWNER === \"execute\") {\n throw new Error(\"[NESTED EXECUTION BLOCKED] The parent execute process owns orchestration and finalization.\");\n }\n\n console.log(\"\\n[AI WORKFLOW] Starting evidence-backed orchestration...\\n\");\n\n const branchGate = new BranchGate({ memoryDir: path.join(cwd, \".ai-workflow\"), cwd });\n const taskSlug = specPath ? normalizeTaskSlugFromSpec(specPath) : \"implementation\";\n const gateResult = branchGate.check(override, { taskSlug });\n if (gateResult.blocked) throw new Error(`[GATE BLOCKED] ${gateResult.reason}`);\n console.log(`[PASS] Branch Gate: ${gateResult.recovered ? `${gateResult.branchBefore} -> ${gateResult.branch}` : `${gateResult.branch} is authorized`}.`);\n\n if (!specPath) throw new Error(\"[SDD BLOCKED] Missing --spec-path. An approved specification is required.\");\n\n const validator = new SpecValidator();\n const absoluteSpecPath = path.isAbsolute(specPath) ? specPath : path.join(cwd, specPath);\n const validation = await validator.validate(absoluteSpecPath);\n if (!validation.valid) throw new Error(`[SDD BLOCKED] Specification is not ready: ${validation.reason}`);\n\n const specTier = validation.tier || \"standard\";\n const riskLevel = specTier === \"deep\" ? \"high\" : specTier === \"tiny\" ? \"low\" : \"medium\";\n const evidencePolicy = specTier === \"deep\" ? \"required\" : \"optional\";\n const remediationLimit = specTier === \"deep\" ? 3 : specTier === \"tiny\" ? 1 : 2;\n\n const specContent = await fs.readFile(absoluteSpecPath, \"utf8\");\n const workflowProfile = resolveWorkflowProfile({ request: specContent });\n const profileDefinition = getWorkflowProfile(workflowProfile);\n console.log(`[PASS] Specification: ${specTier.toUpperCase()} spec is APPROVED.`);\n console.log(`[PROFILE] ${workflowProfile} -> ${profileDefinition.owner}; skills: ${profileDefinition.skills.join(\", \") || \"none\"}.`);\n\n const deepContext = specTier === \"deep\"\n ? await runDeepImplementation(cwd, absoluteSpecPath, specPath, approvalPath, specContent)\n : null;\n\n const validateWorkflow = async () => {\n const evidence = await runCollectEvidence({\n cwd,\n exitOnError: false,\n taskSlug,\n evidencePolicy,\n profile: workflowProfile,\n branchRecovery: gateResult.recovered ? `${gateResult.branchBefore} -> ${gateResult.branch}` : \"NOT_REQUIRED\",\n workflowEvidence: deepContext ? {\n workflowId: deepContext.workflowId,\n baseSha: deepContext.baseSha,\n artifactHashes: deepContext.artifactHashes,\n phaseOrder: deepContext.phaseOrder,\n confirmedActors: deepContext.confirmedActors\n } : null\n });\n const quality = await new QualityGuard({ cwd, taskSlug, evidencePolicy, riskLevel }).verify();\n const combined = combineValidation(evidence, quality);\n if (deepContext) {\n const workflowEvidence = await new EvidenceValidator({ cwd, requireWorkflowEvidence: true }).validate();\n if (!workflowEvidence.valid) {\n combined.overallStatus = \"FAIL_QUALITY_GATE\";\n combined.reason = workflowEvidence.reason;\n }\n }\n return combined;\n };\n\n const observedValidate = async () => deepContext\n ? await deepContext.controller.validate(taskSlug, workflowProfile, validateWorkflow, evidencePolicy)\n : await validateWorkflow();\n\n let result = await observedValidate();\n if (deepContext) await deepContext.ledger.save(deepContext.ledgerPath);\n if (isRecoverableGateFailure(result.overallStatus)) {\n console.log(`\\n[REMEDIATION REQUIRED] ${result.overallStatus}. Starting bounded remediation (limit: ${remediationLimit}).`);\n // Use the provided executor (programmatic API) or fall back to the default CLI executor.\n // The CLI executor re-runs failed npm scripts; it does not modify source code.\n const executor = typeof remediationExecutor === \"function\"\n ? remediationExecutor\n : createCliRemediationExecutor(cwd);\n const healer = new HealerEngine({ cwd, remediationLimit, taskSlug });\n result = await healer.run({ initialResult: result, validate: observedValidate, remediate: executor });\n if (deepContext) await deepContext.ledger.save(deepContext.ledgerPath);\n }\n\n if (isTerminalFailure(result.overallStatus)) {\n throw new Error(`[WORKFLOW BLOCKED] ${result.overallStatus}: ${result.reason || \"Validation could not be resolved safely.\"}`);\n }\n if (isRecoverableGateFailure(result.overallStatus)) {\n throw new Error(`[WORKFLOW BLOCKED] Unresolved gate status after remediation: ${result.overallStatus}`);\n }\n\n console.log(\"\\n--- Final Handoff ---\");\n const handoffEngine = new HandoffEngine({ cwd });\n const handoffPath = await handoffEngine.generate({\n taskId: path.basename(specPath, \".md\"),\n status: result.overallStatus,\n specPaths: [specPath],\n evidence: result.evidence,\n nextActions: `Profile ${workflowProfile}. Observed validation completed. Ready for review or explicitly approved release actions.`\n });\n\n console.log(`\\n[AI WORKFLOW COMPLETE] ${result.overallStatus}`);\n if (result.remediation?.attempts) console.log(`Remediation attempts: ${result.remediation.attempts}`);\n console.log(`Handoff Packet: ${path.relative(cwd, handoffPath)}\\n`);\n return { ...result, workflowProfile, workflowId: deepContext?.workflowId || null };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport Ajv from \"ajv\";\nimport addFormats from \"ajv-formats\";\nimport { hashFile } from \"./workflow-artifacts.js\";\nimport { getPackageRoot } from \"../package-assets.js\";\n\nexport interface ApprovalReceipt {\n workflowId: string;\n approvedSpecHash: string;\n approvedBy: string;\n approvedAt: string;\n authorizationSource: string;\n}\n\nexport interface ApprovalValidationResult {\n valid: boolean;\n reason?: string;\n receipt?: ApprovalReceipt;\n approvedSpecHash?: string;\n}\n\nexport class ApprovalReceiptValidator {\n cwd: string;\n\n constructor({ cwd = process.cwd() }: { cwd?: string } = {}) {\n this.cwd = path.resolve(cwd);\n }\n\n async validate(receiptPath: string, specPath: string, expectedWorkflowId?: string): Promise<ApprovalValidationResult> {\n const absoluteReceiptPath = path.resolve(this.cwd, receiptPath);\n if (absoluteReceiptPath !== this.cwd && !absoluteReceiptPath.startsWith(`${this.cwd}${path.sep}`)) {\n return { valid: false, reason: \"Approval receipt must be inside the repository.\" };\n }\n\n try {\n const stat = await fs.lstat(absoluteReceiptPath);\n if (!stat.isFile() || stat.isSymbolicLink()) {\n return { valid: false, reason: \"Approval receipt must be a regular, non-symlink file.\" };\n }\n } catch {\n return { valid: false, reason: `Approval receipt not found: ${receiptPath}` };\n }\n\n let receipt: ApprovalReceipt;\n try {\n receipt = JSON.parse(await fs.readFile(absoluteReceiptPath, \"utf8\"));\n const root = getPackageRoot();\n const schema = JSON.parse(await fs.readFile(path.join(root, \"dist-assets/schemas/approval-receipt.schema.json\"), \"utf8\"));\n const ajv = new Ajv({ allErrors: true });\n addFormats(ajv);\n const validateSchema = ajv.compile(schema);\n if (!validateSchema(receipt)) {\n const errors = (validateSchema.errors || []).map((error) => `${error.instancePath} ${error.message}`).join(\", \");\n return { valid: false, reason: `Approval receipt schema violation: ${errors}` };\n }\n } catch (error: any) {\n return { valid: false, reason: `Approval receipt validation failed: ${error.message}` };\n }\n\n if (expectedWorkflowId && receipt.workflowId !== expectedWorkflowId) {\n return { valid: false, reason: `Approval receipt workflowId '${receipt.workflowId}' does not match '${expectedWorkflowId}'.` };\n }\n\n const approvedSpecHash = await hashFile(specPath);\n if (receipt.approvedSpecHash !== approvedSpecHash) {\n return { valid: false, reason: \"Approval receipt hash does not match the approved specification bytes.\" };\n }\n\n return { valid: true, receipt, approvedSpecHash };\n }\n}\n","import { createHash } from \"node:crypto\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nexport function sha256(content: string | Buffer): string {\n return createHash(\"sha256\").update(content).digest(\"hex\");\n}\n\nexport async function hashFile(filePath: string): Promise<string> {\n return sha256(await fs.readFile(filePath));\n}\n\nexport async function writeFileAtomic(filePath: string, content: string): Promise<void> {\n await fs.mkdir(path.dirname(filePath), { recursive: true });\n const temporaryPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;\n try {\n await fs.writeFile(temporaryPath, content, { encoding: \"utf8\", flag: \"wx\" });\n await fs.rename(temporaryPath, filePath);\n } catch (error) {\n await fs.rm(temporaryPath, { force: true }).catch(() => {});\n throw error;\n }\n}\n\nexport function stripMarkdownFence(content: string): string {\n const trimmed = content.trim();\n const match = trimmed.match(/^```(?:markdown|md|json)?\\s*\\n([\\s\\S]*?)\\n```$/i);\n return (match ? match[1] : trimmed).trim() + \"\\n\";\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport Ajv from \"ajv\";\nimport { stripMarkdownFence } from \"./workflow-artifacts.js\";\nimport { getPackageRoot } from \"../package-assets.js\";\n\nexport interface TechnicalPlanFile {\n path: string;\n reason: string;\n}\n\nexport interface TechnicalPlan {\n title: string;\n architectureSummary: string;\n filesInScope: TechnicalPlanFile[];\n filesOutOfScope: TechnicalPlanFile[];\n implementationSteps: string[];\n dependencies: string[];\n risks: string[];\n tradeoffs: string[];\n validationPlan: string[];\n rollbackPlan: string[];\n}\n\nexport interface TechnicalPlanValidationResult {\n valid: boolean;\n reason?: string;\n plan?: TechnicalPlan;\n content?: string;\n}\n\nfunction isContained(root: string, candidate: string): boolean {\n return candidate === root || candidate.startsWith(`${root}${path.sep}`);\n}\n\nexport class TechnicalPlanValidator {\n cwd: string;\n\n constructor({ cwd = process.cwd() }: { cwd?: string } = {}) {\n this.cwd = path.resolve(cwd);\n }\n\n private async validateScopedPath(candidate: string, forbiddenPaths: Set<string>): Promise<string | null> {\n if (path.isAbsolute(candidate)) return `Absolute path is not allowed: '${candidate}'.`;\n const normalized = candidate.replaceAll(\"\\\\\", \"/\");\n if (!normalized || normalized.split(\"/\").some((part) => part === \"\" || part === \".\" || part === \"..\")) {\n return `Path must be normalized without empty, '.' or '..' segments: '${candidate}'.`;\n }\n if (normalized === \".git\" || normalized.startsWith(\".git/\") || normalized === \".ai-workflow\" || normalized.startsWith(\".ai-workflow/\")) {\n return `Workflow control path is out of implementation scope: '${candidate}'.`;\n }\n const conflictsWithProtectedPath = [...forbiddenPaths].some((protectedPath) =>\n normalized === protectedPath ||\n normalized.startsWith(`${protectedPath}/`) ||\n protectedPath.startsWith(`${normalized}/`)\n );\n if (normalized === \"EVIDENCE.json\" || conflictsWithProtectedPath) {\n return `Protected workflow artifact is out of implementation scope: '${candidate}'.`;\n }\n\n const absolute = path.resolve(this.cwd, normalized);\n if (!isContained(this.cwd, absolute)) return `Path escapes repository: '${candidate}'.`;\n\n let cursor = this.cwd;\n for (const part of normalized.split(\"/\")) {\n cursor = path.join(cursor, part);\n try {\n const stat = await fs.lstat(cursor);\n if (cursor === absolute && stat.isDirectory()) {\n return `filesInScope must name explicit files, not a directory: '${candidate}'.`;\n }\n if (stat.isSymbolicLink()) {\n const resolved = await fs.realpath(cursor);\n if (!isContained(this.cwd, resolved)) return `Symlink escapes repository: '${candidate}'.`;\n cursor = resolved;\n }\n } catch (error: any) {\n if (error.code !== \"ENOENT\") return `Cannot inspect scoped path '${candidate}': ${error.message}`;\n break;\n }\n }\n return null;\n }\n\n async validateOutput(output: string, protectedPaths: string[] = []): Promise<TechnicalPlanValidationResult> {\n let plan: TechnicalPlan;\n try {\n plan = JSON.parse(stripMarkdownFence(output));\n } catch (error: any) {\n return { valid: false, reason: `Technical plan is not valid JSON: ${error.message}` };\n }\n\n try {\n const schema = JSON.parse(await fs.readFile(path.join(getPackageRoot(), \"dist-assets/schemas/technical-plan.schema.json\"), \"utf8\"));\n const validateSchema = new Ajv({ allErrors: true }).compile(schema);\n if (!validateSchema(plan)) {\n const errors = (validateSchema.errors || []).map((error) => `${error.instancePath} ${error.message}`).join(\", \");\n return { valid: false, reason: `Technical plan schema violation: ${errors}` };\n }\n } catch (error: any) {\n return { valid: false, reason: `Technical plan schema validation failed: ${error.message}` };\n }\n\n if (plan.filesInScope.length === 0) {\n return { valid: false, reason: \"Technical plan filesInScope must not be empty.\" };\n }\n\n const forbidden = new Set(protectedPaths.map((entry) => path.relative(this.cwd, path.resolve(this.cwd, entry)).replaceAll(\"\\\\\", \"/\")));\n for (const entry of plan.filesInScope) {\n const reason = await this.validateScopedPath(entry.path, forbidden);\n if (reason) return { valid: false, reason };\n }\n\n const content = `${JSON.stringify(plan, null, 2)}\\n`;\n return { valid: true, plan, content };\n }\n}\n","import { OpenCodeAdapter } from \"../runtime/opencode-adapter.js\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { execSync } from \"node:child_process\";\nimport { EvidenceLedger } from \"../evidence/evidence-ledger.js\";\n\nexport function createRuntimeRemediationExecutor(cwd: string, ledger: EvidenceLedger | null = null) {\n const adapter = new OpenCodeAdapter({ cwd });\n\n function getChangedFiles(): string[] {\n try {\n const output = execSync(\"git status --short\", { cwd, encoding: \"utf8\" });\n return output\n .split(\"\\n\")\n .filter(Boolean)\n .map((line) => line.slice(3).trim())\n .filter(Boolean);\n } catch {\n return [];\n }\n }\n\n return async function runtimeRemediationExecutor({\n attempt,\n maxAttempts,\n mode,\n affectedChecks,\n requestPath,\n result\n }: {\n attempt: number;\n maxAttempts: number;\n mode: string;\n affectedChecks: string[];\n requestPath: string;\n result: any;\n }): Promise<{ applied: boolean; changedFiles?: string[]; evidenceAdded?: string[]; reason?: string }> {\n console.log(`\\n[HEALER] Running Runtime/Phoenix Structural Remediation [Attempt ${attempt}/${maxAttempts}]`);\n console.log(`[HEALER] Affected checks: ${affectedChecks.join(\", \")}`);\n\n if (ledger) {\n ledger.logEvent({\n actor: \"Phoenix\",\n actorType: \"runtime-agent\",\n observed: true,\n runtime: \"opencode\",\n eventType: \"remediation_start\",\n provenance: \"opencode-adapter\",\n data: {\n attempt,\n affectedChecks,\n event: \"remediation.started\"\n }\n });\n }\n\n let requestContent: any = {};\n try {\n requestContent = JSON.parse(await fs.readFile(requestPath, \"utf8\"));\n } catch {\n // ignore/fallback\n }\n\n const filesBefore = getChangedFiles();\n const fileContentsBefore: Record<string, string | null> = {};\n for (const file of filesBefore) {\n try {\n fileContentsBefore[file] = await fs.readFile(path.join(cwd, file), \"utf8\");\n } catch {\n fileContentsBefore[file] = null;\n }\n }\n \n // Extract concrete command outputs for failing checks\n const failedCommands = (result?.evidence?.commands || [])\n .filter((cmd: any) => [\"FAIL\", \"BLOCKED\"].includes(cmd.status));\n \n let concreteOutput = \"\";\n if (failedCommands.length > 0) {\n concreteOutput = failedCommands.map((cmd: any) => {\n return `Command: ${cmd.name} (${Array.isArray(cmd.command) ? cmd.command.join(\" \") : cmd.command})\nExit Code: ${cmd.exitCode}\nOutput:\n${cmd.output}`;\n }).join(\"\\n\\n\");\n } else {\n concreteOutput = JSON.stringify(result?.quality || result || {}, null, 2);\n }\n\n const promptMsg = `We are in remediation mode (attempt ${attempt}/${maxAttempts}).\nThe following validation checks have failed:\n${affectedChecks.join(\", \")}\n\nDetails of the failure:\n\\`\\`\\`\n${concreteOutput}\n\\`\\`\\`\n\nPlease inspect the code, identify the root cause of these failures (e.g. failing tests, syntax issues, build errors), and write a correction to the relevant files in the workspace to make the tests/validations pass.`;\n\n console.log(`[HEALER] Sending structural healing request to Phoenix agent...`);\n const runResult = await adapter.execute(promptMsg, {\n agent: \"Phoenix\"\n });\n\n const filesAfter = getChangedFiles();\n const changedFiles: string[] = [];\n for (const file of filesAfter) {\n if (!filesBefore.includes(file)) {\n changedFiles.push(file);\n } else {\n try {\n const contentAfter = await fs.readFile(path.join(cwd, file), \"utf8\");\n if (contentAfter !== fileContentsBefore[file]) {\n changedFiles.push(file);\n }\n } catch {\n if (fileContentsBefore[file] !== null) {\n changedFiles.push(file);\n }\n }\n }\n }\n const success = runResult.success && changedFiles.length > 0;\n\n if (!runResult.success) {\n console.log(`[HEALER] Phoenix remediation failed: ${runResult.error || \"Unknown error\"}`);\n return {\n applied: false,\n reason: `Phoenix runtime execution failed: ${runResult.error || \"Unknown error\"}`\n };\n }\n\n if (changedFiles.length === 0) {\n console.log(`[HEALER] Phoenix execution succeeded but no files were modified.`);\n return {\n applied: false,\n reason: \"Phoenix runtime executed but did not modify any files in the workspace.\"\n };\n }\n\n console.log(`[HEALER] Phoenix successfully executed remediation commands.`);\n console.log(`[HEALER] Files modified: ${changedFiles.join(\", \")}`);\n\n return {\n applied: true,\n changedFiles,\n evidenceAdded: [\"phoenix-healing-run\"]\n };\n };\n}\n","import { RequestClassifier, RequestClassifierResult } from \"../../core/request-classifier.js\";\nimport { ExecutionPlanner, ExecutionPlan } from \"../../core/execution-planner.js\";\nimport { WorkflowStateMachine } from \"../../core/workflow-state-machine.js\";\nimport { BranchGate } from \"../../core/gates/branch-gate.js\";\nimport { EvidenceLedger } from \"../../core/evidence/evidence-ledger.js\";\nimport { DelegationController } from \"../../core/delegation-controller.js\";\nimport { OpenCodeAdapter } from \"../../core/runtime/opencode-adapter.js\";\nimport { runCollectEvidence } from \"./collect-evidence.js\";\nimport { QualityGuard } from \"../../core/validation/quality-guard.js\";\nimport { HandoffEngine } from \"../../core/handoff/handoff-engine.js\";\nimport { HealerEngine } from \"../../core/healing/healer-engine.js\";\nimport { createRuntimeRemediationExecutor } from \"../../core/healing/runtime-remediation-executor.js\";\nimport { isRecoverableGateFailure, isTerminalFailure } from \"../../core/statuses.js\";\nimport { Finalizer, VerifyIntegrityResult } from \"../../core/finalization/finalizer.js\";\nimport { WorkspaceSnapshotData } from \"../../core/finalization/workspace-snapshot.js\";\nimport { DeliveryOutcome, parseDeliveryOutcomeClaim } from \"../../core/completion-contract.js\";\nimport { DeliveryDecisionEngine } from \"../../core/validation/delivery-decision-engine.js\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { execSync } from \"node:child_process\";\nimport { SpecValidator } from \"../../core/sdd/validator.js\";\nimport { sha256, stripMarkdownFence, writeFileAtomic } from \"../../core/sdd/workflow-artifacts.js\";\n\n/** Snapshot of workspace state before/after read-only execution. */\ninterface ReadOnlyWorkspaceState {\n snapshot: { files: Record<string, { sha256: string }> };\n head: string;\n branch: string;\n indexTree: string;\n porcelainStatus: string;\n}\n\n/** Combined result from evidence collection and quality guard. */\ninterface ValidationResult {\n overallStatus: string;\n evidence: Record<string, unknown>;\n quality: Record<string, unknown>;\n}\n\n/** Result returned by BranchGate.check(). */\ninterface BranchGateResult {\n blocked: boolean;\n reason: string;\n branch: string;\n branchBefore: string;\n recovered: boolean;\n}\n\nconst INTEGRITY_METADATA_CHANGES = new Set([\"stagedDiff\", \"unstagedDiff\", \"untrackedFiles\"]);\n\n/** Returns only repository paths changed after the execution baseline. */\nexport function extractDeliveryChangedFiles(integrity: VerifyIntegrityResult): string[] {\n const files = new Set<string>();\n\n for (const file of integrity.changes.added) files.add(file);\n for (const file of integrity.changes.deleted) files.add(file);\n for (const change of integrity.changes.modified) {\n if (change.startsWith(\"branch:\") || change.startsWith(\"head:\")) continue;\n if (INTEGRITY_METADATA_CHANGES.has(change)) continue;\n if (change.startsWith(\"indexTree:\")) continue;\n files.add(change);\n }\n\n return [...files].sort();\n}\n\nasync function captureReadOnlyState(cwd: string, fastTrack = false) {\n const finalizer = new Finalizer({ cwd, fastTrack });\n const snapshot = await finalizer.snapshotManager.capture();\n \n const execGit = (args: string) => {\n try {\n return execSync(`git ${args}`, { cwd, encoding: \"utf8\", stdio: \"pipe\" }).trim();\n } catch {\n return \"\";\n }\n };\n\n const head = execGit(\"rev-parse HEAD\");\n const branch = execGit(\"rev-parse --abbrev-ref HEAD\");\n const indexTree = execGit(\"write-tree\");\n const porcelainStatus = execGit(\"status --porcelain\");\n\n return {\n snapshot,\n head,\n branch,\n indexTree,\n porcelainStatus\n };\n}\n\nfunction compareReadOnlyState(before: ReadOnlyWorkspaceState, after: ReadOnlyWorkspaceState) {\n const violations: string[] = [];\n\n // 1. Compare branch\n if (before.branch !== after.branch) {\n violations.push(`Branch changed from '${before.branch}' to '${after.branch}'`);\n }\n\n // 2. Compare HEAD\n if (before.head !== after.head) {\n violations.push(`Git HEAD changed from '${before.head}' to '${after.head}' (commit or reset made inside read-only task)`);\n }\n\n // 3. Compare index tree\n if (before.indexTree !== after.indexTree) {\n violations.push(`Git index tree changed from '${before.indexTree}' to '${after.indexTree}'`);\n }\n\n // 4. Compare porcelain status\n if (before.porcelainStatus !== after.porcelainStatus) {\n violations.push(`Git status changed. Before:\\n${before.porcelainStatus}\\nAfter:\\n${after.porcelainStatus}`);\n }\n\n // 5. Compare workspace files (SHA-256 hashes)\n const beforeFiles = before.snapshot.files || {};\n const afterFiles = after.snapshot.files || {};\n\n for (const [file, info] of Object.entries(afterFiles)) {\n const prevInfo = beforeFiles[file];\n if (!prevInfo) {\n violations.push(`File added: ${file}`);\n } else if (prevInfo.sha256 !== (info as any).sha256) {\n violations.push(`File content modified: ${file}`);\n }\n }\n for (const file of Object.keys(beforeFiles)) {\n if (!afterFiles[file]) {\n violations.push(`File deleted: ${file}`);\n }\n }\n\n return violations;\n}\n\nfunction slugify(text: string): string {\n return text\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 32) || \"task\";\n}\n\nfunction combineValidation(evidence: Record<string, unknown>, quality: Record<string, unknown>): ValidationResult {\n const statuses = [evidence.internalStatus, quality.overallStatus];\n let overallStatus = \"PASS\";\n if (statuses.includes(\"BLOCKED\")) overallStatus = \"BLOCKED\";\n else if (statuses.includes(\"FAIL\")) overallStatus = \"FAIL\";\n else if (statuses.includes(\"FAIL_DELEGATION_GATE\")) overallStatus = \"FAIL_DELEGATION_GATE\";\n else if (statuses.includes(\"FAIL_QUALITY_GATE\")) overallStatus = \"FAIL_QUALITY_GATE\";\n else if (statuses.includes(\"PASS_WITH_NOTES\")) overallStatus = \"PASS_WITH_NOTES\";\n return { overallStatus, evidence, quality };\n}\n\nexport interface ExecuteOptions {\n cwd: string;\n naturalRequest: string;\n taskSlug?: string;\n}\n\n/**\n * classifyAndPlanExecution - Intake analysis and contract formulation.\n */\nasync function classifyAndPlanExecution(\n naturalRequest: string,\n cwd: string,\n taskSlug: string,\n delegationController: DelegationController,\n stateMachine: WorkflowStateMachine\n): Promise<{ plan: ExecutionPlan; classification: RequestClassifierResult }> {\n const classifier = new RequestClassifier();\n const classification = classifier.classify(naturalRequest, { cwd });\n console.log(`[CLASSIFIED] Intent: ${classification.intent}, Mode: ${classification.mode}, Profile: ${classification.profile}`);\n stateMachine.transitionTo(\"CLASSIFIED\");\n\n await delegationController.route(naturalRequest, classification);\n\n const routingDecision = classification.routingDecision || {};\n if (routingDecision.permissionDecision === \"blocked\") {\n stateMachine.transitionTo(\"BLOCKED\");\n throw new Error(`[ROUTE BLOCKED] ${routingDecision.reason}`);\n }\n if (routingDecision.permissionDecision === \"rerouted\") {\n console.log(`[REROUTED] ${routingDecision.reason}`);\n }\n\n const planner = new ExecutionPlanner({ cwd });\n const plan = planner.plan(classification, taskSlug);\n console.log(`[PLANNED] Owner: ${plan.owner}, Remediation limit: ${plan.remediationLimit}`);\n stateMachine.transitionTo(\"PLANNED\");\n\n if (classification.requestUnderstanding.deliveryMode === \"workspace\") {\n const deliveryDecision = await new DeliveryDecisionEngine({ cwd }).determineDecision({ userRequest: naturalRequest });\n if (deliveryDecision.decision.startsWith(\"BLOCK_\")) {\n stateMachine.transitionTo(\"BLOCKED\");\n throw new Error(`[CONTEXT BLOCKED] NEEDS_CLARIFICATION: ${deliveryDecision.reason || deliveryDecision.decision}`);\n }\n }\n\n return { plan, classification };\n}\n\n/**\n * runBranchGate - Authorizes changes within the branch lifecycle.\n */\nfunction runBranchGate(plan: ExecutionPlan, taskSlug: string, cwd: string, stateMachine: WorkflowStateMachine, branchGate: BranchGate): BranchGateResult {\n const gateResult = branchGate.check(\"\", {\n taskSlug,\n readOnly: !plan.branchNeeded\n });\n\n if (gateResult.blocked) {\n stateMachine.transitionTo(\"BLOCKED\");\n throw new Error(`[GATE BLOCKED] ${gateResult.reason}`);\n }\n console.log(`[PASS] Branch Gate: ${gateResult.recovered ? `${gateResult.branchBefore} -> ${gateResult.branch}` : `${gateResult.branch} is authorized`}.`);\n stateMachine.transitionTo(\"BRANCH_READY\");\n return gateResult;\n}\n\n/**\n * createSpecIfRequired - Implements Spec-Driven Development gate.\n */\nasync function createSpecIfRequired(plan: ExecutionPlan, classification: RequestClassifierResult, taskSlug: string, cwd: string): Promise<void> {\n if (plan.specPath) {\n const fullSpecPath = path.join(cwd, plan.specPath);\n const specExists = await fs.access(fullSpecPath).then(() => true).catch(() => false);\n if (!specExists) {\n await fs.mkdir(path.dirname(fullSpecPath), { recursive: true });\n const specTemplatePath = path.join(cwd, \".ai-workflow/templates/specs/standard.md\");\n const templateContent = await fs.readFile(specTemplatePath, \"utf8\").catch(() => {\n return `# [STANDARD] Specification: ${classification.request}\\n\\n## Metadata\\n\\n- ID: SPEC-${taskSlug}\\n- Author: Spec-Engineer\\n- Status: DRAFT\\n- Date: ${new Date().toISOString().split(\"T\")[0]}\\n\\n## Functional Requirements\\n\\n- ${classification.request}\\n\\n## Technical Implementation Plan\\n\\n### Files to Create/Modify\\n\\n- \\`src/index.js\\`\\n\\n## Acceptance Criteria\\n\\n- [ ] Implemented successfully\\n\\n## Testing Strategy\\n\\n- [ ] Behavior tests pass`;\n });\n await fs.writeFile(fullSpecPath, templateContent);\n console.log(`[EXECUTE] Created DRAFT specification template at: ${plan.specPath}`);\n }\n }\n}\n\nasync function runDeepSpecificationCheckpoint(\n plan: ExecutionPlan,\n classification: RequestClassifierResult,\n taskSlug: string,\n cwd: string,\n delegationController: DelegationController,\n stateMachine: WorkflowStateMachine\n): Promise<any> {\n if (!plan.specPath) throw new Error(\"[SDD BLOCKED] Required specification path was not planned.\");\n const absoluteSpecPath = path.resolve(cwd, plan.specPath);\n const relativeSpecPath = path.relative(cwd, absoluteSpecPath).replaceAll(\"\\\\\", \"/\");\n if (relativeSpecPath.startsWith(\"../\") || path.isAbsolute(relativeSpecPath)) {\n throw new Error(\"[SDD BLOCKED] Planned specification path escapes the repository.\");\n }\n if (await fs.access(absoluteSpecPath).then(() => true).catch(() => false)) {\n throw new Error(`[SDD BLOCKED] Refusing to overwrite existing specification: ${relativeSpecPath}`);\n }\n\n const approvalPath = `.ai-workflow/approvals/${taskSlug}.json`;\n const validator = new SpecValidator();\n stateMachine.transitionTo(\"DELEGATED\");\n\n const prompt = [\n \"Produce only the complete Markdown for a [DEEP] specification.\",\n \"The Metadata Status must be exactly DRAFT. Include concrete acceptance criteria as unchecked checkboxes.\",\n \"Do not approve the specification, create a receipt, edit files, or implement code.\",\n `Workflow ID: ${taskSlug}`,\n `Request: ${classification.request}`\n ].join(\"\\n\");\n\n const phaseResult = await delegationController.executePhase({\n phase: \"specification\",\n actor: \"Nexus\",\n prompt,\n readOnly: true,\n requireExplicitActor: true,\n onOutput: async (output) => {\n const content = stripMarkdownFence(output);\n const validation = validator.validateDraftContent(content);\n if (!validation.valid) throw new Error(`Nexus DRAFT rejected: ${validation.reason}`);\n await writeFileAtomic(absoluteSpecPath, content);\n return { artifactPath: relativeSpecPath, artifactHash: sha256(content), draftHash: sha256(content) };\n }\n });\n\n if (!phaseResult.success) {\n stateMachine.transitionTo(\"BLOCKED\");\n throw new Error(`[SDD BLOCKED] Nexus specification phase failed: ${phaseResult.error || \"unknown failure\"}`);\n }\n\n const draftHash = String(phaseResult.artifact?.artifactHash || \"\");\n delegationController.ledger?.logEvent({\n actor: \"Atlas\",\n actorType: \"control-plane\",\n observed: true,\n eventType: \"approval_checkpoint\",\n provenance: \"sdd-control-plane\",\n data: {\n specSource: \"nexus\",\n specPath: relativeSpecPath,\n approvalPath,\n draftHash,\n approvedHash: null,\n planHash: null,\n status: \"BLOCKED\",\n reason: \"SDD APPROVAL REQUIRED\"\n }\n });\n stateMachine.transitionTo(\"BLOCKED\");\n\n const resumeCommand = `aw run --spec-path=${relativeSpecPath} --approval-path=${approvalPath}`;\n console.log(`\\n[BLOCKED] SDD APPROVAL REQUIRED`);\n console.log(`Specification: ${relativeSpecPath}`);\n console.log(`Resume: ${resumeCommand}\\n`);\n return {\n overallStatus: \"BLOCKED\",\n reason: \"SDD APPROVAL REQUIRED\",\n checkpoint: \"approval\",\n exitCode: 2,\n workflowId: taskSlug,\n specPath: relativeSpecPath,\n approvalPath,\n draftHash,\n resumeCommand,\n stateHistory: stateMachine.getHistory()\n };\n}\n\n/**\n * runImplementation - Delegations to the implementation engine.\n */\nasync function runImplementation(\n plan: ExecutionPlan,\n classification: RequestClassifierResult,\n delegationController: DelegationController,\n stateMachine: WorkflowStateMachine,\n fastTrack: boolean = false\n): Promise<any> {\n stateMachine.transitionTo(\"DELEGATED\");\n stateMachine.transitionTo(\"IMPLEMENTING\");\n\n let promptMsg = classification.request;\n if (plan.specPath) {\n promptMsg = `Please review and fill in the specification file at: ${plan.specPath}. Make sure to change the Status field to 'APPROVED' in the Metadata section, and then implement the behavior described.`;\n }\n\n if (plan.branchNeeded) {\n promptMsg = [\n promptMsg,\n \"\",\n \"AIWK delivery contract:\",\n \"- Work in the active repository; printed code is not a substitute for workspace delivery.\",\n \"- Keep the diff scoped and run proportional validation.\",\n \"- The parent already satisfied the branch gate. Do not repeat branch/status checks unless a new safety concern makes them necessary.\",\n \"- Documentation, screenshots, Sage review, Phoenix remediation, and persisted evidence are conditional; do not create them unless the request, risk policy, or an observed finding requires them.\",\n \"- Do not run collect-evidence, create a handoff, or finalize this workflow; the parent execute process is the sole finalization owner.\",\n \"- End with exactly one machine-readable line: AIWK_DELIVERY_OUTCOME: CHANGED or AIWK_DELIVERY_OUTCOME: ALREADY_SATISFIED.\",\n \"- Use ALREADY_SATISFIED only when inspection and relevant validation prove that no repository change is needed.\"\n ].join(\"\\n\");\n }\n\n const runResult = await delegationController.implement(promptMsg, plan.owner, { readOnly: !plan.branchNeeded, fastTrack, orchestratedChild: true });\n\n if (!runResult.success) {\n console.error(`[EXECUTE] OpenCode adapter execution reported failure: ${runResult.error || \"Unknown error\"}`);\n stateMachine.transitionTo(\"BLOCKED\");\n throw new Error(`[WORKFLOW BLOCKED] OpenCode runtime execution failed: ${runResult.error || \"Unknown error\"}`);\n }\n return runResult;\n}\n\n/**\n * runReadOnlyConfinementCheck - Asserts read-only execution constraints.\n */\nasync function runReadOnlyConfinementCheck(readOnlyStateBefore: ReadOnlyWorkspaceState, cwd: string, stateMachine: WorkflowStateMachine, fastTrack = false): Promise<void> {\n const readOnlyStateAfter = await captureReadOnlyState(cwd, fastTrack);\n const violations = compareReadOnlyState(readOnlyStateBefore, readOnlyStateAfter);\n if (violations.length > 0) {\n console.error(`[EXECUTE] Read-only confinement violation detected:`);\n for (const v of violations) {\n console.error(` - ${v}`);\n }\n stateMachine.transitionTo(\"BLOCKED\");\n throw new Error(`[WORKFLOW BLOCKED] Read-only confinement violation: files were written/modified, index or commits modified: \\n${violations.join(\"\\n\")}`);\n }\n}\n\n/**\n * runValidation - Resolves evidence validation contracts.\n */\nasync function runValidation(\n plan: ExecutionPlan,\n taskSlug: string,\n cwd: string,\n gateResult: BranchGateResult,\n naturalRequest: string,\n claimedOutcome: \"CHANGED\" | \"ALREADY_SATISFIED\" | null,\n deliveryBaseline: WorkspaceSnapshotData,\n deliveryFinalizer: Finalizer,\n delegationController: DelegationController,\n stateMachine: WorkflowStateMachine\n): Promise<{ result: ValidationResult; validateWorkflow: () => Promise<ValidationResult> }> {\n stateMachine.transitionTo(\"VALIDATING\");\n\n const validateWorkflow = async () => {\n const deliveryIntegrity = await deliveryFinalizer.verifyIntegrity(deliveryBaseline);\n const deliveryChangedFiles = extractDeliveryChangedFiles(deliveryIntegrity);\n const deliveryAddedFiles = deliveryIntegrity.changes.added.filter((file) => deliveryChangedFiles.includes(file));\n const deliveryDeletedFiles = deliveryIntegrity.changes.deleted.filter((file) => deliveryChangedFiles.includes(file));\n const evidence = await runCollectEvidence({\n cwd,\n exitOnError: false,\n taskSlug,\n evidencePolicy: plan.evidencePolicy,\n profile: plan.profile,\n branchRecovery: gateResult.recovered ? `${gateResult.branchBefore} -> ${gateResult.branch}` : \"NOT_REQUIRED\",\n userRequest: naturalRequest,\n explicitApprovals: process.env.AI_WORKFLOW_APPROVALS ? process.env.AI_WORKFLOW_APPROVALS.split(\",\").map(a => a.trim()) : [],\n claimedOutcome,\n deliveryChangedFiles,\n deliveryAddedFiles,\n deliveryDeletedFiles\n });\n const quality = await new QualityGuard({\n cwd,\n taskSlug,\n evidencePolicy: plan.evidencePolicy,\n riskLevel: plan.riskLevel\n }).verify();\n return combineValidation(evidence, quality);\n };\n\n const result = await delegationController.validate(taskSlug, plan.profile, validateWorkflow, plan.evidencePolicy);\n return { result, validateWorkflow };\n}\n\n/**\n * runBoundedRemediation - Heals gate violations.\n */\nasync function runBoundedRemediation(\n plan: any,\n taskSlug: string,\n cwd: string,\n initialResult: any,\n validateWorkflow: () => Promise<any>,\n ledger: EvidenceLedger,\n delegationController: DelegationController,\n stateMachine: WorkflowStateMachine,\n checkBranchSafety: () => void,\n updateSnapshot: () => Promise<void>\n): Promise<any> {\n if (!isRecoverableGateFailure(initialResult.overallStatus)) {\n return initialResult;\n }\n\n console.log(`\\n[REMEDIATION REQUIRED] ${initialResult.overallStatus}. Starting bounded remediation (limit: ${plan.remediationLimit}).`);\n const executor = createRuntimeRemediationExecutor(cwd, ledger);\n const healer = new HealerEngine({\n cwd,\n remediationLimit: plan.remediationLimit,\n taskSlug,\n ledger\n });\n\n return await healer.run({\n initialResult,\n validate: async () => {\n stateMachine.transitionTo(\"REVALIDATING\");\n return await delegationController.validate(taskSlug, plan.profile, validateWorkflow, plan.evidencePolicy);\n },\n remediate: async (remedCtx) => {\n stateMachine.transitionTo(\"REMEDIATING\");\n const remRes = await executor(remedCtx as any);\n if (remRes.applied) {\n checkBranchSafety();\n await updateSnapshot();\n }\n return remRes;\n }\n });\n}\n\n/**\n * runFinalizerStabilization - Verifies integrity and fidelity.\n */\nasync function runFinalizerStabilization(\n plan: any,\n taskSlug: string,\n cwd: string,\n initialResult: any,\n validateWorkflow: () => Promise<any>,\n delegationController: DelegationController,\n finalizer: Finalizer,\n lastWriteSnapshotRef: { current: any },\n checkBranchSafety: () => void\n): Promise<{ result: any; integrity: any }> {\n let integrity = await finalizer.verifyIntegrity(lastWriteSnapshotRef.current);\n let revalidationCount = 0;\n const maxRevalidations = 2;\n let result = initialResult;\n\n while (!integrity.valid && revalidationCount < maxRevalidations) {\n console.log(`\\n[FINALIZER WARNING] Workspace mutated during validation! Re-running validation to stabilize.`);\n console.log(`Changes detected:`, integrity.changes);\n\n checkBranchSafety();\n\n lastWriteSnapshotRef.current = await finalizer.snapshotManager.capture();\n revalidationCount++;\n\n result = await delegationController.validate(taskSlug, plan.profile, validateWorkflow, plan.evidencePolicy);\n\n checkBranchSafety();\n\n integrity = await finalizer.verifyIntegrity(lastWriteSnapshotRef.current);\n }\n\n return { result, integrity };\n}\n\n/**\n * generateFinalHandoff - Generates Handoff report.\n */\nasync function generateFinalHandoff(plan: ExecutionPlan, taskSlug: string, cwd: string, finalState: string, evidence: Record<string, unknown> | null): Promise<string> {\n console.log(\"\\n--- Final Handoff ---\");\n const handoffEngine = new HandoffEngine({ cwd });\n const handoffPath = await handoffEngine.generate({\n taskId: taskSlug,\n status: finalState,\n specPaths: plan.specPath ? [plan.specPath] : [],\n evidence,\n nextActions: `Profile ${plan.profile}. Observed execution completed with status ${finalState}.`\n });\n\n console.log(`\\n[AI WORKFLOW COMPLETE] ${finalState}`);\n console.log(`Handoff Packet: ${path.relative(cwd, handoffPath)}\\n`);\n return handoffPath;\n}\n\nasync function runFastTrackValidation(cwd: string, result: any, checkBranchSafety: () => void): Promise<string> {\n console.log(`\\n--- [FAST-TRACK] Running Lightweight Validation Gates ---`);\n checkBranchSafety();\n \n const changedFiles = result.evidence?.changedFiles || [];\n console.log(`[FAST-TRACK] Changed files detected:`, changedFiles);\n \n const evidencePath = path.join(cwd, \"EVIDENCE.json\");\n const hasEvidence = await fs.access(evidencePath).then(() => true).catch(() => false);\n \n if (hasEvidence) {\n const { EvidenceValidator } = await import(\"../../core/validation/evidence-validator.js\");\n const isTest = process.env.NODE_ENV === \"test\" || process.env.VITEST === \"true\";\n const evidenceValidator = new EvidenceValidator({ cwd, skipFileCheck: isTest, skipGitCheck: isTest });\n const valResult = await evidenceValidator.validate();\n if (!valResult.valid) {\n console.error(`\\n[FAST-TRACK BLOCKED] EVIDENCE.json validation failed: ${valResult.reason}`);\n return \"FAIL_QUALITY_GATE\";\n }\n }\n return result.overallStatus;\n}\n\nasync function runFidelityValidation(naturalRequest: string, result: any, finalizer: Finalizer): Promise<string> {\n const fidelityResult = await finalizer.verifyFidelity({\n userRequest: naturalRequest,\n projectContext: result.evidence?.deliveryDecision?.projectContext || null,\n deliveryDecision: result.evidence?.deliveryDecision || null,\n changedFiles: result.evidence?.deliveryChangedFiles || result.evidence?.changedFiles || [],\n evidence: result.evidence || null,\n explicitApprovals: process.env.AI_WORKFLOW_APPROVALS ? process.env.AI_WORKFLOW_APPROVALS.split(\",\").map(a => a.trim()) : []\n });\n \n if (!fidelityResult.passed) {\n console.log(`\\n[FINALIZER BLOCKED] BLOCKED: Artifact fidelity check failed!`);\n console.log(`Reason: ${fidelityResult.reason}`);\n return \"FAIL_QUALITY_GATE\";\n }\n return result.overallStatus;\n}\n\nfunction computeFinalState(finalStatus: string): string {\n if (finalStatus === \"PASS\") return \"COMPLETED\";\n if (finalStatus === \"PASS_WITH_NOTES\") return \"COMPLETED_WITH_NOTES\";\n return \"BLOCKED\";\n}\n\nasync function executeReadOnlyWorkflow(\n cwd: string,\n stateMachine: WorkflowStateMachine,\n readOnlyStateBefore: ReadOnlyWorkspaceState,\n fastTrack: boolean,\n deliveryOutcome: Extract<DeliveryOutcome, \"READ_ONLY_RESULT\" | \"PREVIEW_ONLY\">\n): Promise<any> {\n await runReadOnlyConfinementCheck(readOnlyStateBefore, cwd, stateMachine, fastTrack);\n\n stateMachine.transitionTo(\"IMPLEMENTED\");\n stateMachine.transitionTo(\"VALIDATING\");\n stateMachine.transitionTo(\"COMPLETED\");\n\n console.log(\"\\n--- Final Handoff ---\");\n console.log(`\\n[AI WORKFLOW COMPLETE] COMPLETED`);\n console.log(`Handoff Packet: [IN-MEMORY] (No handoff file written in read-only mode)\\n`);\n\n return {\n overallStatus: \"PASS\",\n evidence: {\n internalStatus: \"PASS\",\n commandsRun: [],\n deliveryMode: \"answer-only\",\n deliveryOutcome,\n testAction: \"none\",\n testReason: \"Read-only work does not change executable behavior.\"\n },\n quality: {\n overallStatus: \"PASS\"\n },\n stateHistory: stateMachine.getHistory()\n };\n}\n\n/**\n * runExecute - Coordinators natural request execution.\n */\nexport async function runExecute({ cwd, naturalRequest, taskSlug: taskSlugOverride }: ExecuteOptions): Promise<any> {\n if (process.env.AI_WORKFLOW_FINALIZATION_OWNER === \"execute\") {\n throw new Error(\"[NESTED EXECUTION BLOCKED] The parent execute process owns orchestration and finalization.\");\n }\n if (!naturalRequest || !naturalRequest.trim()) {\n throw new Error(\"Missing request. Please provide a natural request string via positional arguments or --request flag.\");\n }\n\n const taskSlug = taskSlugOverride || slugify(naturalRequest);\n console.log(`\\n[AI WORKFLOW] Executing natural request intake [slug: ${taskSlug}]...\\n`);\n\n const ledger = new EvidenceLedger({ cwd, workflowId: taskSlug });\n const delegationController = new DelegationController({ cwd, ledger, adapter: new OpenCodeAdapter({ cwd }) });\n\n let plan: ExecutionPlan | null = null;\n let branchAuthorized = false;\n try {\n const stateMachine = new WorkflowStateMachine();\n\n const { plan: planObj, classification } = await classifyAndPlanExecution(naturalRequest, cwd, taskSlug, delegationController, stateMachine);\n plan = planObj;\n const fastTrack = plan.riskLevel === \"low\" && (!plan.branchNeeded || plan.evidencePolicy === \"optional\");\n\n const branchGate = new BranchGate({ memoryDir: path.join(cwd, \".ai-workflow\"), cwd });\n const gateResult = runBranchGate(plan, taskSlug, cwd, stateMachine, branchGate);\n branchAuthorized = true;\n\n const checkBranchSafety = () => {\n if (!planObj.branchNeeded) return;\n const currentBranch = branchGate.getCurrentBranch();\n if (branchGate.protectedBranches.includes(currentBranch)) {\n stateMachine.transitionTo(\"BLOCKED\");\n throw new Error(`[WORKFLOW BLOCKED] Security violation: current branch is protected '${currentBranch}'!`);\n }\n };\n\n if (classification.specPolicy === \"required\") {\n return await runDeepSpecificationCheckpoint(plan, classification, taskSlug, cwd, delegationController, stateMachine);\n }\n\n await createSpecIfRequired(plan, classification, taskSlug, cwd);\n\n let readOnlyStateBefore: ReadOnlyWorkspaceState | null = null;\n let deliveryBaseline: WorkspaceSnapshotData | null = null;\n const deliveryFinalizer = new Finalizer({ cwd, fastTrack: false });\n if (!plan.branchNeeded) {\n readOnlyStateBefore = await captureReadOnlyState(cwd, fastTrack);\n } else {\n deliveryBaseline = await deliveryFinalizer.snapshotManager.capture();\n }\n\n const implementationResult = await runImplementation(plan, classification, delegationController, stateMachine, fastTrack);\n const claimedOutcome = parseDeliveryOutcomeClaim(implementationResult.output || \"\");\n\n if (!plan.branchNeeded && readOnlyStateBefore) {\n const readOnlyOutcome = classification.requestUnderstanding.mutationIntent === \"readonly\"\n ? \"READ_ONLY_RESULT\"\n : \"PREVIEW_ONLY\";\n return await executeReadOnlyWorkflow(cwd, stateMachine, readOnlyStateBefore, fastTrack, readOnlyOutcome);\n }\n\n if (!deliveryBaseline) {\n throw new Error(\"[WORKFLOW BLOCKED] Missing delivery baseline for a write workflow.\");\n }\n\n stateMachine.transitionTo(\"IMPLEMENTED\");\n checkBranchSafety();\n\n const finalizer = new Finalizer({ cwd, fastTrack });\n const snapshotRef = { current: await finalizer.snapshotManager.capture() };\n\n const { result: valResult, validateWorkflow } = await runValidation(\n plan,\n taskSlug,\n cwd,\n gateResult,\n naturalRequest,\n claimedOutcome,\n deliveryBaseline,\n deliveryFinalizer,\n delegationController,\n stateMachine\n );\n let result = valResult;\n\n result = await runBoundedRemediation(\n plan,\n taskSlug,\n cwd,\n result,\n validateWorkflow,\n ledger,\n delegationController,\n stateMachine,\n checkBranchSafety,\n async () => {\n snapshotRef.current = await finalizer.snapshotManager.capture();\n }\n );\n\n if (isTerminalFailure(result.overallStatus)) {\n stateMachine.transitionTo(\"BLOCKED\");\n throw new Error(`[WORKFLOW BLOCKED] ${result.overallStatus}: Validation could not be resolved safely.`);\n }\n\n checkBranchSafety();\n\n let integrity = { valid: true, changes: { added: [], modified: [], deleted: [] } };\n if (!fastTrack) {\n const stab = await runFinalizerStabilization(\n plan,\n taskSlug,\n cwd,\n result,\n validateWorkflow,\n delegationController,\n finalizer,\n snapshotRef,\n checkBranchSafety\n );\n result = stab.result;\n integrity = stab.integrity;\n }\n\n let finalStatus = result.overallStatus;\n \n if (fastTrack) {\n finalStatus = await runFastTrackValidation(cwd, result, checkBranchSafety);\n } else if (!integrity.valid) {\n console.log(`\\n[FINALIZER BLOCKED] BLOCKED: workspace did not stabilize`);\n console.log(`Final changes detected:`, integrity.changes);\n finalStatus = \"FAIL_QUALITY_GATE\";\n } else {\n finalStatus = await runFidelityValidation(naturalRequest, result, finalizer);\n }\n\n const finalState = computeFinalState(finalStatus);\n stateMachine.transitionTo(finalState);\n\n ledger.logEvent({\n actor: \"Atlas\",\n actorType: \"control-plane\",\n observed: true,\n eventType: \"finalization_started\",\n provenance: \"execute\",\n data: { owner: \"execute\", status: finalState }\n });\n await generateFinalHandoff(plan, taskSlug, cwd, finalState, result.evidence);\n ledger.logEvent({\n actor: \"Atlas\",\n actorType: \"control-plane\",\n observed: true,\n eventType: \"finalization_completed\",\n provenance: \"execute\",\n data: { owner: \"execute\", status: finalState }\n });\n\n return { ...result, overallStatus: finalStatus, stateHistory: stateMachine.getHistory() };\n } finally {\n if (!branchAuthorized || (plan && !plan.branchNeeded)) {\n console.log(`\\n[READ-ONLY LEDGER] (In-Memory/Stdout)\\n${JSON.stringify(ledger.getEvents(), null, 2)}\\n`);\n } else {\n try {\n await ledger.save(`.ai-workflow/history/${taskSlug}-ledger.json`);\n } catch (err) {\n if (plan?.riskLevel === \"high\") throw err;\n }\n }\n }\n}\n","import { existsSync, rmSync, lstatSync, unlinkSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport readline from \"node:readline\";\n\ninterface CleanOptions {\n cwd: string;\n yes?: boolean;\n dryRun?: boolean;\n purgeAgents?: boolean;\n}\n\nfunction askConfirmation(question: string): Promise<string> {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n return new Promise((resolve) => {\n rl.question(question, (answer) => {\n rl.close();\n resolve(answer.trim().toLowerCase());\n });\n });\n}\n\nfunction isSymlink(filePath: string): boolean {\n try {\n return lstatSync(filePath).isSymbolicLink();\n } catch (_) {\n return false;\n }\n}\n\nexport async function runClean({ cwd, yes = false, dryRun = false, purgeAgents = false }: CleanOptions): Promise<void> {\n const targets = [\n \".ai-workflow\",\n \"opencode.jsonc\",\n \".workflow-state.json\",\n \"opencode\"\n ];\n\n const hasAgents = existsSync(join(cwd, \".agents\"));\n\n // Check what actually exists\n const existingTargets = targets\n .map(name => join(cwd, name))\n .filter(path => existsSync(path) || isSymlink(path));\n\n if (existingTargets.length === 0 && (!hasAgents || !purgeAgents)) {\n console.log(\"No AI Workflow configuration or files found in the current project.\");\n return;\n }\n\n console.log(\"\\n[AI WORKFLOW] De-initialization\");\n console.log(\"===============================\");\n\n if (dryRun) {\n console.log(\"[DRY RUN] The following items would be deleted:\");\n existingTargets.forEach(path => console.log(` - ${path}`));\n if (hasAgents && purgeAgents) {\n console.log(` - ${join(cwd, \".agents\")} (customizations folder)`);\n } else if (hasAgents) {\n console.log(` - NOTE: ${join(cwd, \".agents\")} exists but will NOT be deleted (run with --purge-agents to delete)`);\n }\n return;\n }\n\n // Interactive prompts if --yes / -y is not passed\n if (!yes) {\n if (!process.stdin.isTTY) {\n console.log(\"Error: Non-interactive terminal detected. Run with --yes to bypass confirmation.\");\n if (process.env.NODE_ENV === \"test\") {\n // Allow tests to bypass TTY block if they mock/stub process.stdin\n } else {\n process.exit(1);\n }\n }\n\n const confirmDeinit = await askConfirmation(\"Are you sure you want to de-initialize AI Workflow from the project? [y/N] \");\n if (confirmDeinit !== \"y\" && confirmDeinit !== \"yes\") {\n console.log(\"Aborted.\");\n return;\n }\n\n if (hasAgents && !purgeAgents) {\n const confirmPurge = await askConfirmation(\"A custom '.agents' folder was detected. Do you want to purge it (this deletes custom prompts/rules/skills)? [y/N] \");\n if (confirmPurge === \"y\" || confirmPurge === \"yes\") {\n purgeAgents = true;\n }\n }\n }\n\n // Add .agents if requested and exists\n if (purgeAgents && hasAgents) {\n existingTargets.push(join(cwd, \".agents\"));\n }\n\n console.log(\"\\nRemoving files...\");\n for (const target of existingTargets) {\n try {\n if (isSymlink(target)) {\n unlinkSync(target);\n console.log(`Deleted symlink: ${target}`);\n } else {\n rmSync(target, { recursive: true, force: true });\n console.log(`Deleted directory/file: ${target}`);\n }\n } catch (error: any) {\n console.error(`Failed to delete ${target}: ${error.message}`);\n }\n }\n\n console.log(\"\\nAI Workflow has been successfully removed from this project.\");\n}\n","import { getPackageVersion } from \"../core/package-assets.js\";\nimport { runInit } from \"./commands/init.js\";\nimport { runDoctor } from \"./commands/doctor.js\";\nimport { runCollectEvidence } from \"./commands/collect-evidence.js\";\nimport { runMasterOrchestrator } from \"./commands/run.js\";\nimport { runExecute } from \"./commands/execute.js\";\nimport { runClean } from \"./commands/clean.js\";\n\nfunction printHelp() {\n console.log(`ai-workflow\n\nUsage:\n ai-workflow execute \"<request>\" [--task=<slug>] [--request=\"<request>\"]\n ai-workflow run --spec-path=<path> [--approval-path=<path>]\n ai-workflow init [--yes] [--force] [--dry-run] [--no-install] [--no-overwrite] [--claude] [--codex] [--antigravity] [--profile=<profile>]\n ai-workflow validate [--a11y] [--visual-dist=<path>] [--port=<port>]\n ai-workflow collect-evidence [--task=<slug>] [--evidence-policy=<optional|required>] [--mode=<quick|standard|full>] [--dry-run] [--visual-dist=<path>] [--port=<port>]\n ai-workflow doctor\n ai-workflow clean [--yes] [--dry-run] [--purge-agents]\n ai-workflow lint skills\n ai-workflow skill create <name> [--description=\"<desc>\"] [--dry-run] [--force]\n\nCommands:\n execute Orchestrate execution of a natural request through the state machine\n run Proportionate orchestrator with branch safety, validation, and bounded remediation\n init Install AI workflow defaults (OpenCode). --profile=standard (default) or --profile=full (adds examples)\n collect-evidence Run observed project validation; persists EVIDENCE.json under required evidence policy\n doctor Verify local ai-workflow installation\n clean De-initialize and remove AI Workflow files and symlinks from the project\n lint Run specialized linters (e.g. lint skills)\n skill Manage AI workflow skills (e.g. create)\n`);\n}\n\ninterface ParsedFlags {\n yes: boolean;\n force: boolean;\n dryRun: boolean;\n noInstall: boolean;\n noOverwrite: boolean;\n claude: boolean;\n codex: boolean;\n antigravity: boolean;\n \"dev-mode\": boolean;\n specPath?: string;\n approvalPath?: string;\n profile?: string;\n taskSlug?: string;\n mode?: string;\n evidencePolicy?: \"optional\" | \"required\";\n request?: string;\n visualDist?: string;\n port?: string;\n a11y: boolean;\n purgeAgents?: boolean;\n}\n\nfunction parseFlags(args: string[]): ParsedFlags {\n const specPathArg = args.find((arg) => arg.startsWith(\"--spec-path=\"));\n const approvalPathArg = args.find((arg) => arg.startsWith(\"--approval-path=\"));\n const profileEqArg = args.find((arg) => arg.startsWith(\"--profile=\"));\n const taskArg = args.find((arg) => arg.startsWith(\"--task=\"));\n const modeArg = args.find((arg) => arg.startsWith(\"--mode=\"));\n const evidencePolicyArg = args.find((arg) => arg.startsWith(\"--evidence-policy=\"));\n const requestArg = args.find((arg) => arg.startsWith(\"--request=\"));\n const visualDistArg = args.find((arg) => arg.startsWith(\"--visual-dist=\"));\n const portArg = args.find((arg) => arg.startsWith(\"--port=\"));\n const profileIdx = args.indexOf(\"--profile\");\n const profileVal = profileEqArg\n ? profileEqArg.replace(\"--profile=\", \"\")\n : profileIdx >= 0 && profileIdx + 1 < args.length && !args[profileIdx + 1].startsWith(\"--\")\n ? args[profileIdx + 1]\n : undefined;\n\n return {\n yes: args.includes(\"--yes\"),\n force: args.includes(\"--force\"),\n dryRun: args.includes(\"--dry-run\"),\n noInstall: args.includes(\"--no-install\"),\n noOverwrite: args.includes(\"--no-overwrite\"),\n claude: args.includes(\"--claude\"),\n codex: args.includes(\"--codex\"),\n antigravity: args.includes(\"--antigravity\"),\n \"dev-mode\": args.includes(\"--dev-mode\"),\n specPath: specPathArg ? specPathArg.replace(\"--spec-path=\", \"\") : undefined,\n approvalPath: approvalPathArg ? approvalPathArg.replace(\"--approval-path=\", \"\") : undefined,\n profile: profileVal || undefined,\n taskSlug: taskArg ? taskArg.replace(\"--task=\", \"\") : undefined,\n mode: modeArg ? modeArg.replace(\"--mode=\", \"\") : undefined,\n evidencePolicy: evidencePolicyArg ? (evidencePolicyArg.replace(\"--evidence-policy=\", \"\") as any) : undefined,\n request: requestArg ? requestArg.replace(\"--request=\", \"\") : undefined,\n visualDist: visualDistArg ? visualDistArg.replace(\"--visual-dist=\", \"\") : undefined,\n port: portArg ? portArg.replace(\"--port=\", \"\") : undefined,\n a11y: args.includes(\"--a11y\"),\n purgeAgents: args.includes(\"--purge-agents\") || args.includes(\"--purge\")\n };\n}\n\ntype CommandHandler = (args: string[], flags: ParsedFlags) => Promise<void>;\n\nconst commandMap: Record<string, CommandHandler> = {\n execute: async (args, flags) => {\n const positionals = args.filter((arg) => !arg.startsWith(\"-\"));\n const request = flags.request || positionals.join(\" \");\n const result = await runExecute({\n cwd: process.cwd(),\n naturalRequest: request,\n taskSlug: flags.taskSlug\n });\n if (result && (result.overallStatus === \"FAIL_QUALITY_GATE\" || result.overallStatus === \"BLOCKED\" || result.overallStatus === \"FAIL\")) {\n process.exitCode = result.exitCode === 2 ? 2 : 1;\n }\n },\n run: async (_, flags) => {\n await runMasterOrchestrator({\n cwd: process.cwd(),\n ...flags\n });\n },\n init: async (_, flags) => {\n await runInit({\n cwd: process.cwd(),\n ...flags\n });\n },\n \"collect-evidence\": async (_, flags) => {\n if (flags.mode && ![\"quick\", \"standard\", \"full\"].includes(flags.mode)) {\n throw new Error(\"--mode must be quick, standard, or full\");\n }\n await runCollectEvidence({ \n cwd: process.cwd(), \n taskSlug: flags.taskSlug, \n mode: flags.mode, \n evidencePolicy: flags.evidencePolicy,\n dryRun: flags.dryRun,\n visualDist: flags.visualDist,\n port: flags.port\n });\n },\n validate: async (_, flags) => {\n const { runValidate } = await import(\"./commands/validate.js\");\n await runValidate({\n cwd: process.cwd(),\n taskSlug: flags.taskSlug,\n a11y: flags.a11y,\n visualDist: flags.visualDist,\n port: flags.port\n });\n },\n doctor: async () => {\n await runDoctor({ cwd: process.cwd() });\n },\n clean: async (_, flags) => {\n await runClean({\n cwd: process.cwd(),\n ...flags\n });\n },\n lint: async (args) => {\n if (args[0] === \"skills\") {\n const { runLinter } = await import(\"../linting/skill-frontmatter-linter.js\");\n const { errors, filesScanned } = runLinter(process.cwd());\n\n console.log(`Scanned ${filesScanned} skill files.`);\n\n if (errors.length > 0) {\n console.error(`\\\\nFound ${errors.length} frontmatter issues:`);\n for (const err of errors) {\n console.error(`- ${err.filePath}: ${err.message}`);\n }\n process.exit(1);\n } else {\n console.log(\"All skills passed frontmatter linting.\");\n }\n } else {\n console.error(\"Unknown lint target. Supported: skills\");\n process.exit(1);\n }\n },\n skill: async (args) => {\n if (args[0] === \"create\") {\n const { parseSkillCreateArgs, runSkillCreate } = await import(\"./commands/skill.js\");\n const createOptions = parseSkillCreateArgs(args.slice(1));\n await runSkillCreate({\n cwd: process.cwd(),\n ...createOptions\n });\n } else {\n console.error(\"Unknown skill command. Supported: create\");\n process.exit(1);\n }\n }\n};\n\nexport async function runCli(args: string[]): Promise<void> {\n const [command] = args;\n\n if (command === \"--version\" || command === \"-v\") {\n console.log(getPackageVersion() || \"unknown\");\n return;\n }\n\n if (!command || command === \"--help\" || command === \"-h\") {\n printHelp();\n return;\n }\n\n const handler = commandMap[command];\n if (handler) {\n const argsSlice = args.slice(1);\n const flags = parseFlags(argsSlice);\n await handler(argsSlice, flags);\n return;\n }\n\n throw new Error(`unknown command: ${command}`);\n}\n\nrunCli(process.argv.slice(2)).catch((error) => {\n console.error(`ai-workflow error: ${error.message}`);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,aAAS,OACP,UACA,SAA8B;AAE9B,aAAO,EAAC,UAAU,QAAO;IAC3B;AAEa,YAAA,cAA8B;;MAEzC,MAAM,OAAO,MAAM,WAAW;;MAE9B,MAAM,OAAO,QAAQ,IAAI,GAAG,WAAW;MACvC,aAAa,OAAO,YAAY,IAAI,GAAG,eAAe;MACtD,YAAY,OAAO,QAAO,GAAI,cAAc;MAC5C,iBAAiB,OAAO,YAAW,GAAI,kBAAkB;;MAEzD,UAAU;MACV;MACA,iBACE;;MAEF,gBACE;;;MAGF,KAAK;MACL,OACE;MACF,UACE;;MAEF,MAAM;MACN,MAAM;MACN;;MAEA,MAAM;;;MAGN,gBAAgB;MAChB,6BAA6B;;MAE7B,yBAAyB;;;MAGzB;;MAEA,OAAO,EAAC,MAAM,UAAU,UAAU,cAAa;;MAE/C,OAAO,EAAC,MAAM,UAAU,UAAU,cAAa;;MAE/C,OAAO,EAAC,MAAM,UAAU,UAAU,eAAc;;MAEhD,QAAQ,EAAC,MAAM,UAAU,UAAU,eAAc;;MAEjD,UAAU;;MAEV,QAAQ;;AAGG,YAAA,cAA8B;MACzC,GAAG,QAAA;MACH,MAAM,OAAO,8BAA8B,WAAW;MACtD,MAAM,OACJ,8EACA,WAAW;MAEb,aAAa,OACX,uGACA,eAAe;MAEjB,YAAY,OACV,+EACA,cAAc;MAEhB,iBAAiB,OACf,4GACA,kBAAkB;;MAGpB,KAAK;MACL,iBAAiB;;;;MAI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,KAAK,SAAS;AAC5C;AAAA,EACF;AAEA,MAAI,CAAC,WAAW,YAAY,YAAY,YAAY,MAAM;AACxD,cAAU;AACV;AAAA,EACF;AAEA,QAAM,UAAU,WAAW,OAAO;AAClC,MAAI,SAAS;AACX,UAAM,YAAY,KAAK,MAAM,CAAC;AAC9B,UAAM,QAAQ,WAAW,SAAS;AAClC,UAAM,QAAQ,WAAW,KAAK;AAC9B;AAAA,EACF;AAEA,QAAM,IAAI,MAAM,oBAAoB,OAAO,EAAE;AAC/C;AAEA,OAAO,QAAQ,KAAK,MAAM,CAAC,CAAC,EAAE,MAAM,CAAC,UAAU;AAC7C,UAAQ,MAAM,sBAAsB,MAAM,OAAO,EAAE;AACnD,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["addFormats","fs","fs","path","exists","path","path","path","fs","path","exists","fs","path","fs","path","fs","path","fs","path","fs","path","fs","path","path","fs","next","fs","path","fs","path","execSync","fs","path","path","fs","fs","path","fs","path","path","fs","Ajv","addFormats","import_ajv","fs","path","path","fs","Ajv","path","fs","fs","path","execSync","getChangedFiles","fs","path","execSync","execSync","combineValidation","path","fs","EvidenceValidator","isSymlink","path"]}