@nvwa-os/cli 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +64 -0
- package/bin/nvwa-os +7 -0
- package/dist/cli-z1w83f81.js +7 -0
- package/dist/cli-z1w83f81.js.map +9 -0
- package/dist/cli.js +7988 -0
- package/dist/cli.js.map +40 -0
- package/dist/integration-capabilities-1pm1ad9s.js +169 -0
- package/dist/integration-capabilities-1pm1ad9s.js.map +11 -0
- package/package.json +28 -0
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../agent/run-repo-rewrite.ts", "../../common/src/integration-doc-compile-env.ts", "../../common/src/integration-doc-compile-batch.ts", "../../common/src/integration-doc-compile-catalog.ts", "../../common/src/requirement-intake.ts", "../../common/src/agent-job-config.ts", "../../common/src/dev-pipeline-failure.ts", "../../common/src/requirement-intake-agent-prompt.ts", "../../agent/agent-worker-paths.ts", "../../agent/rewrite-gate.ts", "../../common/src/rewrite-gate.ts", "../../agent/cursor-session-mode.ts", "../../agent/integration-sim-pipeline.ts", "../../agent/integration-doc-compile-pipeline.ts", "../../agent/agent-playbook-paths.ts", "../../agent/agent-skill-context.ts", "../../common/src/integration-docs-client.ts", "../../common/src/nvwa-cli-config.ts", "../../common/src/agent-tool-trace.ts", "../../agent/agent-integration-prompts.ts", "../../common/src/integration-client-package.ts", "../../agent/requirement-intake-materialize.ts", "../../common/src/security-protected-paths.ts", "../../agent/push-gate.ts", "../../common/src/declared-compile-gate.ts", "../../common/src/e2e-playwright-parallel.ts", "../../agent/rewrite-workspace.ts", "../../agent/job-ops-client.ts", "../src/cli-login.ts", "../../agent/skill-tool-trace.ts", "../src/cli.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import { spawn, spawnSync, type ChildProcess } from \"node:child_process\";\nimport {\n cpSync,\n existsSync,\n mkdirSync,\n mkdtempSync,\n readdirSync,\n readFileSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport {\n AGENT_JOB_CONFIG_MOUNT_PATH,\n AGENT_JOB_PIPELINE_CODE_TASK_FEATURE,\n AGENT_JOB_PIPELINE_DEV_PIPELINE_TRIAGE,\n AGENT_JOB_PIPELINE_DEV_UI_CONTRACT,\n AGENT_JOB_PIPELINE_SPEC_BOOTSTRAP_L1_L2,\n AGENT_JOB_PIPELINE_VALIDATION_PLAN,\n AGENT_JOB_PIPELINE_VALIDATION_CODEGEN,\n AGENT_JOB_PIPELINE_INTEGRATION_SIM_SCAFFOLD,\n AGENT_JOB_PIPELINE_INTEGRATION_SIM_REGEN,\n AGENT_JOB_PIPELINE_INTEGRATION_DOC_COMPILE,\n AGENT_JOB_PIPELINE_INTEGRATION_SIM_SKELETON,\n AGENT_JOB_PIPELINE_INTEGRATION_SIM_API_BATCH,\n AGENT_JOB_PIPELINE_OPS_STRUCTURAL_PORT,\n buildAgentJobConfigV1,\n parseAgentCursorSessionMode,\n parseAgentJobConfigV1,\n type AgentJobConfigV1,\n type AgentJobPipeline,\n} from \"../common/src/agent-job-config.ts\";\nimport {\n formatFailureContextForAgent,\n parseDevPipelineFailureContext,\n parseDevPipelineTriageDecision,\n type DevPipelineTriageDecision,\n} from \"../common/src/dev-pipeline-failure.ts\";\nimport {\n appendIntakeImagesToChatContext,\n formatRequirementIntakeImagesPromptBlock,\n} from \"../common/src/requirement-intake-agent-prompt.ts\";\nimport { intakeAttachmentBaseUrlFromCallbackUrl } from \"../common/src/requirement-intake.ts\";\nimport {\n AGENT_OUTPUT_ROOT,\n AGENT_WORKSPACE_DIR,\n applyAgentWorkerPathsEnv,\n resetActiveCursorHomeDir,\n setActiveCursorHomeDir,\n} from \"./agent-worker-paths.ts\";\nimport {\n effectiveRewritePhases,\n runRewriteGate,\n} from \"./rewrite-gate.ts\";\nimport { rewriteGateAllowsSkip } from \"../common/src/rewrite-gate.ts\";\nimport {\n cleanupCursorSessionWorkDir,\n resolveCursorSessionLayout,\n type CursorSessionLayout,\n} from \"./cursor-session-mode.ts\";\nimport {\n buildIntegrationSimAgentPrompt,\n seedIntegrationSimFromTemplate,\n} from \"./integration-sim-pipeline.ts\";\nimport {\n buildIntegrationDocCompilePrompt,\n ensureCompileWorkspace,\n parseCompileResultFromFile,\n readCompileSkillPlaybookForPhase,\n validateCompileResultShape,\n} from \"./integration-doc-compile-pipeline.ts\";\nimport { logAgentSkillContext, logSkillPlaybookInjected } from \"./agent-skill-context.ts\";\nimport { AGENT_PLAYBOOK_PATHS } from \"./agent-playbook-paths.ts\";\nimport {\n integrationBusinessPromptSuffix,\n integrationDocsPromptSuffix,\n} from \"./agent-integration-prompts.ts\";\nimport { materializeRequirementIntakeImages } from \"./requirement-intake-materialize.ts\";\nimport { findDeletedProtectedPaths } from \"../common/src/security-protected-paths.ts\";\nimport {\n runFeaturePushGates,\n verifyBehaviorsBeforePush,\n verifyBunAuditBeforePush,\n verifyDockerParityLockfile,\n verifyFrozenLockfileBeforePush,\n} from \"./push-gate.ts\";\nimport {\n DECLARED_BUILD_FILE,\n parseDeclaredCompileGateFromText,\n resolveWorkspaceToolchain,\n type ResolvedWorkspaceToolchain,\n} from \"../common/src/declared-compile-gate.ts\";\nimport { PARALLEL_SAFE_AUTHORING_RULES } from \"../common/src/e2e-playwright-parallel.ts\";\nimport {\n buildChangeSummary,\n buildDegradedDevelopmentGoalDraft,\n buildRewriteResultFromWorkspace,\n l2PhaseSatisfied,\n l3PhaseSatisfied,\n readDevelopmentGoalJson,\n readRewriteCallbackMeta,\n resolveL2CapabilityPath,\n rewriteWorkspacePaths,\n slugFromRequirementTitle,\n type DevelopmentGoalDraft,\n type RewriteWorkspacePaths,\n} from \"./rewrite-workspace.ts\";\n\nexport { normalizeRepoRelativePath, slugFromRequirementTitle } from \"./rewrite-workspace.ts\";\nexport { buildRewriteResultFromWorkspace } from \"./rewrite-workspace.ts\";\n\nfunction readRequirementIntakeSkillPlaybook(): string {\n try {\n if (!existsSync(AGENT_PLAYBOOK_PATHS.requirementIntakeImages)) return \"\";\n return readFileSync(AGENT_PLAYBOOK_PATHS.requirementIntakeImages, \"utf-8\");\n } catch {\n return \"\";\n }\n}\n\nasync function enrichChatContextWithIntakeImages(\n spec: AgentJobConfigV1,\n chatContext: string,\n): Promise<string> {\n if (!spec.requirementIntakeAttachments?.length) return chatContext;\n const materialized = await materializeRequirementIntakeImages(spec);\n if (materialized.length === 0) return chatContext;\n const playbook = readRequirementIntakeSkillPlaybook();\n logSkillPlaybookInjected(\n spec,\n \"nvwa-requirement-intake-images\",\n playbook.length,\n playbook.length > 0,\n );\n const block = formatRequirementIntakeImagesPromptBlock({\n materialized,\n callbackBaseUrl: intakeAttachmentBaseUrlFromCallbackUrl(spec.callbackUrl),\n });\n let next = appendIntakeImagesToChatContext(chatContext, block);\n if (playbook.trim()) {\n next = appendIntakeImagesToChatContext(next, `## Skill playbook\\n${playbook.slice(0, 4000)}`);\n }\n return next;\n}\n\n/** 由 main() 填充;K8s 上来自挂载的 job.json,worker 由 runRepoRewriteFromConfig 注入 */\nlet jobSpec: AgentJobConfigV1 | null = null;\n\nlet cursorSessionLayout: CursorSessionLayout | null = null;\n\nfunction prepareCursorSession(spec: AgentJobConfigV1): void {\n cursorSessionLayout = resolveCursorSessionLayout(spec);\n setActiveCursorHomeDir(cursorSessionLayout.activeHomeDir);\n setAgentStreamContinueNext(spec.cursorResume === true);\n applyAgentWorkerPathsEnv();\n}\n\nfunction teardownCursorSession(): void {\n cleanupCursorSessionWorkDir(cursorSessionLayout);\n cursorSessionLayout = null;\n resetActiveCursorHomeDir();\n}\n\n/** When false (worker HTTP), failures throw instead of process.exit */\nlet agentExitOnFailure = true;\n\n/** Next agent stream(s) use Cursor `--continue` (worker cross-task reuse). */\nlet agentStreamContinueNext = false;\n\nexport class AgentRunFailure extends Error {\n override name = \"AgentRunFailure\";\n}\n\nexport class AgentRunCancelled extends Error {\n override name = \"AgentRunCancelled\";\n}\n\nlet activeAgentChild: ChildProcess | null = null;\nlet cancelRequested = false;\n\nexport function clearAgentRunCancelState(): void {\n cancelRequested = false;\n activeAgentChild = null;\n}\n\nexport function isAgentRunCancelRequested(): boolean {\n return cancelRequested;\n}\n\nexport function throwIfAgentRunCancelled(): void {\n if (cancelRequested) {\n throw new AgentRunCancelled(\"job cancelled\");\n }\n}\n\n/** Signal the running Cursor/agent child to stop. Returns true if a child was signalled. */\nexport async function cancelActiveAgentRun(): Promise<boolean> {\n cancelRequested = true;\n const child = activeAgentChild;\n if (!child?.pid) return false;\n try {\n child.kill(\"SIGTERM\");\n } catch {\n // ignore\n }\n await new Promise((r) => setTimeout(r, 3000));\n if (activeAgentChild?.pid) {\n try {\n activeAgentChild.kill(\"SIGKILL\");\n } catch {\n // ignore\n }\n }\n return true;\n}\n\nexport function setAgentExitOnFailure(exitOnFailure: boolean): void {\n agentExitOnFailure = exitOnFailure;\n}\n\nexport function setAgentStreamContinueNext(continueSession: boolean): void {\n agentStreamContinueNext = continueSession;\n}\n\nfunction agentExit(code: number): never {\n if (!agentExitOnFailure && code !== 0) {\n throw new AgentRunFailure(`agent exited with code ${code}`);\n }\n process.exit(code);\n}\n\nexport type AgentProviderMode = \"cursor\" | \"claude\" | \"opencode\";\n\nexport type AgentRuntimeValidationResult = {\n ok: boolean;\n mode: AgentProviderMode;\n missingBinaries: string[];\n missingEnv: string[];\n};\n\nconst MODE_BINARY: Record<AgentProviderMode, string> = {\n cursor: \"agent\",\n claude: \"claude\",\n opencode: \"opencode\",\n};\n\nconst MODE_REQUIRED_ENV: Record<AgentProviderMode, string[]> = {\n cursor: [\"CURSOR_API_KEY\"],\n claude: [\"ANTHROPIC_API_KEY\"],\n opencode: [\"OPENCODE_API_KEY\", \"NVWA_OPENCODE_API_KEY\"],\n};\n\ntype RewriteClarificationOption = {\n id: string;\n label: string;\n};\n\ntype RewriteClarification = {\n id: string;\n prompt: string;\n options: RewriteClarificationOption[];\n defaultOptionId: string;\n};\n\ntype RewritePayload = {\n title: string;\n body: string;\n clarifications: RewriteClarification[];\n};\n\ntype SpecBootstrapL1 = {\n entitiesMd: string;\n rulesMd: string;\n runtimeYaml: string;\n};\n\ntype SpecBootstrapL2 = {\n relativePathSuggestion: string;\n markdown: string;\n};\n\ntype SpecBootstrapAcceptanceHint = {\n featurePath: string;\n scenarioTitle: string;\n suggestedRequirementTag?: string;\n};\n\ntype SpecBootstrapPayload = {\n l1: SpecBootstrapL1;\n l2: SpecBootstrapL2;\n clarifications: RewriteClarification[];\n suggestedBehaviorPaths?: string[];\n acceptanceScenarioHints?: SpecBootstrapAcceptanceHint[];\n};\n\nconst SPEC_STRING_FIELD_MAX = 12_000;\nconst SPEC_RUNTIME_YAML_MAX = 6000;\nconst SPEC_L2_MARKDOWN_MAX = 16_000;\nconst SPEC_PATH_SUGGEST_MAX = 512;\n\ntype AgentActivityCounts = { read: number; search: number; grep: number };\n\ntype AgentProgress = {\n stage: \"clone\" | \"analyze\" | \"finalize\";\n message: string;\n eventType?: string;\n updatedAt: string;\n /** Cursor 风格工具轨迹(时间顺序,尾部为最新) */\n activityLines?: string[];\n activityCounts?: AgentActivityCounts;\n /** 折叠摘要,如「读取 12 · 搜索 4 · 匹配 2」 */\n activityHeadline?: string;\n};\n\ntype AgentRunResult = {\n stdout: string;\n stderr: string;\n exitCode: number;\n};\n\nfunction hasCommand(command: string): boolean {\n const r = spawnSync(\"sh\", [\"-lc\", `command -v \"${command}\" >/dev/null 2>&1`], {\n stdio: \"ignore\",\n });\n return (r.status ?? 1) === 0;\n}\n\nfunction firstPresentEnv(keys: string[]): string | null {\n for (const k of keys) {\n if ((process.env[k] ?? \"\").trim()) return k;\n }\n return null;\n}\n\nexport function validateAgentRuntime(mode: AgentProviderMode): AgentRuntimeValidationResult {\n const binary = MODE_BINARY[mode];\n const envKeys = MODE_REQUIRED_ENV[mode];\n const missingBinaries = hasCommand(binary) ? [] : [binary];\n const missingEnv = firstPresentEnv(envKeys) ? [] : [envKeys.join(\" | \")];\n return {\n ok: missingBinaries.length === 0 && missingEnv.length === 0,\n mode,\n missingBinaries,\n missingEnv,\n };\n}\n\nconst MAX_CLARIFICATIONS = 8;\nconst MAX_OPTIONS = 8;\n\nfunction normalizeClarifications(v: unknown): RewriteClarification[] {\n if (!Array.isArray(v)) return [];\n const out: RewriteClarification[] = [];\n for (const item of v) {\n if (!item || typeof item !== \"object\" || Array.isArray(item)) continue;\n const o = item as Record<string, unknown>;\n const id = typeof o.id === \"string\" ? o.id.trim() : \"\";\n const prompt = typeof o.prompt === \"string\" ? o.prompt.trim() : \"\";\n if (!id || !prompt) continue;\n const optionsRaw = Array.isArray(o.options) ? o.options : [];\n const options: RewriteClarificationOption[] = [];\n for (const op of optionsRaw) {\n if (!op || typeof op !== \"object\" || Array.isArray(op)) continue;\n const oo = op as Record<string, unknown>;\n const oid = typeof oo.id === \"string\" ? oo.id.trim() : \"\";\n const label = typeof oo.label === \"string\" ? oo.label.trim() : \"\";\n if (!oid || !label || options.some((x) => x.id === oid)) continue;\n options.push({ id: oid, label });\n if (options.length >= MAX_OPTIONS) break;\n }\n if (options.length < 2) continue;\n let defaultOptionId = typeof o.defaultOptionId === \"string\" ? o.defaultOptionId.trim() : \"\";\n if (!options.some((x) => x.id === defaultOptionId)) defaultOptionId = options[0].id;\n const sortedOptions = [...options].sort((a, b) => {\n if (a.id === defaultOptionId) return -1;\n if (b.id === defaultOptionId) return 1;\n return 0;\n });\n out.push({ id, prompt, options: sortedOptions, defaultOptionId });\n if (out.length >= MAX_CLARIFICATIONS) break;\n }\n return out;\n}\n\nfunction parsePayloadRecord(v: Record<string, unknown>): RewritePayload | null {\n const titleNew = typeof v.title === \"string\" ? v.title.trim() : \"\";\n const bodyNew = typeof v.body === \"string\" ? v.body.trim() : \"\";\n if (bodyNew !== \"\") {\n const derivedTitle =\n titleNew ||\n bodyNew.split(/\\r?\\n/).find((l: string) => l.trim())?.trim() ||\n \"需求更新\";\n return {\n title: derivedTitle.slice(0, 60),\n body: bodyNew,\n clarifications: normalizeClarifications(v.clarifications),\n };\n }\n if (typeof v.assistantText !== \"string\") return null;\n const rewritten = typeof v.rewritten === \"string\" ? v.rewritten.trim() : \"\";\n const assistant = v.assistantText.trim();\n const mergedBody = rewritten !== \"\" ? rewritten : assistant;\n if (mergedBody === \"\") return null;\n const firstLine =\n mergedBody.split(/\\r?\\n/).find((l: string) => l.trim())?.trim() ?? mergedBody;\n const legacyTitle = firstLine.slice(0, 60) || \"需求更新\";\n return {\n title: legacyTitle,\n body: mergedBody,\n clarifications: normalizeClarifications(v.clarifications),\n };\n}\n\nfunction extractJsonObjectText(raw: string): string | null {\n const t = raw.trim();\n const first = t.indexOf(\"{\");\n const last = t.lastIndexOf(\"}\");\n if (first < 0 || last <= first) return null;\n return t.slice(first, last + 1);\n}\n\n/** 从 `start` 处的 `{` 起解析 balanced `{…}`,正确处理字符串内括号 */\nfunction extractBalancedJsonObjectAt(s: string, start: number): string | null {\n if (start < 0 || start >= s.length || s[start] !== \"{\") return null;\n let depth = 0;\n let inString = false;\n let escaped = false;\n for (let i = start; i < s.length; i++) {\n const c = s[i];\n if (inString) {\n if (escaped) escaped = false;\n else if (c === \"\\\\\") escaped = true;\n else if (c === '\"') inString = false;\n } else if (c === '\"') {\n inString = true;\n } else if (c === \"{\") {\n depth++;\n } else if (c === \"}\") {\n depth--;\n if (depth === 0) return s.slice(start, i + 1);\n }\n }\n return null;\n}\n\n/** 在长文本(如 Cursor result 里的 Markdown)中从后往前找 `{\"summary\"` 块 */\nfunction parseCodeTaskSummaryFromProse(raw: string): string | null {\n const needle = '{\"summary\"';\n let pos = raw.length;\n while (pos > 0) {\n const idx = raw.lastIndexOf(needle, pos - 1);\n if (idx < 0) break;\n const objText = extractBalancedJsonObjectAt(raw, idx);\n if (objText) {\n try {\n const o = JSON.parse(objText) as Record<string, unknown>;\n const s = o.summary;\n if (typeof s === \"string\" && s.trim()) return s.trim().slice(0, 8000);\n } catch {\n /* try earlier occurrence */\n }\n }\n pos = idx;\n }\n return null;\n}\n\nfunction parseCodeTaskSummaryFromCursorStdout(stdout: string): string | null {\n if (!stdout.trim()) return null;\n const fromWhole = parseCodeTaskSummaryFromText(stdout);\n if (fromWhole) return fromWhole;\n\n const lines = stdout.split(\"\\n\");\n for (let i = lines.length - 1; i >= 0; i--) {\n const line = lines[i].trim();\n if (!line) continue;\n let parsed = parseCodeTaskSummaryFromText(line);\n if (parsed) return parsed;\n try {\n const evt = JSON.parse(line) as Record<string, unknown>;\n if (typeof evt.result === \"string\" && evt.result.trim()) {\n parsed = parseCodeTaskSummaryFromText(evt.result);\n if (parsed) return parsed;\n }\n } catch {\n continue;\n }\n }\n return null;\n}\n\nfunction parsePayloadFromCursorStdout<T>(stdout: string, parse: (raw: string) => T | null): T | null {\n if (!stdout.trim()) return null;\n const lines = stdout.split(\"\\n\");\n for (let i = lines.length - 1; i >= 0; i--) {\n const line = lines[i].trim();\n if (!line) continue;\n let v = parse(line);\n if (v) return v;\n try {\n const evt = JSON.parse(line) as Record<string, unknown>;\n if (typeof evt.result === \"string\" && evt.result.trim()) {\n v = parse(evt.result);\n if (v) return v;\n }\n } catch {\n continue;\n }\n }\n return null;\n}\n\nfunction parseRewritePayload(raw: string): RewritePayload | null {\n const candidate = raw.trim();\n try {\n const parsed = JSON.parse(candidate) as unknown;\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n const envelope = parsed as Record<string, unknown>;\n if (typeof envelope.result === \"string\") {\n const resultJson = extractJsonObjectText(envelope.result);\n if (resultJson) {\n const inner = JSON.parse(resultJson) as Record<string, unknown>;\n return parsePayloadRecord(inner);\n }\n }\n return parsePayloadRecord(envelope);\n }\n } catch {\n // ignore and try slicing JSON text\n }\n const objectText = extractJsonObjectText(raw);\n if (!objectText) return null;\n try {\n const parsed = JSON.parse(objectText) as Record<string, unknown>;\n return parsePayloadRecord(parsed);\n } catch {\n return null;\n }\n}\n\nfunction sanitizePathSeg(v: string): string {\n const s = v.trim();\n if (!s) return \"unknown-job\";\n return s.replace(/[^a-zA-Z0-9_-]/g, \"_\").slice(0, 120) || \"unknown-job\";\n}\n\nfunction outputPathForJob(jobId: string, pipeline: AgentJobPipeline): { dir: string; resultJsonPath: string } {\n const seg = sanitizePathSeg(jobId);\n const dir = `${AGENT_OUTPUT_ROOT}/${seg}`;\n const file =\n pipeline === AGENT_JOB_PIPELINE_SPEC_BOOTSTRAP_L1_L2\n ? \"spec-bootstrap.result.json\"\n : pipeline === AGENT_JOB_PIPELINE_CODE_TASK_FEATURE\n ? \"code-task.result.json\"\n : pipeline === AGENT_JOB_PIPELINE_DEV_UI_CONTRACT\n ? \"dev-ui-contract.result.json\"\n : pipeline === AGENT_JOB_PIPELINE_VALIDATION_PLAN\n ? \"validation-plan.result.json\"\n : pipeline === AGENT_JOB_PIPELINE_VALIDATION_CODEGEN\n ? \"validation-codegen.result.json\"\n : pipeline === AGENT_JOB_PIPELINE_OPS_STRUCTURAL_PORT\n ? \"ops-structural-port.result.json\"\n : pipeline === AGENT_JOB_PIPELINE_DEV_PIPELINE_TRIAGE\n ? \"dev-pipeline-triage.result.json\"\n : \"rewrite.result.json\";\n return { dir, resultJsonPath: `${dir}/${file}` };\n}\n\nfunction clipSpecField(s: string, max: number): string {\n const t = s.trim();\n return t.length <= max ? t : `${t.slice(0, max - 1)}…`;\n}\n\nfunction parseSpecPayloadRecord(v: Record<string, unknown>): SpecBootstrapPayload | null {\n const l1raw = v.l1;\n if (!l1raw || typeof l1raw !== \"object\" || Array.isArray(l1raw)) return null;\n const l1o = l1raw as Record<string, unknown>;\n const entitiesMd = typeof l1o.entitiesMd === \"string\" ? clipSpecField(l1o.entitiesMd, SPEC_STRING_FIELD_MAX) : \"\";\n const rulesMd = typeof l1o.rulesMd === \"string\" ? clipSpecField(l1o.rulesMd, SPEC_STRING_FIELD_MAX) : \"\";\n const runtimeYaml =\n typeof l1o.runtimeYaml === \"string\" ? clipSpecField(l1o.runtimeYaml, SPEC_RUNTIME_YAML_MAX) : \"\";\n if (!entitiesMd && !rulesMd && !runtimeYaml) return null;\n\n const l2raw = v.l2;\n if (!l2raw || typeof l2raw !== \"object\" || Array.isArray(l2raw)) return null;\n const l2o = l2raw as Record<string, unknown>;\n const relativePathSuggestion =\n typeof l2o.relativePathSuggestion === \"string\"\n ? clipSpecField(l2o.relativePathSuggestion, SPEC_PATH_SUGGEST_MAX)\n : \"\";\n const markdown =\n typeof l2o.markdown === \"string\" ? clipSpecField(l2o.markdown, SPEC_L2_MARKDOWN_MAX) : \"\";\n if (!markdown) return null;\n\n const suggestedBehaviorPaths = normalizeStringList(v.suggestedBehaviorPaths, 32, 512);\n const acceptanceScenarioHints = normalizeAcceptanceHints(v.acceptanceScenarioHints);\n\n return {\n l1: { entitiesMd, rulesMd, runtimeYaml },\n l2: { relativePathSuggestion, markdown },\n clarifications: normalizeClarifications(v.clarifications),\n ...(suggestedBehaviorPaths.length > 0 ? { suggestedBehaviorPaths } : {}),\n ...(acceptanceScenarioHints.length > 0 ? { acceptanceScenarioHints } : {}),\n };\n}\n\nfunction normalizeStringList(raw: unknown, maxItems: number, maxLen: number): string[] {\n if (!Array.isArray(raw)) return [];\n const out: string[] = [];\n for (const item of raw) {\n if (typeof item !== \"string\") continue;\n const t = item.trim().slice(0, maxLen);\n if (!t) continue;\n out.push(t);\n if (out.length >= maxItems) break;\n }\n return out;\n}\n\nfunction normalizeAcceptanceHints(raw: unknown): SpecBootstrapAcceptanceHint[] {\n if (!Array.isArray(raw)) return [];\n const out: SpecBootstrapAcceptanceHint[] = [];\n for (const item of raw) {\n if (!item || typeof item !== \"object\" || Array.isArray(item)) continue;\n const o = item as Record<string, unknown>;\n const featurePath = typeof o.featurePath === \"string\" ? o.featurePath.trim().slice(0, 512) : \"\";\n const scenarioTitle = typeof o.scenarioTitle === \"string\" ? o.scenarioTitle.trim().slice(0, 512) : \"\";\n if (!featurePath || !scenarioTitle) continue;\n const tag =\n typeof o.suggestedRequirementTag === \"string\"\n ? o.suggestedRequirementTag.trim().slice(0, 120)\n : undefined;\n out.push({\n featurePath,\n scenarioTitle,\n ...(tag ? { suggestedRequirementTag: tag } : {}),\n });\n if (out.length >= 24) break;\n }\n return out;\n}\n\nfunction parseSpecBootstrapPayload(raw: string): SpecBootstrapPayload | null {\n const candidate = raw.trim();\n try {\n const parsed = JSON.parse(candidate) as unknown;\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n const envelope = parsed as Record<string, unknown>;\n if (typeof envelope.result === \"string\") {\n const resultJson = extractJsonObjectText(envelope.result);\n if (resultJson) {\n const inner = JSON.parse(resultJson) as Record<string, unknown>;\n return parseSpecPayloadRecord(inner);\n }\n }\n return parseSpecPayloadRecord(envelope);\n }\n } catch {\n /* fall through */\n }\n const objectText = extractJsonObjectText(raw);\n if (!objectText) return null;\n try {\n const parsed = JSON.parse(objectText) as Record<string, unknown>;\n return parseSpecPayloadRecord(parsed);\n } catch {\n return null;\n }\n}\n\nexport function buildSpecBootstrapPrompt(\n title: string,\n raw: string,\n chatContext: string,\n resultPath: string,\n repoFileIndexSample: string,\n): string {\n const hasChat = chatContext.trim() !== \"\";\n const chatBlock = hasChat\n ? `\n--- Conversation history (chronological) ---\n${chatContext}\n--- End conversation ---\n`\n : \"\";\n\n return `\nYou are generating **L1 (Universe)** and **L2 (Feature)** specification drafts for the Nvwa-style layout in the target repository.\nThe repository is cloned at your working directory (e.g. /workspace/repo). Explore the tree with your tools; do not invent file paths or versions that you did not read.\n\nRequirement title: ${title}\n\nRequirement raw input:\n${raw}\n${chatBlock}\n\nOptional index sample (truncated git ls-files, not exhaustive):\n${repoFileIndexSample}\n\n## Rules\n- Read evidence first: root manifests (package.json, bun.lock, etc.), README, CI configs, Dockerfile/Tiltfile/kubernetes if present, existing **spec/** (foundation, capabilities, behaviors, ui-contracts) and wiki/**. Do **not** create \\`.nvwa/**\\` or write rewrite output under \\`spec/capabilities/drafts/{slug}.md\\` (curated notes in \\`drafts/\\` are not rewrite targets).\n- **Do not fabricate** APIs, env vars, services, or stack versions not supported by files you read. If unknown, state assumptions in clarifications instead of inventing facts in L1 text.\n- Prefer concise Markdown in entities/rules; runtimeYaml should be a plausible **draft** (placeholders OK) aligned with what you saw (e.g. Bun monorepo, K8s) — not production secrets.\n\n## Output\nRespond with **exactly one JSON object** (no markdown fence). Keys:\n- l1: { \"entitiesMd\": string, \"rulesMd\": string, \"runtimeYaml\": string }\n - Universe-level draft (terminology, core entities, global rules, stack hints). Use Chinese where the repo docs use Chinese.\n- l2: { \"relativePathSuggestion\": string, \"markdown\": string }\n - relativePathSuggestion: suggested path under spec/capabilities/ (e.g. spec/capabilities/my-feature.md)\n - markdown: one feature / PRD-style spec for **this** requirement (user stories, acceptance criteria, out of scope).\n- clarifications: array of { \"id\", \"prompt\", \"options\": [ { \"id\", \"label\" }, ... ], \"defaultOptionId\" } — same constraints as requirement rewrite (>=2 options per item, defaultOptionId must match an option id). Use [] if nothing blocking.\n- suggestedBehaviorPaths: optional string[] — existing or new paths under spec/behaviors/**/*.feature that best match this requirement (repo-relative, only paths you saw or can justify).\n- acceptanceScenarioHints: optional array of { \"featurePath\", \"scenarioTitle\", \"suggestedRequirementTag\", \"suggestedParallelTag\" } — draft Gherkin scenarios to add; suggestedRequirementTag like @requirement:REQ-CODE; suggestedParallelTag is optional \"@parallel-safe\" only for read-only scenarios (see parallel rules below).\n\n${PARALLEL_SAFE_AUTHORING_RULES}\n\nKeep sizes moderate: entitiesMd/rulesMd each <= ${SPEC_STRING_FIELD_MAX} chars; runtimeYaml <= ${SPEC_RUNTIME_YAML_MAX}; l2.markdown <= ${SPEC_L2_MARKDOWN_MAX}.\n\nAfter generating the JSON:\n1) Write the exact JSON object to file: ${resultPath}\n2) Also print the same JSON object to stdout.`;\n}\n\nfunction buildUserPrompt(title: string, raw: string, chatContext: string, resultPath: string): string {\n const hasChat = chatContext.trim() !== \"\";\n const clarificationHint = hasChat && chatContext.includes(\"【澄清选择】\")\n ? `\nImportant: The conversation may include a User message starting with 「【澄清选择】」 or 「【录入澄清选择】」 — structured answers to prior clarifications. Merge them into \\`body\\`; use clarifications: [] unless new blocking forks remain that were NOT already decided in intake clarification.\n`\n : \"\";\n\n const stage2Hint = hasChat\n ? `\nStage 2 clarifications only: Ask ONLY about forks discovered after reading the repository (spec conflicts, multiple valid implementation paths not visible from intake text). Do NOT repeat topics already covered in 「【录入澄清选择】」 messages. If the user skipped intake clarification (「【跳过录入澄清】」), list assumptions explicitly in \\`body\\`.\n`\n : \"\";\n\n const chatBlock = hasChat\n ? `\n--- Conversation history (chronological; the latest User/Assistant lines are most relevant) ---\n${chatContext}\n--- End conversation ---\n`\n : \"\";\n\n return `\nYou are analyzing a software requirement against a Git repository. The repo is cloned at your working directory (e.g. under /workspace/repo). Do not assume a pre-supplied file list — explore the tree yourself with your tools (list files, search, read files) as needed.\n\nRequirement title: ${title}\n\nRequirement raw input (first user motivation; may be superseded by later conversation):\n${raw}\n${chatBlock}${clarificationHint}${stage2Hint}\nRespond with exactly one JSON object (no markdown fence). Keys:\n- title (string): Short card title summarizing this round (~20 Chinese characters or less when possible; hard max ~60 chars).\n- body (string): Single Markdown document — concrete, actionable requirement text for both the chat message and the card; sections and lists welcome.\n- clarifications (array): Multiple-choice items the user must confirm before you lock the spec. Each item:\n { \"id\": \"stable_id\", \"prompt\": \"question\", \"options\": [ { \"id\": \"o1\", \"label\": \"text\" }, ... ], \"defaultOptionId\": \"must match one option id\" }\n At least 2 options per item; put the recommended default first in options and set defaultOptionId to it. Use [] if nothing needs confirmation.\n\nPut everything important into \\`body\\`; use clarifications only for decisions that materially change the solution and are newly visible from repo exploration (not intake duplicates).\n\nAfter generating the JSON:\n1) Write the exact JSON object to file: ${resultPath}\n2) Also print the same JSON object to stdout.`;\n}\n\nfunction buildL1FoundationRepoPrompt(\n title: string,\n raw: string,\n chatContext: string,\n indexSample: string,\n paths: ReturnType<typeof rewriteWorkspacePaths>,\n): string {\n const chatBlock =\n chatContext.trim() !== \"\"\n ? `\\n--- Conversation history ---\\n${chatContext}\\n--- End conversation ---\\n`\n : \"\";\n\n return `\nYou are **L1 (Universe)** for the Nvwa layout in the cloned repository (your working directory).\n\nRequirement title: ${title}\nRequirement raw input:\n${raw}\n${chatBlock}\n\nOptional index sample (truncated):\n${indexSample}\n\n## Task\nExplore the repository (manifests, README, existing spec/**) and **write or incrementally update these files** (create directories as needed). Prefer updating existing curated L1 files in place rather than replacing them wholesale:\n1. \\`${paths.l1Entities}\\` — entities / terminology (Markdown, Chinese where appropriate)\n2. \\`${paths.l1Rules}\\` — global rules (Markdown)\n3. \\`${paths.l1Runtime}\\` — runtime/stack draft (YAML; no production secrets)\n\nDo not fabricate stack facts; use evidence from the repo or state assumptions in the files.\n\n## Metadata only (optional, not committed)\nBlocking clarifications only: append or write \\`${paths.callbackMeta}\\` as JSON: { \"clarifications\": [ ... ] }\n\n**Do not** treat agent-out JSON as the primary deliverable. The server reads the repo files in a later emit step.`;\n}\n\nfunction buildL2CapabilitiesRepoPrompt(\n title: string,\n raw: string,\n chatContext: string,\n paths: RewriteWorkspacePaths,\n): string {\n const chatBlock =\n chatContext.trim() !== \"\"\n ? `\\n--- Conversation history ---\\n${chatContext}\\n--- End conversation ---\\n`\n : \"\";\n\n return `\nYou are **L2 (Feature / capability)** for this requirement. L1 universe files live under \\`spec/foundation/\\`.\n\nRequirement title: ${title}\nRequirement raw input:\n${raw}\n${chatBlock}\n\n## Task (repo changes — required)\n1. Create or update **one** capability document at \\`spec/capabilities/{能力名}.md\\` (choose a short, semantic filename in Chinese or English — **not** tied to the requirement title slug).\n2. Add or update a row in \\`${paths.capabilitiesRoot}\\` module index table linking to that file.\n3. Write \\`${paths.callbackMeta}\\` JSON including **l2RelativePath** (repo-relative, e.g. \\`spec/capabilities/validation-records.md\\`) — required.\n\nPRD-style Markdown in the capability file: user stories, acceptance criteria, scope / out of scope.\n\nDo **not** use \\`spec/capabilities/drafts/\\`. Do not put the main L2 content only in agent-out.`;\n}\n\nfunction buildL2CapabilitiesCorrectionPrompt(\n title: string,\n paths: RewriteWorkspacePaths,\n): string {\n return `\n**Correction (L2):** The previous step did not produce a valid L2 capability file.\n\nYou must:\n1. Write \\`spec/capabilities/{能力名}.md\\` with full PRD content.\n2. Update \\`${paths.capabilitiesRoot}\\` index.\n3. Set \\`l2RelativePath\\` in \\`${paths.callbackMeta}\\` to the exact capability file path.\n\nRequirement: ${title}`;\n}\n\nexport function buildL3BehaviorsRepoPrompt(\n title: string,\n raw: string,\n chatContext: string,\n paths: RewriteWorkspacePaths,\n): string {\n const chatBlock =\n chatContext.trim() !== \"\"\n ? `\\n--- Conversation history ---\\n${chatContext}\\n--- End conversation ---\\n`\n : \"\";\n\n return `\nYou are **L3 (Behaviors + requirement narrative)**. L1 and L2 capability docs are in the repo.\n\nRequirement title: ${title}\nRequirement raw input:\n${raw}\n${chatBlock}\n\n## Task (repo changes — required)\n1. **Create or update** \\`spec/behaviors/**\\` Gherkin features and \\`spec/ui-contracts/**\\` test-id contracts when this requirement needs verifiable UI behavior (follow existing repo patterns).\n2. **Do not** modify \\`apps/**\\` in this phase — implementation is a later dev-pipeline step.\n\n${PARALLEL_SAFE_AUTHORING_RULES}\n\n## Callback metadata (\\`${paths.callbackMeta}\\` — merge with existing JSON)\nMust include:\n- \"title\" (string, card title)\n- \"body\" (string, Markdown requirement document for the Studio card — goals, AC, scope)\n- \"clarifications\" (array, use [] if none)\n- optional \"suggestedBehaviorPaths\", \"acceptanceScenarioHints\"\n\nRequirement body belongs in callback meta (\\`agent-out/rewrite-callback-meta.json\\`), not a \\`spec/requirements/\\` file. Primary spec changes live under \\`spec/behaviors/**\\` and \\`spec/ui-contracts/**\\`.`;\n}\n\nfunction buildL3BehaviorsCorrectionPrompt(\n title: string,\n paths: RewriteWorkspacePaths,\n): string {\n return `\n**Correction (L3):** Missing requirement body in callback meta and/or spec behavior changes.\n\nYou must:\n1. Update \\`spec/behaviors/**\\` and/or \\`spec/ui-contracts/**\\` as needed.\n2. Write \\`${paths.callbackMeta}\\` with \"title\" and \"body\" (full Markdown for the card).\n\n${PARALLEL_SAFE_AUTHORING_RULES}\n\nDo not modify \\`apps/**\\`. Requirement: ${title}`;\n}\n\nfunction buildUserPromptAfterBootstrap(\n title: string,\n raw: string,\n chatContext: string,\n resultPath: string,\n l1l2: SpecBootstrapPayload,\n): string {\n const hasChat = chatContext.trim() !== \"\";\n const chatBlock = hasChat\n ? `\n--- Conversation history ---\n${chatContext}\n--- End conversation ---\n`\n : \"\";\n const l1l2Json = JSON.stringify(l1l2, null, 2).slice(0, 24_000);\n\n return `\nYou are completing **L3 (requirement body)** for an Nvwa requirement. L1/L2 were already drafted in this session.\n\nRequirement title: ${title}\n\nRequirement raw input:\n${raw}\n${chatBlock}\n\n--- L1/L2 draft (authoritative; do not contradict without noting in clarifications) ---\n${l1l2Json}\n--- End L1/L2 ---\n\n## Rules\n- **Do not** run broad repository exploration (no full-tree \\`ls\\`, repo-wide \\`grep\\`, or reading unrelated packages).\n- You may read at most 1–2 files only if L3 text truly depends on a specific path mentioned in L1/L2.\n- Produce the L3 JSON from the requirement text and L1/L2 above.\n\nRespond with exactly one JSON object (no markdown fence). Keys:\n- title (string): Short card title (~20 Chinese characters when possible; max ~60).\n- body (string): Markdown requirement document for the card.\n- clarifications (array): Same schema as requirement rewrite; use [] if nothing blocking.\n\nAfter generating the JSON:\n1) Write the exact JSON object to file: ${resultPath}\n2) Also print the same JSON object to stdout.`;\n}\n\nfunction buildDevelopmentGoalPrompt(\n title: string,\n raw: string,\n chatContext: string,\n l3Body: string,\n wsPaths: RewriteWorkspacePaths,\n resultPath: string,\n specBootstrap?: SpecBootstrapPayload | null,\n): string {\n const hasChat = chatContext.trim() !== \"\";\n const chatBlock = hasChat\n ? `\n--- Conversation history ---\n${chatContext}\n--- End conversation ---\n`\n : \"\";\n const l1l2Json = specBootstrap ? JSON.stringify(specBootstrap, null, 2).slice(0, 12_000) : \"\";\n const l1l2Block = l1l2Json\n ? `\n--- L1/L2 spec bootstrap (reference) ---\n${l1l2Json}\n--- End L1/L2 ---\n`\n : \"\";\n\n return `\nYou are writing the **development task goal** for an Nvwa requirement after L1–L3 spec work in the repo.\n\nThis JSON becomes the **single source of truth** for later dev-pipeline jobs (UI contract, validation codegen, implementation). It must be actionable and phase-specific.\n\nRequirement title: ${title}\nUser raw input (audit only): ${raw}\n${chatBlock}\n${l1l2Block}\n\nL2 capability path (from meta): ${wsPaths.callbackMeta} → l2RelativePath\nPrimary behavior paths (from meta): suggestedBehaviorPaths\n\nRequirement body excerpt (reference):\n${l3Body.slice(0, 6000)}\n\n## Output (mandatory)\nWrite **exactly one JSON object** to: **${resultPath}**\n- UTF-8, no BOM; first non-whitespace char is \\`{\\`, last is \\`}\\`\n- No markdown fences or commentary outside JSON\n\nSchema:\n{\n \"summary\": \"one-line card summary (~20 Chinese chars when possible)\",\n \"body\": \"Markdown: user goal, scope, out-of-scope, acceptance criteria\",\n \"acceptanceHints\": [\"string hints for E2E/validation\"],\n \"specRefs\": {\n \"l2CapabilityPath\": \"spec/capabilities/your-capability.md\",\n \"l3RequirementPath\": \"spec/behaviors/.../feature.feature (optional primary behavior path)\",\n \"suggestedBehaviorPaths\": [\"spec/behaviors/...\"]\n },\n \"phaseGuidance\": {\n \"UI_CONTRACT\": \"what P1 must deliver (L4 ui-contracts only, no app UI code)\",\n \"VALIDATION_CODE\": \"what P2 must deliver (behaviors/e2e skeleton only, no full app UI)\",\n \"IMPLEMENTATION\": \"what P3 must deliver (apps/web business code; must leave git-committable diffs)\"\n },\n \"implementationPlan\": {\n \"needsPhasedImplementation\": false,\n \"reason\": \"why phased or not (one sentence)\",\n \"subtasks\": [\n {\n \"title\": \"phase title (only when needsPhasedImplementation is true)\",\n \"description\": \"what this phase delivers\",\n \"guidance\": \"L6 implementation scope for this phase only; note dependencies on prior phases\"\n }\n ]\n }\n}\n\nRules for implementationPlan:\n- After L1–L3 spec is in the repo, decide if **business implementation (P3)** needs **2–8 ordered phases**.\n- Set needsPhasedImplementation true only when multiple sequential implementation slices reduce risk; **do not** split spec/L3 into multiple features.\n- When false, omit subtasks or use an empty array.\n- When true, subtasks must be **2–8** items in delivery order; each guidance must say what to implement **in that phase only**.\n\n${PARALLEL_SAFE_AUTHORING_RULES}\n\nAlso print the same single-line JSON to stdout.`;\n}\n\nfunction cloneUrl(repo: string, token: string): string {\n if (!token) return repo;\n const gitUsername = (process.env.GIT_USERNAME ?? \"\").trim();\n try {\n const u = new URL(repo);\n if (u.protocol === \"https:\" || u.protocol === \"http:\") {\n if (!u.username) {\n u.username = gitUsername || \"x-access-token\";\n u.password = token;\n }\n }\n return u.toString();\n } catch {\n return repo;\n }\n}\n\n/** Batch Job workspace PVC or Deployment worker — reuse repo + node_modules across jobs on the same card. */\nexport function agentWorkspaceIsPersistent(): boolean {\n return (\n process.env.NVWA_AGENT_RUNTIME === \"worker\" ||\n process.env.NVWA_AGENT_WORKSPACE_PERSIST === \"1\"\n );\n}\n\n/** Deployment / PVC workspace mount — delete children only, not the mount point. */\nfunction clearWorkspaceDirectoryContents(dir: string): void {\n for (const name of readdirSync(dir)) {\n if (name === \".\" || name === \"..\") continue;\n rmSync(join(dir, name), { recursive: true, force: true });\n }\n}\n\nexport function prepareGitCloneDirectory(dir: string): string | null {\n try {\n const parent = dirname(dir);\n mkdirSync(parent, { recursive: true });\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n return null;\n }\n if (agentWorkspaceIsPersistent()) {\n clearWorkspaceDirectoryContents(dir);\n return null;\n }\n rmSync(dir, { recursive: true, force: true });\n mkdirSync(dir, { recursive: true });\n return null;\n } catch (e) {\n return `prepare clone dir: ${e instanceof Error ? e.message : String(e)}`;\n }\n}\n\nfunction gitClone(repo: string, ref: string, dir: string, token: string): string | null {\n agentLog(\"git clone start\", { ref, dir });\n const prepErr = prepareGitCloneDirectory(dir);\n if (prepErr) {\n agentLog(\"git clone failed\", { error: prepErr });\n return prepErr;\n }\n\n const url = cloneUrl(repo, token);\n const r1 = spawnSync(\"git\", [\"clone\", \"--depth\", \"1\", \"--branch\", ref, url, dir], {\n encoding: \"utf-8\",\n env: { ...process.env, GIT_TERMINAL_PROMPT: \"0\" },\n timeout: 600_000,\n });\n if (r1.status === 0) {\n agentLog(\"git clone ok\", { ref, head: gitHeadSha(dir) });\n return null;\n }\n agentLog(\"git clone branch ref failed, retrying default clone + fetch\", {\n ref,\n stderr: (r1.stderr || r1.stdout || \"\").slice(0, 400),\n });\n const r2 = spawnSync(\"git\", [\"clone\", \"--depth\", \"1\", url, dir], {\n encoding: \"utf-8\",\n env: { ...process.env, GIT_TERMINAL_PROMPT: \"0\" },\n timeout: 600_000,\n });\n if (r2.status !== 0) {\n const err = r2.stderr || r2.stdout || \"clone failed\";\n agentLog(\"git clone failed\", { error: err.slice(0, 400) });\n return err;\n }\n const r3 = spawnSync(\"git\", [\"-C\", dir, \"fetch\", \"--depth\", \"1\", \"origin\", ref], {\n encoding: \"utf-8\",\n timeout: 600_000,\n });\n if (r3.status !== 0) {\n const err = r3.stderr || \"fetch failed\";\n agentLog(\"git clone fetch ref failed\", { ref, error: err.slice(0, 400) });\n return err;\n }\n const r4 = spawnSync(\"git\", [\"-C\", dir, \"checkout\", \"FETCH_HEAD\"], {\n encoding: \"utf-8\",\n timeout: 120_000,\n });\n if (r4.status !== 0) {\n const err = r4.stderr || \"checkout failed\";\n agentLog(\"git clone checkout failed\", { error: err.slice(0, 400) });\n return err;\n }\n agentLog(\"git clone ok (fetch+checkout)\", { ref, head: gitHeadSha(dir) });\n return null;\n}\n\nfunction gitRepoInitialized(dir: string): boolean {\n return existsSync(`${dir}/.git`);\n}\n\nconst STALE_GIT_LOCK_FILES = [\n \"shallow.lock\",\n \"index.lock\",\n \"HEAD.lock\",\n \"config.lock\",\n \"packed-refs.lock\",\n] as const;\n\n/** Remove stale git lock files left by crashed pods on a persistent PVC workspace. */\nexport function clearStaleGitLocks(dir: string): string[] {\n if (!agentWorkspaceIsPersistent()) return [];\n const gitDir = join(dir, \".git\");\n if (!existsSync(gitDir)) return [];\n const cleared: string[] = [];\n for (const name of STALE_GIT_LOCK_FILES) {\n const lockPath = join(gitDir, name);\n if (!existsSync(lockPath)) continue;\n try {\n rmSync(lockPath, { force: true });\n cleared.push(name);\n } catch {\n /* ignore */\n }\n }\n if (cleared.length > 0) {\n agentLog(\"persistent workspace cleared stale git locks\", { cleared });\n }\n return cleared;\n}\n\nfunction workspaceSync(repo: string, ref: string, dir: string, token: string): string | null {\n clearStaleGitLocks(dir);\n agentLog(\"workspace sync start\", { ref, dir, head: gitHeadSha(dir) });\n const url = cloneUrl(repo, token);\n let err = gitWorkspaceErr(dir, [\"remote\", \"set-url\", \"origin\", url]);\n if (err) {\n err = gitWorkspaceErr(dir, [\"remote\", \"add\", \"origin\", url]);\n }\n if (err) return err;\n err = gitWorkspaceErr(dir, [\"fetch\", \"--depth\", \"50\", \"origin\", ref]);\n if (err) {\n err = gitWorkspaceErr(dir, [\"fetch\", \"--depth\", \"50\", \"origin\"]);\n if (err) return err;\n }\n const co = gitWorkspaceErr(dir, [\"checkout\", ref]);\n if (co) {\n const coFetch = gitWorkspaceErr(dir, [\"checkout\", \"FETCH_HEAD\"]);\n if (coFetch) return coFetch;\n }\n agentLog(\"workspace sync ok\", { ref, head: gitHeadSha(dir) });\n return null;\n}\n\n/**\n * Clone on first use; on worker PVC reuse existing repo and fetch ref.\n * Sync failure on persistent workspace falls back to one full reclone.\n */\nexport function ensureWorkspaceReady(\n repo: string,\n ref: string,\n dir: string,\n token: string,\n opts?: { forceReclone?: boolean },\n): string | null {\n if (opts?.forceReclone && agentWorkspaceIsPersistent() && existsSync(dir)) {\n try {\n clearWorkspaceDirectoryContents(dir);\n } catch (e) {\n return `prepare workspace reclone: ${e instanceof Error ? e.message : String(e)}`;\n }\n }\n if (!opts?.forceReclone && gitRepoInitialized(dir)) {\n const syncErr = workspaceSync(repo, ref, dir, token);\n if (!syncErr) return null;\n if (!agentWorkspaceIsPersistent()) return syncErr;\n agentLog(\"persistent workspace sync failed, force reclone\", {\n ref,\n error: syncErr.slice(0, 400),\n });\n try {\n clearWorkspaceDirectoryContents(dir);\n } catch (e) {\n return `prepare workspace reclone: ${e instanceof Error ? e.message : String(e)}`;\n }\n return gitClone(repo, ref, dir, token);\n }\n return gitClone(repo, ref, dir, token);\n}\n\nexport function resolveWorkspaceToolchainFromDir(\n dir: string,\n): { toolchain: ResolvedWorkspaceToolchain; source: string } | null {\n const buildPath = join(dir, DECLARED_BUILD_FILE);\n if (!existsSync(buildPath)) return null;\n let content: string;\n try {\n content = readFileSync(buildPath, \"utf8\");\n } catch {\n return null;\n }\n try {\n const cfg = parseDeclaredCompileGateFromText(content);\n if (!cfg) return null;\n return { toolchain: resolveWorkspaceToolchain(cfg), source: DECLARED_BUILD_FILE };\n } catch {\n return null;\n }\n}\n\nfunction workspaceNeedsDependencyWarm(dir: string, toolchain: ResolvedWorkspaceToolchain): boolean {\n const nm = join(dir, toolchain.modulesDir);\n if (!existsSync(nm)) return true;\n const lockPath = join(dir, toolchain.lockFile);\n if (!existsSync(lockPath)) return false;\n try {\n const lockMtime = statSync(lockPath).mtimeMs;\n const nmMtime = statSync(nm).mtimeMs;\n return lockMtime > nmMtime;\n } catch {\n return true;\n }\n}\n\nconst DEPS_WARM_RETRY_DELAYS_MS = [2000, 5000] as const;\nconst DEPS_WARM_MAX_ATTEMPTS = 3;\n\nfunction syncSleepMs(ms: number): void {\n const end = Date.now() + ms;\n while (Date.now() < end) {\n /* spin — short backoff during workspace warm only */\n }\n}\n\nlet workspaceWarmRetrySleep: (ms: number) => void = syncSleepMs;\n\n/** @internal Test hook to avoid long backoff delays in unit tests. */\nexport function __setWorkspaceWarmRetrySleepForTest(fn: ((ms: number) => void) | null): void {\n workspaceWarmRetrySleep = fn ?? syncSleepMs;\n}\n\nexport function isRetryableDepsWarmError(output: string): boolean {\n const t = output.trim();\n if (!t) return false;\n return (\n /failed to download/i.test(t) ||\n /Fail extracting tarball/i.test(t) ||\n /ECONNRESET/i.test(t) ||\n /ETIMEDOUT/i.test(t) ||\n /socket hang up/i.test(t)\n );\n}\n\nfunction runWorkspaceInstall(\n dir: string,\n installCommand: string,\n): { status: number | null; tail: string } {\n const result = spawnSync(\"sh\", [\"-ec\", installCommand], {\n cwd: dir,\n encoding: \"utf8\",\n timeout: 180_000,\n });\n const tail = (result.stderr || result.stdout || \"\").trim().slice(-2500);\n return { status: result.status, tail };\n}\n\ntype WorkspaceWarmInstall = (\n dir: string,\n installCommand: string,\n) => { status: number | null; tail: string };\n\nlet workspaceWarmInstall: WorkspaceWarmInstall = runWorkspaceInstall;\n\n/** @internal Test hook for workspace warm retry behavior. */\nexport function __setWorkspaceWarmBunInstallForTest(fn: WorkspaceWarmInstall | null): void {\n workspaceWarmInstall = fn ?? runWorkspaceInstall;\n}\n\n/** After clone/sync on a persistent workspace, ensure dependencies match lockfile per nvwa.build.yml. */\nexport function warmWorkspaceDependencies(\n dir: string,\n): { ok: true; skipped: boolean; durationMs: number } | { ok: false; error: string } {\n if (!agentWorkspaceIsPersistent()) {\n return { ok: true, skipped: true, durationMs: 0 };\n }\n if (!existsSync(join(dir, \"package.json\"))) {\n agentLog(\"workspace deps warm skipped\", { reason: \"no_package_json\" });\n return { ok: true, skipped: true, durationMs: 0 };\n }\n const resolved = resolveWorkspaceToolchainFromDir(dir);\n if (!resolved) {\n agentLog(\"workspace deps warm skipped\", { reason: \"toolchain_not_configured\" });\n return { ok: true, skipped: true, durationMs: 0 };\n }\n const { toolchain, source } = resolved;\n if (!workspaceNeedsDependencyWarm(dir, toolchain)) {\n agentLog(\"workspace deps warm skipped\", {\n reason: \"modules_current\",\n source,\n lockFile: toolchain.lockFile,\n modulesDir: toolchain.modulesDir,\n });\n return { ok: true, skipped: true, durationMs: 0 };\n }\n const started = Date.now();\n agentLog(\"workspace deps warm start\", {\n dir,\n source,\n installCommand: toolchain.installCommand,\n lockFile: toolchain.lockFile,\n modulesDir: toolchain.modulesDir,\n });\n\n let lastTail = \"\";\n for (let attempt = 1; attempt <= DEPS_WARM_MAX_ATTEMPTS; attempt++) {\n const { status, tail } = workspaceWarmInstall(dir, toolchain.installCommand);\n lastTail = tail;\n if (status === 0) {\n const durationMs = Date.now() - started;\n agentLog(\"workspace deps warm ok\", { durationMs, attempt });\n return { ok: true, skipped: false, durationMs };\n }\n const retryable = isRetryableDepsWarmError(tail);\n const hasMoreAttempts = attempt < DEPS_WARM_MAX_ATTEMPTS;\n if (!retryable || !hasMoreAttempts) break;\n const delayMs = DEPS_WARM_RETRY_DELAYS_MS[attempt - 1] ?? 5000;\n agentLog(\"workspace deps warm retry\", {\n attempt,\n nextAttempt: attempt + 1,\n delayMs,\n error: tail.slice(0, 500),\n });\n workspaceWarmRetrySleep(delayMs);\n }\n\n if (isRetryableDepsWarmError(lastTail)) {\n const nm = join(dir, toolchain.modulesDir);\n if (existsSync(nm)) {\n agentLog(\"workspace deps warm clearing modules dir after retryable failures\", {\n dir,\n modulesDir: toolchain.modulesDir,\n });\n try {\n rmSync(nm, { recursive: true, force: true });\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n agentLog(\"workspace deps warm modules clear failed\", { error: msg.slice(0, 200) });\n }\n }\n for (let attempt = 1; attempt <= DEPS_WARM_MAX_ATTEMPTS; attempt++) {\n const { status, tail } = workspaceWarmInstall(dir, toolchain.installCommand);\n lastTail = tail;\n if (status === 0) {\n const durationMs = Date.now() - started;\n agentLog(\"workspace deps warm ok\", { durationMs, attempt, afterNodeModulesClear: true });\n return { ok: true, skipped: false, durationMs };\n }\n const retryable = isRetryableDepsWarmError(tail);\n const hasMoreAttempts = attempt < DEPS_WARM_MAX_ATTEMPTS;\n if (!retryable || !hasMoreAttempts) break;\n const delayMs = DEPS_WARM_RETRY_DELAYS_MS[attempt - 1] ?? 5000;\n agentLog(\"workspace deps warm retry\", {\n attempt,\n nextAttempt: attempt + 1,\n delayMs,\n afterNodeModulesClear: true,\n error: tail.slice(0, 500),\n });\n workspaceWarmRetrySleep(delayMs);\n }\n }\n\n const durationMs = Date.now() - started;\n agentLog(\"workspace deps warm failed\", { durationMs, error: lastTail.slice(0, 500) });\n return {\n ok: false,\n error: `${toolchain.installCommand} failed during workspace warm${lastTail ? `:\\n${lastTail}` : \"\"}`,\n };\n}\n\nfunction sanitizePersistentWorkspaceBeforeFeature(\n dir: string,\n feature: string,\n integration: string,\n): string | null {\n if (!agentWorkspaceIsPersistent()) return null;\n const feat = branchShortName(feature);\n const integ = integration.trim();\n const resetRef = remoteOriginBranchExists(dir, feat)\n ? `origin/${feat}`\n : integ\n ? `origin/${branchShortName(integ)}`\n : null;\n if (resetRef) {\n const resetErr = gitWorkspaceErr(dir, [\"reset\", \"--hard\", resetRef]);\n if (resetErr) return resetErr;\n }\n const cleanErr = gitWorkspaceErr(dir, [\"clean\", \"-fd\", \"-e\", \"node_modules\"]);\n if (cleanErr) return cleanErr;\n agentLog(\"persistent workspace sanitized\", { resetRef, feature: feat });\n return null;\n}\n\n/** Non-interactive Git env for K8s agent pods (rebase --continue must not open an editor). */\nfunction gitWorkspaceEnv(): NodeJS.ProcessEnv {\n return {\n ...process.env,\n GIT_TERMINAL_PROMPT: \"0\",\n GIT_EDITOR: \"true\",\n EDITOR: \"true\",\n VISUAL: \"true\",\n };\n}\n\nfunction gitWorkspaceErr(dir: string, args: string[], timeoutMs = 600_000): string | null {\n const r = spawnSync(\"git\", [\"-C\", dir, ...args], {\n encoding: \"utf-8\",\n env: gitWorkspaceEnv(),\n timeout: timeoutMs,\n });\n if (r.status !== 0) return (r.stderr || r.stdout || \"git error\").slice(0, 4000);\n return null;\n}\n\nconst FEATURE_FETCH_DEPTH = 250;\n\nfunction branchShortName(branch: string): string {\n return branch.replace(/^refs\\/heads\\//, \"\").trim();\n}\n\nfunction integrationBranchFromSpec(spec: AgentJobConfigV1): string {\n return (\n spec.integrationBranch?.trim() ||\n spec.mergeSourceBranch?.trim() ||\n (spec.workspaceBase === \"integration\" ? spec.gitRef.trim() : \"\") ||\n \"dev\"\n );\n}\n\nfunction remoteOriginBranchExists(dir: string, branch: string): boolean {\n const short = branchShortName(branch);\n const r = spawnSync(\"git\", [\"-C\", dir, \"rev-parse\", \"--verify\", `refs/remotes/origin/${short}`], {\n stdio: \"ignore\",\n env: { ...process.env, GIT_TERMINAL_PROMPT: \"0\" },\n });\n return (r.status ?? 1) === 0;\n}\n\n/** Explicit refspec so shallow clones get `refs/remotes/origin/<branch>` (not only FETCH_HEAD). */\nfunction originFetchRefspec(branch: string): string {\n const short = branchShortName(branch);\n return `refs/heads/${short}:refs/remotes/origin/${short}`;\n}\n\n/** Remote tip for force-with-lease; prefers ls-remote so stale PVC tracking refs cannot skew the lease. */\nfunction originHeadShaForPushLease(dir: string, branch: string): string | null {\n const short = branchShortName(branch);\n const r = spawnSync(\n \"git\",\n [\"-C\", dir, \"ls-remote\", \"--heads\", \"origin\", `refs/heads/${short}`],\n {\n encoding: \"utf-8\",\n env: { ...process.env, GIT_TERMINAL_PROMPT: \"0\" },\n timeout: 120_000,\n },\n );\n if ((r.status ?? 1) === 0) {\n const line = (r.stdout ?? \"\").trim().split(\"\\n\").find(Boolean);\n const sha = line?.split(/\\s+/)[0]?.trim() ?? \"\";\n if (/^[0-9a-f]{40}$/i.test(sha)) return sha.toLowerCase();\n }\n return gitRemoteBranchSha(dir, short);\n}\n\n/** Best-effort fetch; missing remote feature ref must not fail workspace prep. */\nfunction fetchOriginRefOptional(dir: string, ref: string): boolean {\n const short = branchShortName(ref);\n const refspec = originFetchRefspec(ref);\n const runFetch = (extraArgs: string[]) => {\n const r = spawnSync(\n \"git\",\n [\"-C\", dir, \"fetch\", \"--depth\", String(FEATURE_FETCH_DEPTH), ...extraArgs, \"origin\", refspec],\n {\n encoding: \"utf-8\",\n env: { ...process.env, GIT_TERMINAL_PROMPT: \"0\" },\n timeout: 600_000,\n },\n );\n return {\n ok: (r.status ?? 1) === 0,\n stderr: ((r.stderr || r.stdout || \"\") as string).slice(0, 400),\n };\n };\n\n let result = runFetch([]);\n if (!result.ok && /non-fast-forward|fetch would clobber ref/i.test(result.stderr)) {\n agentLog(\"git fetch origin (feature) retry with --force after non-fast-forward\", {\n ref: short,\n priorTip: gitRemoteTip(dir, short),\n });\n result = runFetch([\"--force\"]);\n }\n\n const ok = result.ok;\n const detail: Record<string, unknown> = {\n ref: short,\n depth: FEATURE_FETCH_DEPTH,\n ok,\n remoteTip: ok ? gitRemoteTip(dir, short) : gitRemoteTip(dir, short),\n };\n if (!ok) {\n detail.stderr = result.stderr;\n }\n agentLog(\"git fetch origin (feature)\", detail);\n return ok;\n}\n\n/**\n * Checkout existing `origin/<feature>` or create feature branch from `origin/<integration>`.\n * Integration is always fetched first so a not-yet-pushed feature branch can be created locally.\n */\nexport function prepareFeatureWorkspace(\n dir: string,\n branch: string,\n integrationBranch: string,\n): { ok: true; created: boolean } | { ok: false; error: string } {\n const feat = branchShortName(branch);\n const integration = integrationBranch.trim();\n if (!feat.startsWith(\"feature/\")) {\n return { ok: false, error: `invalid feature branch: ${branch}` };\n }\n if (!integration) {\n return { ok: false, error: \"integration branch is empty\" };\n }\n\n agentLog(\"prepare feature workspace start\", { feature: feat, integration });\n\n const fetchIntegrationErr = gitWorkspaceErr(dir, [\n \"fetch\",\n \"--depth\",\n String(FEATURE_FETCH_DEPTH),\n \"origin\",\n originFetchRefspec(integration),\n ]);\n if (fetchIntegrationErr) {\n agentLog(\"prepare feature workspace failed\", { step: \"fetch integration\", error: fetchIntegrationErr });\n return { ok: false, error: fetchIntegrationErr };\n }\n agentLog(\"git fetch origin (integration) ok\", {\n integration,\n tip: gitRemoteTip(dir, integration),\n });\n\n const featFetched = fetchOriginRefOptional(dir, feat);\n const remoteExists = remoteOriginBranchExists(dir, feat);\n\n const sanitizeErr = sanitizePersistentWorkspaceBeforeFeature(dir, feat, integration);\n if (sanitizeErr) {\n agentLog(\"prepare feature workspace failed\", { step: \"sanitize persistent\", error: sanitizeErr });\n return { ok: false, error: sanitizeErr };\n }\n\n if (remoteExists) {\n agentLog(\"checkout existing remote feature branch\", {\n feature: feat,\n remoteTip: gitRemoteTip(dir, feat),\n featFetched,\n });\n const coErr = gitWorkspaceErr(dir, [\"checkout\", \"-B\", feat, `origin/${feat}`]);\n if (coErr) {\n agentLog(\"prepare feature workspace failed\", { step: \"checkout origin/feature\", error: coErr });\n return { ok: false, error: coErr };\n }\n agentLog(\"prepare feature workspace ok\", {\n created: false,\n branch: feat,\n head: gitHeadSha(dir),\n });\n return { ok: true, created: false };\n }\n\n agentLog(\"create feature branch from integration (no remote feature ref)\", {\n feature: feat,\n integration,\n featFetched,\n integrationTip: gitRemoteTip(dir, integration),\n });\n const detachErr = gitWorkspaceErr(dir, [\"checkout\", \"--detach\", `origin/${integration}`]);\n if (detachErr) {\n agentLog(\"prepare feature workspace failed\", { step: \"detach integration\", error: detachErr });\n return { ok: false, error: detachErr };\n }\n const berr = gitWorkspaceErr(dir, [\"checkout\", \"-B\", feat]);\n if (berr) {\n agentLog(\"prepare feature workspace failed\", { step: \"checkout -B feature\", error: berr });\n return { ok: false, error: berr };\n }\n agentLog(\"prepare feature workspace ok\", {\n created: true,\n branch: feat,\n head: gitHeadSha(dir),\n });\n return { ok: true, created: true };\n}\n\n/** Resolved feature branch from job.json (required for L1–L3 push). */\nexport function resolveFeatureBranchFromSpec(spec: AgentJobConfigV1): string | null {\n const tb = spec.targetBranch?.trim() ?? \"\";\n return tb.startsWith(\"feature/\") ? tb : null;\n}\n\n/** Ephemeral agent job output; never commit to the application repo. */\nexport const AGENT_JOB_OUTPUT_DIR = \"agent-out\";\n\nexport type FeatureWorkspacePushResult =\n | { ok: true; commitSha: string; committed: boolean; pushed: boolean }\n | { ok: false; error: string };\n\n/** Paths never staged for Agent feature commits (also listed in repo `.gitignore`). */\nconst WORKSPACE_COMMIT_EXCLUDE_PATHS = [\n AGENT_JOB_OUTPUT_DIR,\n \"test-results\",\n \"playwright-report\",\n \"blob-report\",\n \"test-results.json\",\n] as const;\n\n/** Stage tracked/untracked changes under `dir`, excluding agent output and test artifacts. */\nexport function stageWorkspaceForCommit(\n dir: string,\n opts?: { onlySubpath?: string },\n): { ok: true } | { ok: false; error: string } {\n const onlySubpath = opts?.onlySubpath?.trim();\n const addErr = onlySubpath\n ? gitWorkspaceErr(dir, [\"add\", \"--\", onlySubpath])\n : gitWorkspaceErr(dir, [\"add\", \"-A\"]);\n if (addErr) {\n return { ok: false, error: `git add failed: ${addErr}` };\n }\n if (!onlySubpath) {\n for (const excludePath of WORKSPACE_COMMIT_EXCLUDE_PATHS) {\n gitWorkspaceErr(dir, [\"reset\", \"HEAD\", \"--\", excludePath], 30_000);\n }\n }\n return { ok: true };\n}\n\nexport function workspaceHasStagedChanges(dir: string): boolean {\n const staged = spawnSync(\"git\", [\"-C\", dir, \"diff\", \"--cached\", \"--quiet\"], { stdio: \"ignore\" });\n return (staged.status ?? 1) !== 0;\n}\n\nconst CODE_TASK_PLACEHOLDER_SUMMARIES = new Set([\"代码任务已完成(未生成有效摘要)\"]);\n\nfunction firstLineTrimmed(text: string, maxLen = 72): string {\n const line =\n text\n .split(/\\r?\\n/)\n .map((l) => l.replace(/\\s+/g, \" \").trim())\n .find((l) => l.length > 0) ?? \"\";\n return line.slice(0, maxLen);\n}\n\nfunction repairBriefFromChatContext(chatContext: string): string | null {\n const trimmed = chatContext.trim();\n if (!trimmed) return null;\n\n const userFeedbackIdx = trimmed.indexOf(\"User feedback:\");\n if (userFeedbackIdx >= 0) {\n const line = firstLineTrimmed(trimmed.slice(userFeedbackIdx + \"User feedback:\".length));\n if (line) return line;\n }\n\n const fixMarker = \"【修复指令】\";\n const fixIdx = trimmed.indexOf(fixMarker);\n if (fixIdx >= 0) {\n const line = firstLineTrimmed(trimmed.slice(fixIdx + fixMarker.length));\n if (line) return line;\n }\n\n const userLines = trimmed\n .split(/\\r?\\n/)\n .map((l) => l.trim())\n .filter((l) => l.startsWith(\"User:\"));\n if (userLines.length > 0) {\n const last = userLines[userLines.length - 1]!;\n const line = firstLineTrimmed(last.slice(\"User:\".length));\n if (line) return line;\n }\n\n return null;\n}\n\n/** Subject line for code-task commits: prefer this run's agent summary, then fix chat context. */\nexport function buildCodeTaskCommitSubject(\n spec: Pick<AgentJobConfigV1, \"requirementTitle\" | \"requirementChatContext\">,\n agentSummary: string,\n): string {\n const summaryLine = firstLineTrimmed(agentSummary);\n if (summaryLine && !CODE_TASK_PLACEHOLDER_SUMMARIES.has(summaryLine)) {\n return summaryLine;\n }\n const fromChat = repairBriefFromChatContext(spec.requirementChatContext ?? \"\");\n if (fromChat) return fromChat;\n return firstLineTrimmed(spec.requirementTitle) || \"code task\";\n}\n\nexport function buildCodeTaskCommitMessage(\n spec: AgentJobConfigV1,\n agentSummary: string,\n): string {\n const subject = buildCodeTaskCommitSubject(spec, agentSummary);\n return `nvwa(task): ${subject}\\n\\n${triggeredByTrailerFromSpec(spec)}`;\n}\n\nexport {\n verifyBehaviorsBeforePush,\n verifyFrozenLockfileBeforePush,\n verifyBunAuditBeforePush,\n verifyDockerParityLockfile,\n} from \"./push-gate.ts\";\n\nfunction ensureLocalBranchAtHead(dir: string, branch: string): string | null {\n const short = branchShortName(branch);\n if (gitCurrentBranch(dir) === short) return null;\n return gitWorkspaceErr(dir, [\"checkout\", \"-B\", short]);\n}\n\nexport function commitFeatureWorkspace(\n dir: string,\n branch: string,\n message: string,\n opts?: { onlySubpath?: string },\n): FeatureWorkspacePushResult {\n const feat = branchShortName(branch);\n const branchErr = ensureLocalBranchAtHead(dir, feat);\n if (branchErr) {\n return { ok: false, error: `git checkout -B ${feat} failed: ${branchErr}` };\n }\n const headBefore = gitHeadSha(dir) ?? \"\";\n agentLog(\"git commit start\", {\n branch: feat,\n headBefore,\n ...(opts?.onlySubpath ? { onlySubpath: opts.onlySubpath } : {}),\n });\n\n const staged = stageWorkspaceForCommit(dir, opts);\n if (!staged.ok) {\n agentLog(\"git commit failed\", { step: \"add\", error: staged.error });\n return { ok: false, error: staged.error };\n }\n\n const hasStagedChanges = workspaceHasStagedChanges(dir);\n agentLog(\"git commit staging\", { hasStagedChanges });\n\n let commitSha = headBefore;\n let committed = false;\n\n if (hasStagedChanges) {\n const commitErr = gitWorkspaceErr(dir, [\"commit\", \"-m\", message]);\n if (commitErr) {\n agentLog(\"git commit failed\", { step: \"commit\", error: commitErr });\n return { ok: false, error: `git commit failed: ${commitErr}` };\n }\n commitSha = gitHeadSha(dir, false) ?? headBefore;\n committed = true;\n }\n\n const headFull = gitHeadSha(dir, false) ?? headBefore;\n const remoteFull = gitRemoteBranchSha(dir, feat);\n const needsPublish =\n remoteFull == null || (headFull.length > 0 && remoteFull !== headFull);\n\n if (!committed && !needsPublish) {\n agentLog(\"git commit skipped (no repo changes, branch already on origin)\", {\n branch: feat,\n head: headBefore,\n });\n return { ok: true, commitSha: headBefore, committed: false, pushed: false };\n }\n\n return { ok: true, commitSha, committed, pushed: false };\n}\n\nfunction gitDiffNameStatusLines(dir: string): string[] {\n const out: string[] = [];\n for (const extra of [[\"diff\", \"--name-status\"], [\"diff\", \"--cached\", \"--name-status\"]] as const) {\n const r = spawnSync(\"git\", [\"-C\", dir, ...extra], { encoding: \"utf8\" });\n if (r.status !== 0) continue;\n for (const line of (r.stdout ?? \"\").split(\"\\n\")) {\n const t = line.trim();\n if (t) out.push(t);\n }\n }\n return out;\n}\n\nexport function commitAndPushFeatureWorkspace(\n dir: string,\n branch: string,\n message: string,\n opts?: { onlySubpath?: string; forceWithLease?: boolean },\n): FeatureWorkspacePushResult {\n const deletedProtected = findDeletedProtectedPaths(gitDiffNameStatusLines(dir));\n if (deletedProtected.length > 0) {\n return {\n ok: false,\n error: `Cannot delete platform security paths: ${deletedProtected.join(\", \")}`,\n };\n }\n const committed = commitFeatureWorkspace(dir, branch, message, opts);\n if (!committed.ok) return committed;\n\n const feat = branchShortName(branch);\n const headFull = gitHeadSha(dir, false) ?? committed.commitSha;\n const remoteFull = gitRemoteBranchSha(dir, feat);\n const needsPublish =\n remoteFull == null || (headFull.length > 0 && remoteFull !== headFull);\n\n if (!committed.committed && !needsPublish) {\n return committed;\n }\n\n agentLog(\n committed.committed ? \"git push start\" : \"git push start (publish branch, no new commit)\",\n {\n branch: feat,\n commitSha: headFull,\n remoteTipBefore: gitRemoteTip(dir, feat),\n forceWithLease: opts?.forceWithLease === true,\n },\n );\n const pushed = pushFeatureBranchWorkspace(dir, branch, {\n forceWithLease: opts?.forceWithLease === true,\n });\n if (!pushed.ok) {\n agentLog(\"git push failed\", { branch: feat, error: pushed.error.slice(0, 800) });\n return { ok: false, error: pushed.error };\n }\n agentLog(\"git push ok\", {\n branch: feat,\n commitSha: gitHeadSha(dir),\n remoteTip: gitRemoteTip(dir, feat),\n });\n return { ok: true, commitSha: pushed.commitSha, committed: committed.committed, pushed: true };\n}\n\n/** @internal Exported for unit tests. */\nexport function pushFeatureBranchWorkspace(\n dir: string,\n branch: string,\n opts?: { forceWithLease?: boolean },\n): { ok: true; commitSha: string } | { ok: false; error: string } {\n const feat = branchShortName(branch);\n let pushArgs: string[];\n if (opts?.forceWithLease) {\n fetchOriginRefOptional(dir, feat);\n const remoteSha = originHeadShaForPushLease(dir, branch);\n if (remoteSha) {\n pushArgs = [\n \"push\",\n `--force-with-lease=refs/heads/${feat}:${remoteSha}`,\n \"-u\",\n \"origin\",\n feat,\n ];\n agentLog(\"git push force-with-lease (explicit remote tip)\", {\n branch: feat,\n localHead: gitHeadSha(dir),\n leaseSha: remoteSha.slice(0, 8),\n localRemoteTip: gitRemoteTip(dir, feat),\n });\n } else {\n pushArgs = [\"push\", \"-u\", \"origin\", feat];\n agentLog(\"git push (no remote ref for force-with-lease)\", { branch: feat });\n }\n } else {\n pushArgs = [\"push\", \"-u\", \"origin\", feat];\n }\n const pushErr = gitWorkspaceErr(dir, pushArgs, 900_000);\n if (pushErr) return { ok: false, error: `git push failed: ${pushErr}` };\n const shaOut = spawnSync(\"git\", [\"-C\", dir, \"rev-parse\", \"HEAD\"], {\n encoding: \"utf-8\",\n env: { ...process.env, GIT_TERMINAL_PROMPT: \"0\" },\n });\n const commitSha = (shaOut.stdout ?? \"\").trim().slice(0, 64);\n return { ok: true, commitSha };\n}\n\nfunction gitIdentityFromSpec(spec: AgentJobConfigV1): { name: string; email: string } {\n const name =\n spec.triggeredByName?.trim() ||\n spec.triggeredByUsername?.trim() ||\n spec.projectGitCommitName?.trim() ||\n \"Nvwa Agent\";\n const email =\n spec.triggeredByEmail?.trim() ||\n (spec.triggeredByUserId?.trim() ? `nvwa-user-${spec.triggeredByUserId.trim()}@users.noreply.nvwa.work` : \"\") ||\n (spec.triggeredByUsername?.trim() ? `${spec.triggeredByUsername.trim()}@users.noreply.nvwa.work` : \"\") ||\n spec.projectGitCommitEmail?.trim() ||\n \"nvwa-agent@local.invalid\";\n return { name, email };\n}\n\nfunction configureGitIdentityForWorkspace(dir: string, spec: AgentJobConfigV1): void {\n const id = gitIdentityFromSpec(spec);\n const env = gitWorkspaceEnv();\n spawnSync(\"git\", [\"-C\", dir, \"config\", \"user.email\", id.email], { stdio: \"ignore\", env });\n spawnSync(\"git\", [\"-C\", dir, \"config\", \"user.name\", id.name], { stdio: \"ignore\", env });\n spawnSync(\"git\", [\"-C\", dir, \"config\", \"core.editor\", \"true\"], { stdio: \"ignore\", env });\n spawnSync(\"git\", [\"-C\", dir, \"config\", \"sequence.editor\", \"true\"], { stdio: \"ignore\", env });\n}\n\nfunction triggeredByTrailerFromSpec(spec: AgentJobConfigV1): string {\n const id = gitIdentityFromSpec(spec);\n const userId = spec.triggeredByUserId?.trim() || \"\";\n if (!userId) return `Triggered-by: ${id.name} <${id.email}>`;\n return `Triggered-by: ${id.name} <${id.email}>\\nNvwa-User-Id: ${userId}`;\n}\n\nfunction fileTreeSnippet(dir: string, max = 200): string {\n const ls = spawnSync(\"git\", [\"-C\", dir, \"ls-files\"], {\n encoding: \"utf-8\",\n maxBuffer: 10_000_000,\n });\n if (ls.status !== 0) return \"(could not list files)\";\n return ls.stdout.split(\"\\n\").filter(Boolean).slice(0, max).join(\"\\n\");\n}\n\nconst MAX_ACTIVITY_LINES = 120;\n/** 相同 progress 文案时,至少间隔这么久才再 POST callback */\nconst PROGRESS_EMIT_MIN_MS = 5000;\n/** 有新的工具活动行时,最短 callback 间隔 */\nconst PROGRESS_EMIT_BURST_MS = 1500;\n/** 长时间无变化时,仍向 Creator 发一次心跳 progress */\nconst PROGRESS_HEARTBEAT_MS = 20_000;\nconst LOG_TEXT_MAX = 2000;\nconst LOG_PROMPT_MAX = 4000;\nconst LOG_ARGS_MAX = 1200;\nconst ASSISTANT_LOG_THROTTLE_MS = 2500;\n\nfunction firstStringArg(o: Record<string, unknown>, keys: string[]): string {\n for (const k of keys) {\n const v = o[k];\n if (typeof v === \"string\" && v.trim()) return v.trim();\n }\n return \"\";\n}\n\nfunction getNestedCall(evt: Record<string, unknown>): Record<string, unknown> | null {\n for (const key of [\"tool_call\", \"toolCall\", \"call\", \"tool_use\"]) {\n const v = evt[key];\n if (v && typeof v === \"object\" && !Array.isArray(v)) return v as Record<string, unknown>;\n }\n return null;\n}\n\ntype CursorToolCallInfo = {\n tool: string;\n args: Record<string, unknown>;\n resultPreview?: string;\n};\n\n/** Cursor stream-json: tool_call.readToolCall / writeToolCall / … */\nfunction parseCursorToolCall(evt: Record<string, unknown>): CursorToolCallInfo | null {\n const raw = evt.tool_call ?? evt.toolCall ?? getNestedCall(evt);\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return null;\n const tc = raw as Record<string, unknown>;\n\n const fn = tc.function;\n if (fn && typeof fn === \"object\" && !Array.isArray(fn)) {\n const f = fn as Record<string, unknown>;\n const name = typeof f.name === \"string\" && f.name.trim() ? f.name.trim() : \"function\";\n let args: Record<string, unknown> = {};\n if (typeof f.arguments === \"string\" && f.arguments.trim()) {\n try {\n const j = JSON.parse(f.arguments) as unknown;\n if (j && typeof j === \"object\" && !Array.isArray(j)) args = j as Record<string, unknown>;\n } catch {\n args = { raw: f.arguments };\n }\n }\n return { tool: name, args };\n }\n\n for (const key of Object.keys(tc)) {\n const norm = key.replace(/_/g, \"\").toLowerCase();\n if (!norm.endsWith(\"toolcall\")) continue;\n const inner = tc[key];\n if (!inner || typeof inner !== \"object\" || Array.isArray(inner)) continue;\n const block = inner as Record<string, unknown>;\n const tool = key.replace(/ToolCall$/, \"\");\n const args =\n block.args && typeof block.args === \"object\" && !Array.isArray(block.args)\n ? (block.args as Record<string, unknown>)\n : {};\n let resultPreview: string | undefined;\n if (block.result !== undefined) {\n resultPreview = truncateForLog(JSON.stringify(block.result), LOG_ARGS_MAX);\n }\n return { tool, args, resultPreview };\n }\n return null;\n}\n\nfunction textFromContentBlocks(content: unknown): string {\n if (!Array.isArray(content)) return \"\";\n const parts: string[] = [];\n for (const block of content) {\n if (!block || typeof block !== \"object\" || Array.isArray(block)) continue;\n const b = block as Record<string, unknown>;\n if (typeof b.text === \"string\" && b.text) parts.push(b.text);\n }\n return parts.join(\"\");\n}\n\nfunction extractCursorMessageText(evt: Record<string, unknown>): string {\n const msg = evt.message;\n if (msg && typeof msg === \"object\" && !Array.isArray(msg)) {\n const fromMsg = textFromContentBlocks((msg as Record<string, unknown>).content);\n if (fromMsg) return fromMsg;\n }\n if (Array.isArray(evt.content)) {\n const fromTop = textFromContentBlocks(evt.content);\n if (fromTop) return fromTop;\n }\n if (typeof evt.content === \"string\" && evt.content.trim()) return evt.content.trim();\n return \"\";\n}\n\nfunction isDuplicateAssistantStreamEvent(evt: Record<string, unknown>): boolean {\n return evt.type === \"assistant\" && typeof evt.model_call_id === \"string\" && !!evt.model_call_id.trim();\n}\n\nfunction shouldEmitProgressForStreamEvent(\n evt: Record<string, unknown>,\n activityLineAdded: boolean,\n): boolean {\n if (activityLineAdded) return true;\n const type = typeof evt.type === \"string\" ? evt.type : \"\";\n const subtype = typeof evt.subtype === \"string\" ? evt.subtype : \"\";\n if (type === \"result\" || type === \"error\") return true;\n if (type === \"tool_call\" && subtype === \"completed\") return true;\n if (type === \"assistant\" && !isDuplicateAssistantStreamEvent(evt)) return true;\n return false;\n}\n\nfunction parseToolArgs(call: Record<string, unknown> | null, evt?: Record<string, unknown>): Record<string, unknown> {\n if (evt) {\n const parsed = parseCursorToolCall(evt);\n if (parsed && Object.keys(parsed.args).length > 0) return parsed.args;\n }\n if (!call) return {};\n const raw = call.args ?? call.arguments ?? call.input ?? call.parameters;\n if (raw && typeof raw === \"object\" && !Array.isArray(raw)) return raw as Record<string, unknown>;\n if (typeof raw === \"string\") {\n try {\n const j = JSON.parse(raw) as unknown;\n if (j && typeof j === \"object\" && !Array.isArray(j)) return j as Record<string, unknown>;\n } catch {\n /* ignore */\n }\n }\n return {};\n}\n\nfunction toolNameFrom(evt: Record<string, unknown>, call: Record<string, unknown> | null): string {\n const parsed = parseCursorToolCall(evt);\n if (parsed?.tool) return parsed.tool;\n const objs = [call, evt].filter((x): x is Record<string, unknown> => x != null);\n for (const o of objs) {\n for (const key of [\"name\", \"tool\", \"toolName\", \"tool_name\", \"command\"]) {\n const v = o[key];\n if (typeof v === \"string\" && v.trim()) return v.trim();\n }\n const fn = o.function;\n if (fn && typeof fn === \"object\" && !Array.isArray(fn)) {\n const n = (fn as Record<string, unknown>).name;\n if (typeof n === \"string\" && n.trim()) return n.trim();\n }\n }\n return \"\";\n}\n\nfunction fileBasename(path: string): string {\n const s = path.replace(/\\\\/g, \"/\");\n return s.split(\"/\").filter(Boolean).pop() ?? path;\n}\n\nfunction lineRangeFromArgs(args: Record<string, unknown>): string | null {\n const start =\n typeof args.startLine === \"number\"\n ? args.startLine\n : typeof args.start_line === \"number\"\n ? args.start_line\n : typeof args.line === \"number\"\n ? args.line\n : null;\n const end =\n typeof args.endLine === \"number\"\n ? args.endLine\n : typeof args.end_line === \"number\"\n ? args.end_line\n : null;\n if (start != null && end != null && end >= start) return `L${start}-${end}`;\n if (start != null) return `L${start}`;\n return null;\n}\n\nfunction truncateMid(s: string, max: number): string {\n if (s.length <= max) return s;\n return `${s.slice(0, max - 1)}…`;\n}\n\nfunction truncateForLog(s: string, max: number): string {\n return truncateMid(s.replace(/\\s+/g, \" \").trim(), max);\n}\n\nfunction promptPreviewForLog(prompt: string): string {\n const t = prompt.trim();\n if (t.length <= LOG_PROMPT_MAX) return t;\n const head = t.slice(0, Math.floor(LOG_PROMPT_MAX * 0.7));\n const tail = t.slice(-Math.floor(LOG_PROMPT_MAX * 0.25));\n return `${head}\\n…(${t.length} chars)…\\n${tail}`;\n}\n\nfunction callbackUrlForLog(url: string): string {\n try {\n const u = new URL(url);\n return `${u.origin}${u.pathname}`;\n } catch {\n return truncateForLog(url, 160);\n }\n}\n\nfunction agentLog(message: string, detail?: Record<string, unknown>): void {\n const ts = new Date().toISOString();\n if (detail && Object.keys(detail).length > 0) {\n console.error(`[nvwa-agent] ${ts} | ${message}`, JSON.stringify(detail));\n } else {\n console.error(`[nvwa-agent] ${ts} | ${message}`);\n }\n}\n\nfunction extractStreamEventText(evt: Record<string, unknown>): string {\n const fromCursorMsg = extractCursorMessageText(evt);\n if (fromCursorMsg) return fromCursorMsg;\n for (const key of [\n \"text\",\n \"delta\",\n \"thinking\",\n \"message\",\n \"content\",\n \"result\",\n \"output\",\n \"stderr\",\n ]) {\n const v = evt[key];\n if (typeof v === \"string\" && v.trim()) return v.trim();\n }\n if (evt.thinking && typeof evt.thinking === \"object\" && !Array.isArray(evt.thinking)) {\n const th = evt.thinking as Record<string, unknown>;\n if (typeof th.text === \"string\" && th.text.trim()) return th.text.trim();\n const fromTh = textFromContentBlocks(th.content);\n if (fromTh) return fromTh;\n }\n const call = getNestedCall(evt);\n if (call) {\n for (const key of [\"output\", \"result\", \"content\", \"message\", \"stderr\", \"stdout\"]) {\n const v = call[key];\n if (typeof v === \"string\" && v.trim()) return v.trim();\n }\n }\n return \"\";\n}\n\nfunction streamEventLogLabel(evt: Record<string, unknown>): string {\n const type = typeof evt.type === \"string\" ? evt.type : \"\";\n if (type === \"user\") return \"cursor ← user (CLI 收到的 prompt)\";\n if (type === \"assistant\") return \"cursor → assistant\";\n if (type === \"thinking\") return \"cursor → thinking\";\n if (type === \"tool_call\") return \"cursor → tool_call\";\n if (type === \"result\") return \"cursor → result\";\n if (type === \"system\") return \"cursor → system\";\n if (type === \"error\") return \"cursor → error\";\n return \"cursor ← stream\";\n}\n\ntype StreamLogContext = { dialogBuf?: string };\n\nfunction attachStreamParseFallback(\n detail: Record<string, unknown>,\n evt: Record<string, unknown>,\n type: string,\n): void {\n const hasText = typeof detail.text === \"string\" && detail.text.length > 0;\n const hasTool = typeof detail.tool === \"string\";\n if (type === \"tool_call\" && !hasTool) {\n const raw = evt.tool_call ?? evt.toolCall;\n if (raw !== undefined) {\n detail.rawToolCall = truncateForLog(JSON.stringify(raw), LOG_ARGS_MAX);\n } else {\n detail.rawEventKeys = Object.keys(evt);\n }\n }\n if ((type === \"user\" || type === \"assistant\" || type === \"thinking\") && !hasText) {\n detail.rawEvent = truncateForLog(JSON.stringify(evt), 1200);\n }\n}\n\nfunction streamEventLogDetail(\n evt: Record<string, unknown>,\n ctx?: StreamLogContext,\n): Record<string, unknown> {\n const type = typeof evt.type === \"string\" ? evt.type : \"\";\n const subtype = typeof evt.subtype === \"string\" ? evt.subtype : \"\";\n const detail: Record<string, unknown> = {\n event: subtype ? `${type}/${subtype}` : type || \"unknown\",\n };\n\n if (typeof evt.call_id === \"string\" && evt.call_id) detail.callId = evt.call_id;\n if (typeof evt.session_id === \"string\" && evt.session_id) {\n detail.sessionId = evt.session_id.slice(0, 8);\n }\n\n let text = extractStreamEventText(evt);\n if (\n !text &&\n ctx?.dialogBuf &&\n (type === \"thinking\" || type === \"assistant\") &&\n (subtype === \"completed\" || subtype === \"done\" || subtype === \"success\" || subtype === \"\")\n ) {\n text = ctx.dialogBuf;\n }\n if (text) detail.text = truncateForLog(text, LOG_TEXT_MAX);\n\n if (type === \"tool_call\") {\n const parsed = parseCursorToolCall(evt);\n if (parsed) {\n detail.tool = parsed.tool;\n if (Object.keys(parsed.args).length > 0) {\n detail.args = truncateForLog(JSON.stringify(parsed.args), LOG_ARGS_MAX);\n }\n if (parsed.resultPreview) detail.result = parsed.resultPreview;\n }\n const activity = formatToolActivityLine(evt);\n if (activity) detail.summary = activity;\n }\n\n if (type === \"system\") {\n if (typeof evt.model === \"string\" && evt.model) detail.model = evt.model;\n if (typeof evt.cwd === \"string\" && evt.cwd) detail.cwd = evt.cwd;\n }\n\n if (type === \"result\") {\n if (typeof evt.duration_ms === \"number\") detail.durationMs = evt.duration_ms;\n if (evt.is_error === true) detail.status = \"error\";\n else detail.status = \"ok\";\n if (typeof evt.result === \"string\" && evt.result.trim()) {\n detail.result = truncateForLog(evt.result, LOG_TEXT_MAX);\n }\n }\n\n if (type === \"assistant\" && isDuplicateAssistantStreamEvent(evt)) {\n detail.skippedDuplicate = true;\n }\n\n if (type === \"error\" || evt.is_error === true) {\n detail.status = \"error\";\n }\n\n attachStreamParseFallback(detail, evt, type);\n return detail;\n}\n\nfunction shouldThrottleAssistantStreamLog(\n type: string,\n subtype: string,\n textLen: number,\n lastLogAt: number,\n): boolean {\n if (type !== \"assistant\" && type !== \"thinking\") return false;\n if (subtype === \"completed\" || subtype === \"done\" || subtype === \"success\") return false;\n if (textLen >= 400) return false;\n return Date.now() - lastLogAt < ASSISTANT_LOG_THROTTLE_MS;\n}\n\nfunction gitHeadSha(dir: string, short = true): string | null {\n const args = short ? [\"rev-parse\", \"--short\", \"HEAD\"] : [\"rev-parse\", \"HEAD\"];\n const r = spawnSync(\"git\", [\"-C\", dir, ...args], {\n encoding: \"utf-8\",\n env: { ...process.env, GIT_TERMINAL_PROMPT: \"0\" },\n });\n const sha = (r.stdout ?? \"\").trim();\n return (r.status ?? 1) === 0 && sha ? sha : null;\n}\n\nfunction gitRemoteBranchSha(dir: string, branch: string): string | null {\n const short = branchShortName(branch);\n const r = spawnSync(\"git\", [\"-C\", dir, \"rev-parse\", `refs/remotes/origin/${short}`], {\n encoding: \"utf-8\",\n env: { ...process.env, GIT_TERMINAL_PROMPT: \"0\" },\n });\n const sha = (r.stdout ?? \"\").trim();\n return (r.status ?? 1) === 0 && sha ? sha : null;\n}\n\nfunction gitRemoteTip(dir: string, branch: string): string | null {\n const full = gitRemoteBranchSha(dir, branch);\n if (!full) return null;\n const r = spawnSync(\"git\", [\"-C\", dir, \"rev-parse\", \"--short\", full], {\n encoding: \"utf-8\",\n env: { ...process.env, GIT_TERMINAL_PROMPT: \"0\" },\n });\n const sha = (r.stdout ?? \"\").trim();\n return (r.status ?? 1) === 0 && sha ? sha : null;\n}\n\nfunction gitIsAncestor(dir: string, ancestorSha: string, descendantSha: string): boolean {\n const r = spawnSync(\n \"git\",\n [\"-C\", dir, \"merge-base\", \"--is-ancestor\", ancestorSha, descendantSha],\n { encoding: \"utf-8\", env: gitWorkspaceEnv() },\n );\n return (r.status ?? 1) === 0;\n}\n\nfunction featureRebaseHasUniqueChangesVsMergeSource(\n dir: string,\n mergeSource: string,\n): { ok: true } | { ok: false; error: string } {\n const ms = branchShortName(mergeSource);\n const devSha = gitRemoteBranchSha(dir, ms);\n const headSha = gitHeadSha(dir, false);\n if (!devSha || !headSha) {\n return { ok: false, error: \"could not resolve dev or HEAD after rebase\" };\n }\n if (devSha === headSha) {\n return {\n ok: false,\n error:\n `rebase 完成后 feature 与 origin/${ms} 指向同一提交;本卡相对 dev 的变更可能已在冲突处理中丢失。` +\n \"请勿整段采用 dev/HEAD 侧内容。请 git rebase --abort 后从 rebase 前的 commit 恢复并重试。\",\n };\n }\n const diff = spawnSync(\"git\", [\"-C\", dir, \"diff\", \"--quiet\", `origin/${ms}`, \"HEAD\"], {\n encoding: \"utf-8\",\n env: gitWorkspaceEnv(),\n });\n if ((diff.status ?? 1) === 0) {\n return {\n ok: false,\n error:\n `rebase 完成后 feature 与 origin/${ms} 无文件差异;本卡提交可能已在冲突处理中被丢弃。` +\n \"请恢复 rebase 前的 feature 分支后重新处理冲突。\",\n };\n }\n return { ok: true };\n}\n\nfunction formatToolActivityFromParsed(\n tool: string,\n args: Record<string, unknown>,\n subtype: string,\n): string | null {\n const lowered = tool.toLowerCase();\n const path = firstStringArg(args, [\"path\", \"file_path\", \"target_file\", \"file\", \"filename\"]);\n const pattern = firstStringArg(args, [\"pattern\", \"regex\", \"query\", \"search\"]);\n const glob = firstStringArg(args, [\"glob\", \"glob_pattern\", \"include\", \"target_directory\"]);\n const cmd = firstStringArg(args, [\"command\", \"cmd\"]);\n\n if ((lowered.includes(\"read\") || lowered === \"read\") && path) {\n const lr = lineRangeFromArgs(args);\n const base = fileBasename(path);\n return lr ? `Read ${base} ${lr}` : `Read ${base}`;\n }\n if (lowered.includes(\"write\") || lowered.includes(\"edit\")) {\n if (path) return `${subtype === \"completed\" ? \"Wrote\" : \"Write\"} ${fileBasename(path)}`;\n }\n if (lowered.includes(\"grep\") || lowered.includes(\"ripgrep\")) {\n const pat = pattern || glob || \"…\";\n const where = path || glob || \"repo\";\n return `Grepped ${truncateMid(pat, 72)} in ${truncateMid(where, 48)}`;\n }\n if (lowered.includes(\"shell\") && cmd) {\n return `Shell ${truncateMid(cmd, 96)}`;\n }\n if (\n lowered.includes(\"search\") ||\n lowered.includes(\"glob\") ||\n lowered.includes(\"ls\") ||\n lowered.includes(\"list\")\n ) {\n const hint = glob || pattern || path || tool;\n return `Searched ${truncateMid(hint, 96)}`;\n }\n if (path) return `${tool} ${fileBasename(path)}`;\n if (subtype === \"started\") return `${tool}…`;\n if (subtype === \"completed\") return `${tool} done`;\n return `${tool}`;\n}\n\n/** 从 stream-json 事件抽出类似 Cursor 的单行工具描述;无则返回 null。 */\nfunction formatToolActivityLine(evt: Record<string, unknown>): string | null {\n const type = typeof evt.type === \"string\" ? evt.type : \"\";\n const subtype = typeof evt.subtype === \"string\" ? evt.subtype : \"\";\n\n const strMsg = typeof evt.message === \"string\" ? evt.message.trim() : \"\";\n if (strMsg) {\n if (type === \"assistant\") return null;\n return strMsg;\n }\n\n if (type === \"tool_call\") {\n const parsed = parseCursorToolCall(evt);\n if (parsed?.tool) {\n return formatToolActivityFromParsed(parsed.tool, parsed.args, subtype);\n }\n const call = getNestedCall(evt);\n const tool = toolNameFrom(evt, call);\n if (tool) return formatToolActivityFromParsed(tool, parseToolArgs(call, evt), subtype);\n const raw = evt.tool_call ?? evt.toolCall;\n if (raw && typeof raw === \"object\" && !Array.isArray(raw)) {\n const keys = Object.keys(raw as Record<string, unknown>).filter((k) => k !== \"function\");\n const id =\n typeof evt.call_id === \"string\" && evt.call_id ? evt.call_id.slice(-10) : \"\";\n if (keys.length > 0) {\n return `Tool ${keys.join(\"+\")}${id ? ` [${id}]` : \"\"}`;\n }\n }\n if (typeof evt.call_id === \"string\" && evt.call_id) {\n return `tool_call ${evt.call_id.slice(-12)}`;\n }\n }\n\n return null;\n}\n\nfunction isThinkingLine(s: string): boolean {\n return s.startsWith(\"思考中\") || s.startsWith(\"Thinking\");\n}\n\nfunction bumpActivityCounts(\n counts: AgentActivityCounts,\n line: string,\n evt: Record<string, unknown>,\n): void {\n const type = typeof evt.type === \"string\" ? evt.type : \"\";\n if (type === \"tool_call\") {\n const call = getNestedCall(evt);\n const tool = toolNameFrom(evt, call).toLowerCase();\n if (tool.includes(\"grep\") || tool.includes(\"ripgrep\")) {\n counts.grep++;\n return;\n }\n if (tool.includes(\"read\")) {\n counts.read++;\n return;\n }\n if (\n tool.includes(\"search\") ||\n tool.includes(\"glob\") ||\n tool.includes(\"list_dir\") ||\n tool.includes(\"listdir\") ||\n tool.includes(\"file_search\") ||\n tool.includes(\"codebase\")\n ) {\n counts.search++;\n return;\n }\n return;\n }\n if (/^grepped\\s/i.test(line)) counts.grep++;\n else if (/^read\\s/i.test(line)) counts.read++;\n else if (/^searched\\s/i.test(line)) counts.search++;\n}\n\nfunction summarizeStreamEvent(evt: Record<string, unknown>): string | null {\n const type = typeof evt.type === \"string\" ? evt.type : \"\";\n const subtype = typeof evt.subtype === \"string\" ? evt.subtype : \"\";\n if (type === \"assistant\") {\n if (isDuplicateAssistantStreamEvent(evt)) return null;\n const text = extractCursorMessageText(evt);\n return text ? truncateForLog(text, 400) : null;\n }\n if (type === \"thinking\") {\n const text = extractStreamEventText(evt);\n return text ? truncateForLog(text, 400) : null;\n }\n const toolLine = formatToolActivityLine(evt);\n if (toolLine) return toolLine;\n if (type === \"result\" && subtype === \"success\") return \"Agent completed successfully\";\n if (type === \"result\" && typeof evt.result === \"string\" && evt.result.trim()) {\n return truncateForLog(evt.result.trim(), 400);\n }\n if (type && subtype) return `${type}/${subtype}`;\n if (type) return type;\n return null;\n}\n\ntype RewritePipelineTodoId =\n | \"rewrite_gate\"\n | \"l1_foundation\"\n | \"l2_capabilities\"\n | \"l3_behaviors\"\n | \"development_goal\"\n | \"emit_result\";\n\ntype RewritePipelineTodoStatus = \"pending\" | \"running\" | \"done\" | \"failed\" | \"skipped\";\n\nfunction buildRewritePipelineProgressPayload(\n jobCode: string,\n currentTodoId: RewritePipelineTodoId,\n statusById: Partial<Record<RewritePipelineTodoId, RewritePipelineTodoStatus>>,\n): Record<string, unknown> {\n const ids: RewritePipelineTodoId[] = [\n \"rewrite_gate\",\n \"l1_foundation\",\n \"l2_capabilities\",\n \"l3_behaviors\",\n \"development_goal\",\n \"emit_result\",\n ];\n return {\n rewritePipeline: {\n jobCode,\n currentTodoId,\n todos: ids.map((id) => ({\n id,\n status: statusById[id] ?? \"pending\",\n ...([\"done\", \"skipped\", \"failed\"].includes(statusById[id] ?? \"\")\n ? { finishedAt: new Date().toISOString() }\n : {}),\n })),\n updatedAt: new Date().toISOString(),\n },\n };\n}\n\nasync function postRewritePipelineProgress(\n jobCode: string,\n currentTodoId: RewritePipelineTodoId,\n statusById: Partial<Record<RewritePipelineTodoId, RewritePipelineTodoStatus>>,\n): Promise<void> {\n await postCallback({\n ok: true,\n final: false,\n progress: buildRewritePipelineProgressPayload(jobCode, currentTodoId, statusById),\n });\n}\n\nasync function runRewriteAgentPhase(input: {\n prompt: string;\n correctionPrompt?: string;\n satisfied: () => boolean;\n dir: string;\n runnerCommand: string;\n onProgress: (progress: AgentProgress) => Promise<void>;\n streamOpts?: { extraArgs?: string[] };\n}): Promise<{ exitCode: number }> {\n const first = await tryAgentStream(input.prompt, input.dir, input.runnerCommand, input.onProgress, input.streamOpts);\n if (first.exitCode !== 0) return first;\n if (input.satisfied() || !input.correctionPrompt?.trim()) return first;\n return tryAgentStream(input.correctionPrompt, input.dir, input.runnerCommand, input.onProgress, {\n extraArgs: [\"--continue\"],\n });\n}\n\nasync function executeRewriteL1L3Pipeline(input: {\n spec: AgentJobConfigV1;\n dir: string;\n runnerCommand: string;\n outputPath: { dir: string; resultJsonPath: string };\n indexSample: string;\n title: string;\n raw: string;\n chatContext: string;\n}): Promise<void> {\n const { spec, dir, runnerCommand, outputPath, indexSample, title, raw, chatContext } = input;\n const rawWithDocs = raw + integrationBusinessPromptSuffix(spec);\n const jobCode = spec.jobCode?.trim() || spec.jobId;\n const featureBranch = resolveFeatureBranchFromSpec(spec);\n if (!featureBranch) {\n await postCallback({\n ok: false,\n error: \"missing targetBranch (feature/*) in job.json for L1–L3 rewrite\",\n });\n agentExit(1);\n }\n\n const slug = slugFromRequirementTitle(title);\n const wsPaths = rewriteWorkspacePaths(slug);\n const integrationBranch = integrationBranchFromSpec(spec);\n\n configureGitIdentityForWorkspace(dir, spec);\n const prep = prepareFeatureWorkspace(dir, featureBranch, integrationBranch);\n if (!prep.ok) {\n await postCallback({\n ok: false,\n error: `could not prepare feature workspace for rewrite: ${prep.error}`,\n });\n agentExit(1);\n }\n\n await postRewritePipelineProgress(jobCode, \"rewrite_gate\", {\n rewrite_gate: \"running\",\n l1_foundation: \"pending\",\n l2_capabilities: \"pending\",\n l3_behaviors: \"pending\",\n development_goal: \"pending\",\n emit_result: \"pending\",\n });\n\n const gateJsonPath = join(outputPath.dir, \"rewrite-gate.json\");\n const gateResult = await runRewriteGate({\n dir,\n integrationBranch,\n deltaText: chatContext,\n title,\n rawInput: raw,\n rewriteForceFull: spec.rewriteForceFull === true,\n llmBaseUrl: spec.llmBaseUrl,\n llmModel: spec.llmModel,\n llmApiKey: (process.env.NVWA_OS_LLM_GATEWAY_API_KEY ?? \"\").trim() || null,\n specRefsHint: spec.rewriteGateSpecRefs ?? undefined,\n outputPath: gateJsonPath,\n });\n\n await postCallback({\n ok: true,\n final: false,\n rewriteGate: gateResult,\n progress: buildRewritePipelineProgressPayload(jobCode, \"rewrite_gate\", {\n rewrite_gate: \"done\",\n l1_foundation: \"pending\",\n l2_capabilities: \"pending\",\n l3_behaviors: \"pending\",\n development_goal: \"pending\",\n emit_result: \"pending\",\n }),\n });\n\n if (rewriteGateAllowsSkip(gateResult)) {\n await postRewritePipelineProgress(jobCode, \"rewrite_gate\", {\n rewrite_gate: \"done\",\n l1_foundation: \"skipped\",\n l2_capabilities: \"skipped\",\n l3_behaviors: \"skipped\",\n development_goal: \"skipped\",\n emit_result: \"skipped\",\n });\n await postCallback({\n ok: true,\n final: true,\n rewriteGate: gateResult,\n progress: buildRewritePipelineProgressPayload(jobCode, \"rewrite_gate\", {\n rewrite_gate: \"done\",\n l1_foundation: \"skipped\",\n l2_capabilities: \"skipped\",\n l3_behaviors: \"skipped\",\n development_goal: \"skipped\",\n emit_result: \"skipped\",\n }),\n });\n return;\n }\n\n const rewritePhases = effectiveRewritePhases(gateResult.decision);\n const runL1 = rewritePhases.includes(\"l1\");\n const runL2 = rewritePhases.includes(\"l2\");\n const runL3 = rewritePhases.includes(\"l3\");\n\n if (runL1) {\n await postRewritePipelineProgress(jobCode, \"l1_foundation\", {\n rewrite_gate: \"done\",\n l1_foundation: \"running\",\n l2_capabilities: runL2 ? \"pending\" : \"skipped\",\n l3_behaviors: runL3 ? \"pending\" : \"skipped\",\n development_goal: \"pending\",\n emit_result: \"pending\",\n });\n\n const l1Prompt = buildL1FoundationRepoPrompt(title, rawWithDocs, chatContext, indexSample, wsPaths);\n const l1Run = await tryAgentStream(l1Prompt, dir, runnerCommand, async (progress) => {\n await postCallback({ ok: true, final: false, progress });\n });\n if (l1Run.exitCode !== 0) {\n await postCallback({ ok: false, error: \"L1 foundation phase failed\" });\n agentExit(1);\n }\n } else {\n await postRewritePipelineProgress(jobCode, runL2 ? \"l2_capabilities\" : \"l3_behaviors\", {\n rewrite_gate: \"done\",\n l1_foundation: \"skipped\",\n l2_capabilities: runL2 ? \"pending\" : \"skipped\",\n l3_behaviors: runL3 ? \"pending\" : \"skipped\",\n development_goal: \"pending\",\n emit_result: \"pending\",\n });\n }\n\n if (runL2) {\n await postRewritePipelineProgress(jobCode, \"l2_capabilities\", {\n rewrite_gate: \"done\",\n l1_foundation: runL1 ? \"done\" : \"skipped\",\n l2_capabilities: \"running\",\n l3_behaviors: runL3 ? \"pending\" : \"skipped\",\n development_goal: \"pending\",\n emit_result: \"pending\",\n });\n\n const l2Prompt = buildL2CapabilitiesRepoPrompt(title, rawWithDocs, chatContext, wsPaths);\n const l2Run = await runRewriteAgentPhase({\n prompt: l2Prompt,\n correctionPrompt: buildL2CapabilitiesCorrectionPrompt(title, wsPaths),\n satisfied: () => l2PhaseSatisfied(dir, readRewriteCallbackMeta(dir, slug), slug),\n dir,\n runnerCommand,\n onProgress: async (progress) => {\n await postCallback({ ok: true, final: false, progress });\n },\n streamOpts: { extraArgs: [\"--continue\"] },\n });\n if (l2Run.exitCode !== 0) {\n await postCallback({ ok: false, error: \"L2 capabilities phase failed\", final: true });\n agentExit(1);\n }\n if (!l2PhaseSatisfied(dir, readRewriteCallbackMeta(dir, slug), slug)) {\n await postCallback({\n ok: false,\n error:\n \"L2 capabilities phase: missing spec/capabilities/{name}.md and l2RelativePath in callback meta\",\n final: true,\n });\n agentExit(1);\n }\n }\n\n if (runL3) {\n await postRewritePipelineProgress(jobCode, \"l3_behaviors\", {\n rewrite_gate: \"done\",\n l1_foundation: runL1 ? \"done\" : \"skipped\",\n l2_capabilities: runL2 ? \"done\" : \"skipped\",\n l3_behaviors: \"running\",\n development_goal: \"pending\",\n emit_result: \"pending\",\n });\n } else {\n await postCallback({\n ok: false,\n error: \"rewrite gate returned no executable L3 phase\",\n final: true,\n });\n agentExit(1);\n }\n\n const l3Prompt = buildL3BehaviorsRepoPrompt(title, rawWithDocs, chatContext, wsPaths);\n const l3Run = await runRewriteAgentPhase({\n prompt: l3Prompt,\n correctionPrompt: buildL3BehaviorsCorrectionPrompt(title, wsPaths),\n satisfied: () => l3PhaseSatisfied(dir, readRewriteCallbackMeta(dir, slug), slug),\n dir,\n runnerCommand,\n onProgress: async (progress) => {\n await postCallback({ ok: true, final: false, progress });\n },\n streamOpts: { extraArgs: [\"--continue\"] },\n });\n if (l3Run.exitCode !== 0) {\n await postCallback({ ok: false, error: \"L3 behaviors phase failed\", final: true });\n agentExit(1);\n }\n\n const metaAfterL3 = readRewriteCallbackMeta(dir, slug);\n if (!l3PhaseSatisfied(dir, metaAfterL3, slug)) {\n await postCallback({\n ok: false,\n error: \"L3 behaviors phase: missing body in callback meta and spec/behaviors or spec/ui-contracts changes\",\n final: true,\n });\n agentExit(1);\n }\n\n const builtAfterL3 = buildRewriteResultFromWorkspace(dir, title, metaAfterL3, {\n integrationBranch,\n });\n const l3BodyExcerpt = builtAfterL3?.rewrite.body ?? \"\";\n\n const l1DoneOrSkipped = runL1 ? \"done\" : \"skipped\";\n const l2DoneOrSkipped = runL2 ? \"done\" : \"skipped\";\n\n await postRewritePipelineProgress(jobCode, \"development_goal\", {\n rewrite_gate: \"done\",\n l1_foundation: l1DoneOrSkipped,\n l2_capabilities: l2DoneOrSkipped,\n l3_behaviors: \"done\",\n development_goal: \"running\",\n emit_result: \"pending\",\n });\n\n const dgResultPath = join(outputPath.dir, \"development-goal.json\");\n const dgPrompt = buildDevelopmentGoalPrompt(\n title,\n raw,\n chatContext,\n l3BodyExcerpt,\n wsPaths,\n dgResultPath,\n builtAfterL3?.spec ?? null,\n );\n const dgRun = await tryAgentStream(dgPrompt, dir, runnerCommand, async (progress) => {\n await postCallback({ ok: true, final: false, progress });\n }, { extraArgs: [\"--continue\"] });\n if (dgRun.exitCode !== 0) {\n await postCallback({ ok: false, error: \"development_goal phase failed\" });\n agentExit(1);\n }\n\n await postRewritePipelineProgress(jobCode, \"emit_result\", {\n rewrite_gate: \"done\",\n l1_foundation: l1DoneOrSkipped,\n l2_capabilities: l2DoneOrSkipped,\n l3_behaviors: \"done\",\n development_goal: \"done\",\n emit_result: \"running\",\n });\n\n const meta = readRewriteCallbackMeta(dir, slug);\n const built = buildRewriteResultFromWorkspace(dir, title, meta, { integrationBranch });\n if (!built) {\n await postCallback({\n ok: false,\n error:\n \"emit_result: no spec changes detected (expected spec/capabilities, spec/behaviors, spec/ui-contracts, or body in callback meta)\",\n final: true,\n });\n agentExit(1);\n }\n const { spec: specParsed, rewrite: rewriteParsed } = built;\n const changeSummary = buildChangeSummary(dir, integrationBranch, meta, built);\n const l2Path = resolveL2CapabilityPath(meta) ?? specParsed.l2.relativePathSuggestion;\n const primaryBehavior = meta.suggestedBehaviorPaths?.[0] ?? specParsed.suggestedBehaviorPaths?.[0] ?? null;\n\n let developmentGoalDraft: DevelopmentGoalDraft | null = readDevelopmentGoalJson(outputPath.dir);\n let developmentGoalDegraded = false;\n if (!developmentGoalDraft) {\n developmentGoalDraft = buildDegradedDevelopmentGoalDraft({\n body: rewriteParsed.body,\n title: rewriteParsed.title,\n rawInput: raw,\n meta,\n spec: specParsed,\n l2CapabilityPath: l2Path,\n primaryBehaviorPath: primaryBehavior,\n });\n developmentGoalDegraded = true;\n }\n\n writeFileSync(outputPath.resultJsonPath, JSON.stringify({ ...rewriteParsed, l1: specParsed.l1, l2: specParsed.l2 }, null, 2), \"utf-8\");\n\n const msg = `nvwa(rewrite): ${rewriteParsed.title.slice(0, 72)}\\n\\n${triggeredByTrailerFromSpec(spec)}`;\n const pushed = commitAndPushFeatureWorkspace(dir, featureBranch, msg);\n if (!pushed.ok) {\n await postCallback({ ok: false, error: pushed.error });\n agentExit(1);\n }\n\n await postRewritePipelineProgress(jobCode, \"emit_result\", {\n rewrite_gate: \"done\",\n l1_foundation: l1DoneOrSkipped,\n l2_capabilities: l2DoneOrSkipped,\n l3_behaviors: \"done\",\n development_goal: \"done\",\n emit_result: \"done\",\n });\n\n const rewriteBody = rewriteParsed.body.trim();\n const metaHasBody = Boolean(meta.body?.trim());\n const l2MarkdownLen = specParsed.l2.markdown.trim().length;\n agentLog(\"rewrite emit_result payload\", {\n jobCode,\n metaHasBody,\n l2Path: l2Path ?? null,\n l2MarkdownLen,\n rewriteBodyLen: rewriteBody.length,\n developmentGoalBodyLen: developmentGoalDraft.body.trim().length,\n hasTitle: Boolean(rewriteParsed.title.trim()),\n });\n\n if (!rewriteBody) {\n await postCallback({\n ok: false,\n final: true,\n error:\n \"emit_result: rewrite body empty after workspace assembly (set body in rewrite-callback-meta.json or ensure L2 capability markdown is readable)\",\n outputFile: outputPath.resultJsonPath,\n branch: featureBranch,\n commitSha: pushed.commitSha,\n });\n agentExit(1);\n }\n\n await postCallback({\n ok: true,\n final: true,\n outputFile: outputPath.resultJsonPath,\n branch: featureBranch,\n commitSha: pushed.commitSha,\n repoCommitted: pushed.committed,\n rewriteGate: gateResult,\n title: rewriteParsed.title,\n body: rewriteParsed.body,\n clarifications: rewriteParsed.clarifications,\n l1: specParsed.l1,\n l2: specParsed.l2,\n suggestedBehaviorPaths: specParsed.suggestedBehaviorPaths,\n acceptanceScenarioHints: specParsed.acceptanceScenarioHints,\n changeSummary,\n developmentGoal: {\n version: 1,\n summary: developmentGoalDraft.summary,\n body: developmentGoalDraft.body,\n acceptanceHints: developmentGoalDraft.acceptanceHints,\n specRefs: developmentGoalDraft.specRefs,\n phaseGuidance: developmentGoalDraft.phaseGuidance,\n sourceJobCode: jobCode,\n rawInputSnapshot: raw,\n updatedAt: new Date().toISOString(),\n ...(developmentGoalDegraded ? { degraded: true } : {}),\n ...(developmentGoalDraft.implementationPlan\n ? { implementationPlan: developmentGoalDraft.implementationPlan }\n : {}),\n },\n });\n}\n\nfunction callbackBodyLogDetail(body: Record<string, unknown>): Record<string, unknown> {\n const detail: Record<string, unknown> = {\n ok: body.ok === true,\n final: body.final === true,\n };\n if (typeof body.error === \"string\" && body.error) {\n detail.error = truncateForLog(body.error, LOG_TEXT_MAX);\n }\n const progress = body.progress;\n if (progress && typeof progress === \"object\" && !Array.isArray(progress)) {\n const p = progress as Record<string, unknown>;\n if (typeof p.stage === \"string\") detail.stage = p.stage;\n if (typeof p.message === \"string\") detail.message = truncateForLog(p.message, LOG_TEXT_MAX);\n if (typeof p.eventType === \"string\") detail.eventType = p.eventType;\n if (typeof p.activityHeadline === \"string\" && p.activityHeadline) {\n detail.activityHeadline = truncateForLog(p.activityHeadline, 400);\n }\n if (Array.isArray(p.activityLines)) {\n const lines = p.activityLines.filter((x): x is string => typeof x === \"string\");\n detail.activityLineCount = lines.length;\n if (lines.length > 0) {\n detail.activityLinesTail = lines.slice(-6).map((x) => truncateForLog(x, 240));\n }\n }\n const rp = p.rewritePipeline;\n if (rp && typeof rp === \"object\" && !Array.isArray(rp)) {\n const r = rp as Record<string, unknown>;\n detail.rewritePipeline = {\n jobCode: r.jobCode,\n currentTodoId: r.currentTodoId,\n todos: Array.isArray(r.todos)\n ? (r.todos as unknown[]).map((t) => {\n if (!t || typeof t !== \"object\" || Array.isArray(t)) return t;\n const todo = t as Record<string, unknown>;\n return { id: todo.id, status: todo.status };\n })\n : undefined,\n };\n }\n }\n if (typeof body.commitSha === \"string\" && body.commitSha) {\n detail.commitSha = body.commitSha.slice(0, 12);\n }\n if (typeof body.outputFile === \"string\" && body.outputFile) {\n detail.outputFile = body.outputFile;\n }\n if (body.final === true) {\n const rewriteBody = typeof body.body === \"string\" ? body.body.trim() : \"\";\n detail.hasTitle = typeof body.title === \"string\" && body.title.trim().length > 0;\n detail.bodyLen = rewriteBody.length;\n detail.hasDevelopmentGoal = body.developmentGoal != null;\n const l2 = body.l2;\n if (l2 && typeof l2 === \"object\" && !Array.isArray(l2)) {\n const md = (l2 as Record<string, unknown>).markdown;\n detail.l2MarkdownLen = typeof md === \"string\" ? md.trim().length : 0;\n } else {\n detail.l2MarkdownLen = 0;\n }\n detail.callbackKeyCount = Object.keys(body).length;\n }\n return detail;\n}\n\nfunction resolveAgentStreamArgv(\n command: string,\n prompt: string,\n streamOpts?: { extraArgs?: string[]; freshSession?: boolean },\n): string[] {\n const extra = [...(streamOpts?.extraArgs ?? [])];\n if (agentStreamContinueNext && !streamOpts?.freshSession && !extra.includes(\"--continue\")) {\n extra.push(\"--continue\");\n }\n return [\n \"--trust\",\n \"--force\",\n \"--model\",\n \"auto\",\n ...extra,\n \"-p\",\n \"--output-format\",\n \"stream-json\",\n \"--stream-partial-output\",\n prompt,\n ];\n}\n\nasync function tryAgentStream(\n prompt: string,\n cwd: string,\n command: string,\n onProgress: (progress: AgentProgress) => Promise<void>,\n streamOpts?: { extraArgs?: string[]; freshSession?: boolean },\n): Promise<AgentRunResult> {\n const extraArgs = streamOpts?.extraArgs ?? [];\n const effectiveContinue =\n !streamOpts?.freshSession &&\n (agentStreamContinueNext || extraArgs.includes(\"--continue\"));\n agentLog(\"agent stream start (outbound prompt)\", {\n cwd,\n promptChars: prompt.length,\n prompt: promptPreviewForLog(prompt),\n extraArgs,\n continueSession: agentStreamContinueNext,\n effectiveContinue,\n });\n throwIfAgentRunCancelled();\n\n const child = spawn(\n command,\n resolveAgentStreamArgv(command, prompt, streamOpts),\n {\n cwd,\n env: process.env,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n },\n );\n activeAgentChild = child;\n child.on(\"close\", () => {\n if (activeAgentChild === child) activeAgentChild = null;\n });\n\n let stdoutAll = \"\";\n let stderrAll = \"\";\n let stdoutBuf = \"\";\n let lastEmitAt = Date.now();\n let lastEmittedLineLen = -1;\n let lastBanner = \"\";\n let lastAssistantLogAt = 0;\n let assistantStreamChars = 0;\n let dialogStreamBuf = \"\";\n let lastProgressLogMessage = \"\";\n let lastCallbackMessage = \"\";\n const activityLines: string[] = [];\n const counts: AgentActivityCounts = { read: 0, search: 0, grep: 0 };\n\n function pushActivityLine(s: string): boolean {\n const t = s.trim();\n if (!t) return false;\n if (activityLines.length > 0 && activityLines[activityLines.length - 1] === t) return false;\n activityLines.push(t);\n while (activityLines.length > MAX_ACTIVITY_LINES) activityLines.shift();\n return true;\n }\n\n const tryEmitProgress = async (eventType?: string, force = false): Promise<void> => {\n const now = Date.now();\n const len = activityLines.length;\n const elapsed = now - lastEmitAt;\n const newLines = len !== lastEmittedLineLen;\n if (!force) {\n if (!newLines && elapsed < PROGRESS_EMIT_MIN_MS) return;\n if (newLines && elapsed < PROGRESS_EMIT_BURST_MS) return;\n }\n\n const headlineParts: string[] = [];\n if (counts.read > 0) headlineParts.push(`读取 ${counts.read}`);\n if (counts.search > 0) headlineParts.push(`搜索 ${counts.search}`);\n if (counts.grep > 0) headlineParts.push(`匹配 ${counts.grep}`);\n const headline =\n headlineParts.length > 0\n ? headlineParts.join(\" · \")\n : len > 0\n ? `工具活动 · ${len} 条`\n : \"\";\n\n const message = (lastBanner || headline || \"分析中…\").slice(0, 400);\n if (!force && message === lastCallbackMessage && !newLines) return;\n\n lastEmitAt = now;\n lastEmittedLineLen = len;\n lastCallbackMessage = message;\n\n if (force || message !== lastProgressLogMessage || newLines) {\n lastProgressLogMessage = message;\n agentLog(\"progress → callback\", {\n stage: \"analyze\",\n message,\n eventType,\n activityLineCount: len,\n ...(headline ? { activityHeadline: headline } : {}),\n ...(len > 0 ? { activityLinesTail: activityLines.slice(-4) } : {}),\n });\n }\n\n try {\n await onProgress({\n stage: \"analyze\",\n message,\n eventType,\n updatedAt: new Date().toISOString(),\n ...(len > 0\n ? {\n activityLines: [...activityLines],\n activityCounts: { ...counts },\n activityHeadline: headline,\n }\n : {}),\n });\n } catch (e) {\n console.error(\"[nvwa-agent] progress callback failed:\", e);\n }\n };\n\n const readStdout = (async () => {\n for await (const chunk of child.stdout) {\n const text = Buffer.from(chunk).toString(\"utf-8\");\n stdoutAll += text;\n stdoutBuf += text;\n let idx = stdoutBuf.indexOf(\"\\n\");\n while (idx >= 0) {\n const line = stdoutBuf.slice(0, idx).trim();\n stdoutBuf = stdoutBuf.slice(idx + 1);\n if (line) {\n try {\n const evt = JSON.parse(line) as Record<string, unknown>;\n const eventType = typeof evt.type === \"string\" ? evt.type : \"\";\n const eventSubtype = typeof evt.subtype === \"string\" ? evt.subtype : \"\";\n const chunkText = extractStreamEventText(evt);\n if (\n chunkText &&\n (eventType === \"user\" ||\n eventType === \"thinking\" ||\n (eventType === \"assistant\" && !isDuplicateAssistantStreamEvent(evt)))\n ) {\n dialogStreamBuf += chunkText;\n }\n const streamDetail = streamEventLogDetail(evt, { dialogBuf: dialogStreamBuf });\n const textLen =\n typeof streamDetail.text === \"string\" ? (streamDetail.text as string).length : 0;\n if (eventType === \"assistant\" || eventType === \"thinking\") {\n assistantStreamChars += chunkText.length;\n streamDetail.assistantStreamChars = assistantStreamChars;\n if (!streamDetail.text && dialogStreamBuf) {\n streamDetail.text = truncateForLog(dialogStreamBuf, LOG_TEXT_MAX);\n }\n }\n const skipDupAssistantLog =\n eventType === \"assistant\" && isDuplicateAssistantStreamEvent(evt);\n if (\n !skipDupAssistantLog &&\n !shouldThrottleAssistantStreamLog(eventType, eventSubtype, textLen, lastAssistantLogAt)\n ) {\n agentLog(streamEventLogLabel(evt), streamDetail);\n if (eventType === \"assistant\" || eventType === \"thinking\") {\n lastAssistantLogAt = Date.now();\n }\n }\n const evtTypeForProgress = eventType || undefined;\n\n let activityLineAdded = false;\n const toolLine = formatToolActivityLine(evt);\n if (toolLine && !isThinkingLine(toolLine)) {\n activityLineAdded = pushActivityLine(toolLine);\n bumpActivityCounts(counts, toolLine, evt);\n lastBanner = toolLine;\n } else {\n const summaryMsg = summarizeStreamEvent(evt);\n if (summaryMsg) lastBanner = summaryMsg;\n }\n\n const heartbeatDue = Date.now() - lastEmitAt >= PROGRESS_HEARTBEAT_MS;\n if (\n shouldEmitProgressForStreamEvent(evt, activityLineAdded) ||\n heartbeatDue\n ) {\n await tryEmitProgress(evtTypeForProgress, heartbeatDue);\n }\n } catch {\n // not JSON line; ignore\n }\n }\n idx = stdoutBuf.indexOf(\"\\n\");\n }\n }\n })();\n\n const readStderr = (async () => {\n for await (const chunk of child.stderr) {\n const text = Buffer.from(chunk).toString(\"utf-8\");\n stderrAll += text;\n const trimmed = text.trim();\n if (trimmed) {\n agentLog(\"agent stderr\", { text: truncateForLog(trimmed, LOG_TEXT_MAX) });\n }\n }\n })();\n\n const exitCode = await new Promise<number>((resolve) => {\n child.on(\"close\", (code) => resolve(code ?? 1));\n });\n await Promise.all([readStdout, readStderr]);\n await tryEmitProgress(\"stream_closed\", true);\n\n if (activeAgentChild === child) activeAgentChild = null;\n if (cancelRequested) {\n throw new AgentRunCancelled(\"agent stream cancelled\");\n }\n\n if (dialogStreamBuf.trim()) {\n agentLog(\"cursor dialog summary (accumulated user/assistant/thinking)\", {\n chars: dialogStreamBuf.length,\n text: truncateForLog(dialogStreamBuf, LOG_TEXT_MAX),\n });\n }\n\n const detail: Record<string, unknown> = {\n exitCode,\n activityLines: activityLines.length,\n stdoutBytes: stdoutAll.length,\n dialogChars: dialogStreamBuf.length,\n };\n if (exitCode !== 0 && stderrAll.trim()) {\n detail.stderrTail = stderrAll.trim().slice(-800);\n }\n agentLog(exitCode === 0 ? \"agent stream done\" : \"agent stream failed\", detail);\n\n if (\n exitCode !== 0 &&\n effectiveContinue &&\n /No previous chats found/i.test(stderrAll)\n ) {\n agentLog(\"agent stream retry without --continue\", { reason: \"no_previous_chats\" });\n return tryAgentStream(prompt, cwd, command, onProgress, {\n ...streamOpts,\n freshSession: true,\n });\n }\n\n return { stdout: stdoutAll, stderr: stderrAll, exitCode };\n}\n\nfunction callbackUrlFromJobFile(): string | null {\n try {\n const raw = readFileSync(AGENT_JOB_CONFIG_MOUNT_PATH, \"utf-8\");\n const j = JSON.parse(raw) as { callbackUrl?: unknown };\n return typeof j.callbackUrl === \"string\" && j.callbackUrl.trim() ? j.callbackUrl.trim() : null;\n } catch {\n return null;\n }\n}\n\nfunction resolveCallbackUrl(): string | null {\n const fromSpec = jobSpec?.callbackUrl?.trim();\n if (fromSpec) return fromSpec;\n const fromEnv = (process.env.NVWA_CALLBACK_URL ?? \"\").trim();\n if (fromEnv) return fromEnv;\n return callbackUrlFromJobFile();\n}\n\n/**\n * 尽力将失败写回 Creator(避免 DB 长期停在 running)。用于 job.json 未解析等早退路径。\n */\nasync function postCallbackBestEffort(body: Record<string, unknown>): Promise<boolean> {\n const url = resolveCallbackUrl();\n const sec = (process.env.NVWA_CALLBACK_SECRET ?? \"\").trim();\n if (!url || !sec) {\n console.error(\"[nvwa-agent] postCallbackBestEffort: missing callback URL or NVWA_CALLBACK_SECRET\");\n return false;\n }\n const reqDetail = callbackBodyLogDetail(body);\n agentLog(\"callback → server (best-effort)\", { url: callbackUrlForLog(url), body: reqDetail });\n for (let attempt = 0; attempt < 3; attempt++) {\n try {\n const res = await fetch(url, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"x-nvwa-callback-secret\": sec,\n },\n body: JSON.stringify(body),\n });\n const text = await res.text();\n if (res.ok) {\n agentLog(\"callback ← server ok (best-effort)\", {\n url: callbackUrlForLog(url),\n httpStatus: res.status,\n attempt: attempt + 1,\n request: reqDetail,\n response: truncateForLog(text, LOG_TEXT_MAX),\n });\n return true;\n }\n agentLog(\"callback ← server failed (best-effort)\", {\n url: callbackUrlForLog(url),\n httpStatus: res.status,\n attempt: attempt + 1,\n request: reqDetail,\n response: truncateForLog(text, LOG_TEXT_MAX),\n });\n if (res.status >= 500 && res.status < 600 && attempt < 2) {\n await new Promise((r) => setTimeout(r, 600 * (attempt + 1)));\n continue;\n }\n } catch (e) {\n console.error(\"[nvwa-agent] callback fetch error\", e);\n if (attempt < 2) await new Promise((r) => setTimeout(r, 600 * (attempt + 1)));\n }\n }\n return false;\n}\n\nasync function postCallback(body: Record<string, unknown>): Promise<void> {\n const url = resolveCallbackUrl();\n const sec = process.env.NVWA_CALLBACK_SECRET;\n if (!url || !sec) {\n console.error(\"[nvwa-agent] missing callback URL (job.json or NVWA_CALLBACK_URL) or NVWA_CALLBACK_SECRET\");\n agentExit(1);\n }\n const reqDetail = callbackBodyLogDetail(body);\n agentLog(\"callback → server\", { url: callbackUrlForLog(url), body: reqDetail });\n let lastText = \"\";\n for (let attempt = 0; attempt < 3; attempt++) {\n const res = await fetch(url, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"x-nvwa-callback-secret\": sec,\n },\n body: JSON.stringify(body),\n });\n lastText = await res.text();\n if (res.ok) {\n agentLog(\"callback ← server ok\", {\n url: callbackUrlForLog(url),\n httpStatus: res.status,\n attempt: attempt + 1,\n request: reqDetail,\n response: truncateForLog(lastText, LOG_TEXT_MAX),\n });\n return;\n }\n agentLog(\"callback ← server failed\", {\n url: callbackUrlForLog(url),\n httpStatus: res.status,\n attempt: attempt + 1,\n request: reqDetail,\n response: truncateForLog(lastText, LOG_TEXT_MAX),\n });\n if (res.status >= 500 && res.status < 600 && attempt < 2) {\n await new Promise((r) => setTimeout(r, 600 * (attempt + 1)));\n continue;\n }\n break;\n }\n agentExit(1);\n}\n\nfunction buildMergeDevResolutionPrompt(\n title: string,\n raw: string,\n branch: string,\n mergeSource: string,\n resultPath: string,\n repoFileIndexSample: string,\n): string {\n return `\nYou are resolving a Git rebase conflict in repository at /workspace/repo (or current directory).\nYou are on branch **${branch}** — do not rename or switch branches.\nA rebase of this branch onto **origin/${mergeSource}** produced conflicts while replaying commits. Resolve them with minimal, correct edits.\n\nContext (card title / notes):\n${title}\n\nAdditional notes:\n${raw}\n\nRepository file index (sample):\n${repoFileIndexSample}\n\nRules:\n- During rebase onto **origin/${mergeSource}**, conflict markers separate **upstream (dev / HEAD during replay)** from **incoming (the card commit being replayed)**.\n- Preserve the **functional intent of this card's incoming commits**. Do **not** resolve every conflict by wholesale keeping dev/HEAD/upstream.\n- When dev already contains equivalent lines, merge both sides thoughtfully; keep card-specific behavior, tests, and contract/version bumps from incoming unless they are truly redundant.\n- If you cannot preserve incoming changes without breaking the build, explain in \\`summary\\` — do not silently drop the card's diff.\n- Fix conflict markers and ensure the project still builds logically where obvious from context.\n- Do not push and do **not** run \\`git add\\` / \\`git rebase --continue\\` yourself — only edit conflicted files; the runner will stage, run \\`git rebase --continue\\`, and push with force-with-lease.\n\n## Mandatory machine-readable summary (job will fail without this file)\n\nTreat this path as the **primary** machine-readable summary (orchestrator falls back to scanning Cursor stream-json stdout only if the file is missing or invalid):\n**${resultPath}**\n\n1. After all conflict edits, write **exactly one JSON object** to that file (UTF-8, no BOM).\n2. The file content must be **only** JSON: first non-whitespace character is \\`{\\`, last is \\`}\\`. No Markdown, no code fences, no commentary before or after.\n3. Schema: \\`{ \"summary\": \"short Chinese summary of conflict resolution\" }\\`\n4. Keep \\`summary\\` under ~8000 chars; one paragraph is enough.\n5. You may explain details in tools/chat, but the **file above must still contain valid JSON** matching the schema.\n6. Also print the **same single-line JSON object** to stdout (for logging); the file is the source of truth.`;\n}\n\nfunction buildCodeTaskAgentPrompt(\n title: string,\n raw: string,\n chatContext: string,\n branch: string,\n resultPath: string,\n repoFileIndexSample: string,\n): string {\n const phaseSection =\n chatContext.trim() !== \"\" && chatContext.includes(\"本阶段职责\")\n ? `\n${chatContext}\n`\n : \"\";\n const hasExtraChat = chatContext.trim() !== \"\" && !phaseSection;\n const chatBlock = hasExtraChat\n ? `\n--- Additional context ---\n${chatContext}\n--- End context ---\n`\n : \"\";\n\n return `\nYou are implementing a concrete coding task in an existing Git repository at /workspace/repo (or current directory).\nYou are already on branch **${branch}** — do not rename or switch branches.\n\nTask title: ${title}\n\nTask description:\n${raw}\n${phaseSection}${chatBlock}\n\nRepository file index (sample):\n${repoFileIndexSample}\n\nRules:\n- When calling external integrations, use @nvwa-os/integration-client from npm (see Integration runtime section below). Do not copy or inline URL helpers.\n- Make minimal, focused edits; follow existing style and patterns.\n- Do not push — the runner will commit and push.\n- Do not change CI unrelated files unless required for the task.\n- When you change business logic, add or update colocated unit tests (*.test.ts or the project's test convention). Keep tests runnable via the repo's test script (e.g. bun test).\n- Pure layout-only UI changes may rely on E2E coverage, but must not break existing unit tests.\n- When you add or change any package.json dependency (root or workspace): run \\`bun install\\` at repo root so bun.lock stays in sync; the runner verifies \\`bun install --frozen-lockfile\\` and \\`bun audit\\` (zero vulnerabilities) before push.\n- When you add a new workspace package: update COPY package.json lines in apps/server/Dockerfile and apps/web/Dockerfile so Docker builds include it.\n\n## Mandatory machine-readable summary (job will fail without this file)\n\nTreat this path as the **primary** machine-readable summary (orchestrator falls back to scanning Cursor stream-json stdout only if the file is missing or invalid):\n**${resultPath}**\n\nThis path is on the Pod's \\`/agent-out\\` volume (outside the Git clone). **Do not** create an \\`agent-out/\\` directory inside the repository.\n\n1. After code edits, write **exactly one JSON object** to that file (UTF-8, no BOM).\n2. The file content must be **only** JSON: first non-whitespace character is \\`{\\`, last is \\`}\\`. No Markdown, no code fences, no commentary before or after.\n3. Schema: \\`{ \"summary\": \"short Chinese summary of what you changed\" }\\`\n4. Keep \\`summary\\` under ~8000 chars; state user-visible outcome, not internal reasoning.\n5. You may write a long Markdown explanation elsewhere (e.g. tool output); the **file above must still contain valid JSON** matching the schema.\n6. Also print the **same single-line JSON object** to stdout (for logging); the file is the source of truth.`;\n}\n\nfunction parseCodeTaskSummaryFromText(raw: string | null | undefined): string | null {\n if (!raw?.trim()) return null;\n const trimmed = raw.trim();\n const objectText = extractJsonObjectText(trimmed) ?? trimmed;\n try {\n const o = JSON.parse(objectText) as unknown;\n if (o && typeof o === \"object\" && !Array.isArray(o)) {\n const s = (o as Record<string, unknown>).summary;\n if (typeof s === \"string\" && s.trim()) return s.trim().slice(0, 8000);\n }\n } catch {\n /* fall through */\n }\n return parseCodeTaskSummaryFromProse(trimmed);\n}\n\nfunction gitRebaseInProgress(dir: string): boolean {\n const gitDir = spawnSync(\"git\", [\"-C\", dir, \"rev-parse\", \"--git-dir\"], {\n encoding: \"utf-8\",\n env: gitWorkspaceEnv(),\n });\n const raw = (gitDir.stdout ?? \"\").trim();\n if (!raw) return false;\n const gitDirPath = raw === \".git\" ? join(dir, \".git\") : raw.startsWith(\"/\") ? raw : join(dir, raw);\n return existsSync(join(gitDirPath, \"rebase-merge\")) || existsSync(join(gitDirPath, \"rebase-apply\"));\n}\n\nfunction listUnmergedPaths(dir: string): string {\n const unmerged = spawnSync(\"git\", [\"-C\", dir, \"diff\", \"--name-only\", \"--diff-filter=U\"], {\n encoding: \"utf-8\",\n env: gitWorkspaceEnv(),\n });\n return (unmerged.stdout ?? \"\").trim();\n}\n\n/** Agent or a prior interrupted run may have already run `git rebase --continue`. */\nexport function isRebaseContinueAlreadyFinishedError(err: string): boolean {\n return /no rebase in progress/i.test(err);\n}\n\nfunction gitCurrentBranch(dir: string): string | null {\n const r = spawnSync(\"git\", [\"-C\", dir, \"branch\", \"--show-current\"], {\n encoding: \"utf-8\",\n env: gitWorkspaceEnv(),\n });\n const branch = (r.stdout ?? \"\").trim();\n if ((r.status ?? 1) === 0 && branch) return branch;\n\n // During rebase, --show-current is empty; read the branch being replayed.\n const gitDir = spawnSync(\"git\", [\"-C\", dir, \"rev-parse\", \"--git-dir\"], {\n encoding: \"utf-8\",\n env: gitWorkspaceEnv(),\n });\n const raw = (gitDir.stdout ?? \"\").trim();\n if (!raw) return null;\n const gitDirPath = raw === \".git\" ? join(dir, \".git\") : raw.startsWith(\"/\") ? raw : join(dir, raw);\n for (const sub of [\"rebase-merge/head-name\", \"rebase-apply/head-name\"] as const) {\n const headNamePath = join(gitDirPath, sub);\n if (!existsSync(headNamePath)) continue;\n try {\n const ref = readFileSync(headNamePath, \"utf-8\").trim();\n const short = ref.replace(/^refs\\/heads\\//, \"\");\n if (short) return short;\n } catch {\n /* try next */\n }\n }\n return null;\n}\n\nfunction gitWorkingTreeClean(dir: string): boolean {\n const r = spawnSync(\"git\", [\"-C\", dir, \"status\", \"--porcelain\"], {\n encoding: \"utf-8\",\n env: gitWorkspaceEnv(),\n });\n return (r.status ?? 1) === 0 && !(r.stdout ?? \"\").trim();\n}\n\n/** True when HEAD is rebased onto origin/<mergeSource> with card-unique changes (PVC resume). */\nexport function workspaceRebaseOntoMergeSourceComplete(\n dir: string,\n mergeSource: string,\n featureBranch: string,\n): boolean {\n const feat = branchShortName(featureBranch);\n const ms = branchShortName(mergeSource);\n if (gitCurrentBranch(dir) !== feat) return false;\n if (gitRebaseInProgress(dir)) return false;\n if (listUnmergedPaths(dir)) return false;\n if (!gitWorkingTreeClean(dir)) return false;\n const mergeSha = gitRemoteBranchSha(dir, ms);\n const headSha = gitHeadSha(dir, false);\n if (!mergeSha || !headSha) return false;\n if (!gitIsAncestor(dir, mergeSha, headSha)) return false;\n return featureRebaseHasUniqueChangesVsMergeSource(dir, mergeSource).ok;\n}\n\nexport type MergeDevRebaseState = \"fresh\" | \"already_complete\" | \"in_progress\";\n\n/**\n * Like prepareFeatureWorkspace, but on a persistent PVC keeps an in-progress or\n * already-finished merge-dev rebase instead of resetting to origin/feature.\n */\nexport function prepareMergeDevWorkspace(\n dir: string,\n branch: string,\n mergeSource: string,\n):\n | { ok: true; rebaseState: MergeDevRebaseState; created: boolean; conflictPaths?: string }\n | { ok: false; error: string } {\n const feat = branchShortName(branch);\n const integration = branchShortName(mergeSource);\n if (!feat.startsWith(\"feature/\")) {\n return { ok: false, error: `invalid feature branch: ${branch}` };\n }\n if (!integration) {\n return { ok: false, error: \"merge source branch is empty\" };\n }\n\n agentLog(\"prepare merge-dev workspace start\", { feature: feat, integration });\n\n const fetchIntegrationErr = gitWorkspaceErr(dir, [\n \"fetch\",\n \"--depth\",\n String(FEATURE_FETCH_DEPTH),\n \"origin\",\n originFetchRefspec(integration),\n ]);\n if (fetchIntegrationErr) {\n return { ok: false, error: fetchIntegrationErr };\n }\n fetchOriginRefOptional(dir, feat);\n\n if (agentWorkspaceIsPersistent()) {\n const onFeature = gitCurrentBranch(dir) === feat;\n if (onFeature && workspaceRebaseOntoMergeSourceComplete(dir, mergeSource, branch)) {\n agentLog(\"merge-dev workspace resume: rebase already complete on PVC\", {\n feature: feat,\n head: gitHeadSha(dir),\n });\n return { ok: true, rebaseState: \"already_complete\", created: false };\n }\n if (onFeature && gitRebaseInProgress(dir)) {\n const conflictPaths = listUnmergedPaths(dir);\n agentLog(\"merge-dev workspace resume: rebase in progress on PVC\", {\n feature: feat,\n conflictCount: conflictPaths ? conflictPaths.split(\"\\n\").filter(Boolean).length : 0,\n });\n return {\n ok: true,\n rebaseState: \"in_progress\",\n created: false,\n conflictPaths,\n };\n }\n }\n\n const prep = prepareFeatureWorkspace(dir, branch, integration);\n if (!prep.ok) return prep;\n return { ok: true, rebaseState: \"fresh\", created: prep.created };\n}\n\ntype RebaseContinueAdvanceResult = { ok: true } | { ok: false; error: string };\n\nasync function advanceRebaseAfterAgentResolution(opts: {\n dir: string;\n spec: AgentJobConfigV1;\n branch: string;\n mergeSource: string;\n runnerCommand: string;\n outputPath: { dir: string; resultJsonPath: string };\n indexSample: string;\n maxAttempts?: number;\n errorPrefix?: string;\n}): Promise<RebaseContinueAdvanceResult> {\n const maxContinueAttempts = opts.maxAttempts ?? 32;\n const prefix = opts.errorPrefix ?? \"git rebase --continue failed\";\n for (let attempt = 0; attempt < maxContinueAttempts; attempt++) {\n const continueErr = gitWorkspaceErr(opts.dir, [\"rebase\", \"--continue\"], 600_000);\n if (!continueErr) {\n return { ok: true };\n }\n if (!gitRebaseInProgress(opts.dir)) {\n if (!listUnmergedPaths(opts.dir) && isRebaseContinueAlreadyFinishedError(continueErr)) {\n return { ok: true };\n }\n return { ok: false, error: `${prefix}: ${continueErr.slice(0, 3500)}` };\n }\n const conflictPaths = listUnmergedPaths(opts.dir);\n if (!conflictPaths) {\n return {\n ok: false,\n error: `${prefix} (no unmerged paths listed): ${continueErr.slice(0, 3500)}`,\n };\n }\n await resolveRebaseConflictsWithAgent({\n spec: opts.spec,\n dir: opts.dir,\n branch: opts.branch,\n mergeSource: opts.mergeSource,\n runnerCommand: opts.runnerCommand,\n outputPath: opts.outputPath,\n indexSample: opts.indexSample,\n conflictPaths,\n });\n }\n if (gitRebaseInProgress(opts.dir)) {\n return {\n ok: false,\n error: `git rebase onto origin/${opts.mergeSource} did not complete after ${maxContinueAttempts} continue attempts`,\n };\n }\n return { ok: true };\n}\n\nasync function resolveRebaseConflictsWithAgent(opts: {\n spec: AgentJobConfigV1;\n dir: string;\n branch: string;\n mergeSource: string;\n runnerCommand: string;\n outputPath: { dir: string; resultJsonPath: string };\n indexSample: string;\n conflictPaths: string;\n}): Promise<string> {\n const { spec, dir, branch, mergeSource, runnerCommand, outputPath, indexSample, conflictPaths } = opts;\n\n await postCallback({\n ok: true,\n final: false,\n progress: {\n stage: \"rebase_conflicts\",\n message: `Resolving rebase conflicts onto origin/${mergeSource} (${conflictPaths.split(\"\\n\").filter(Boolean).length} paths)`,\n updatedAt: new Date().toISOString(),\n },\n });\n\n const indexLive = fileTreeSnippet(dir, 120);\n const prompt = buildMergeDevResolutionPrompt(\n spec.requirementTitle,\n spec.requirementRawInput,\n branch,\n mergeSource,\n outputPath.resultJsonPath,\n indexLive || indexSample,\n );\n\n const agentRun = await tryAgentStream(prompt, dir, runnerCommand, async (progress) => {\n await postCallback({ ok: true, final: false, progress });\n });\n\n if (agentRun.exitCode !== 0) {\n const tail = agentRun.stderr.slice(-4000) || agentRun.stdout.slice(-4000) || \"(no stderr/stdout)\";\n await postCallback({\n ok: false,\n error: `rebase-conflict agent exited with code ${agentRun.exitCode}; tail: ${tail.slice(0, 3500)}`,\n });\n agentExit(1);\n }\n\n const fileRaw = existsSync(outputPath.resultJsonPath) ? readFileSync(outputPath.resultJsonPath, \"utf-8\") : null;\n let parsedSummary = parseCodeTaskSummaryFromText(fileRaw);\n if (!parsedSummary) {\n console.warn(\n \"[nvwa-agent] rebase-conflict summary missing from file; trying Cursor agent stdout (stream-json)\",\n );\n parsedSummary =\n parseCodeTaskSummaryFromCursorStdout(agentRun.stdout) ?? \"已解决 rebase 到开发分支的冲突\";\n }\n\n const addErr = gitWorkspaceErr(dir, [\"add\", \"-A\"]);\n if (addErr) {\n await postCallback({ ok: false, error: `git add failed after conflict resolution: ${addErr}` });\n agentExit(1);\n }\n\n return parsedSummary;\n}\n\nexport type SyncFeatureBranchBeforePushResult =\n | { ok: true; rebased: boolean }\n | { ok: false; error: string };\n\n/** Fetch origin/feature and rebase local commits before push (agent resolves conflicts). */\nexport async function syncFeatureBranchBeforePush(opts: {\n dir: string;\n branch: string;\n spec: AgentJobConfigV1;\n runnerCommand: string;\n outputPath: { dir: string; resultJsonPath: string };\n indexSample: string;\n}): Promise<SyncFeatureBranchBeforePushResult> {\n const { dir, branch, spec, runnerCommand, outputPath, indexSample } = opts;\n const feat = branchShortName(branch);\n fetchOriginRefOptional(dir, feat);\n if (!remoteOriginBranchExists(dir, feat)) {\n return { ok: true, rebased: false };\n }\n\n const remoteSha = gitRemoteBranchSha(dir, feat);\n const localSha = gitHeadSha(dir, false);\n if (!remoteSha || !localSha) {\n return { ok: false, error: \"could not resolve local or remote feature branch HEAD before push\" };\n }\n if (remoteSha === localSha) {\n return { ok: true, rebased: false };\n }\n if (gitIsAncestor(dir, remoteSha, localSha)) {\n return { ok: true, rebased: false };\n }\n\n await postCallback({\n ok: true,\n final: false,\n progress: {\n stage: \"sync_feature\",\n message: `Rebasing onto origin/${feat} before push`,\n updatedAt: new Date().toISOString(),\n },\n });\n\n const rebaseRes = spawnSync(\"git\", [\"-C\", dir, \"rebase\", `origin/${feat}`], {\n encoding: \"utf-8\",\n env: gitWorkspaceEnv(),\n timeout: 600_000,\n });\n\n if ((rebaseRes.status ?? 1) === 0) {\n return { ok: true, rebased: true };\n }\n\n let conflictPaths = listUnmergedPaths(dir);\n if (!conflictPaths && !gitRebaseInProgress(dir)) {\n const abort = gitWorkspaceErr(dir, [\"rebase\", \"--abort\"]);\n const tail = [rebaseRes.stderr, rebaseRes.stdout, abort].filter(Boolean).join(\" | \").slice(0, 3500);\n return {\n ok: false,\n error: `git rebase origin/${feat} failed before push (not a simple conflict set): ${tail}`,\n };\n }\n\n await resolveRebaseConflictsWithAgent({\n spec,\n dir,\n branch,\n mergeSource: feat,\n runnerCommand,\n outputPath,\n indexSample,\n conflictPaths: conflictPaths || \"(rebase in progress)\",\n });\n\n const advanced = await advanceRebaseAfterAgentResolution({\n dir,\n spec,\n branch,\n mergeSource: feat,\n runnerCommand,\n outputPath,\n indexSample,\n errorPrefix: \"git rebase --continue failed before push\",\n });\n if (!advanced.ok) {\n return { ok: false, error: advanced.error };\n }\n return { ok: true, rebased: true };\n}\n\n/** Commit, rebase onto latest origin/feature (agent resolves conflicts), then push. */\nasync function commitSyncAndPushFeatureWorkspace(opts: {\n dir: string;\n branch: string;\n message: string;\n spec: AgentJobConfigV1;\n runnerCommand: string;\n outputPath: { dir: string; resultJsonPath: string };\n indexSample: string;\n onlySubpath?: string;\n}): Promise<FeatureWorkspacePushResult> {\n const deletedProtected = findDeletedProtectedPaths(gitDiffNameStatusLines(opts.dir));\n if (deletedProtected.length > 0) {\n return {\n ok: false,\n error: `Cannot delete platform security paths: ${deletedProtected.join(\", \")}`,\n };\n }\n\n const committed = commitFeatureWorkspace(opts.dir, opts.branch, opts.message, {\n onlySubpath: opts.onlySubpath,\n });\n if (!committed.ok) return committed;\n\n const sync = await syncFeatureBranchBeforePush({\n dir: opts.dir,\n branch: opts.branch,\n spec: opts.spec,\n runnerCommand: opts.runnerCommand,\n outputPath: opts.outputPath,\n indexSample: opts.indexSample,\n });\n if (!sync.ok) return { ok: false, error: sync.error };\n\n const feat = branchShortName(opts.branch);\n const headFull = gitHeadSha(opts.dir, false) ?? committed.commitSha;\n const remoteFull = gitRemoteBranchSha(opts.dir, feat);\n const needsPublish =\n remoteFull == null || (headFull.length > 0 && remoteFull !== headFull);\n if (!committed.committed && !needsPublish) {\n return committed;\n }\n\n const pushed = pushFeatureBranchWorkspace(opts.dir, opts.branch, {\n forceWithLease: sync.rebased,\n });\n if (!pushed.ok) return { ok: false, error: pushed.error };\n return {\n ok: true,\n commitSha: pushed.commitSha,\n committed: committed.committed,\n pushed: true,\n };\n}\n\nasync function runMergeDevIntoFeaturePhase(opts: {\n spec: AgentJobConfigV1;\n dir: string;\n runnerCommand: string;\n outputPath: { dir: string; resultJsonPath: string };\n indexSample: string;\n}): Promise<void> {\n const { spec, dir, runnerCommand, outputPath, indexSample } = opts;\n const branch = spec.targetBranch?.trim() ?? \"\";\n const mergeSource = (spec.mergeSourceBranch?.trim() || \"dev\").replace(/\\r?\\n/g, \"\").trim();\n\n await postCallback({\n ok: true,\n final: false,\n progress: {\n stage: \"fetch\",\n message: `Fetching ${mergeSource} and ${branch} for rebase onto dev`,\n updatedAt: new Date().toISOString(),\n },\n });\n\n const integration = integrationBranchFromSpec(spec);\n const prep = prepareMergeDevWorkspace(dir, branch, integration);\n if (!prep.ok) {\n await postCallback({\n ok: false,\n error: `could not prepare feature workspace for merge-dev: ${prep.error}`,\n });\n agentExit(1);\n }\n\n let summary: string;\n if (prep.rebaseState === \"already_complete\") {\n summary = `共享工作区 rebase 已完成(onto origin/${mergeSource}),续跑 push`;\n agentLog(\"merge-dev skip rebase: PVC already rebased\", { branch, mergeSource });\n } else if (prep.rebaseState === \"in_progress\") {\n const conflictPaths = prep.conflictPaths?.trim() ?? \"\";\n if (conflictPaths) {\n summary = await resolveRebaseConflictsWithAgent({\n spec,\n dir,\n branch,\n mergeSource,\n runnerCommand,\n outputPath,\n indexSample,\n conflictPaths,\n });\n } else {\n summary = `续跑进行中的 rebase(onto origin/${mergeSource})`;\n }\n const advanced = await advanceRebaseAfterAgentResolution({\n dir,\n spec,\n branch,\n mergeSource,\n runnerCommand,\n outputPath,\n indexSample,\n errorPrefix: \"git rebase --continue failed after conflict resolution\",\n });\n if (!advanced.ok) {\n await postCallback({ ok: false, error: advanced.error });\n agentExit(1);\n }\n } else {\n const rebaseRes = spawnSync(\"git\", [\"-C\", dir, \"rebase\", `origin/${mergeSource}`], {\n encoding: \"utf-8\",\n env: gitWorkspaceEnv(),\n timeout: 600_000,\n });\n\n if ((rebaseRes.status ?? 1) === 0) {\n const combined = `${rebaseRes.stdout ?? \"\"}\\n${rebaseRes.stderr ?? \"\"}`;\n summary = combined.includes(\"is up to date\") || combined.includes(\"up to date\")\n ? `已与 origin/${mergeSource} 同步(rebase 无需新提交)`\n : `已将 ${branch} rebase 到 origin/${mergeSource}(无冲突)`;\n } else {\n let conflictPaths = listUnmergedPaths(dir);\n if (!conflictPaths && !gitRebaseInProgress(dir)) {\n const abort = gitWorkspaceErr(dir, [\"rebase\", \"--abort\"]);\n const tail = [rebaseRes.stderr, rebaseRes.stdout, abort].filter(Boolean).join(\" | \").slice(0, 3500);\n await postCallback({\n ok: false,\n error: `git rebase origin/${mergeSource} failed (not a simple conflict set): ${tail}`,\n });\n agentExit(1);\n }\n\n summary = await resolveRebaseConflictsWithAgent({\n spec,\n dir,\n branch,\n mergeSource,\n runnerCommand,\n outputPath,\n indexSample,\n conflictPaths: conflictPaths || \"(rebase in progress)\",\n });\n\n const advanced = await advanceRebaseAfterAgentResolution({\n dir,\n spec,\n branch,\n mergeSource,\n runnerCommand,\n outputPath,\n indexSample,\n errorPrefix: \"git rebase --continue failed after conflict resolution\",\n });\n if (!advanced.ok) {\n await postCallback({ ok: false, error: advanced.error });\n agentExit(1);\n }\n }\n }\n\n const unique = featureRebaseHasUniqueChangesVsMergeSource(dir, mergeSource);\n if (!unique.ok) {\n await postCallback({ ok: false, error: unique.error });\n agentExit(1);\n }\n\n const pushed = pushFeatureBranchWorkspace(dir, branch, { forceWithLease: true });\n if (!pushed.ok) {\n await postCallback({ ok: false, error: pushed.error });\n agentExit(1);\n }\n\n await postCallback({\n ok: true,\n final: true,\n branch,\n commitSha: pushed.commitSha || undefined,\n summary,\n });\n}\n\nfunction defaultDevUiContractPayload(appName: string): Record<string, unknown> {\n return {\n uiContractPath: `spec/ui-contracts/${appName}/web-ui.contract.json`,\n appName,\n summary: \"D1 dev pipeline UI contract scaffold (agent fallback)\",\n };\n}\n\nfunction defaultValidationPlanPayload(): Record<string, unknown> {\n return {\n validationPlan: {\n featurePaths: [\n \"spec/behaviors/01-auth/login.feature\",\n \"spec/behaviors/01-auth/session.feature\",\n ],\n l2Tags: [\"@l2-auth-access\"],\n rationale: \"Agent fallback: minimal auth foundation for validation scope\",\n summary: \"Validation plan scaffold (agent fallback)\",\n confidence: \"low\",\n },\n };\n}\n\nfunction defaultValidationCodegenPayload(reqCode: string): Record<string, unknown> {\n return {\n validationCodegen: {\n featurePaths: [`spec/behaviors/06-requirement/dev-pipeline-linear.feature`],\n stepsPaths: [`e2e/steps/dev-pipeline.steps.ts`],\n summary: `Validation codegen scaffold for ${reqCode}`,\n },\n };\n}\n\nasync function executeDevUiContractPipeline(opts: {\n spec: AgentJobConfigV1;\n dir: string;\n runnerCommand: string;\n outputPath: { dir: string; resultJsonPath: string };\n indexSample: string;\n title: string;\n raw: string;\n}): Promise<void> {\n const { spec, dir } = opts;\n const featureBranch = spec.targetBranch?.trim() ?? \"\";\n configureGitIdentityForWorkspace(dir, spec);\n if (featureBranch.startsWith(\"feature/\")) {\n const prep = prepareFeatureWorkspace(dir, featureBranch, integrationBranchFromSpec(spec));\n if (!prep.ok) {\n await postCallback({\n ok: false,\n error: `could not prepare feature workspace for UI contract: ${prep.error}`,\n });\n agentExit(1);\n }\n }\n\n const appName = \"studio\";\n const contractRel = `spec/ui-contracts/${appName}/web-ui.contract.json`;\n const prompt = [\n \"You are generating a web UI contract JSON for Nvwa Studio.\",\n `Write ${contractRel} with anchors for requirement dev pipeline (requirement-dev-phase, requirement-dev-phase-*).`,\n `Also write a summary JSON to ${opts.outputPath.resultJsonPath} with keys: uiContractPath, appName, summary.`,\n `Requirement title: ${opts.title}`,\n `Requirement input:\\n${opts.raw.slice(0, 4000)}`,\n `Repo index sample:\\n${opts.indexSample.slice(0, 2000)}`,\n ].join(\"\\n\\n\") + integrationBusinessPromptSuffix(spec);\n\n await postCallback({\n ok: true,\n final: false,\n progress: { stage: \"dev_ui_contract\", message: \"Generating L4 UI contract\", updatedAt: new Date().toISOString() },\n });\n\n const agentRun = await tryAgentStream(prompt, opts.dir, opts.runnerCommand, async (progress) => {\n await postCallback({ ok: true, final: false, progress });\n });\n\n let payload = defaultDevUiContractPayload(appName);\n const fileRaw = existsSync(opts.outputPath.resultJsonPath)\n ? readFileSync(opts.outputPath.resultJsonPath, \"utf-8\")\n : null;\n if (fileRaw) {\n try {\n const parsed = JSON.parse(fileRaw) as Record<string, unknown>;\n if (typeof parsed.uiContractPath === \"string\") payload = parsed;\n } catch {\n /* use fallback */\n }\n }\n if (agentRun.exitCode !== 0) {\n writeFileSync(opts.outputPath.resultJsonPath, JSON.stringify(payload, null, 2), \"utf-8\");\n }\n\n if (featureBranch.startsWith(\"feature/\")) {\n const msg = `nvwa(dev): UI contract ${opts.title.slice(0, 60)}\\n\\n${triggeredByTrailerFromSpec(spec)}`;\n const pushed = await commitSyncAndPushFeatureWorkspace({\n dir,\n branch: featureBranch,\n message: msg,\n spec,\n runnerCommand: opts.runnerCommand,\n outputPath: opts.outputPath,\n indexSample: opts.indexSample,\n });\n if (!pushed.ok) {\n await postCallback({ ok: false, error: pushed.error });\n agentExit(1);\n }\n }\n\n await postCallback({\n ok: true,\n final: true,\n result: payload,\n ...payload,\n });\n}\n\nasync function executeValidationPlanPipeline(opts: {\n spec: AgentJobConfigV1;\n dir: string;\n runnerCommand: string;\n outputPath: { dir: string; resultJsonPath: string };\n indexSample: string;\n title: string;\n raw: string;\n chatContext: string;\n}): Promise<void> {\n const { spec, dir } = opts;\n const featureBranch = spec.targetBranch?.trim() ?? \"\";\n configureGitIdentityForWorkspace(dir, spec);\n if (featureBranch.startsWith(\"feature/\")) {\n const prep = prepareFeatureWorkspace(dir, featureBranch, integrationBranchFromSpec(spec));\n if (!prep.ok) {\n await postCallback({\n ok: false,\n error: `could not prepare feature workspace for validation plan: ${prep.error}`,\n });\n agentExit(1);\n }\n }\n\n const ymlHint = existsSync(join(dir, \"nvwa.validation.yml\"))\n ? readFileSync(join(dir, \"nvwa.validation.yml\"), \"utf-8\").slice(0, 2000)\n : \"(no nvwa.validation.yml)\";\n\n const prompt = [\n \"You are planning which existing Playwright BDD feature files should run during P5 validation for this requirement.\",\n \"Read-only analysis: do NOT modify the repository; only write the JSON result file.\",\n `Write JSON to ${opts.outputPath.resultJsonPath} with validationPlan: { featurePaths[], l2Tags?, rationale, summary, confidence? }.`,\n \"Rules:\",\n \"- featurePaths must be existing paths under spec/behaviors/**/*.feature in this repo\",\n \"- Always include spec/behaviors/01-auth/** foundation features (auth API regression runs in INTEGRATION_VERIFY)\",\n \"- Respect nvwa.validation.yml behaviors.exclude (do not select excluded features unless clearly required by the requirement)\",\n \"- Prefer features matching developmentGoal specRefs and @l2-* tags relevant to this requirement\",\n \"- Note in rationale which selected features contain @parallel-safe scenarios (read-only / Phase 1 parallel when E2E_WORKERS>1); do not select only for parallel — correctness first\",\n PARALLEL_SAFE_AUTHORING_RULES,\n \"- Do not select expensive agent-triggering scenarios (e.g. entry.feature) unless the requirement explicitly needs them\",\n `Requirement title: ${opts.title}`,\n opts.raw.slice(0, 4000),\n opts.chatContext ? `Context:\\n${opts.chatContext.slice(0, 8000)}` : \"\",\n `nvwa.validation.yml excerpt:\\n${ymlHint}`,\n `Repo index sample:\\n${opts.indexSample.slice(0, 3000)}`,\n ]\n .filter(Boolean)\n .join(\"\\n\\n\");\n\n await postCallback({\n ok: true,\n final: false,\n progress: { stage: \"validation_plan\", message: \"Planning validation scope\", updatedAt: new Date().toISOString() },\n });\n\n const agentRun = await tryAgentStream(prompt, opts.dir, opts.runnerCommand, async (progress) => {\n await postCallback({ ok: true, final: false, progress });\n });\n\n let payload = defaultValidationPlanPayload();\n const fileRaw = existsSync(opts.outputPath.resultJsonPath)\n ? readFileSync(opts.outputPath.resultJsonPath, \"utf-8\")\n : null;\n if (fileRaw) {\n try {\n const parsed = JSON.parse(fileRaw) as Record<string, unknown>;\n if (parsed.validationPlan || parsed.featurePaths) payload = parsed;\n } catch {\n /* fallback */\n }\n }\n if (agentRun.exitCode !== 0) {\n writeFileSync(opts.outputPath.resultJsonPath, JSON.stringify(payload, null, 2), \"utf-8\");\n }\n\n const nested = payload.validationPlan as Record<string, unknown> | undefined;\n await postCallback({\n ok: true,\n final: true,\n result: payload,\n validationPlan: nested ?? payload,\n ...(nested ?? {}),\n });\n}\n\nasync function executeOpsStructuralPortPipeline(opts: {\n spec: AgentJobConfigV1;\n dir: string;\n runnerCommand: string;\n outputPath: { dir: string; resultJsonPath: string };\n title: string;\n raw: string;\n chatContext: string;\n}): Promise<void> {\n const { spec, dir } = opts;\n const opsUrl = spec.gitopsRepoUrl?.trim() ?? \"\";\n if (!opsUrl) {\n await postCallback({ ok: false, error: \"gitopsRepoUrl missing in job config\" });\n agentExit(1);\n }\n const opsDir = join(dir, \"ops-repo\");\n mkdirSync(opsDir, { recursive: true });\n const mainRef = (spec.gitopsMainRef ?? \"main\").trim() || \"main\";\n const featureRef = (spec.gitopsFeatureBranch ?? spec.targetBranch ?? \"\").trim();\n const prep = spawnSync(\"git\", [\"clone\", \"--depth\", \"1\", \"--branch\", mainRef, opsUrl, opsDir], {\n cwd: dir,\n encoding: \"utf8\",\n env: process.env,\n });\n if (prep.status !== 0) {\n await postCallback({\n ok: false,\n error: `ops repo clone failed: ${(prep.stderr || prep.stdout || \"\").slice(0, 500)}`,\n });\n agentExit(1);\n }\n if (featureRef) {\n spawnSync(\"git\", [\"fetch\", \"origin\", featureRef], { cwd: opsDir, encoding: \"utf8\" });\n }\n\n const skill = readSkillPlaybook(AGENT_PLAYBOOK_PATHS.opsStructuralPort);\n const chatRevision = spec.opsStructuralChatMessage?.trim();\n const prompt = [\n skill,\n \"Application requirement context repo is the current working directory; ops repo is ./ops-repo.\",\n `Port structural manifests from ops feature branch ${featureRef || \"(requirement branch)\"} to dev on ${mainRef}.`,\n `Paths: feature=${spec.gitopsPathFeature ?? \"environments/feature\"}, dev=${spec.gitopsPathDev ?? \"environments/dev\"}.`,\n `Write JSON to ${opts.outputPath.resultJsonPath} with key opsStructuralDraft: { files: [{ path, content }], summary?, sourceOpsFeatureSha?, targetMainSha? }.`,\n \"Do NOT modify or include any nvwa.deployment.yml. Do NOT git push.\",\n chatRevision ? `User revision:\\n${chatRevision}` : \"\",\n `Requirement: ${opts.title}`,\n opts.raw.slice(0, 4000),\n opts.chatContext ? `Context:\\n${opts.chatContext.slice(0, 8000)}` : \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\\n\");\n\n await postCallback({\n ok: true,\n final: false,\n progress: { stage: \"ops_structural_port\", message: \"Generating ops structural port draft\", updatedAt: new Date().toISOString() },\n });\n\n const agentRun = await tryAgentStream(prompt, dir, opts.runnerCommand, async (progress) => {\n await postCallback({ ok: true, final: false, progress });\n });\n\n let payload: Record<string, unknown> = { opsStructuralDraft: { files: [], summary: \"empty draft\" } };\n if (existsSync(opts.outputPath.resultJsonPath)) {\n try {\n payload = JSON.parse(readFileSync(opts.outputPath.resultJsonPath, \"utf-8\")) as Record<string, unknown>;\n } catch {\n /* fallback */\n }\n }\n if (agentRun.exitCode !== 0) {\n await postCallback({ ok: false, error: agentRun.stderr.slice(-2000) || \"ops structural port agent failed\" });\n agentExit(1);\n }\n await postCallback({ ok: true, final: true, ...payload });\n agentExit(0);\n}\n\nasync function executeValidationCodegenPipeline(opts: {\n spec: AgentJobConfigV1;\n dir: string;\n runnerCommand: string;\n outputPath: { dir: string; resultJsonPath: string };\n indexSample: string;\n title: string;\n raw: string;\n chatContext: string;\n}): Promise<void> {\n const { spec, dir } = opts;\n const featureBranch = spec.targetBranch?.trim() ?? \"\";\n configureGitIdentityForWorkspace(dir, spec);\n if (featureBranch.startsWith(\"feature/\")) {\n const prep = prepareFeatureWorkspace(dir, featureBranch, integrationBranchFromSpec(spec));\n if (!prep.ok) {\n await postCallback({\n ok: false,\n error: `could not prepare feature workspace for validation codegen: ${prep.error}`,\n });\n agentExit(1);\n }\n }\n\n const reqCode = (opts.spec.jobCode ?? opts.spec.jobId).slice(0, 40);\n const prompt = [\n \"Generate Playwright BDD skeleton paths for this requirement; write files under spec/behaviors and e2e/steps as needed.\",\n `Write JSON to ${opts.outputPath.resultJsonPath} with validationCodegen: { featurePaths[], stepsPaths[], summary }.`,\n \"If Validation Plan feature paths were provided in context, prioritize extending those features; you may add new feature files for this requirement.\",\n PARALLEL_SAFE_AUTHORING_RULES,\n `Requirement: ${opts.title}`,\n opts.raw.slice(0, 4000),\n opts.chatContext ? `Context:\\n${opts.chatContext.slice(0, 8000)}` : \"\",\n opts.indexSample.slice(0, 2000),\n integrationBusinessPromptSuffix(spec, { e2e: true }),\n ]\n .filter(Boolean)\n .join(\"\\n\\n\");\n\n await postCallback({\n ok: true,\n final: false,\n progress: { stage: \"validation_codegen\", message: \"Generating validation skeleton\", updatedAt: new Date().toISOString() },\n });\n\n const agentRun = await tryAgentStream(prompt, opts.dir, opts.runnerCommand, async (progress) => {\n await postCallback({ ok: true, final: false, progress });\n });\n\n let payload = defaultValidationCodegenPayload(reqCode);\n const fileRaw = existsSync(opts.outputPath.resultJsonPath)\n ? readFileSync(opts.outputPath.resultJsonPath, \"utf-8\")\n : null;\n if (fileRaw) {\n try {\n const parsed = JSON.parse(fileRaw) as Record<string, unknown>;\n if (parsed.validationCodegen || parsed.featurePaths) payload = parsed;\n } catch {\n /* fallback */\n }\n }\n if (agentRun.exitCode !== 0) {\n writeFileSync(opts.outputPath.resultJsonPath, JSON.stringify(payload, null, 2), \"utf-8\");\n }\n\n if (featureBranch.startsWith(\"feature/\")) {\n const behaviorsCheck = verifyBehaviorsBeforePush(dir);\n if (!behaviorsCheck.ok) {\n await postCallback({ ok: false, error: behaviorsCheck.error });\n agentExit(1);\n }\n const msg = `nvwa(dev): validation codegen ${opts.title.slice(0, 60)}\\n\\n${triggeredByTrailerFromSpec(spec)}`;\n const pushed = await commitSyncAndPushFeatureWorkspace({\n dir,\n branch: featureBranch,\n message: msg,\n spec,\n runnerCommand: opts.runnerCommand,\n outputPath: opts.outputPath,\n indexSample: opts.indexSample,\n });\n if (!pushed.ok) {\n await postCallback({ ok: false, error: pushed.error });\n agentExit(1);\n }\n }\n\n const nested = payload.validationCodegen as Record<string, unknown> | undefined;\n await postCallback({\n ok: true,\n final: true,\n result: payload,\n validationCodegen: nested ?? payload,\n ...(nested ?? {}),\n });\n}\n\nconst JOB_OPS_PLAYBOOK_MAX_CHARS = 4096;\n\nfunction readSkillPlaybook(path: string): string {\n try {\n if (!existsSync(path)) return \"\";\n return readFileSync(path, \"utf-8\").slice(0, JOB_OPS_PLAYBOOK_MAX_CHARS);\n } catch {\n return \"\";\n }\n}\n\nfunction readJobOpsPlaybook(): string {\n return readSkillPlaybook(AGENT_PLAYBOOK_PATHS.jobDeployOps);\n}\n\nexport function buildDevPipelineTriagePrompt(\n spec: AgentJobConfigV1,\n failureBlock: string,\n resultPath: string,\n indexSample: string,\n): string {\n const opsPlaybook = readJobOpsPlaybook();\n if (opsPlaybook) {\n logSkillPlaybookInjected(spec, \"nvwa-job-deploy-ops\", opsPlaybook.length, true);\n }\n const opsSection = opsPlaybook\n ? `\\n\\n## Deploy observation (optional)\\nUse absolute path \\`/usr/local/bin/nvwa-os ops …\\` when you need live Argo/K8s evidence (do not modify GitOps):\\n${opsPlaybook}\\n`\n : \"\";\n\n return `\nYou are triaging a failed Nvwa development pipeline step. Read the failure context and repository layout, then decide how to recover.\n\nRequirement title: ${spec.requirementTitle}\nRequirement: ${spec.requirementRawInput.slice(0, 2000)}\n\n${failureBlock}\n\nRepository sample (truncated):\n${indexSample.slice(0, 3000)}\n\nOutput exactly one JSON object to ${resultPath} (and print the same JSON to stdout). Schema:\n{\n \"targetPhase\": \"UI_CONTRACT\" | \"VALIDATION_PLAN\" | \"VALIDATION_CODE\" | \"IMPLEMENTATION\" | \"LOCAL_VERIFY\" | \"VALIDATE\" | \"SECURITY_VERIFY\" | \"DEPLOY\",\n \"fixCategory\": \"code\" | \"spec\" | \"infra\" | \"retry_only\" | \"none\",\n \"rationale\": \"中文,给用户看\",\n \"agentBrief\": \"给下一步修复 Agent 的明确指令(中文)\"\n}\n\nRules:\n- fixCategory \"infra\": Ingress/DNS/GitOps/Argo sync issues — do NOT tell the next agent to change application business logic; use targetPhase VALIDATE or DEPLOY only.\n- fixCategory \"retry_only\": transient env issue — targetPhase VALIDATE to re-run tests only; for npm tarball / push gate transient failures use targetPhase IMPLEMENTATION to retry push without code changes.\n- fixCategory \"none\": cannot auto-fix (missing credentials, policy block).\n- When failure context shows 失败类型: build or image build Job failure: you MUST use fixCategory \"code\" and targetPhase \"IMPLEMENTATION\" (never \"infra\"). Fix the repository (e.g. bun.lock, Dockerfile, source) before redeploying.\n- When 失败类型 is build: use「失败 Dockerfile / 构建错误摘录」as the primary root cause. Do NOT attribute build failure to unrelated delivery debt (test.skip, spec-ui-drift, L2 doc status, duplicate package.json override warnings) unless the build log explicitly mentions them.\n- When build failure excerpt mentions runtime build / Bundle failed / externals: agentBrief must name the Dockerfile and suggest build-runtime externals + \\`bun run check:runtime-images:docker-context\\`.\n- feature_app_missing when release/build never succeeded is a symptom of failed DEPLOY, not infra — route to IMPLEMENTATION or DEPLOY after code fix, not infra wait.\n- When failure context shows push_gate:docker_parity or npm \"fail extracting tarball\" / registry.npmjs.org download errors: fixCategory \"retry_only\", targetPhase IMPLEMENTATION (do not change business logic).\n- lockfile / frozen-lockfile / \"lockfile had changes\" in build logs: fixCategory \"code\", targetPhase \"IMPLEMENTATION\"; agentBrief must say run \\`bun install\\`, commit bun.lock, push.\n- targetPhase VALIDATE = re-run Playwright only; DEPLOY = re-run release/build only.\n- When targetPhase is VALIDATION_CODE, agentBrief must remind: default Gherkin scenarios serial (no tag); opt-in @parallel-safe only for read-only UI/API without scan world-state.\n${PARALLEL_SAFE_AUTHORING_RULES}\n- No markdown fences; file must be valid JSON only.\n${opsSection}`.trim();\n}\n\nasync function executeDevPipelineTriagePipeline(opts: {\n spec: AgentJobConfigV1;\n dir: string;\n runnerCommand: string;\n outputPath: { dir: string; resultJsonPath: string };\n indexSample: string;\n}): Promise<void> {\n const { spec, dir, runnerCommand, outputPath, indexSample } = opts;\n const failureRaw = spec.failureContext;\n const failure =\n failureRaw != null ? parseDevPipelineFailureContext(failureRaw) : null;\n const failureBlock = failure\n ? formatFailureContextForAgent(failure)\n : spec.requirementChatContext || \"(no failure context)\";\n\n configureGitIdentityForWorkspace(dir, spec);\n const branch = spec.targetBranch?.trim() ?? \"\";\n if (branch.startsWith(\"feature/\")) {\n const prep = prepareFeatureWorkspace(dir, branch, integrationBranchFromSpec(spec));\n if (!prep.ok) {\n await postCallback({ ok: false, error: `triage workspace prep failed: ${prep.error}` });\n agentExit(1);\n }\n }\n\n const prompt = buildDevPipelineTriagePrompt(spec, failureBlock, outputPath.resultJsonPath, indexSample);\n\n await postCallback({\n ok: true,\n final: false,\n progress: {\n stage: \"triage\",\n message: \"Analyzing pipeline failure\",\n updatedAt: new Date().toISOString(),\n },\n });\n\n const agentRun = await tryAgentStream(prompt, dir, runnerCommand, async (progress) => {\n await postCallback({ ok: true, final: false, progress });\n });\n\n let decision: DevPipelineTriageDecision = {\n targetPhase: \"IMPLEMENTATION\",\n fixCategory: \"code\",\n rationale: \"Triage agent did not return valid JSON; defaulting to implementation retry.\",\n agentBrief: failure?.summary ?? \"请根据失败上下文修复问题。\",\n };\n\n const fileRaw = existsSync(outputPath.resultJsonPath)\n ? readFileSync(outputPath.resultJsonPath, \"utf-8\")\n : null;\n if (fileRaw) {\n try {\n const parsed = JSON.parse(fileRaw) as unknown;\n const fromFile = parseDevPipelineTriageDecision(parsed);\n if (fromFile) decision = fromFile;\n } catch {\n /* use default */\n }\n }\n\n if (agentRun.exitCode !== 0) {\n writeFileSync(outputPath.resultJsonPath, JSON.stringify(decision, null, 2), \"utf-8\");\n }\n\n await postCallback({\n ok: true,\n final: true,\n result: decision,\n triage: decision,\n ...decision,\n });\n}\n\nasync function executeCodeTaskFeaturePipeline(opts: {\n spec: AgentJobConfigV1;\n dir: string;\n runnerCommand: string;\n outputPath: { dir: string; resultJsonPath: string };\n indexSample: string;\n}): Promise<void> {\n const { spec, dir, runnerCommand, outputPath, indexSample } = opts;\n const branch = spec.targetBranch?.trim() ?? \"\";\n if (!branch.startsWith(\"feature/\")) {\n await postCallback({\n ok: false,\n error: `invalid targetBranch in job.json (must start with feature/): ${branch || \"(empty)\"}`,\n });\n agentExit(1);\n }\n\n configureGitIdentityForWorkspace(dir, spec);\n\n if (spec.codeTaskPhase === \"merge_dev\" || spec.codeTaskPhase === \"pipeline_sync_dev\") {\n await runMergeDevIntoFeaturePhase({ spec, dir, runnerCommand, outputPath, indexSample });\n return;\n }\n\n const integration = integrationBranchFromSpec(spec);\n const prep = prepareFeatureWorkspace(dir, branch, integration);\n if (!prep.ok) {\n await postCallback({\n ok: false,\n error: `could not prepare feature workspace: ${prep.error}`,\n });\n agentExit(1);\n }\n\n await postCallback({\n ok: true,\n final: false,\n progress: {\n stage: \"analyze\",\n message: `Branch ${branch}${prep.created ? \" (new from integration)\" : \" (tracking remote)\"}: running code agent`,\n updatedAt: new Date().toISOString(),\n },\n });\n\n const prompt =\n buildCodeTaskAgentPrompt(\n spec.requirementTitle,\n spec.requirementRawInput,\n spec.requirementChatContext,\n branch,\n outputPath.resultJsonPath,\n indexSample,\n ) + integrationBusinessPromptSuffix(spec);\n\n console.error(\"[nvwa-agent] code_task_feature pipeline\\n\", prompt);\n\n const agentRun = await tryAgentStream(prompt, dir, runnerCommand, async (progress) => {\n await postCallback({ ok: true, final: false, progress });\n });\n\n if (agentRun.exitCode !== 0) {\n const tail = agentRun.stderr.slice(-4000) || agentRun.stdout.slice(-4000) || \"(no stderr/stdout)\";\n console.error(\"[nvwa-agent] code-task agent stderr tail:\", tail);\n await postCallback({\n ok: false,\n error: `code agent exited with code ${agentRun.exitCode}; stderr/stdout tail: ${tail.slice(0, 3500)}`,\n });\n agentExit(1);\n }\n\n let fileRaw = existsSync(outputPath.resultJsonPath) ? readFileSync(outputPath.resultJsonPath, \"utf-8\") : null;\n let summary = parseCodeTaskSummaryFromText(fileRaw);\n if (!summary) {\n console.warn(\"[nvwa-agent] code-task summary missing from file; trying Cursor agent stdout (stream-json)\");\n summary =\n parseCodeTaskSummaryFromCursorStdout(agentRun.stdout) ?? \"代码任务已完成(未生成有效摘要)\";\n }\n\n const msg = buildCodeTaskCommitMessage(spec, summary);\n const committed = commitFeatureWorkspace(dir, branch, msg);\n if (!committed.ok) {\n await postCallback({ ok: false, error: committed.error });\n agentExit(1);\n }\n\n const pushGateResult = runFeaturePushGates(dir);\n\n const sync = await syncFeatureBranchBeforePush({\n dir,\n branch,\n spec,\n runnerCommand,\n outputPath,\n indexSample,\n });\n if (!sync.ok) {\n await postCallback({ ok: false, error: `push_failed: ${sync.error}` });\n agentExit(1);\n }\n const feat = branchShortName(branch);\n const headFull = gitHeadSha(dir, false) ?? committed.commitSha;\n const remoteFull = gitRemoteBranchSha(dir, feat);\n const needsPublish =\n remoteFull == null || (headFull.length > 0 && remoteFull !== headFull);\n if (!committed.committed && !needsPublish) {\n if (!pushGateResult.ok) {\n await postCallback({ ok: false, error: pushGateResult.error });\n agentExit(1);\n }\n await postCallback({\n ok: true,\n final: true,\n branch,\n commitSha: committed.commitSha || undefined,\n repoCommitted: false,\n summary,\n });\n return;\n }\n const pushed = pushFeatureBranchWorkspace(dir, branch, { forceWithLease: sync.rebased });\n if (!pushed.ok) {\n await postCallback({ ok: false, error: `push_failed: ${pushed.error}` });\n agentExit(1);\n }\n\n if (!pushGateResult.ok) {\n await postCallback({ ok: false, error: pushGateResult.error });\n agentExit(1);\n }\n\n await postCallback({\n ok: true,\n final: true,\n branch,\n commitSha: pushed.commitSha || undefined,\n repoCommitted: committed.committed,\n summary,\n });\n}\n\nexport type RunRepoRewriteOptions = {\n mode?: AgentProviderMode;\n agentCommand?: string;\n workspaceDir?: string;\n /** When false, throw AgentRunFailure instead of process.exit (worker HTTP). */\n exitOnFailure?: boolean;\n /** Cursor CLI --continue for this run (worker cross-task). */\n cursorContinue?: boolean;\n callbackSecret?: string;\n};\n\nexport async function runRepoRewriteFromConfig(\n spec: AgentJobConfigV1,\n options?: RunRepoRewriteOptions,\n): Promise<void> {\n clearAgentRunCancelState();\n const mode = options?.mode ?? \"cursor\";\n const runtime = validateAgentRuntime(mode);\n if (!runtime.ok) {\n throw new Error(\n [\n `[nvwa-agent] mode '${mode}' runtime check failed`,\n ...(runtime.missingBinaries.length > 0\n ? [`missing binaries: ${runtime.missingBinaries.join(\", \")}`]\n : []),\n ...(runtime.missingEnv.length > 0 ? [`missing env: ${runtime.missingEnv.join(\", \")}`] : []),\n ].join(\"\\n\"),\n );\n }\n setAgentExitOnFailure(options?.exitOnFailure !== false);\n jobSpec = spec;\n if (options?.callbackSecret?.trim()) {\n process.env.NVWA_CALLBACK_SECRET = options.callbackSecret.trim();\n }\n process.env.NVWA_AGENT_RUNTIME = \"worker\";\n if (!spec.callbackUrl.trim()) {\n throw new AgentRunFailure(\"empty callbackUrl in job configuration\");\n }\n if (!(process.env.NVWA_CALLBACK_SECRET ?? \"\").trim()) {\n throw new AgentRunFailure(\"missing NVWA_CALLBACK_SECRET\");\n }\n\n prepareCursorSession(spec);\n try {\n await executeRunRepoRewriteBody(spec, options);\n } finally {\n teardownCursorSession();\n }\n}\n\nexport async function runRepoRewrite(options?: RunRepoRewriteOptions): Promise<void> {\n const mode = options?.mode ?? \"cursor\";\n const runtime = validateAgentRuntime(mode);\n if (!runtime.ok) {\n const details = [\n `[nvwa-agent] mode '${mode}' runtime check failed`,\n ...(runtime.missingBinaries.length > 0\n ? [`missing binaries: ${runtime.missingBinaries.join(\", \")}`]\n : []),\n ...(runtime.missingEnv.length > 0 ? [`missing env: ${runtime.missingEnv.join(\", \")}`] : []),\n ];\n throw new Error(details.join(\"\\n\"));\n }\n\n if (existsSync(AGENT_JOB_CONFIG_MOUNT_PATH)) {\n const raw = readFileSync(AGENT_JOB_CONFIG_MOUNT_PATH, \"utf-8\");\n jobSpec = parseAgentJobConfigV1(raw);\n if (!jobSpec) {\n console.error(\"[nvwa-agent] invalid job.json at\", AGENT_JOB_CONFIG_MOUNT_PATH, raw.slice(0, 500));\n const ok = await postCallbackBestEffort({\n ok: false,\n error: `invalid job.json at ${AGENT_JOB_CONFIG_MOUNT_PATH} (parseAgentJobConfigV1 returned null)`,\n });\n if (!ok) console.error(\"[nvwa-agent] could not report invalid job.json to Creator API\");\n agentExit(1);\n }\n } else {\n const repoUrl = process.env.GIT_REPO_URL ?? \"\";\n if (!repoUrl.trim()) {\n console.error(\n \"[nvwa-agent] missing job.json (expected\",\n AGENT_JOB_CONFIG_MOUNT_PATH,\n \") and GIT_REPO_URL for local fallback\",\n );\n await postCallbackBestEffort({\n ok: false,\n error: `missing job.json (${AGENT_JOB_CONFIG_MOUNT_PATH}) and GIT_REPO_URL`,\n });\n agentExit(1);\n }\n jobSpec = buildAgentJobConfigV1({\n jobId: process.env.NVWA_JOB_ID || \"unknown-job\",\n requirementId: process.env.NVWA_REQUIREMENT_ID || \"\",\n callbackUrl: process.env.NVWA_CALLBACK_URL || \"\",\n gitRepoUrl: repoUrl,\n gitRef: process.env.GIT_REF || \"main\",\n requirementTitle: process.env.NVWA_REQUIREMENT_TITLE || \"\",\n requirementRawInput: process.env.NVWA_REQUIREMENT_RAW_INPUT || \"\",\n requirementChatContext: process.env.NVWA_REQUIREMENT_CHAT_CONTEXT || \"\",\n llmBaseUrl: process.env.NVWA_OS_LLM_GATEWAY_BASE_URL?.trim() || null,\n llmModel: process.env.NVWA_OS_LLM_FLASH_MODEL?.trim() || null,\n targetBranch: process.env.NVWA_TARGET_BRANCH?.trim() || null,\n cursorSessionMode: parseAgentCursorSessionMode(process.env.NVWA_AGENT_CURSOR_SESSION_MODE),\n });\n }\n\n const spec = jobSpec;\n if (!spec.callbackUrl.trim()) {\n console.error(\"[nvwa-agent] empty callbackUrl in job configuration\");\n await postCallbackBestEffort({ ok: false, error: \"empty callbackUrl in job configuration\" });\n agentExit(1);\n }\n if (!(process.env.NVWA_CALLBACK_SECRET ?? \"\").trim()) {\n console.error(\"[nvwa-agent] missing NVWA_CALLBACK_SECRET\");\n await postCallbackBestEffort({ ok: false, error: \"missing NVWA_CALLBACK_SECRET in pod env\" });\n agentExit(1);\n }\n\n prepareCursorSession(spec);\n try {\n await executeRunRepoRewriteBody(spec, options);\n } finally {\n teardownCursorSession();\n }\n}\n\nfunction realBaseUrlFromIntegrationSimSpec(spec: AgentJobConfigV1): string {\n const m = /Real vendor base URL:\\s*(\\S+)/.exec(spec.requirementRawInput);\n const url = m?.[1]?.trim() ?? \"\";\n if (!url || url === \"(placeholder)\") return \"https://integration-sim.local\";\n return url.replace(/\\/$/, \"\");\n}\n\nasync function executeIntegrationDocCompilePipeline(opts: {\n spec: AgentJobConfigV1;\n dir: string;\n runnerCommand: string;\n outputPath: { dir: string; resultJsonPath: string };\n}): Promise<void> {\n const { spec, dir, runnerCommand, outputPath } = opts;\n const contractCode = spec.integrationContractCode?.trim() || \"contract\";\n const jobCode = spec.jobCode?.trim() || spec.jobId;\n const phase =\n spec.integrationDocCompilePhase === \"classify\" ||\n spec.integrationDocCompilePhase === \"extract\" ||\n spec.integrationDocCompilePhase === \"full\"\n ? spec.integrationDocCompilePhase\n : \"full\";\n\n ensureCompileWorkspace(dir);\n\n const playbook = readCompileSkillPlaybookForPhase(phase);\n const playbookName =\n phase === \"classify\"\n ? \"nvwa-integration-doc-classify\"\n : phase === \"extract\"\n ? \"nvwa-integration-doc-extract\"\n : \"nvwa-integration-doc-compile\";\n logSkillPlaybookInjected(spec, playbookName, playbook.length, playbook.length > 0);\n\n const prompt = buildIntegrationDocCompilePrompt({\n spec,\n resultJsonPath: outputPath.resultJsonPath,\n playbook,\n });\n\n await postCallback({\n ok: true,\n final: false,\n progress: {\n stage: phase === \"classify\" ? \"classifyAll\" : phase === \"extract\" ? \"extractApis\" : \"fetchAll\",\n message: `Starting doc compile (${phase})`,\n updatedAt: new Date().toISOString(),\n },\n });\n\n const agentRun = await tryAgentStream(prompt, dir, runnerCommand, async (progress) => {\n await postCallback({ ok: true, final: false, progress });\n });\n\n const compileResult = parseCompileResultFromFile(outputPath.resultJsonPath);\n if (!compileResult) {\n await postCallback({\n ok: false,\n error: agentRun.exitCode !== 0 ? `agent exited ${agentRun.exitCode}` : \"compileResult missing in result.json\",\n });\n agentExit(1);\n }\n\n const shapeError = validateCompileResultShape(compileResult, phase);\n if (shapeError) {\n await postCallback({ ok: false, error: shapeError });\n agentExit(1);\n }\n\n await postCallback({\n ok: true,\n final: true,\n compileResult,\n summary: `doc compile ${contractCode} (${phase})`,\n contractCode,\n compileJobCode: jobCode,\n integrationDocCompilePhase: phase,\n });\n}\n\nasync function executeIntegrationSimPipeline(opts: {\n spec: AgentJobConfigV1;\n dir: string;\n runnerCommand: string;\n outputPath: { dir: string; resultJsonPath: string };\n indexSample: string;\n mode: \"scaffold\" | \"regen\" | \"skeleton\" | \"api_batch\";\n}): Promise<void> {\n const { spec, dir, runnerCommand, outputPath, indexSample, mode } = opts;\n const subpath = spec.integrationSimRepoSubpath?.trim();\n if (!subpath) {\n await postCallback({ ok: false, error: \"integrationSimRepoSubpath missing in job.json\" });\n agentExit(1);\n }\n const contractId = spec.integrationContractCode?.trim() || \"contract\";\n const gitRef = spec.gitRef?.trim() || \"main\";\n\n configureGitIdentityForWorkspace(dir, spec);\n\n if (mode === \"scaffold\" || mode === \"skeleton\") {\n const seedErr = seedIntegrationSimFromTemplate(dir, subpath, {\n contractId,\n realBaseUrl: realBaseUrlFromIntegrationSimSpec(spec),\n });\n if (seedErr) {\n await postCallback({ ok: false, error: seedErr });\n agentExit(1);\n }\n }\n\n const stageMessage =\n mode === \"regen\"\n ? \"Regenerating integration sim\"\n : mode === \"skeleton\"\n ? \"Generating integration sim skeleton\"\n : mode === \"api_batch\"\n ? \"Implementing api batch\"\n : \"Scaffolding integration sim\";\n\n const prompt =\n buildIntegrationSimAgentPrompt({\n spec,\n mode,\n indexSample,\n resultJsonPath: outputPath.resultJsonPath,\n }) + integrationDocsPromptSuffix(spec);\n\n await postCallback({\n ok: true,\n final: false,\n progress: {\n stage: \"integration_sim\",\n message: stageMessage,\n updatedAt: new Date().toISOString(),\n },\n });\n\n const agentRun = await tryAgentStream(prompt, dir, runnerCommand, async (progress) => {\n await postCallback({ ok: true, final: false, progress });\n });\n\n const simDir = join(dir, subpath);\n\n if (mode === \"api_batch\" || mode === \"regen\") {\n const { refreshIntegrationSimCapabilitiesFile, validateIntegrationSimCapabilitiesGate } =\n await import(\"./integration-capabilities.ts\");\n const refreshErr = refreshIntegrationSimCapabilitiesFile(simDir, contractId);\n if (refreshErr) {\n await postCallback({ ok: false, error: refreshErr });\n agentExit(1);\n }\n }\n\n const testProc = spawnSync(\"bun\", [\"test\"], { cwd: simDir, encoding: \"utf-8\" });\n if (testProc.status !== 0) {\n const errOut = `${testProc.stderr ?? \"\"}\\n${testProc.stdout ?? \"\"}`.trim().slice(0, 2000);\n await postCallback({\n ok: false,\n error: `bun test failed in ${subpath}: ${errOut || `exit ${testProc.status}`}`,\n });\n agentExit(1);\n }\n\n if (mode === \"api_batch\" || mode === \"regen\") {\n const { validateIntegrationSimCapabilitiesGate } = await import(\"./integration-capabilities.ts\");\n const gateErr = validateIntegrationSimCapabilitiesGate(simDir);\n if (gateErr) {\n await postCallback({ ok: false, error: gateErr });\n agentExit(1);\n }\n }\n\n if (agentRun.exitCode !== 0) {\n await postCallback({\n ok: false,\n error: `agent exited ${agentRun.exitCode}`,\n });\n agentExit(1);\n }\n\n const msg = `nvwa(integration-sim): ${mode} ${contractId}\\n\\n${triggeredByTrailerFromSpec(spec)}`;\n const pushed = commitAndPushFeatureWorkspace(dir, gitRef, msg, { onlySubpath: subpath });\n if (!pushed.ok) {\n await postCallback({ ok: false, error: pushed.error });\n agentExit(1);\n }\n\n await postCallback({\n ok: true,\n final: true,\n summary: `integration sim ${mode} ${contractId}`,\n contractCode: contractId,\n commitSha: pushed.commitSha,\n branch: gitRef,\n });\n}\n\nasync function executeRunRepoRewriteBody(\n spec: AgentJobConfigV1,\n options?: RunRepoRewriteOptions,\n): Promise<void> {\n throwIfAgentRunCancelled();\n logAgentSkillContext(spec);\n\n const mode = options?.mode ?? \"cursor\";\n const runnerCommand = options?.agentCommand ?? MODE_BINARY[mode];\n\n const repoUrl = spec.gitRepoUrl;\n const ref = spec.gitRef || \"main\";\n const token = process.env.GIT_TOKEN || \"\";\n const title = spec.requirementTitle;\n const raw = spec.requirementRawInput;\n let chatContext = spec.requirementChatContext;\n const jobId = spec.jobId;\n const dir = options?.workspaceDir?.trim() || AGENT_WORKSPACE_DIR;\n const pipeline = spec.pipeline;\n const outputPath = outputPathForJob(jobId, pipeline);\n\n mkdirSync(outputPath.dir, { recursive: true });\n\n if (pipeline === AGENT_JOB_PIPELINE_INTEGRATION_DOC_COMPILE) {\n await executeIntegrationDocCompilePipeline({\n spec,\n dir,\n runnerCommand,\n outputPath,\n });\n return;\n }\n\n if (!repoUrl.trim()) {\n await postCallback({ ok: false, error: \"GIT_REPO_URL missing\" });\n agentExit(1);\n }\n\n await postCallback({\n ok: true,\n final: false,\n progress: {\n stage: \"clone\",\n message: gitRepoInitialized(dir) ? \"Syncing repository\" : \"Cloning repository\",\n updatedAt: new Date().toISOString(),\n },\n });\n\n const cloneErr = ensureWorkspaceReady(repoUrl, ref, dir, token);\n if (cloneErr) {\n await postCallback({ ok: false, error: `git: ${cloneErr.slice(0, 2000)}` });\n agentExit(1);\n }\n\n const depsWarm = warmWorkspaceDependencies(dir);\n if (!depsWarm.ok) {\n await postCallback({ ok: false, error: depsWarm.error.slice(0, 2000) });\n agentExit(1);\n }\n\n chatContext = await enrichChatContextWithIntakeImages(spec, chatContext);\n\n throwIfAgentRunCancelled();\n\n const indexSample = fileTreeSnippet(dir, 120);\n\n if (\n pipeline === AGENT_JOB_PIPELINE_INTEGRATION_SIM_SCAFFOLD ||\n pipeline === AGENT_JOB_PIPELINE_INTEGRATION_SIM_REGEN ||\n pipeline === AGENT_JOB_PIPELINE_INTEGRATION_SIM_SKELETON ||\n pipeline === AGENT_JOB_PIPELINE_INTEGRATION_SIM_API_BATCH\n ) {\n const mode =\n pipeline === AGENT_JOB_PIPELINE_INTEGRATION_SIM_REGEN\n ? \"regen\"\n : pipeline === AGENT_JOB_PIPELINE_INTEGRATION_SIM_SKELETON\n ? \"skeleton\"\n : pipeline === AGENT_JOB_PIPELINE_INTEGRATION_SIM_API_BATCH\n ? \"api_batch\"\n : \"scaffold\";\n await executeIntegrationSimPipeline({\n spec,\n dir,\n runnerCommand,\n outputPath,\n indexSample,\n mode,\n });\n return;\n }\n\n if (\n pipeline !== AGENT_JOB_PIPELINE_CODE_TASK_FEATURE &&\n pipeline !== AGENT_JOB_PIPELINE_SPEC_BOOTSTRAP_L1_L2 &&\n pipeline !== AGENT_JOB_PIPELINE_DEV_UI_CONTRACT &&\n pipeline !== AGENT_JOB_PIPELINE_VALIDATION_PLAN &&\n pipeline !== AGENT_JOB_PIPELINE_VALIDATION_CODEGEN &&\n pipeline !== AGENT_JOB_PIPELINE_DEV_PIPELINE_TRIAGE &&\n spec.rewritePhases?.length === 3\n ) {\n await executeRewriteL1L3Pipeline({\n spec,\n dir,\n runnerCommand,\n outputPath,\n indexSample,\n title,\n raw,\n chatContext,\n });\n return;\n }\n\n if (pipeline === AGENT_JOB_PIPELINE_DEV_PIPELINE_TRIAGE) {\n await executeDevPipelineTriagePipeline({\n spec,\n dir,\n runnerCommand,\n outputPath,\n indexSample,\n });\n return;\n }\n\n if (pipeline === AGENT_JOB_PIPELINE_CODE_TASK_FEATURE) {\n await executeCodeTaskFeaturePipeline({\n spec,\n dir,\n runnerCommand,\n outputPath,\n indexSample,\n });\n return;\n }\n\n if (pipeline === AGENT_JOB_PIPELINE_DEV_UI_CONTRACT) {\n await executeDevUiContractPipeline({\n spec,\n dir,\n runnerCommand,\n outputPath,\n indexSample,\n title,\n raw,\n });\n return;\n }\n\n if (pipeline === AGENT_JOB_PIPELINE_VALIDATION_PLAN) {\n await executeValidationPlanPipeline({\n spec,\n dir,\n runnerCommand,\n outputPath,\n indexSample,\n title,\n raw,\n chatContext,\n });\n return;\n }\n\n if (pipeline === AGENT_JOB_PIPELINE_VALIDATION_CODEGEN) {\n await executeValidationCodegenPipeline({\n spec,\n dir,\n runnerCommand,\n outputPath,\n indexSample,\n title,\n raw,\n chatContext,\n });\n return;\n }\n\n if (pipeline === AGENT_JOB_PIPELINE_OPS_STRUCTURAL_PORT) {\n await executeOpsStructuralPortPipeline({\n spec,\n dir,\n runnerCommand,\n outputPath,\n title,\n raw,\n chatContext,\n });\n return;\n }\n\n const prompt =\n pipeline === AGENT_JOB_PIPELINE_SPEC_BOOTSTRAP_L1_L2\n ? buildSpecBootstrapPrompt(title, raw, chatContext, outputPath.resultJsonPath, indexSample)\n : buildUserPrompt(title, raw, chatContext, outputPath.resultJsonPath);\n\n console.error(\"[nvwa-agent] mode:\", mode, \"pipeline:\", pipeline, \"\\n\", prompt);\n\n await postCallback({\n ok: true,\n final: false,\n progress: {\n stage: \"analyze\",\n message:\n pipeline === AGENT_JOB_PIPELINE_SPEC_BOOTSTRAP_L1_L2\n ? \"Starting L1/L2 universe and feature spec draft\"\n : \"Starting repository analysis\",\n updatedAt: new Date().toISOString(),\n },\n });\n\n const agentRun = await tryAgentStream(prompt, dir, runnerCommand, async (progress) => {\n await postCallback({\n ok: true,\n final: false,\n progress,\n });\n });\n console.error(\n \"[nvwa-agent] stream finished:\",\n JSON.stringify({\n exitCode: agentRun.exitCode,\n stdoutLen: agentRun.stdout.length,\n stderrLen: agentRun.stderr.length,\n }),\n );\n if (agentRun.exitCode !== 0) {\n console.error(\"[nvwa-agent] agent stderr tail:\", agentRun.stderr.slice(-2000));\n }\n\n const fileRaw = existsSync(outputPath.resultJsonPath)\n ? readFileSync(outputPath.resultJsonPath, \"utf-8\")\n : null;\n\n if (pipeline === AGENT_JOB_PIPELINE_SPEC_BOOTSTRAP_L1_L2) {\n let parsedSpec = fileRaw ? parseSpecBootstrapPayload(fileRaw) : null;\n if (!parsedSpec) {\n console.warn(\"[nvwa-agent] spec-bootstrap result missing/invalid, trying Cursor agent stdout (stream-json)\");\n parsedSpec = parsePayloadFromCursorStdout(agentRun.stdout, parseSpecBootstrapPayload);\n if (parsedSpec) {\n writeFileSync(outputPath.resultJsonPath, JSON.stringify(parsedSpec, null, 2), \"utf-8\");\n }\n }\n\n if (!parsedSpec) {\n const debugMeta = {\n pipeline,\n fileExists: existsSync(outputPath.resultJsonPath),\n streamExitCode: agentRun.exitCode,\n streamStderrTail: agentRun.stderr.slice(-2000),\n filePreview: fileRaw ? fileRaw.slice(0, 1200) : null,\n streamStdoutTail: agentRun.stdout.slice(-1200),\n };\n writeFileSync(\n `${outputPath.dir}/debug-meta.json`,\n JSON.stringify(debugMeta, null, 2),\n \"utf-8\",\n );\n writeFileSync(`${outputPath.dir}/stream-stdout-tail.txt`, agentRun.stdout.slice(-2_000_000), \"utf-8\");\n await postCallback({\n ok: false,\n error: `spec bootstrap output missing or invalid JSON; expected ${outputPath.resultJsonPath}`,\n });\n agentExit(1);\n }\n\n writeFileSync(outputPath.resultJsonPath, JSON.stringify(parsedSpec, null, 2), \"utf-8\");\n await postCallback({\n ok: true,\n final: true,\n outputFile: outputPath.resultJsonPath,\n l1: parsedSpec.l1,\n l2: parsedSpec.l2,\n clarifications: parsedSpec.clarifications,\n });\n return;\n }\n\n let parsed = fileRaw ? parseRewritePayload(fileRaw) : null;\n if (!parsed) {\n console.warn(\"[nvwa-agent] result file missing/invalid, trying Cursor agent stdout (stream-json)\");\n parsed = parsePayloadFromCursorStdout(agentRun.stdout, parseRewritePayload);\n if (parsed) {\n writeFileSync(outputPath.resultJsonPath, JSON.stringify(parsed, null, 2), \"utf-8\");\n }\n }\n\n if (!parsed) {\n const debugMeta = {\n fileExists: existsSync(outputPath.resultJsonPath),\n streamExitCode: agentRun.exitCode,\n streamStderrTail: agentRun.stderr.slice(-2000),\n filePreview: fileRaw ? fileRaw.slice(0, 1200) : null,\n streamStdoutTail: agentRun.stdout.slice(-1200),\n };\n writeFileSync(\n `${outputPath.dir}/debug-meta.json`,\n JSON.stringify(debugMeta, null, 2),\n \"utf-8\",\n );\n writeFileSync(`${outputPath.dir}/stream-stdout-tail.txt`, agentRun.stdout.slice(-2_000_000), \"utf-8\");\n await postCallback({\n ok: false,\n error: `rewrite output missing or invalid JSON schema; expected ${outputPath.resultJsonPath}`,\n });\n agentExit(1);\n }\n\n writeFileSync(outputPath.resultJsonPath, JSON.stringify(parsed, null, 2), \"utf-8\");\n await postCallback({\n ok: true,\n final: true,\n outputFile: outputPath.resultJsonPath,\n ...parsed,\n });\n}\n\n/** 仅在被 Bun 直接作为入口执行时跑主流程;被 `nvwa-os`/cli import 时不应触发(否则会与入口的 `main()` 叠跑多轮 Job) */\nif (import.meta.main) {\n runRepoRewrite().catch(async (e) => {\n console.error(e);\n const reported = await postCallbackBestEffort({ ok: false, error: String(e) });\n if (!reported) {\n try {\n const url = jobSpec?.callbackUrl || process.env.NVWA_CALLBACK_URL?.trim() || callbackUrlFromJobFile();\n const sec = process.env.NVWA_CALLBACK_SECRET;\n if (url && sec) {\n await fetch(url, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"x-nvwa-callback-secret\": sec,\n },\n body: JSON.stringify({ ok: false, error: String(e) }),\n });\n }\n } catch {\n /* ignore */\n }\n }\n agentExit(1);\n });\n}\n",
|
|
6
|
+
"/** Env-driven limits for two-phase integration doc compile. */\n\nconst DEFAULT_CLASSIFY_BATCH_SIZE = 128;\nconst DEFAULT_EXTRACT_BATCH_SIZE = 64;\nconst DEFAULT_LEGACY_FULL_MAX_DOCS = 64;\n\nfunction parsePositiveInt(raw: string | undefined, fallback: number): number {\n const n = Number.parseInt((raw ?? \"\").trim(), 10);\n if (!Number.isFinite(n) || n < 1) return fallback;\n return Math.min(n, 512);\n}\n\nexport function integrationDocClassifyBatchSize(): number {\n return parsePositiveInt(process.env.NVWA_INTEGRATION_DOC_CLASSIFY_BATCH_SIZE, DEFAULT_CLASSIFY_BATCH_SIZE);\n}\n\nexport function integrationDocExtractBatchSize(): number {\n return parsePositiveInt(process.env.NVWA_INTEGRATION_DOC_EXTRACT_BATCH_SIZE, DEFAULT_EXTRACT_BATCH_SIZE);\n}\n\nexport function integrationDocCompileLegacyFullEnabled(): boolean {\n return (process.env.NVWA_INTEGRATION_DOC_COMPILE_LEGACY_FULL ?? \"\").trim() === \"1\";\n}\n\nexport function integrationDocLegacyFullMaxDocs(): number {\n return DEFAULT_LEGACY_FULL_MAX_DOCS;\n}\n",
|
|
7
|
+
"/** Batch planning and merge helpers for two-phase integration doc compile. */\n\nimport type {\n ClassifyManifest,\n ClassifyManifestDocument,\n ClassifyNoiseEntry,\n ClassifyResultPayload,\n CompilePageKind,\n} from \"./integration-doc-classify-artifact\";\nimport { countClassifyStats } from \"./integration-doc-classify-artifact\";\nimport type { IntegrationDocCompileDocumentEntry } from \"./integration-doc-compile-catalog\";\nimport {\n integrationDocClassifyBatchSize,\n integrationDocExtractBatchSize,\n integrationDocLegacyFullMaxDocs,\n} from \"./integration-doc-compile-env\";\n\nexport type CompileBatchPlan<T> = {\n batches: T[][];\n totalRegistered: number;\n};\n\nexport type NormalizeCompileDocumentsResult = {\n documents: IntegrationDocCompileDocumentEntry[];\n omittedCount: number;\n maxDocs: number;\n};\n\nconst EXTRACTABLE_PAGE_KINDS = new Set<CompilePageKind | string>([\"api\", \"mixed\", \"guide\"]);\n\nexport function normalizeCompileDocumentBatch(\n docs: IntegrationDocCompileDocumentEntry[] | null | undefined,\n maxDocs: number,\n): NormalizeCompileDocumentsResult {\n const MAX_ID = 80;\n const MAX_TITLE = 200;\n const MAX_URL = 2048;\n const cap = Math.max(1, Math.min(maxDocs, 512));\n\n if (!docs?.length) {\n return { documents: [], omittedCount: 0, maxDocs: cap };\n }\n\n const out: IntegrationDocCompileDocumentEntry[] = [];\n for (const row of docs) {\n const documentId = row.documentId?.trim().slice(0, MAX_ID) ?? \"\";\n const url = row.url?.trim().slice(0, MAX_URL) ?? \"\";\n if (!documentId || !url) continue;\n const title = (row.title ?? \"\").trim().slice(0, MAX_TITLE);\n out.push({\n documentId,\n title: title || documentId,\n url,\n });\n if (out.length >= cap) break;\n }\n\n const validInput = docs.filter((d) => d.documentId?.trim() && d.url?.trim()).length;\n return {\n documents: out,\n omittedCount: Math.max(0, validInput - out.length),\n maxDocs: cap,\n };\n}\n\nexport function planClassifyBatches(\n docs: IntegrationDocCompileDocumentEntry[],\n batchSize = integrationDocClassifyBatchSize(),\n): CompileBatchPlan<IntegrationDocCompileDocumentEntry> {\n return planDocumentBatches(docs, batchSize);\n}\n\nexport function planExtractBatches(\n classifyManifest: ClassifyManifest,\n catalogById: Map<string, IntegrationDocCompileDocumentEntry>,\n batchSize = integrationDocExtractBatchSize(),\n): CompileBatchPlan<IntegrationDocCompileDocumentEntry> {\n const extractable: IntegrationDocCompileDocumentEntry[] = [];\n for (const doc of classifyManifest.documents) {\n if (!EXTRACTABLE_PAGE_KINDS.has(doc.pageKind)) continue;\n const row = catalogById.get(doc.documentId);\n if (!row) continue;\n extractable.push(row);\n }\n return planDocumentBatches(extractable, batchSize);\n}\n\nexport function planDocumentBatches<T>(docs: T[], batchSize: number): CompileBatchPlan<T> {\n const size = Math.max(1, batchSize);\n const batches: T[][] = [];\n for (let i = 0; i < docs.length; i += size) {\n batches.push(docs.slice(i, i + size));\n }\n if (batches.length === 0) batches.push([]);\n return { batches, totalRegistered: docs.length };\n}\n\nexport function mergeClassifyPartials(\n partials: ClassifyResultPayload[],\n input: { contractCode: string; compileJobCode: string; extractedAt: string },\n): ClassifyResultPayload {\n const byId = new Map<string, ClassifyManifestDocument>();\n const noiseById = new Map<string, ClassifyNoiseEntry>();\n const warnings: string[] = [];\n\n for (const partial of partials) {\n for (const doc of partial.manifest.documents) {\n byId.set(doc.documentId, doc);\n }\n for (const n of partial.noise) {\n noiseById.set(n.documentId, n);\n }\n for (const w of partial.manifest.warnings ?? []) {\n if (w) warnings.push(w);\n }\n }\n\n const documents = [...byId.values()];\n const noise = [...noiseById.values()];\n\n return {\n manifest: {\n contractCode: input.contractCode,\n extractedAt: input.extractedAt,\n compileJobCode: input.compileJobCode,\n stats: countClassifyStats(documents),\n documents,\n warnings: [...new Set(warnings)].slice(0, 80),\n },\n noise,\n };\n}\n\nexport type ExtractPartialCompileResult = {\n manifest: {\n contractCode: string;\n extractedAt: string;\n compileJobCode: string;\n stats: { documents: number; guides: number; apis: number; noise: number };\n documents: ClassifyManifestDocument[];\n guideIds: string[];\n apiIds: string[];\n warnings?: string[];\n profileWarnings?: string[];\n vendorProfile?: Record<string, unknown>;\n };\n guides: Array<{ guideId: string; documentId: string; [key: string]: unknown }>;\n apis: Array<{ apiId: string; method?: string; path?: string; documentId?: string; [key: string]: unknown }>;\n noise: ClassifyNoiseEntry[];\n};\n\nfunction apiMatchKey(api: { method?: string; path?: string }): string {\n const method = (api.method ?? \"GET\").toUpperCase();\n const path = (api.path ?? \"\").trim();\n return `${method} ${path}`;\n}\n\n/** Merge extract batch partials into a single compile result (apis deduped by method+path). */\nexport function mergeExtractPartials(\n classifyManifest: ClassifyManifest,\n partials: ExtractPartialCompileResult[],\n input: { contractCode: string; compileJobCode: string; extractedAt: string },\n): ExtractPartialCompileResult {\n const guidesById = new Map<string, ExtractPartialCompileResult[\"guides\"][number]>();\n const apisByKey = new Map<string, ExtractPartialCompileResult[\"apis\"][number]>();\n const noiseById = new Map<string, ClassifyNoiseEntry>();\n const docById = new Map<string, ClassifyManifestDocument>();\n const warnings: string[] = [];\n const profileWarnings: string[] = [];\n let vendorProfile: Record<string, unknown> | undefined;\n\n for (const doc of classifyManifest.documents) {\n docById.set(doc.documentId, doc);\n }\n\n for (const partial of partials) {\n for (const doc of partial.manifest.documents) {\n docById.set(doc.documentId, doc);\n }\n for (const guide of partial.guides) {\n guidesById.set(guide.guideId, guide);\n }\n for (const api of partial.apis) {\n apisByKey.set(apiMatchKey(api), api);\n }\n for (const n of partial.noise) {\n noiseById.set(n.documentId, n);\n }\n for (const w of partial.manifest.warnings ?? []) {\n if (w) warnings.push(w);\n }\n for (const w of partial.manifest.profileWarnings ?? []) {\n if (w) profileWarnings.push(w);\n }\n if (partial.manifest.vendorProfile) {\n vendorProfile = partial.manifest.vendorProfile;\n }\n }\n\n const guides = [...guidesById.values()];\n const apis = [...apisByKey.values()];\n const documents = [...docById.values()];\n const noise = [...noiseById.values()];\n\n return {\n manifest: {\n contractCode: input.contractCode,\n extractedAt: input.extractedAt,\n compileJobCode: input.compileJobCode,\n stats: {\n documents: documents.length,\n guides: guides.length,\n apis: apis.length,\n noise: noise.length,\n },\n documents,\n guideIds: guides.map((g) => g.guideId),\n apiIds: apis.map((a) => a.apiId),\n warnings: [...new Set([...warnings, `merged ${partials.length} extract batch(es)`])].slice(0, 80),\n profileWarnings: [...new Set(profileWarnings)].slice(0, 40),\n vendorProfile,\n },\n guides,\n apis,\n noise,\n };\n}\n\nexport function legacyFullCompileMaxDocs(): number {\n return integrationDocLegacyFullMaxDocs();\n}\n\nexport function defaultClassifyBatchSize(): number {\n return integrationDocClassifyBatchSize();\n}\n\nexport function defaultExtractBatchSize(): number {\n return integrationDocExtractBatchSize();\n}\n\nexport function isExtractablePageKind(pageKind: string): boolean {\n return EXTRACTABLE_PAGE_KINDS.has(pageKind);\n}\n",
|
|
8
|
+
"/** Structured vendor document rows for integration_doc_compile (not subject to rawInput 8k cap). */\n\nimport {\n defaultExtractBatchSize,\n legacyFullCompileMaxDocs,\n normalizeCompileDocumentBatch,\n} from \"./integration-doc-compile-batch\";\nimport {\n integrationDocClassifyBatchSize,\n integrationDocCompileLegacyFullEnabled,\n} from \"./integration-doc-compile-env\";\n\nexport type IntegrationDocCompileDocumentEntry = {\n documentId: string;\n title: string;\n url: string;\n};\n\nexport type IntegrationDocCompilePhase = \"classify\" | \"extract\" | \"full\";\n\nexport type NormalizeIntegrationDocCompileDocumentsOptions = {\n maxDocs?: number;\n phase?: IntegrationDocCompilePhase;\n};\n\nexport function resolveCompileBatchMaxDocs(\n phase: IntegrationDocCompilePhase = \"full\",\n override?: number,\n): number {\n if (override != null && override > 0) return override;\n if (phase === \"classify\") return integrationDocClassifyBatchSize();\n if (phase === \"extract\") {\n return defaultExtractBatchSize();\n }\n if (integrationDocCompileLegacyFullEnabled()) {\n return legacyFullCompileMaxDocs();\n }\n return defaultExtractBatchSize();\n}\n\nexport function normalizeIntegrationDocCompileDocuments(\n docs: IntegrationDocCompileDocumentEntry[] | null | undefined,\n opts?: NormalizeIntegrationDocCompileDocumentsOptions,\n): IntegrationDocCompileDocumentEntry[] | null {\n const phase = opts?.phase ?? \"full\";\n const maxDocs = opts?.maxDocs ?? resolveCompileBatchMaxDocs(phase);\n const { documents } = normalizeCompileDocumentBatch(docs, maxDocs);\n return documents.length > 0 ? documents : null;\n}\n\nexport function normalizeIntegrationDocCompileDocumentsWithMeta(\n docs: IntegrationDocCompileDocumentEntry[] | null | undefined,\n opts?: NormalizeIntegrationDocCompileDocumentsOptions,\n) {\n const phase = opts?.phase ?? \"full\";\n const maxDocs = opts?.maxDocs ?? resolveCompileBatchMaxDocs(phase);\n return normalizeCompileDocumentBatch(docs, maxDocs);\n}\n\nexport function formatIntegrationDocCompileCatalog(\n docs: IntegrationDocCompileDocumentEntry[],\n): string {\n return docs\n .map((d, i) => `${i + 1}. [${d.documentId}] ${d.title}: ${d.url}`)\n .join(\"\\n\");\n}\n\nexport function integrationDocCompileDocumentIdsFromCatalog(\n docs: IntegrationDocCompileDocumentEntry[] | null | undefined,\n): string[] | null {\n if (!docs?.length) return null;\n return docs.map((d) => d.documentId);\n}\n",
|
|
9
|
+
"/** Requirement intake image limits — L2 spec/capabilities/requirement-intake-images.md */\n\nexport const INTAKE_IMAGE_MAX_FILES_PER_SEND = 5;\nexport const INTAKE_IMAGE_MAX_BYTES = 8 * 1024 * 1024;\n\nexport const INTAKE_ALLOWED_MIME_TYPES = new Set([\n \"image/png\",\n \"image/jpeg\",\n \"image/webp\",\n \"image/gif\",\n]);\n\nexport type IntakeImageAnalysisSection = {\n label: string;\n analysisText: string;\n};\n\nexport function isAllowedIntakeImageMime(mime: string): boolean {\n return INTAKE_ALLOWED_MIME_TYPES.has(mime.trim().toLowerCase());\n}\n\nexport function parseAttachmentIds(raw: unknown): string[] {\n if (!Array.isArray(raw)) return [];\n const out: string[] = [];\n for (const x of raw) {\n if (typeof x !== \"string\") continue;\n const id = x.trim();\n if (id && !out.includes(id)) out.push(id);\n }\n return out.slice(0, INTAKE_IMAGE_MAX_FILES_PER_SEND);\n}\n\n/**\n * Merge user text with vision analysis blocks for `rawInput`.\n * L2 format: `## 图片理解(<label>)\\n<text>`\n */\nexport function composeRawInputWithImageAnalysis(\n userText: string,\n sections: IntakeImageAnalysisSection[],\n): string {\n const parts: string[] = [];\n const trimmedUser = userText.trim();\n if (trimmedUser) parts.push(trimmedUser);\n for (const s of sections) {\n const body = s.analysisText.trim();\n if (!body) continue;\n const label = s.label.trim() || \"图片\";\n parts.push(`## 图片理解(${label})\\n${body}`);\n }\n return parts.join(\"\\n\\n\").trim();\n}\n\nconst GENERIC_INTAKE_FILE_NAMES = new Set([\n \"image\",\n \"image.png\",\n \"image.jpeg\",\n \"image.jpg\",\n \"image.webp\",\n \"image.gif\",\n \"screenshot\",\n \"screenshot.png\",\n \"pasted-image\",\n \"pasted-image.png\",\n \"clipboard\",\n \"clipboard.png\",\n]);\n\n/** Requirement-global sequence label, e.g. 图1. */\nexport function formatIntakeSequenceLabel(intakeIndex: number): string {\n const n = Math.max(1, Math.floor(intakeIndex));\n return `图${n}`;\n}\n\nexport function isGenericIntakeFileName(name: string): boolean {\n const base = (name.split(/[/\\\\]/).pop() ?? name).trim().toLowerCase();\n if (!base) return true;\n return GENERIC_INTAKE_FILE_NAMES.has(base);\n}\n\n/** Display label for rawInput headings and UI: 图N, optionally with distinctive fileName. */\nexport function formatIntakeDisplayLabel(intakeIndex: number, fileName?: string): string {\n const seq = formatIntakeSequenceLabel(intakeIndex);\n const trimmed = fileName?.trim() ?? \"\";\n if (trimmed && !isGenericIntakeFileName(trimmed)) {\n return `${seq} · ${sanitizeIntakeFileName(trimmed)}`;\n }\n return seq;\n}\n\n/** Resolve 1-based intakeIndex from artifact or array position fallback. */\nexport function resolveIntakeIndex(artifact: unknown, fallbackIndex: number): number {\n if (artifact && typeof artifact === \"object\" && !Array.isArray(artifact)) {\n const raw = (artifact as Record<string, unknown>).intakeIndex;\n if (typeof raw === \"number\" && Number.isFinite(raw) && raw >= 1) {\n return Math.floor(raw);\n }\n }\n return Math.max(1, Math.floor(fallbackIndex) + 1);\n}\n\nexport function intakeFileExtensionFromMime(mimeType: string): string {\n switch (mimeType.trim().toLowerCase()) {\n case \"image/jpeg\":\n return \".jpg\";\n case \"image/webp\":\n return \".webp\";\n case \"image/gif\":\n return \".gif\";\n case \"image/png\":\n default:\n return \".png\";\n }\n}\n\n/** Local workspace filename for Agent prefetch — avoids generic fileName collisions. */\nexport function intakeMaterializedLocalFileName(\n intakeIndex: number,\n attachmentId: string,\n mimeType: string,\n): string {\n const idPart = attachmentId.trim().slice(0, 8) || \"att\";\n const ext = intakeFileExtensionFromMime(mimeType);\n return `intake-${Math.max(1, Math.floor(intakeIndex))}-${idPart}${ext}`;\n}\n\nexport function titleFromIntakeInput(userText: string, sections: IntakeImageAnalysisSection[]): string {\n const fromUser = userText\n .split(/\\r?\\n/)\n .map((l) => l.trim())\n .find(Boolean);\n if (fromUser) return fromUser.slice(0, 120);\n const first = sections.find((s) => s.analysisText.trim());\n if (first) {\n const line = first.analysisText.trim().split(/\\r?\\n/).find(Boolean) ?? \"\";\n if (line) return `图片需求 · ${line.slice(0, 80)}`;\n }\n return \"图片需求\";\n}\n\n/** Public attachment ref for Agent job.json — no storageKey. */\nexport type RequirementIntakeAttachmentJobRef = {\n id: string;\n fileName: string;\n mimeType: string;\n intakeIndex: number;\n};\n\nexport function sanitizeIntakeFileName(name: string): string {\n const base = name.split(/[/\\\\]/).pop() ?? \"image\";\n const safe = base.replace(/[^\\w.\\-()+ ]/g, \"_\").slice(0, 120);\n return safe || \"image.png\";\n}\n\n/** Extract intake attachments for job.json from requirement artifacts. */\nexport function pickIntakeAttachmentsForAgentJob(\n artifacts: unknown,\n): RequirementIntakeAttachmentJobRef[] {\n if (!artifacts || typeof artifacts !== \"object\" || Array.isArray(artifacts)) return [];\n const list = (artifacts as Record<string, unknown>).intakeAttachments;\n if (!Array.isArray(list)) return [];\n const out: RequirementIntakeAttachmentJobRef[] = [];\n for (let i = 0; i < list.length; i++) {\n const item = list[i];\n if (!item || typeof item !== \"object\") continue;\n const o = item as Record<string, unknown>;\n const id = typeof o.id === \"string\" ? o.id.trim() : \"\";\n if (!id) continue;\n const mimeType =\n typeof o.mimeType === \"string\" && o.mimeType.trim()\n ? o.mimeType.trim().toLowerCase()\n : \"\";\n if (!mimeType || !isAllowedIntakeImageMime(mimeType)) continue;\n const fileName =\n typeof o.fileName === \"string\" && o.fileName.trim()\n ? sanitizeIntakeFileName(o.fileName.trim())\n : `${id}.png`;\n const intakeIndex = resolveIntakeIndex(item, i);\n out.push({ id, fileName, mimeType, intakeIndex });\n if (out.length >= INTAKE_IMAGE_MAX_FILES_PER_SEND) break;\n }\n return out;\n}\n\n/** `.../callback` → `.../requirement-intake-attachments` base (no trailing slash). */\nexport function intakeAttachmentBaseUrlFromCallbackUrl(callbackUrl: string): string | null {\n const t = callbackUrl.trim();\n const suffix = \"/callback\";\n if (!t.endsWith(suffix)) return null;\n return `${t.slice(0, -suffix.length)}/requirement-intake-attachments`;\n}\n\nexport function intakeAttachmentContentUrlFromCallback(\n callbackUrl: string,\n attachmentId: string,\n): string | null {\n const base = intakeAttachmentBaseUrlFromCallbackUrl(callbackUrl);\n const id = attachmentId.trim();\n if (!base || !id) return null;\n return `${base}/${encodeURIComponent(id)}/content`;\n}\n",
|
|
10
|
+
"/** Agent Batch Job 非敏感配置:写入 ConfigMap `data[job.json]` 并挂载为 {@link AGENT_JOB_CONFIG_MOUNT_PATH} */\n\nimport type {\n IntegrationDocCompileDocumentEntry,\n IntegrationDocCompilePhase,\n} from \"./integration-doc-compile-catalog\";\nimport { normalizeIntegrationDocCompileDocuments } from \"./integration-doc-compile-catalog\";\nimport type { AgentJobIntegrationDocsHints } from \"./integration-docs-types\";\nimport type { AgentJobOpsHints } from \"./job-ops-types\";\nimport {\n INTAKE_IMAGE_MAX_FILES_PER_SEND,\n isAllowedIntakeImageMime,\n type RequirementIntakeAttachmentJobRef,\n sanitizeIntakeFileName,\n} from \"./requirement-intake\";\n\nexport type { AgentJobIntegrationDocsHints } from \"./integration-docs-types\";\nexport type { AgentJobOpsHints } from \"./job-ops-types\";\nexport type { IntegrationDocCompileDocumentEntry } from \"./integration-doc-compile-catalog\";\nexport type { RequirementIntakeAttachmentJobRef } from \"./requirement-intake\";\n\nexport const AGENT_JOB_CONFIG_VERSION = 1 as const;\n\n/** 与 Job Pod 内挂载路径一致(单文件 subPath) */\nexport const AGENT_JOB_CONFIG_MOUNT_PATH = \"/etc/nvwa/job.json\";\n\n/** ConfigMap `data` 的 key */\nexport const AGENT_JOB_CONFIG_DATA_KEY = \"job.json\";\n\n/** 与 `k8sJobName` 强绑定,便于 kubectl 对照 */\nexport function agentJobConfigMapName(k8sJobName: string): string {\n return `${k8sJobName}-jobconfig`;\n}\n\n/** Pod 内流水线;缺省解析为 requirement_rewrite(向后兼容旧 job.json) */\nexport const AGENT_JOB_PIPELINE_REQUIREMENT_REWRITE = \"requirement_rewrite\" as const;\nexport const AGENT_JOB_PIPELINE_SPEC_BOOTSTRAP_L1_L2 = \"spec_bootstrap_l1_l2\" as const;\nexport const AGENT_JOB_PIPELINE_CODE_TASK_FEATURE = \"code_task_feature\" as const;\n/** 验证运行:对卡片 feature 子环境跑 Playwright BDD(独立镜像,不复用 Cursor agent 镜像) */\nexport const AGENT_JOB_PIPELINE_VALIDATION_RUN = \"validation_run\" as const;\n\n/** Environment-level validation scopes: no requirement card title/body in job.json or Playwright anchor env. */\nexport const VALIDATION_BEHAVIOR_SCOPE_DEV_DEPLOY = \"dev_deploy\" as const;\nexport const VALIDATION_BEHAVIOR_SCOPE_PROD_DEPLOY = \"prod_deploy\" as const;\n/** D1 P1: L4 web UI contract JSON in target repo */\nexport const AGENT_JOB_PIPELINE_DEV_UI_CONTRACT = \"dev_ui_contract\" as const;\n/** D1 P1.5: validation plan (which behaviors to run at P5) */\nexport const AGENT_JOB_PIPELINE_VALIDATION_PLAN = \"validation_plan\" as const;\n/** D1 P2: validation codegen skeleton (e2e steps / feature paths) */\nexport const AGENT_JOB_PIPELINE_VALIDATION_CODEGEN = \"validation_codegen\" as const;\n/** P6: analyze FailureContext and route fix (read-only clone optional) */\nexport const AGENT_JOB_PIPELINE_DEV_PIPELINE_TRIAGE = \"dev_pipeline_triage\" as const;\n/** D1: frozen install + check + unit tests (project-provided image, non-Agent) */\nexport const AGENT_JOB_PIPELINE_COMPILE_GATE = \"compile_gate\" as const;\n/** D1: static security scanners only (deps/secrets/sast, same local-check image) */\nexport const AGENT_JOB_PIPELINE_STATIC_SECURITY = \"static_security\" as const;\n/** @deprecated Use compile_gate; kept for in-flight Job job.json */\nexport const AGENT_JOB_PIPELINE_LOCAL_VERIFY = \"local_verify\" as const;\n/** D1: Gherkin/bddgen gate after validation codegen (same image as local_verify) */\nexport const AGENT_JOB_PIPELINE_BEHAVIORS_GATE = \"behaviors_gate\" as const;\n/** Post-E2E DAST security verify (YAML verify.scanners only) */\nexport const AGENT_JOB_PIPELINE_SECURITY_VERIFY = \"security_verify\" as const;\n/** Integration sim: scaffold contract repo */\nexport const AGENT_JOB_PIPELINE_INTEGRATION_SIM_SCAFFOLD = \"integration_sim_scaffold\" as const;\nexport const AGENT_JOB_PIPELINE_INTEGRATION_SIM_REGEN = \"integration_sim_regen\" as const;\nexport const AGENT_JOB_PIPELINE_INTEGRATION_SIM_DEPLOY = \"integration_sim_deploy\" as const;\nexport const AGENT_JOB_PIPELINE_INTEGRATION_DOC_COMPILE = \"integration_doc_compile\" as const;\nexport const AGENT_JOB_PIPELINE_INTEGRATION_SIM_SKELETON = \"integration_sim_skeleton\" as const;\nexport const AGENT_JOB_PIPELINE_INTEGRATION_SIM_API_BATCH = \"integration_sim_api_batch\" as const;\n/** Ops structural port: clone ops repo, draft patch for main/dev */\nexport const AGENT_JOB_PIPELINE_OPS_STRUCTURAL_PORT = \"ops_structural_port\" as const;\n/** Integration doc fetch: discover / fetch_pages / page_preview (nvwa-os-integration-doc-fetcher image) */\nexport const AGENT_JOB_PIPELINE_INTEGRATION_DOC_FETCH = \"integration_doc_fetch\" as const;\n\nexport const REWRITE_PHASES_L1_L3 = [\"l1\", \"l2\", \"l3\"] as const;\nexport type RewritePhase = (typeof REWRITE_PHASES_L1_L3)[number];\n\nexport type AgentJobPipeline =\n | typeof AGENT_JOB_PIPELINE_REQUIREMENT_REWRITE\n | typeof AGENT_JOB_PIPELINE_SPEC_BOOTSTRAP_L1_L2\n | typeof AGENT_JOB_PIPELINE_CODE_TASK_FEATURE\n | typeof AGENT_JOB_PIPELINE_VALIDATION_RUN\n | typeof AGENT_JOB_PIPELINE_DEV_UI_CONTRACT\n | typeof AGENT_JOB_PIPELINE_VALIDATION_PLAN\n | typeof AGENT_JOB_PIPELINE_VALIDATION_CODEGEN\n | typeof AGENT_JOB_PIPELINE_DEV_PIPELINE_TRIAGE\n | typeof AGENT_JOB_PIPELINE_COMPILE_GATE\n | typeof AGENT_JOB_PIPELINE_STATIC_SECURITY\n | typeof AGENT_JOB_PIPELINE_LOCAL_VERIFY\n | typeof AGENT_JOB_PIPELINE_BEHAVIORS_GATE\n | typeof AGENT_JOB_PIPELINE_SECURITY_VERIFY\n | typeof AGENT_JOB_PIPELINE_INTEGRATION_SIM_SCAFFOLD\n | typeof AGENT_JOB_PIPELINE_INTEGRATION_SIM_REGEN\n | typeof AGENT_JOB_PIPELINE_INTEGRATION_SIM_DEPLOY\n | typeof AGENT_JOB_PIPELINE_INTEGRATION_DOC_COMPILE\n | typeof AGENT_JOB_PIPELINE_INTEGRATION_SIM_SKELETON\n | typeof AGENT_JOB_PIPELINE_INTEGRATION_SIM_API_BATCH\n | typeof AGENT_JOB_PIPELINE_OPS_STRUCTURAL_PORT\n | typeof AGENT_JOB_PIPELINE_INTEGRATION_DOC_FETCH;\n\nexport function validationRunOmitsRequirementCardAnchor(\n pipeline: AgentJobPipeline,\n behaviorScope: string | null | undefined,\n): boolean {\n if (pipeline !== AGENT_JOB_PIPELINE_VALIDATION_RUN) return false;\n const s = (behaviorScope ?? \"\").trim();\n return s === VALIDATION_BEHAVIOR_SCOPE_DEV_DEPLOY || s === VALIDATION_BEHAVIOR_SCOPE_PROD_DEPLOY;\n}\n\n/** Pipelines that do not anchor on a requirement card title/body in job.json. */\nexport function agentJobOmitsRequirementCardAnchor(\n pipeline: AgentJobPipeline,\n behaviorScope: string | null | undefined,\n): boolean {\n if (isIntegrationDocFetcherJobPipeline(pipeline)) return true;\n return validationRunOmitsRequirementCardAnchor(pipeline, behaviorScope);\n}\n\n/** Playwright E2E / smoke pipelines (`nvwa-os-validation` image). */\nexport function isValidationRunnerJobPipeline(pipeline: AgentJobPipeline): boolean {\n return pipeline === AGENT_JOB_PIPELINE_VALIDATION_RUN;\n}\n\n/** DAST-only pipeline (`nvwa-os-dast` image). */\nexport function isDastRunnerJobPipeline(pipeline: AgentJobPipeline): boolean {\n return pipeline === AGENT_JOB_PIPELINE_SECURITY_VERIFY;\n}\n\n/** Integration doc fetch pipeline (`nvwa-os-integration-doc-fetcher` image). */\nexport function isIntegrationDocFetcherJobPipeline(pipeline: AgentJobPipeline): boolean {\n return pipeline === AGENT_JOB_PIPELINE_INTEGRATION_DOC_FETCH;\n}\n\n/** Shared job.json fields for Playwright validation and DAST runner images. */\nexport function isRunnerJobWithTargetUrl(pipeline: AgentJobPipeline): boolean {\n return isValidationRunnerJobPipeline(pipeline) || isDastRunnerJobPipeline(pipeline);\n}\n\nexport function parseAgentJobPipeline(raw: unknown): AgentJobPipeline {\n if (raw === AGENT_JOB_PIPELINE_SPEC_BOOTSTRAP_L1_L2) return AGENT_JOB_PIPELINE_SPEC_BOOTSTRAP_L1_L2;\n if (raw === AGENT_JOB_PIPELINE_CODE_TASK_FEATURE) return AGENT_JOB_PIPELINE_CODE_TASK_FEATURE;\n if (raw === AGENT_JOB_PIPELINE_VALIDATION_RUN) return AGENT_JOB_PIPELINE_VALIDATION_RUN;\n if (raw === AGENT_JOB_PIPELINE_DEV_UI_CONTRACT) return AGENT_JOB_PIPELINE_DEV_UI_CONTRACT;\n if (raw === AGENT_JOB_PIPELINE_VALIDATION_PLAN) return AGENT_JOB_PIPELINE_VALIDATION_PLAN;\n if (raw === AGENT_JOB_PIPELINE_VALIDATION_CODEGEN) return AGENT_JOB_PIPELINE_VALIDATION_CODEGEN;\n if (raw === AGENT_JOB_PIPELINE_DEV_PIPELINE_TRIAGE) return AGENT_JOB_PIPELINE_DEV_PIPELINE_TRIAGE;\n if (raw === AGENT_JOB_PIPELINE_COMPILE_GATE) return AGENT_JOB_PIPELINE_COMPILE_GATE;\n if (raw === AGENT_JOB_PIPELINE_STATIC_SECURITY) return AGENT_JOB_PIPELINE_STATIC_SECURITY;\n if (raw === AGENT_JOB_PIPELINE_LOCAL_VERIFY) return AGENT_JOB_PIPELINE_COMPILE_GATE;\n if (raw === AGENT_JOB_PIPELINE_BEHAVIORS_GATE) return AGENT_JOB_PIPELINE_BEHAVIORS_GATE;\n if (raw === AGENT_JOB_PIPELINE_SECURITY_VERIFY) return AGENT_JOB_PIPELINE_SECURITY_VERIFY;\n if (raw === AGENT_JOB_PIPELINE_INTEGRATION_SIM_SCAFFOLD) return AGENT_JOB_PIPELINE_INTEGRATION_SIM_SCAFFOLD;\n if (raw === AGENT_JOB_PIPELINE_INTEGRATION_SIM_REGEN) return AGENT_JOB_PIPELINE_INTEGRATION_SIM_REGEN;\n if (raw === AGENT_JOB_PIPELINE_INTEGRATION_SIM_DEPLOY) return AGENT_JOB_PIPELINE_INTEGRATION_SIM_DEPLOY;\n if (raw === AGENT_JOB_PIPELINE_INTEGRATION_DOC_COMPILE) return AGENT_JOB_PIPELINE_INTEGRATION_DOC_COMPILE;\n if (raw === AGENT_JOB_PIPELINE_INTEGRATION_SIM_SKELETON) return AGENT_JOB_PIPELINE_INTEGRATION_SIM_SKELETON;\n if (raw === AGENT_JOB_PIPELINE_INTEGRATION_SIM_API_BATCH) return AGENT_JOB_PIPELINE_INTEGRATION_SIM_API_BATCH;\n if (raw === AGENT_JOB_PIPELINE_OPS_STRUCTURAL_PORT) return AGENT_JOB_PIPELINE_OPS_STRUCTURAL_PORT;\n if (raw === AGENT_JOB_PIPELINE_INTEGRATION_DOC_FETCH) return AGENT_JOB_PIPELINE_INTEGRATION_DOC_FETCH;\n return AGENT_JOB_PIPELINE_REQUIREMENT_REWRITE;\n}\n\n/** 仅 `code_task_feature` 流水线:create 为首次建分支;merge_dev 为验收合并前 sync;pipeline_sync_dev 为进入开发流水线前 sync */\nexport type AgentCodeTaskPhase = \"create\" | \"merge_dev\" | \"pipeline_sync_dev\";\n\nexport function parseAgentCodeTaskPhase(raw: unknown): AgentCodeTaskPhase {\n if (raw === \"merge_dev\") return \"merge_dev\";\n if (raw === \"pipeline_sync_dev\") return \"pipeline_sync_dev\";\n return \"create\";\n}\n\nexport type AgentWorkspaceBase = \"feature\" | \"integration\" | \"default\";\n\nexport function parseAgentWorkspaceBase(raw: unknown): AgentWorkspaceBase | null {\n if (raw === \"feature\" || raw === \"integration\" || raw === \"default\") return raw;\n return null;\n}\n\n/** Cursor CLI home on PVC (`main`) or ephemeral copy (`fork`; does not write back). */\nexport const AGENT_CURSOR_SESSION_MODE_MAIN = \"main\" as const;\nexport const AGENT_CURSOR_SESSION_MODE_FORK = \"fork\" as const;\n\nexport type AgentCursorSessionMode =\n | typeof AGENT_CURSOR_SESSION_MODE_MAIN\n | typeof AGENT_CURSOR_SESSION_MODE_FORK;\n\nexport function parseAgentCursorSessionMode(raw: unknown): AgentCursorSessionMode {\n if (raw === AGENT_CURSOR_SESSION_MODE_FORK) return AGENT_CURSOR_SESSION_MODE_FORK;\n return AGENT_CURSOR_SESSION_MODE_MAIN;\n}\n\nexport type AgentJobDastTierScanMode = \"smoke\" | \"zap\";\n\nexport type AgentJobDastTierScansConfig = {\n session: { enabled: boolean };\n callback: { enabled: boolean; mode: AgentJobDastTierScanMode };\n integrationDocs: { enabled: boolean; mode: AgentJobDastTierScanMode };\n embed: { enabled: boolean; mode: AgentJobDastTierScanMode };\n};\n\nexport type AgentJobDastOpenApiSource = \"bundled\" | \"url\";\n\nexport type AgentJobDastApiServiceEntry = {\n name: string;\n openapiSpecPath: string;\n coverageManifestPath?: string | null;\n};\n\nexport type AgentJobDastConfig = {\n authEnabled: boolean;\n crawlMode: \"none\" | \"traditional\" | \"ajax\" | \"both\";\n seedUrls: string[];\n failOn: (\"critical\" | \"high\" | \"medium\" | \"low\")[];\n projectCode: string | null;\n requirementCode: string | null;\n apiScanEnabled: boolean;\n apiScanIncludePaths: string[];\n openapiSource: AgentJobDastOpenApiSource;\n openapiSpecPath: string | null;\n openapiUrl: string | null;\n openapiImportRequired: boolean;\n /** L1-ordered API services for sequential OpenAPI import + ascan. */\n apiServices: AgentJobDastApiServiceEntry[];\n maxAscanUrls: number;\n maxAscanOperations: number;\n methodAwareAscan: boolean;\n ascanBudgetRatio: number;\n crawlBudgetRatio: number;\n readOnlyMethodsOnly: boolean;\n dastProfile: \"default\" | \"deep-api\";\n preflightDiscovery: boolean;\n probeFallback: boolean;\n preflightBootstrap: boolean;\n tierScans: AgentJobDastTierScansConfig;\n ignorePaths: string[];\n failOnLoginError: boolean;\n crawlMaxDurationSeconds: number;\n crawlMaxDepth: number;\n timeoutSeconds: number;\n};\n\nexport type AgentJobIntegrationDocFetchConfig = {\n mode: \"discover\" | \"fetch_pages\" | \"page_preview\" | \"import_openapi\";\n projectCode: string;\n projectId: string;\n discover?: { entryUrl: string; sameOriginOnly?: boolean };\n fetchPages?: {\n contractCode: string;\n documents: Array<{ documentId: string; url: string }>;\n };\n pagePreview?: { sessionId: string; url: string };\n /** Pre-generated session id for discover mode */\n sessionId?: string | null;\n importOpenapi?: {\n contractCode: string;\n documentId: string;\n specUrl: string;\n };\n};\n\nexport type AgentJobIntegrationDocFetchArtifacts = {\n bucketPrefix: string;\n documents: Array<{\n documentId: string;\n pageMdKey: string;\n pageHtmlKey: string;\n fetchedAt: string | null;\n }>;\n};\n\nexport type AgentJobConfigV1 = {\n version: typeof AGENT_JOB_CONFIG_VERSION;\n jobId: string;\n /** Public job code for UI / rewritePipeline artifact (falls back to jobId when absent) */\n jobCode: string | null;\n requirementId: string;\n /** Only validation_run: anchor requirement public `code`. */\n requirementCode: string | null;\n callbackUrl: string;\n gitRepoUrl: string;\n gitRef: string;\n requirementTitle: string;\n requirementRawInput: string;\n requirementChatContext: string;\n llmBaseUrl: string | null;\n llmModel: string | null;\n pipeline: AgentJobPipeline;\n /** 代码任务流水线:服务端预定的全部分支名(须以 feature/ 开头) */\n targetBranch: string | null;\n /** 仅 `code_task_feature`;旧 job.json 缺省视为 create */\n codeTaskPhase: AgentCodeTaskPhase;\n /** 仅 `merge_dev`:rebase 目标远端分支短名(如 dev) */\n mergeSourceBranch: string | null;\n /** 触发任务的用户身份(用于 commit author;缺失时由执行端回退默认 bot) */\n triggeredByName: string | null;\n triggeredByEmail: string | null;\n triggeredByUsername: string | null;\n triggeredByUserId: string | null;\n projectGitCommitName: string | null;\n projectGitCommitEmail: string | null;\n /** 仅 `validation_run`:被测应用根 URL(来自 Argo CD 子 Application externalUrls[0]) */\n baseUrl: string | null;\n /** 仅 `validation_run`:scope 内各 UI app 的规则 baseURL(多 app 时 probe / 未来 per-scenario 切换) */\n baseUrlsByApp: Record<string, string> | null;\n /** 仅 `validation_run`:feature 子 Application 名(透传方便 Pod 日志与 UI 展示) */\n argoAppName: string | null;\n /** 仅 `validation_run`:Argo 报告的 sync revision(透传给 UI 展示「validated against …」) */\n deployedRevision: string | null;\n /**\n * 仅 `validation_run`:当 {@link gitRef} 为 commit SHA 时,用于浅克隆的远端分支名(如 dev、main)。\n * 多数 Git 托管方不支持 `git fetch origin <sha>`,需先 clone 分支再 checkout 该提交。\n */\n gitBranchHint: string | null;\n /** Only validation_run: `dev_deploy`, `full`, `plan`, or legacy `requirement:<code>` for BDD feature filtering */\n behaviorScope: string | null;\n /** Only validation_run: explicit feature paths from ValidationPlan (+ codegen union at enqueue time) */\n validationFeaturePaths: string[] | null;\n /** Only validation_run: cap tier filter (`smoke` | `integration` | `pipeline`) */\n validationMaxTier: string | null;\n /** Only validation_run guided: 0 = first segment, 1+ = resume after human checkpoint */\n validationSegment: number | null;\n /** Only validation_run guided segment ≥1: S3 object key for checkpoint JSON */\n checkpointObjectKey: string | null;\n /** Only validation_run: scenario includes human checkpoint steps */\n guidedRun: boolean | null;\n /** Only requirement_rewrite with Plan C L1–L3 pipeline */\n rewritePhases: RewritePhase[] | null;\n /** When true, Agent skips rewrite_gate and runs full L1–L3 */\n rewriteForceFull: boolean | null;\n /** Server hint: prior developmentGoal specRefs for gate baseline */\n rewriteGateSpecRefs: RewriteGateSpecRefs | null;\n /** Integration branch (gitDevRef) for forking or fetching alongside feature */\n integrationBranch: string | null;\n /** Server hint: which ref strategy the Pod should use */\n workspaceBase: AgentWorkspaceBase | null;\n /** P6 triage: structured failure payload from server */\n failureContext: Record<string, unknown> | null;\n /** When true, Cursor agent uses `--continue` for same-card session on project PVC */\n cursorResume: boolean;\n /** `main` = PVC cursor home; `fork` = copy-on-start to ephemeral dir, no write-back */\n cursorSessionMode: AgentCursorSessionMode;\n /** Server-filled deploy observation hints for nvwa-os ops (non-secret). */\n opsHints: AgentJobOpsHints | null;\n /** Integration sim pipelines: project contract public code */\n integrationContractCode: string | null;\n /** Integration sim: cwd under per-project sim repo (`{code}/`) */\n integrationSimRepoSubpath: string | null;\n /** Integration sim deploy/scaffold target Nvwa env */\n integrationSimTargetEnv: string | null;\n /** Vendor document URLs from control plane (for openapi scaffold) */\n integrationSimDocumentUrls: string[] | null;\n /** Integration vendor docs API (token via env; non-secret base URL) */\n integrationDocsHints: AgentJobIntegrationDocsHints | null;\n /** integration_doc_compile: document row ids to fetch */\n integrationDocCompileDocumentIds: string[] | null;\n /** integration_doc_compile: full id/title/url catalog (authoritative for fetchAll) */\n integrationDocCompileDocuments: IntegrationDocCompileDocumentEntry[] | null;\n /** integration_doc_compile: classify | extract | full (legacy single job) */\n integrationDocCompilePhase: IntegrationDocCompilePhase | null;\n /** integration_doc_compile: batch index within classify/extract orchestration */\n integrationDocCompileBatch: { index: number; total: number } | null;\n /** integration_doc_compile extract: MinIO key for merged classify manifest */\n integrationDocClassifyManifestKey: string | null;\n /** integration_sim_api_batch: apiId slugs from compile manifest */\n integrationSimApiIds: string[] | null;\n /** Server-resolved execution mode audit (sim/live per dimension) */\n executionMode: Record<string, unknown> | null;\n /** Only security_verify: non-secret DAST scan options */\n dast: AgentJobDastConfig | null;\n /** Requirement intake images for Agent optional Read (id, fileName, mimeType only) */\n requirementIntakeAttachments: RequirementIntakeAttachmentJobRef[] | null;\n /** ops_structural_port: GitOps repo clone URL */\n gitopsRepoUrl: string | null;\n gitopsMainRef: string | null;\n gitopsFeatureBranch: string | null;\n gitopsPathDev: string | null;\n gitopsPathFeature: string | null;\n /** ops_structural_port chat refinement message */\n opsStructuralChatMessage: string | null;\n /** integration_doc_fetch runner payload */\n integrationDocFetch: AgentJobIntegrationDocFetchConfig | null;\n /** integration_doc_compile: pre-fetched page artifacts in project MinIO */\n integrationDocFetchArtifacts: AgentJobIntegrationDocFetchArtifacts | null;\n};\n\nexport type RewriteGateSpecRefs = {\n l2CapabilityPath?: string;\n suggestedBehaviorPaths?: string[];\n};\n\nexport type BuildAgentJobConfigV1Input = {\n jobId: string;\n jobCode?: string | null;\n requirementId: string;\n /** Only validation_run: anchor card public code for runner / Playwright. */\n requirementCode?: string | null;\n callbackUrl: string;\n gitRepoUrl: string;\n gitRef: string;\n requirementTitle: string;\n requirementRawInput: string;\n requirementChatContext?: string | null;\n llmBaseUrl?: string | null;\n llmModel?: string | null;\n pipeline?: AgentJobPipeline | null;\n /** 仅 code_task_feature;省略或非该流水线时为 null */\n targetBranch?: string | null;\n /** 仅 code_task_feature;缺省 create */\n codeTaskPhase?: AgentCodeTaskPhase | null;\n /** 仅 code_task_feature 且 merge_dev;缺省 dev */\n mergeSourceBranch?: string | null;\n triggeredByName?: string | null;\n triggeredByEmail?: string | null;\n triggeredByUsername?: string | null;\n triggeredByUserId?: string | null;\n projectGitCommitName?: string | null;\n projectGitCommitEmail?: string | null;\n /** 仅 validation_run;其它流水线写入会被忽略 */\n baseUrl?: string | null;\n baseUrlsByApp?: Record<string, string> | null;\n argoAppName?: string | null;\n deployedRevision?: string | null;\n /** 仅 validation_run:gitRef 为 SHA 时的克隆分支提示 */\n gitBranchHint?: string | null;\n behaviorScope?: string | null;\n validationFeaturePaths?: string[] | null;\n validationMaxTier?: string | null;\n validationSegment?: number | null;\n checkpointObjectKey?: string | null;\n guidedRun?: boolean | null;\n /** When set to l1,l2,l3 the agent runs three sequential rewrite phases */\n rewritePhases?: RewritePhase[] | null;\n rewriteForceFull?: boolean | null;\n rewriteGateSpecRefs?: RewriteGateSpecRefs | null;\n integrationBranch?: string | null;\n workspaceBase?: AgentWorkspaceBase | null;\n failureContext?: Record<string, unknown> | null;\n cursorResume?: boolean | null;\n cursorSessionMode?: AgentCursorSessionMode | null;\n opsHints?: AgentJobOpsHints | null;\n integrationContractCode?: string | null;\n integrationSimRepoSubpath?: string | null;\n integrationSimTargetEnv?: string | null;\n integrationSimDocumentUrls?: string[] | null;\n integrationDocsHints?: AgentJobIntegrationDocsHints | null;\n integrationDocCompileDocumentIds?: string[] | null;\n integrationDocCompileDocuments?: IntegrationDocCompileDocumentEntry[] | null;\n integrationDocCompilePhase?: IntegrationDocCompilePhase | null;\n integrationDocCompileBatch?: { index: number; total: number } | null;\n integrationDocClassifyManifestKey?: string | null;\n integrationSimApiIds?: string[] | null;\n executionMode?: Record<string, unknown> | null;\n dast?: AgentJobDastConfig | null;\n requirementIntakeAttachments?: RequirementIntakeAttachmentJobRef[] | null;\n gitopsRepoUrl?: string | null;\n gitopsMainRef?: string | null;\n gitopsFeatureBranch?: string | null;\n gitopsPathDev?: string | null;\n gitopsPathFeature?: string | null;\n opsStructuralChatMessage?: string | null;\n integrationDocFetch?: AgentJobIntegrationDocFetchConfig | null;\n integrationDocFetchArtifacts?: AgentJobIntegrationDocFetchArtifacts | null;\n};\n\nfunction normalizeIntegrationDocCompilePhase(raw: unknown): IntegrationDocCompilePhase | null {\n if (raw === \"classify\" || raw === \"extract\" || raw === \"full\") return raw;\n return null;\n}\n\nfunction normalizeIntegrationDocCompileBatch(\n raw: unknown,\n): { index: number; total: number } | null {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return null;\n const o = raw as Record<string, unknown>;\n const index = typeof o.index === \"number\" ? Math.floor(o.index) : -1;\n const total = typeof o.total === \"number\" ? Math.floor(o.total) : 0;\n if (index < 0 || total < 1 || index >= total) return null;\n return { index, total };\n}\n\nfunction normalizeAgentJobIntegrationDocFetchConfig(\n raw: AgentJobIntegrationDocFetchConfig | null | undefined,\n): AgentJobIntegrationDocFetchConfig | null {\n if (!raw || typeof raw !== \"object\") return null;\n const mode = raw.mode;\n if (mode !== \"discover\" && mode !== \"fetch_pages\" && mode !== \"page_preview\" && mode !== \"import_openapi\") return null;\n const projectCode = raw.projectCode?.trim();\n const projectId = raw.projectId?.trim();\n if (!projectCode || !projectId) return null;\n const out: AgentJobIntegrationDocFetchConfig = {\n mode,\n projectCode: projectCode.slice(0, 80),\n projectId: projectId.slice(0, 80),\n sessionId: raw.sessionId?.trim()?.slice(0, 80) ?? null,\n };\n if (raw.discover?.entryUrl?.trim()) {\n out.discover = {\n entryUrl: raw.discover.entryUrl.trim().slice(0, 2048),\n sameOriginOnly: raw.discover.sameOriginOnly !== false,\n };\n }\n if (raw.fetchPages?.contractCode?.trim() && Array.isArray(raw.fetchPages.documents)) {\n const documents: Array<{ documentId: string; url: string }> = [];\n for (const d of raw.fetchPages.documents) {\n if (!d?.documentId?.trim() || !d?.url?.trim()) continue;\n documents.push({\n documentId: d.documentId.trim().slice(0, 80),\n url: d.url.trim().slice(0, 2048),\n });\n if (documents.length >= 128) break;\n }\n if (documents.length > 0) {\n out.fetchPages = {\n contractCode: raw.fetchPages.contractCode.trim().slice(0, 80),\n documents,\n };\n }\n }\n if (raw.pagePreview?.sessionId?.trim() && raw.pagePreview?.url?.trim()) {\n out.pagePreview = {\n sessionId: raw.pagePreview.sessionId.trim().slice(0, 80),\n url: raw.pagePreview.url.trim().slice(0, 2048),\n };\n }\n if (\n raw.importOpenapi?.contractCode?.trim() &&\n raw.importOpenapi?.documentId?.trim() &&\n raw.importOpenapi?.specUrl?.trim()\n ) {\n out.importOpenapi = {\n contractCode: raw.importOpenapi.contractCode.trim().slice(0, 80),\n documentId: raw.importOpenapi.documentId.trim().slice(0, 80),\n specUrl: raw.importOpenapi.specUrl.trim().slice(0, 2048),\n };\n }\n return out;\n}\n\nfunction normalizeAgentJobIntegrationDocFetchArtifacts(\n raw: AgentJobIntegrationDocFetchArtifacts | null | undefined,\n): AgentJobIntegrationDocFetchArtifacts | null {\n if (!raw || typeof raw !== \"object\") return null;\n const bucketPrefix = raw.bucketPrefix?.trim();\n if (!bucketPrefix || !Array.isArray(raw.documents)) return null;\n const documents: AgentJobIntegrationDocFetchArtifacts[\"documents\"] = [];\n for (const d of raw.documents) {\n if (!d?.documentId?.trim() || !d.pageMdKey?.trim() || !d.pageHtmlKey?.trim()) continue;\n documents.push({\n documentId: d.documentId.trim().slice(0, 80),\n pageMdKey: d.pageMdKey.trim().slice(0, 500),\n pageHtmlKey: d.pageHtmlKey.trim().slice(0, 500),\n fetchedAt: typeof d.fetchedAt === \"string\" ? d.fetchedAt.slice(0, 40) : null,\n });\n if (documents.length >= 128) break;\n }\n if (documents.length === 0) return null;\n return { bucketPrefix: bucketPrefix.slice(0, 300), documents };\n}\n\nfunction pipelineUsesPlannedFeatureBranch(pipeline: AgentJobPipeline): boolean {\n return (\n pipeline === AGENT_JOB_PIPELINE_CODE_TASK_FEATURE ||\n pipeline === AGENT_JOB_PIPELINE_REQUIREMENT_REWRITE ||\n pipeline === AGENT_JOB_PIPELINE_DEV_UI_CONTRACT ||\n pipeline === AGENT_JOB_PIPELINE_VALIDATION_PLAN ||\n pipeline === AGENT_JOB_PIPELINE_VALIDATION_CODEGEN ||\n pipeline === AGENT_JOB_PIPELINE_DEV_PIPELINE_TRIAGE\n );\n}\n\nfunction normalizeRequirementIntakeAttachmentsForJob(\n raw: RequirementIntakeAttachmentJobRef[] | null | undefined,\n): RequirementIntakeAttachmentJobRef[] | null {\n if (!raw?.length) return null;\n const out: RequirementIntakeAttachmentJobRef[] = [];\n for (const item of raw) {\n const id = item.id?.trim() ?? \"\";\n if (!id) continue;\n const mimeType = item.mimeType?.trim().toLowerCase() ?? \"\";\n if (!mimeType || !isAllowedIntakeImageMime(mimeType)) continue;\n const fileName = item.fileName?.trim()\n ? sanitizeIntakeFileName(item.fileName.trim())\n : `${id}.png`;\n const intakeIndex =\n typeof item.intakeIndex === \"number\" && Number.isFinite(item.intakeIndex) && item.intakeIndex >= 1\n ? Math.floor(item.intakeIndex)\n : out.length + 1;\n out.push({ id: id.slice(0, 80), fileName, mimeType, intakeIndex });\n if (out.length >= INTAKE_IMAGE_MAX_FILES_PER_SEND) break;\n }\n return out.length > 0 ? out : null;\n}\n\nfunction normalizeRewriteGateSpecRefs(\n raw: RewriteGateSpecRefs | null | undefined,\n): RewriteGateSpecRefs | null {\n if (!raw || typeof raw !== \"object\") return null;\n const l2 =\n typeof raw.l2CapabilityPath === \"string\" && raw.l2CapabilityPath.trim()\n ? raw.l2CapabilityPath.trim().slice(0, 512)\n : undefined;\n const paths: string[] = [];\n if (Array.isArray(raw.suggestedBehaviorPaths)) {\n for (const p of raw.suggestedBehaviorPaths) {\n if (typeof p !== \"string\") continue;\n const t = p.trim();\n if (t) paths.push(t.slice(0, 512));\n if (paths.length >= 16) break;\n }\n }\n if (!l2 && paths.length === 0) return null;\n return {\n ...(l2 ? { l2CapabilityPath: l2 } : {}),\n ...(paths.length ? { suggestedBehaviorPaths: paths } : {}),\n };\n}\n\nexport function buildAgentJobConfigV1(input: BuildAgentJobConfigV1Input): AgentJobConfigV1 {\n const pipeline = input.pipeline ?? AGENT_JOB_PIPELINE_REQUIREMENT_REWRITE;\n const isCodeTask = pipeline === AGENT_JOB_PIPELINE_CODE_TASK_FEATURE;\n const isValidation = isRunnerJobWithTargetUrl(pipeline);\n const isSecurityVerify = pipeline === AGENT_JOB_PIPELINE_SECURITY_VERIFY;\n const usesFeatureBranch = pipelineUsesPlannedFeatureBranch(pipeline);\n const phase: AgentCodeTaskPhase =\n isCodeTask && input.codeTaskPhase === \"merge_dev\"\n ? \"merge_dev\"\n : isCodeTask && input.codeTaskPhase === \"pipeline_sync_dev\"\n ? \"pipeline_sync_dev\"\n : \"create\";\n const mergeSource =\n isCodeTask && (phase === \"merge_dev\" || phase === \"pipeline_sync_dev\")\n ? (input.mergeSourceBranch?.trim() ? input.mergeSourceBranch.trim().slice(0, 200) : \"dev\")\n : null;\n return {\n version: AGENT_JOB_CONFIG_VERSION,\n jobId: input.jobId,\n jobCode: input.jobCode?.trim() ? input.jobCode.trim().slice(0, 80) : null,\n requirementId: input.requirementId,\n requirementCode:\n isValidation && input.requirementCode?.trim()\n ? input.requirementCode.trim().slice(0, 80)\n : null,\n callbackUrl: input.callbackUrl,\n gitRepoUrl: input.gitRepoUrl.trim(),\n gitRef: (input.gitRef || \"main\").trim(),\n requirementTitle: input.requirementTitle.slice(0, 500),\n requirementRawInput: input.requirementRawInput.slice(0, 8000),\n requirementChatContext: (input.requirementChatContext ?? \"\").trim().slice(0, 24_000),\n llmBaseUrl: input.llmBaseUrl?.trim() ? input.llmBaseUrl.replace(/\\/$/, \"\").trim() : null,\n llmModel: input.llmModel?.trim() ? input.llmModel.trim() : null,\n pipeline,\n targetBranch:\n usesFeatureBranch && input.targetBranch?.trim() ? input.targetBranch.trim().slice(0, 200) : null,\n codeTaskPhase: isCodeTask ? phase : \"create\",\n mergeSourceBranch: isCodeTask ? mergeSource : null,\n triggeredByName: input.triggeredByName?.trim() ? input.triggeredByName.trim().slice(0, 200) : null,\n triggeredByEmail: input.triggeredByEmail?.trim() ? input.triggeredByEmail.trim().slice(0, 240) : null,\n triggeredByUsername: input.triggeredByUsername?.trim() ? input.triggeredByUsername.trim().slice(0, 200) : null,\n triggeredByUserId: input.triggeredByUserId?.trim() ? input.triggeredByUserId.trim().slice(0, 200) : null,\n projectGitCommitName: input.projectGitCommitName?.trim()\n ? input.projectGitCommitName.trim().slice(0, 200)\n : null,\n projectGitCommitEmail: input.projectGitCommitEmail?.trim()\n ? input.projectGitCommitEmail.trim().slice(0, 240)\n : null,\n baseUrl: isValidation && input.baseUrl?.trim() ? input.baseUrl.trim().slice(0, 1024) : null,\n baseUrlsByApp:\n isValidation && input.baseUrlsByApp && Object.keys(input.baseUrlsByApp).length > 0\n ? Object.fromEntries(\n Object.entries(input.baseUrlsByApp)\n .slice(0, 16)\n .map(([k, v]) => [k.trim().toLowerCase().slice(0, 64), v.trim().slice(0, 1024)]),\n )\n : null,\n argoAppName: isValidation && input.argoAppName?.trim() ? input.argoAppName.trim().slice(0, 240) : null,\n deployedRevision:\n isValidation && input.deployedRevision?.trim() ? input.deployedRevision.trim().slice(0, 200) : null,\n gitBranchHint:\n isValidation && input.gitBranchHint?.trim() ? input.gitBranchHint.trim().slice(0, 200) : null,\n behaviorScope:\n isValidation && input.behaviorScope?.trim() ? input.behaviorScope.trim().slice(0, 120) : null,\n validationFeaturePaths:\n isValidation && input.validationFeaturePaths?.length\n ? input.validationFeaturePaths\n .map((p) => p.trim())\n .filter(Boolean)\n .slice(0, 64)\n .map((p) => p.slice(0, 512))\n : null,\n validationMaxTier:\n isValidation && input.validationMaxTier?.trim()\n ? input.validationMaxTier.trim().slice(0, 32)\n : null,\n validationSegment:\n isValidation && typeof input.validationSegment === \"number\" && Number.isFinite(input.validationSegment)\n ? Math.max(0, Math.floor(input.validationSegment))\n : null,\n checkpointObjectKey:\n isValidation && input.checkpointObjectKey?.trim()\n ? input.checkpointObjectKey.trim().slice(0, 512)\n : null,\n guidedRun: isValidation && input.guidedRun === true ? true : null,\n rewritePhases:\n pipeline === AGENT_JOB_PIPELINE_REQUIREMENT_REWRITE &&\n input.rewritePhases?.length === 3 &&\n input.rewritePhases.every((p) => p === \"l1\" || p === \"l2\" || p === \"l3\")\n ? [...input.rewritePhases]\n : null,\n rewriteForceFull:\n pipeline === AGENT_JOB_PIPELINE_REQUIREMENT_REWRITE && input.rewriteForceFull === true\n ? true\n : null,\n rewriteGateSpecRefs:\n pipeline === AGENT_JOB_PIPELINE_REQUIREMENT_REWRITE\n ? normalizeRewriteGateSpecRefs(input.rewriteGateSpecRefs)\n : null,\n integrationBranch: input.integrationBranch?.trim()\n ? input.integrationBranch.trim().slice(0, 200)\n : null,\n workspaceBase: input.workspaceBase ?? null,\n failureContext:\n pipeline === AGENT_JOB_PIPELINE_DEV_PIPELINE_TRIAGE &&\n input.failureContext &&\n typeof input.failureContext === \"object\" &&\n !Array.isArray(input.failureContext)\n ? (input.failureContext as Record<string, unknown>)\n : null,\n cursorResume: input.cursorResume === true,\n cursorSessionMode: parseAgentCursorSessionMode(input.cursorSessionMode),\n opsHints: input.opsHints ?? null,\n integrationContractCode: input.integrationContractCode?.trim()\n ? input.integrationContractCode.trim().slice(0, 80)\n : null,\n integrationSimRepoSubpath: input.integrationSimRepoSubpath?.trim()\n ? input.integrationSimRepoSubpath.trim().slice(0, 200)\n : null,\n integrationSimTargetEnv: input.integrationSimTargetEnv?.trim()\n ? input.integrationSimTargetEnv.trim().slice(0, 32)\n : null,\n integrationSimDocumentUrls:\n input.integrationSimDocumentUrls?.length\n ? input.integrationSimDocumentUrls\n .map((u) => u.trim())\n .filter(Boolean)\n .slice(0, 32)\n .map((u) => u.slice(0, 2048))\n : null,\n integrationDocsHints: input.integrationDocsHints ?? null,\n integrationDocCompileDocumentIds:\n input.integrationDocCompileDocumentIds?.length\n ? input.integrationDocCompileDocumentIds\n .map((id) => id.trim())\n .filter(Boolean)\n .slice(0, 512)\n .map((id) => id.slice(0, 80))\n : null,\n integrationDocCompileDocuments: normalizeIntegrationDocCompileDocuments(\n input.integrationDocCompileDocuments,\n {\n phase: input.integrationDocCompilePhase ?? \"full\",\n },\n ),\n integrationDocCompilePhase: normalizeIntegrationDocCompilePhase(input.integrationDocCompilePhase),\n integrationDocCompileBatch: normalizeIntegrationDocCompileBatch(input.integrationDocCompileBatch),\n integrationDocClassifyManifestKey: input.integrationDocClassifyManifestKey?.trim()\n ? input.integrationDocClassifyManifestKey.trim().slice(0, 500)\n : null,\n integrationSimApiIds:\n input.integrationSimApiIds?.length\n ? input.integrationSimApiIds\n .map((id) => id.trim())\n .filter(Boolean)\n .slice(0, 32)\n .map((id) => id.slice(0, 120))\n : null,\n executionMode:\n input.executionMode && typeof input.executionMode === \"object\" && !Array.isArray(input.executionMode)\n ? (input.executionMode as Record<string, unknown>)\n : null,\n dast: isSecurityVerify && input.dast ? normalizeAgentJobDastConfig(input.dast) : null,\n requirementIntakeAttachments: normalizeRequirementIntakeAttachmentsForJob(\n input.requirementIntakeAttachments,\n ),\n gitopsRepoUrl: input.gitopsRepoUrl?.trim() ? input.gitopsRepoUrl.trim().slice(0, 2000) : null,\n gitopsMainRef: input.gitopsMainRef?.trim() ? input.gitopsMainRef.trim().slice(0, 200) : null,\n gitopsFeatureBranch: input.gitopsFeatureBranch?.trim()\n ? input.gitopsFeatureBranch.trim().slice(0, 200)\n : null,\n gitopsPathDev: input.gitopsPathDev?.trim() ? input.gitopsPathDev.trim().slice(0, 500) : null,\n gitopsPathFeature: input.gitopsPathFeature?.trim()\n ? input.gitopsPathFeature.trim().slice(0, 500)\n : null,\n opsStructuralChatMessage: input.opsStructuralChatMessage?.trim()\n ? input.opsStructuralChatMessage.trim().slice(0, 8000)\n : null,\n integrationDocFetch: normalizeAgentJobIntegrationDocFetchConfig(input.integrationDocFetch),\n integrationDocFetchArtifacts: normalizeAgentJobIntegrationDocFetchArtifacts(\n input.integrationDocFetchArtifacts,\n ),\n };\n}\n\nconst DEFAULT_TIER_SCANS: AgentJobDastTierScansConfig = {\n session: { enabled: true },\n callback: { enabled: true, mode: \"smoke\" },\n integrationDocs: { enabled: true, mode: \"smoke\" },\n embed: { enabled: true, mode: \"smoke\" },\n};\n\nexport function normalizeAgentJobDastTierScans(\n raw: AgentJobDastTierScansConfig | undefined,\n): AgentJobDastTierScansConfig {\n if (!raw) return DEFAULT_TIER_SCANS;\n const mode = (m: unknown): AgentJobDastTierScanMode => (m === \"zap\" ? \"zap\" : \"smoke\");\n return {\n session: { enabled: raw.session?.enabled !== false },\n callback: { enabled: raw.callback?.enabled === true, mode: mode(raw.callback?.mode) },\n integrationDocs: {\n enabled: raw.integrationDocs?.enabled === true,\n mode: mode(raw.integrationDocs?.mode),\n },\n embed: { enabled: raw.embed?.enabled === true, mode: mode(raw.embed?.mode) },\n };\n}\n\nfunction normalizeAgentJobDastConfig(raw: AgentJobDastConfig): AgentJobDastConfig {\n const crawlMode = raw.crawlMode;\n const mode =\n crawlMode === \"traditional\" || crawlMode === \"ajax\" || crawlMode === \"both\" ? crawlMode : \"none\";\n return {\n authEnabled: raw.authEnabled === true,\n crawlMode: mode,\n seedUrls: (raw.seedUrls ?? []).slice(0, 32).map((u) => u.trim().slice(0, 2048)).filter(Boolean),\n failOn: (raw.failOn ?? [\"high\", \"medium\"]).slice(0, 4),\n projectCode: raw.projectCode?.trim() ? raw.projectCode.trim().slice(0, 80) : null,\n requirementCode: raw.requirementCode?.trim() ? raw.requirementCode.trim().slice(0, 80) : null,\n apiScanEnabled: raw.apiScanEnabled === true,\n apiScanIncludePaths: (raw.apiScanIncludePaths ?? [])\n .slice(0, 16)\n .map((p) => p.trim().slice(0, 256))\n .filter(Boolean),\n openapiSource: raw.openapiSource === \"url\" ? \"url\" : \"bundled\",\n openapiSpecPath: raw.openapiSpecPath?.trim() ? raw.openapiSpecPath.trim().slice(0, 2048) : null,\n openapiUrl: raw.openapiUrl?.trim() ? raw.openapiUrl.trim().slice(0, 2048) : null,\n openapiImportRequired: raw.openapiImportRequired === true,\n maxAscanUrls: Math.max(10, Math.min(500, Math.floor(raw.maxAscanUrls ?? 200))),\n maxAscanOperations: Math.max(10, Math.min(600, Math.floor(raw.maxAscanOperations ?? raw.maxAscanUrls ?? 200))),\n methodAwareAscan: raw.methodAwareAscan === true,\n ascanBudgetRatio: Math.max(0.05, Math.min(0.9, Number(raw.ascanBudgetRatio ?? 0.45) || 0.45)),\n crawlBudgetRatio: Math.max(0.05, Math.min(0.9, Number(raw.crawlBudgetRatio ?? 0.45) || 0.45)),\n readOnlyMethodsOnly: raw.readOnlyMethodsOnly === true,\n dastProfile: raw.dastProfile === \"deep-api\" ? \"deep-api\" : \"default\",\n preflightDiscovery: raw.preflightDiscovery === true,\n probeFallback: raw.probeFallback === true,\n preflightBootstrap: raw.preflightBootstrap === true,\n tierScans: normalizeAgentJobDastTierScans(raw.tierScans),\n ignorePaths: (raw.ignorePaths ?? []).slice(0, 16).map((p) => p.trim().slice(0, 256)).filter(Boolean),\n failOnLoginError: raw.failOnLoginError !== false,\n crawlMaxDurationSeconds: Math.max(30, Math.min(3600, Math.floor(raw.crawlMaxDurationSeconds ?? 300))),\n crawlMaxDepth: Math.max(1, Math.min(20, Math.floor(raw.crawlMaxDepth ?? 5))),\n timeoutSeconds: Math.max(60, Math.min(10800, Math.floor(raw.timeoutSeconds ?? 7200))),\n apiServices: (raw.apiServices ?? [])\n .slice(0, 8)\n .map((entry) => ({\n name: entry.name.trim().toLowerCase().slice(0, 80),\n openapiSpecPath: entry.openapiSpecPath.trim().slice(0, 2048),\n coverageManifestPath: entry.coverageManifestPath?.trim()\n ? entry.coverageManifestPath.trim().slice(0, 2048)\n : null,\n }))\n .filter((entry) => entry.name && entry.openapiSpecPath),\n };\n}\n\nexport function failureContextFromAgentJobConfig(\n config: AgentJobConfigV1,\n): Record<string, unknown> | null {\n return config.failureContext;\n}\n\nexport function serializeAgentJobConfigV1(config: AgentJobConfigV1): string {\n return JSON.stringify(config);\n}\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === \"object\" && !Array.isArray(v);\n}\n\nexport function parseAgentJobConfigV1(raw: string): AgentJobConfigV1 | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw) as unknown;\n } catch {\n return null;\n }\n if (!isRecord(parsed)) return null;\n if (parsed.version !== AGENT_JOB_CONFIG_VERSION) return null;\n\n const str = (k: string): string | null => {\n const v = parsed[k];\n return typeof v === \"string\" ? v : null;\n };\n\n const jobId = str(\"jobId\");\n const jobCodeRaw = parsed.jobCode;\n const jobCode =\n typeof jobCodeRaw === \"string\" && jobCodeRaw.trim() !== \"\" ? jobCodeRaw.trim().slice(0, 80) : null;\n const requirementId = str(\"requirementId\");\n const callbackUrl = str(\"callbackUrl\");\n const gitRepoUrl = str(\"gitRepoUrl\");\n const gitRef = str(\"gitRef\");\n const pipelineEarly = parseAgentJobPipeline(parsed.pipeline);\n const behaviorScopePeek =\n typeof parsed.behaviorScope === \"string\" ? parsed.behaviorScope.trim() : \"\";\n const omitCardAnchor = agentJobOmitsRequirementCardAnchor(pipelineEarly, behaviorScopePeek);\n\n const requirementTitle =\n typeof parsed.requirementTitle === \"string\" ? parsed.requirementTitle : null;\n const requirementRawInput =\n typeof parsed.requirementRawInput === \"string\" ? parsed.requirementRawInput : null;\n if (!jobId || !callbackUrl || !gitRepoUrl || !gitRef) {\n return null;\n }\n /** Dev/prod deploy validation has no anchor card; job.json may omit requirementId. */\n if (!omitCardAnchor && !requirementId) {\n return null;\n }\n if (!omitCardAnchor && (!requirementTitle?.trim() || !requirementRawInput?.trim())) {\n return null;\n }\n\n const chat =\n typeof parsed.requirementChatContext === \"string\" ? parsed.requirementChatContext : \"\";\n\n const llmBaseUrl =\n parsed.llmBaseUrl === null\n ? null\n : typeof parsed.llmBaseUrl === \"string\"\n ? parsed.llmBaseUrl.replace(/\\/$/, \"\").trim() || null\n : null;\n const llmModel =\n parsed.llmModel === null\n ? null\n : typeof parsed.llmModel === \"string\"\n ? parsed.llmModel.trim() || null\n : null;\n\n const pipeline = pipelineEarly;\n\n const tbRaw = parsed.targetBranch;\n const targetBranch =\n typeof tbRaw === \"string\" && tbRaw.trim() !== \"\" ? tbRaw.trim().slice(0, 200) : null;\n\n let codeTaskPhase = parseAgentCodeTaskPhase(parsed.codeTaskPhase);\n const msRaw = parsed.mergeSourceBranch;\n let mergeSourceBranch =\n typeof msRaw === \"string\" && msRaw.trim() !== \"\" ? msRaw.trim().slice(0, 200) : null;\n const triggeredByName =\n typeof parsed.triggeredByName === \"string\" && parsed.triggeredByName.trim() !== \"\"\n ? parsed.triggeredByName.trim().slice(0, 200)\n : null;\n const triggeredByEmail =\n typeof parsed.triggeredByEmail === \"string\" && parsed.triggeredByEmail.trim() !== \"\"\n ? parsed.triggeredByEmail.trim().slice(0, 240)\n : null;\n const triggeredByUsername =\n typeof parsed.triggeredByUsername === \"string\" && parsed.triggeredByUsername.trim() !== \"\"\n ? parsed.triggeredByUsername.trim().slice(0, 200)\n : null;\n const triggeredByUserId =\n typeof parsed.triggeredByUserId === \"string\" && parsed.triggeredByUserId.trim() !== \"\"\n ? parsed.triggeredByUserId.trim().slice(0, 200)\n : null;\n const projectGitCommitName =\n typeof parsed.projectGitCommitName === \"string\" && parsed.projectGitCommitName.trim() !== \"\"\n ? parsed.projectGitCommitName.trim().slice(0, 200)\n : null;\n const projectGitCommitEmail =\n typeof parsed.projectGitCommitEmail === \"string\" && parsed.projectGitCommitEmail.trim() !== \"\"\n ? parsed.projectGitCommitEmail.trim().slice(0, 240)\n : null;\n\n if (pipeline !== AGENT_JOB_PIPELINE_CODE_TASK_FEATURE) {\n codeTaskPhase = \"create\";\n mergeSourceBranch = null;\n } else if (codeTaskPhase === \"create\") {\n mergeSourceBranch = null;\n } else if (\n (codeTaskPhase === \"merge_dev\" || codeTaskPhase === \"pipeline_sync_dev\") &&\n !mergeSourceBranch\n ) {\n mergeSourceBranch = \"dev\";\n }\n\n const isValidation = isRunnerJobWithTargetUrl(pipeline);\n const baseUrlRaw = parsed.baseUrl;\n const argoAppNameRaw = parsed.argoAppName;\n const deployedRevisionRaw = parsed.deployedRevision;\n const baseUrl =\n isValidation && typeof baseUrlRaw === \"string\" && baseUrlRaw.trim() !== \"\"\n ? baseUrlRaw.trim().slice(0, 1024)\n : null;\n let baseUrlsByApp: Record<string, string> | null = null;\n if (isValidation && parsed.baseUrlsByApp && typeof parsed.baseUrlsByApp === \"object\" && !Array.isArray(parsed.baseUrlsByApp)) {\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(parsed.baseUrlsByApp as Record<string, unknown>)) {\n if (typeof k !== \"string\" || typeof v !== \"string\") continue;\n const name = k.trim().toLowerCase();\n const url = v.trim();\n if (!name || !url) continue;\n out[name.slice(0, 64)] = url.slice(0, 1024);\n if (Object.keys(out).length >= 16) break;\n }\n baseUrlsByApp = Object.keys(out).length > 0 ? out : null;\n }\n const argoAppName =\n isValidation && typeof argoAppNameRaw === \"string\" && argoAppNameRaw.trim() !== \"\"\n ? argoAppNameRaw.trim().slice(0, 240)\n : null;\n const deployedRevision =\n isValidation && typeof deployedRevisionRaw === \"string\" && deployedRevisionRaw.trim() !== \"\"\n ? deployedRevisionRaw.trim().slice(0, 200)\n : null;\n const gitBranchHintRaw = parsed.gitBranchHint;\n const gitBranchHint =\n isValidation && typeof gitBranchHintRaw === \"string\" && gitBranchHintRaw.trim() !== \"\"\n ? gitBranchHintRaw.trim().slice(0, 200)\n : null;\n const behaviorScopeRaw = parsed.behaviorScope;\n const behaviorScope =\n isValidation && typeof behaviorScopeRaw === \"string\" && behaviorScopeRaw.trim() !== \"\"\n ? behaviorScopeRaw.trim().slice(0, 120)\n : null;\n const validationFeaturePathsRaw = parsed.validationFeaturePaths;\n let validationFeaturePaths: string[] | null = null;\n if (isValidation && Array.isArray(validationFeaturePathsRaw)) {\n const paths: string[] = [];\n for (const item of validationFeaturePathsRaw) {\n if (typeof item !== \"string\") continue;\n const t = item.trim();\n if (!t) continue;\n paths.push(t.slice(0, 512));\n if (paths.length >= 64) break;\n }\n validationFeaturePaths = paths.length > 0 ? paths : null;\n }\n const validationMaxTierRaw = parsed.validationMaxTier;\n const validationMaxTier =\n isValidation && typeof validationMaxTierRaw === \"string\" && validationMaxTierRaw.trim() !== \"\"\n ? validationMaxTierRaw.trim().slice(0, 32)\n : null;\n const validationSegmentRaw = parsed.validationSegment;\n const validationSegment =\n isValidation && typeof validationSegmentRaw === \"number\" && Number.isFinite(validationSegmentRaw)\n ? Math.max(0, Math.floor(validationSegmentRaw))\n : null;\n const checkpointObjectKeyRaw = parsed.checkpointObjectKey;\n const checkpointObjectKey =\n isValidation && typeof checkpointObjectKeyRaw === \"string\" && checkpointObjectKeyRaw.trim() !== \"\"\n ? checkpointObjectKeyRaw.trim().slice(0, 512)\n : null;\n const guidedRun = isValidation && parsed.guidedRun === true ? true : null;\n const integrationContractCodeRaw = parsed.integrationContractCode;\n const integrationContractCode =\n typeof integrationContractCodeRaw === \"string\" && integrationContractCodeRaw.trim() !== \"\"\n ? integrationContractCodeRaw.trim().slice(0, 80)\n : null;\n const requirementCodeRaw = parsed.requirementCode;\n const requirementCode =\n isValidation && typeof requirementCodeRaw === \"string\" && requirementCodeRaw.trim() !== \"\"\n ? requirementCodeRaw.trim().slice(0, 80)\n : null;\n\n const rewritePhasesRaw = parsed.rewritePhases;\n let rewritePhases: RewritePhase[] | null = null;\n if (Array.isArray(rewritePhasesRaw) && rewritePhasesRaw.length === 3) {\n const phases = rewritePhasesRaw.map((x) => (typeof x === \"string\" ? x.trim() : \"\"));\n if (phases.every((p) => p === \"l1\" || p === \"l2\" || p === \"l3\")) {\n rewritePhases = phases as RewritePhase[];\n }\n }\n\n const integrationBranchRaw = parsed.integrationBranch;\n const integrationBranch =\n typeof integrationBranchRaw === \"string\" && integrationBranchRaw.trim() !== \"\"\n ? integrationBranchRaw.trim().slice(0, 200)\n : null;\n const workspaceBase = parseAgentWorkspaceBase(parsed.workspaceBase);\n\n const failureContextRaw = parsed.failureContext;\n const failureContext =\n pipeline === AGENT_JOB_PIPELINE_DEV_PIPELINE_TRIAGE &&\n failureContextRaw &&\n typeof failureContextRaw === \"object\" &&\n !Array.isArray(failureContextRaw)\n ? (failureContextRaw as Record<string, unknown>)\n : null;\n\n const cursorResume = parsed.cursorResume === true;\n const cursorSessionMode = parseAgentCursorSessionMode(parsed.cursorSessionMode);\n\n let opsHints: AgentJobOpsHints | null = null;\n const opsHintsRaw = parsed.opsHints;\n if (opsHintsRaw && typeof opsHintsRaw === \"object\" && !Array.isArray(opsHintsRaw)) {\n const oh = opsHintsRaw as Record<string, unknown>;\n const projectCode = typeof oh.projectCode === \"string\" ? oh.projectCode.trim() : \"\";\n const defaultEnv = oh.defaultEnv;\n if (\n projectCode &&\n (defaultEnv === \"prod\" || defaultEnv === \"dev\" || defaultEnv === \"feature\")\n ) {\n const blt = oh.buildLogTarget;\n let buildLogTarget: AgentJobOpsHints[\"buildLogTarget\"] = null;\n if (blt && typeof blt === \"object\" && !Array.isArray(blt)) {\n const b = blt as Record<string, unknown>;\n const env = b.env;\n const kind = typeof b.kind === \"string\" ? b.kind.trim() : \"\";\n const name = typeof b.name === \"string\" ? b.name.trim() : \"\";\n const namespace = typeof b.namespace === \"string\" ? b.namespace.trim() : \"\";\n if (\n (env === \"prod\" || env === \"dev\" || env === \"feature\") &&\n kind &&\n name &&\n namespace\n ) {\n buildLogTarget = { env, kind, name, namespace };\n }\n }\n opsHints = {\n projectCode: projectCode.slice(0, 80),\n defaultEnv,\n featureAppName:\n typeof oh.featureAppName === \"string\" && oh.featureAppName.trim()\n ? oh.featureAppName.trim().slice(0, 240)\n : null,\n releaseTaskCode:\n typeof oh.releaseTaskCode === \"string\" && oh.releaseTaskCode.trim()\n ? oh.releaseTaskCode.trim().slice(0, 80)\n : null,\n buildLogTarget,\n };\n }\n }\n\n return {\n version: AGENT_JOB_CONFIG_VERSION,\n jobId,\n jobCode,\n requirementId: requirementId ?? \"\",\n requirementCode,\n callbackUrl,\n gitRepoUrl,\n gitRef,\n requirementTitle: omitCardAnchor ? (requirementTitle ?? \"\") : requirementTitle!,\n requirementRawInput: omitCardAnchor ? (requirementRawInput ?? \"\") : requirementRawInput!,\n requirementChatContext: chat,\n llmBaseUrl,\n llmModel,\n pipeline,\n targetBranch,\n codeTaskPhase,\n mergeSourceBranch,\n triggeredByName,\n triggeredByEmail,\n triggeredByUsername,\n triggeredByUserId,\n projectGitCommitName,\n projectGitCommitEmail,\n baseUrl,\n baseUrlsByApp,\n argoAppName,\n deployedRevision,\n gitBranchHint,\n behaviorScope,\n validationFeaturePaths,\n validationMaxTier,\n validationSegment,\n checkpointObjectKey,\n guidedRun,\n rewritePhases,\n rewriteForceFull: parsed.rewriteForceFull === true ? true : null,\n rewriteGateSpecRefs: (() => {\n const raw = parsed.rewriteGateSpecRefs;\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return null;\n return normalizeRewriteGateSpecRefs(raw as RewriteGateSpecRefs);\n })(),\n integrationBranch,\n workspaceBase,\n failureContext,\n cursorResume,\n cursorSessionMode,\n opsHints,\n integrationContractCode,\n integrationSimRepoSubpath:\n typeof parsed.integrationSimRepoSubpath === \"string\" && parsed.integrationSimRepoSubpath.trim()\n ? parsed.integrationSimRepoSubpath.trim().slice(0, 200)\n : null,\n integrationSimTargetEnv:\n typeof parsed.integrationSimTargetEnv === \"string\" && parsed.integrationSimTargetEnv.trim()\n ? parsed.integrationSimTargetEnv.trim().slice(0, 32)\n : null,\n integrationSimDocumentUrls: (() => {\n const raw = parsed.integrationSimDocumentUrls;\n if (!Array.isArray(raw)) return null;\n const urls: string[] = [];\n for (const item of raw) {\n if (typeof item !== \"string\") continue;\n const t = item.trim();\n if (t) urls.push(t.slice(0, 2048));\n if (urls.length >= 32) break;\n }\n return urls.length > 0 ? urls : null;\n })(),\n integrationDocsHints: (() => {\n const raw = parsed.integrationDocsHints;\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return null;\n const o = raw as Record<string, unknown>;\n const projectCode = typeof o.projectCode === \"string\" ? o.projectCode.trim() : \"\";\n const apiBaseUrl = typeof o.apiBaseUrl === \"string\" ? o.apiBaseUrl.trim() : \"\";\n if (!projectCode || !apiBaseUrl) return null;\n return { projectCode: projectCode.slice(0, 80), apiBaseUrl: apiBaseUrl.slice(0, 512) };\n })(),\n integrationDocCompileDocumentIds: (() => {\n const raw = parsed.integrationDocCompileDocumentIds;\n if (!Array.isArray(raw)) return null;\n const ids: string[] = [];\n for (const item of raw) {\n if (typeof item !== \"string\") continue;\n const t = item.trim();\n if (t) ids.push(t.slice(0, 80));\n if (ids.length >= 512) break;\n }\n return ids.length > 0 ? ids : null;\n })(),\n integrationDocCompileDocuments: (() => {\n const raw = parsed.integrationDocCompileDocuments;\n const phase = normalizeIntegrationDocCompilePhase(parsed.integrationDocCompilePhase) ?? \"full\";\n if (!Array.isArray(raw)) return null;\n const rows: IntegrationDocCompileDocumentEntry[] = [];\n for (const item of raw) {\n if (!item || typeof item !== \"object\" || Array.isArray(item)) continue;\n const o = item as Record<string, unknown>;\n rows.push({\n documentId: typeof o.documentId === \"string\" ? o.documentId : \"\",\n title: typeof o.title === \"string\" ? o.title : \"\",\n url: typeof o.url === \"string\" ? o.url : \"\",\n });\n }\n return normalizeIntegrationDocCompileDocuments(rows, { phase });\n })(),\n integrationDocCompilePhase: normalizeIntegrationDocCompilePhase(parsed.integrationDocCompilePhase),\n integrationDocCompileBatch: normalizeIntegrationDocCompileBatch(parsed.integrationDocCompileBatch),\n integrationDocClassifyManifestKey:\n typeof parsed.integrationDocClassifyManifestKey === \"string\" &&\n parsed.integrationDocClassifyManifestKey.trim()\n ? parsed.integrationDocClassifyManifestKey.trim().slice(0, 500)\n : null,\n integrationSimApiIds: (() => {\n const raw = parsed.integrationSimApiIds;\n if (!Array.isArray(raw)) return null;\n const ids: string[] = [];\n for (const item of raw) {\n if (typeof item !== \"string\") continue;\n const t = item.trim();\n if (t) ids.push(t.slice(0, 120));\n if (ids.length >= 32) break;\n }\n return ids.length > 0 ? ids : null;\n })(),\n requirementIntakeAttachments: (() => {\n const raw = parsed.requirementIntakeAttachments;\n if (!Array.isArray(raw)) return null;\n const rows: RequirementIntakeAttachmentJobRef[] = [];\n for (const item of raw) {\n if (!item || typeof item !== \"object\" || Array.isArray(item)) continue;\n const o = item as Record<string, unknown>;\n rows.push({\n id: typeof o.id === \"string\" ? o.id : \"\",\n fileName: typeof o.fileName === \"string\" ? o.fileName : \"\",\n mimeType: typeof o.mimeType === \"string\" ? o.mimeType : \"\",\n intakeIndex:\n typeof o.intakeIndex === \"number\" && Number.isFinite(o.intakeIndex) && o.intakeIndex >= 1\n ? Math.floor(o.intakeIndex)\n : rows.length + 1,\n });\n }\n return normalizeRequirementIntakeAttachmentsForJob(rows);\n })(),\n executionMode:\n parsed.executionMode &&\n typeof parsed.executionMode === \"object\" &&\n !Array.isArray(parsed.executionMode)\n ? (parsed.executionMode as Record<string, unknown>)\n : null,\n dast: (() => {\n if (pipeline !== AGENT_JOB_PIPELINE_SECURITY_VERIFY) return null;\n const raw = parsed.dast;\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return null;\n const o = raw as Record<string, unknown>;\n const crawlModeRaw = typeof o.crawlMode === \"string\" ? o.crawlMode.trim() : \"none\";\n const crawlMode =\n crawlModeRaw === \"traditional\" || crawlModeRaw === \"ajax\" || crawlModeRaw === \"both\"\n ? crawlModeRaw\n : \"none\";\n const seedUrls: string[] = [];\n if (Array.isArray(o.seedUrls)) {\n for (const item of o.seedUrls) {\n if (typeof item !== \"string\") continue;\n const t = item.trim();\n if (t) seedUrls.push(t.slice(0, 2048));\n if (seedUrls.length >= 32) break;\n }\n }\n const failOn: (\"critical\" | \"high\" | \"medium\" | \"low\")[] = [];\n if (Array.isArray(o.failOn)) {\n for (const item of o.failOn) {\n if (item === \"critical\" || item === \"high\" || item === \"medium\" || item === \"low\") {\n if (!failOn.includes(item)) failOn.push(item);\n }\n }\n }\n const ignorePaths: string[] = [];\n if (Array.isArray(o.ignorePaths)) {\n for (const item of o.ignorePaths) {\n if (typeof item !== \"string\") continue;\n const t = item.trim();\n if (t) ignorePaths.push(t.slice(0, 256));\n }\n }\n const apiScanIncludePaths: string[] = [];\n if (Array.isArray(o.apiScanIncludePaths)) {\n for (const item of o.apiScanIncludePaths) {\n if (typeof item !== \"string\") continue;\n const t = item.trim();\n if (t) apiScanIncludePaths.push(t.slice(0, 256));\n }\n }\n const tierRaw =\n o.tierScans && typeof o.tierScans === \"object\" && !Array.isArray(o.tierScans)\n ? (o.tierScans as AgentJobDastTierScansConfig)\n : undefined;\n return normalizeAgentJobDastConfig({\n authEnabled: o.authEnabled === true,\n crawlMode,\n seedUrls,\n failOn: failOn.length ? failOn : [\"high\", \"medium\"],\n projectCode: typeof o.projectCode === \"string\" ? o.projectCode : null,\n requirementCode: typeof o.requirementCode === \"string\" ? o.requirementCode : null,\n apiScanEnabled: o.apiScanEnabled === true,\n apiScanIncludePaths,\n openapiSource: o.openapiSource === \"url\" ? \"url\" : \"bundled\",\n openapiSpecPath: typeof o.openapiSpecPath === \"string\" ? o.openapiSpecPath : null,\n openapiUrl: typeof o.openapiUrl === \"string\" ? o.openapiUrl : null,\n openapiImportRequired: o.openapiImportRequired === true,\n maxAscanUrls: typeof o.maxAscanUrls === \"number\" ? o.maxAscanUrls : 200,\n maxAscanOperations:\n typeof o.maxAscanOperations === \"number\" ? o.maxAscanOperations : 200,\n methodAwareAscan: o.methodAwareAscan === true,\n ascanBudgetRatio: typeof o.ascanBudgetRatio === \"number\" ? o.ascanBudgetRatio : 0.45,\n crawlBudgetRatio: typeof o.crawlBudgetRatio === \"number\" ? o.crawlBudgetRatio : 0.45,\n readOnlyMethodsOnly: o.readOnlyMethodsOnly === true,\n dastProfile: o.dastProfile === \"deep-api\" ? \"deep-api\" : \"default\",\n preflightDiscovery: o.preflightDiscovery === true,\n probeFallback: o.probeFallback === true,\n preflightBootstrap: o.preflightBootstrap === true,\n tierScans: normalizeAgentJobDastTierScans(tierRaw),\n ignorePaths,\n failOnLoginError: o.failOnLoginError !== false,\n crawlMaxDurationSeconds:\n typeof o.crawlMaxDurationSeconds === \"number\" ? o.crawlMaxDurationSeconds : 300,\n crawlMaxDepth: typeof o.crawlMaxDepth === \"number\" ? o.crawlMaxDepth : 5,\n timeoutSeconds: typeof o.timeoutSeconds === \"number\" ? o.timeoutSeconds : 7200,\n apiServices: (() => {\n if (!Array.isArray(o.apiServices)) return [];\n const out: AgentJobDastApiServiceEntry[] = [];\n for (const item of o.apiServices) {\n if (!item || typeof item !== \"object\" || Array.isArray(item)) continue;\n const row = item as Record<string, unknown>;\n const name = typeof row.name === \"string\" ? row.name.trim() : \"\";\n const openapiSpecPath =\n typeof row.openapiSpecPath === \"string\" ? row.openapiSpecPath.trim() : \"\";\n if (!name || !openapiSpecPath) continue;\n out.push({\n name,\n openapiSpecPath,\n coverageManifestPath:\n typeof row.coverageManifestPath === \"string\" ? row.coverageManifestPath.trim() : null,\n });\n if (out.length >= 8) break;\n }\n return out;\n })(),\n });\n })(),\n gitopsRepoUrl: typeof parsed.gitopsRepoUrl === \"string\" ? parsed.gitopsRepoUrl : null,\n gitopsMainRef: typeof parsed.gitopsMainRef === \"string\" ? parsed.gitopsMainRef : null,\n gitopsFeatureBranch:\n typeof parsed.gitopsFeatureBranch === \"string\" ? parsed.gitopsFeatureBranch : null,\n gitopsPathDev: typeof parsed.gitopsPathDev === \"string\" ? parsed.gitopsPathDev : null,\n gitopsPathFeature: typeof parsed.gitopsPathFeature === \"string\" ? parsed.gitopsPathFeature : null,\n opsStructuralChatMessage:\n typeof parsed.opsStructuralChatMessage === \"string\" ? parsed.opsStructuralChatMessage : null,\n integrationDocFetch: (() => {\n const raw = parsed.integrationDocFetch;\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return null;\n const o = raw as Record<string, unknown>;\n const mode = o.mode;\n if (mode !== \"discover\" && mode !== \"fetch_pages\" && mode !== \"page_preview\" && mode !== \"import_openapi\") return null;\n return normalizeAgentJobIntegrationDocFetchConfig({\n mode,\n projectCode: typeof o.projectCode === \"string\" ? o.projectCode : \"\",\n projectId: typeof o.projectId === \"string\" ? o.projectId : \"\",\n sessionId: typeof o.sessionId === \"string\" ? o.sessionId : null,\n discover:\n o.discover && typeof o.discover === \"object\" && !Array.isArray(o.discover)\n ? (o.discover as AgentJobIntegrationDocFetchConfig[\"discover\"])\n : undefined,\n fetchPages:\n o.fetchPages && typeof o.fetchPages === \"object\" && !Array.isArray(o.fetchPages)\n ? (o.fetchPages as AgentJobIntegrationDocFetchConfig[\"fetchPages\"])\n : undefined,\n pagePreview:\n o.pagePreview && typeof o.pagePreview === \"object\" && !Array.isArray(o.pagePreview)\n ? (o.pagePreview as AgentJobIntegrationDocFetchConfig[\"pagePreview\"])\n : undefined,\n importOpenapi:\n o.importOpenapi && typeof o.importOpenapi === \"object\" && !Array.isArray(o.importOpenapi)\n ? (o.importOpenapi as AgentJobIntegrationDocFetchConfig[\"importOpenapi\"])\n : undefined,\n });\n })(),\n integrationDocFetchArtifacts: (() => {\n const raw = parsed.integrationDocFetchArtifacts;\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return null;\n return normalizeAgentJobIntegrationDocFetchArtifacts(raw as AgentJobIntegrationDocFetchArtifacts);\n })(),\n };\n}\n",
|
|
11
|
+
"import {\n type LocalSecurityCallbackResult,\n isLocalSecurityInfraFromScanners,\n} from \"./local-verify-callback\";\nimport type { ValidationFailurePhase } from \"./validation-failure\";\nimport type { ValidationDiagnosisSummary } from \"./validation-diagnosis\";\n\n/** Logical phase where a dev-pipeline failure occurred (includes P5 validate as a phase label). */\nexport const DEV_PIPELINE_FAILURE_FROM_PHASES = [\n \"UI_CONTRACT\",\n \"VALIDATION_PLAN\",\n \"VALIDATION_CODE\",\n \"BEHAVIORS_GATE\",\n \"IMPLEMENTATION\",\n \"COMPILE_GATE\",\n \"STATIC_SECURITY\",\n \"LOCAL_VERIFY\",\n \"DEPLOY\",\n \"DEPLOY_FAILED\",\n \"VALIDATE\",\n \"FIX\",\n] as const;\n\nexport type DevPipelineFailureFromPhase = (typeof DEV_PIPELINE_FAILURE_FROM_PHASES)[number];\n\nexport const DEV_PIPELINE_FAILURE_KINDS = [\n \"build\",\n \"deploy_runtime\",\n \"validation\",\n \"compile_gate\",\n \"static_security\",\n /** @deprecated */\n \"local_verify\",\n /** @deprecated */\n \"local_security\",\n \"security\",\n \"agent_job\",\n] as const;\n\nexport type DevPipelineFailureKind = (typeof DEV_PIPELINE_FAILURE_KINDS)[number];\n\nexport type DevPipelineFailingTestRef = {\n name: string;\n error?: string;\n scenario?: string;\n};\n\nexport type DevPipelineFailureContext = {\n version: 1;\n kind: DevPipelineFailureKind;\n fromPhase: DevPipelineFailureFromPhase;\n at: string;\n summary: string;\n releaseTaskCode?: string;\n buildLogTail?: string;\n /** Parsed from BuildKit log when kind=build */\n buildFailedDockerfile?: string;\n buildErrorExcerpt?: string;\n buildJobName?: string;\n argoAppName?: string;\n argoSyncStatus?: string;\n argoHealthStatus?: string;\n argoMessage?: string;\n validationJobCode?: string;\n securityJobCode?: string;\n failingTests?: DevPipelineFailingTestRef[];\n stderrTail?: string;\n artifactUrls?: { htmlReport?: string | null };\n rawError?: string;\n /** validation-runner failurePhase when kind=validation */\n failurePhase?: ValidationFailurePhase;\n hints?: string[];\n /** Structured skip/fail triage from validation-runner callback. */\n diagnosis?: ValidationDiagnosisSummary;\n /** spawn-fix mode when card created from validation center. */\n spawnMode?: \"failure\" | \"coverage\";\n /** Workstream Story code when IMPLEMENTATION failed on a story card. */\n workstreamStoryCode?: string;\n /** Structured push gate metadata (IMPLEMENTATION agent push). */\n pushGateKind?: \"docker_parity\" | \"frozen_lockfile\" | \"bun_audit\" | \"check_behaviors\";\n pushGateClass?: PushGateFailureClass;\n auditFindings?: string[];\n};\n\nexport type PushGateFailureClass =\n | \"transient_npm\"\n | \"baseline_bun_audit\"\n | \"lockfile_drift\"\n | \"code_other\";\n\nexport type PushGateFailureKind =\n | \"docker_parity\"\n | \"frozen_lockfile\"\n | \"bun_audit\"\n | \"check_behaviors\";\n\nexport const DEV_PIPELINE_TRIAGE_TARGET_PHASES = [\n \"UI_CONTRACT\",\n \"VALIDATION_PLAN\",\n \"VALIDATION_CODE\",\n \"BEHAVIORS_GATE\",\n \"IMPLEMENTATION\",\n \"COMPILE_GATE\",\n \"STATIC_SECURITY\",\n \"LOCAL_VERIFY\",\n \"VALIDATE\",\n \"DEPLOY\",\n] as const;\n\nexport type DevPipelineTriageTargetPhase = (typeof DEV_PIPELINE_TRIAGE_TARGET_PHASES)[number];\n\nexport const DEV_PIPELINE_FIX_CATEGORIES = [\n \"code\",\n \"spec\",\n \"infra\",\n \"retry_only\",\n \"none\",\n] as const;\n\nexport type DevPipelineFixCategory = (typeof DEV_PIPELINE_FIX_CATEGORIES)[number];\n\nexport type DevPipelineTriageDecision = {\n targetPhase: DevPipelineTriageTargetPhase;\n fixCategory: DevPipelineFixCategory;\n rationale: string;\n agentBrief: string;\n};\n\nexport type DevPipelineLastTriage = DevPipelineTriageDecision & {\n jobCode: string;\n at: string;\n};\n\nconst SUMMARY_MAX = 500;\nconst BUILD_LOG_MAX = 8000;\nconst STDERR_MAX = 4000;\nconst FAILING_TESTS_MAX = 20;\n\nexport function truncateDevPipelineText(s: string, max: number): string {\n const t = s.trim();\n if (t.length <= max) return t;\n return `${t.slice(0, max - 20)}\\n…(truncated)`;\n}\n\nexport function isDevPipelineFailureFromPhase(v: string): v is DevPipelineFailureFromPhase {\n return (DEV_PIPELINE_FAILURE_FROM_PHASES as readonly string[]).includes(v);\n}\n\nexport function isDevPipelineFailureKind(v: string): v is DevPipelineFailureKind {\n return (DEV_PIPELINE_FAILURE_KINDS as readonly string[]).includes(v);\n}\n\nexport function parseDevPipelineFailureContext(raw: unknown): DevPipelineFailureContext | null {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return null;\n const o = raw as Record<string, unknown>;\n if (o.version !== 1) return null;\n const kind = typeof o.kind === \"string\" ? o.kind : \"\";\n const fromPhase = typeof o.fromPhase === \"string\" ? o.fromPhase : \"\";\n const summary = typeof o.summary === \"string\" ? o.summary.trim() : \"\";\n const at = typeof o.at === \"string\" ? o.at : \"\";\n if (!isDevPipelineFailureKind(kind) || !isDevPipelineFailureFromPhase(fromPhase) || !summary || !at) {\n return null;\n }\n const ctx: DevPipelineFailureContext = {\n version: 1,\n kind,\n fromPhase,\n at,\n summary: truncateDevPipelineText(summary, SUMMARY_MAX),\n };\n const optStr = (key: keyof DevPipelineFailureContext, max: number) => {\n const v = o[key];\n if (typeof v === \"string\" && v.trim()) (ctx as Record<string, unknown>)[key] = truncateDevPipelineText(v, max);\n };\n optStr(\"releaseTaskCode\", 80);\n optStr(\"buildLogTail\", BUILD_LOG_MAX);\n optStr(\"buildFailedDockerfile\", 240);\n optStr(\"buildErrorExcerpt\", 1200);\n optStr(\"buildJobName\", 200);\n optStr(\"argoAppName\", 240);\n optStr(\"argoSyncStatus\", 80);\n optStr(\"argoHealthStatus\", 80);\n optStr(\"argoMessage\", 4000);\n optStr(\"validationJobCode\", 80);\n optStr(\"securityJobCode\", 80);\n optStr(\"stderrTail\", STDERR_MAX);\n optStr(\"rawError\", 8000);\n optStr(\"workstreamStoryCode\", 80);\n const pushGateKind = typeof o.pushGateKind === \"string\" ? o.pushGateKind.trim() : \"\";\n if (\n pushGateKind === \"docker_parity\" ||\n pushGateKind === \"frozen_lockfile\" ||\n pushGateKind === \"bun_audit\" ||\n pushGateKind === \"check_behaviors\"\n ) {\n ctx.pushGateKind = pushGateKind;\n }\n const pushGateClass = typeof o.pushGateClass === \"string\" ? o.pushGateClass.trim() : \"\";\n if (\n pushGateClass === \"transient_npm\" ||\n pushGateClass === \"baseline_bun_audit\" ||\n pushGateClass === \"lockfile_drift\" ||\n pushGateClass === \"code_other\"\n ) {\n ctx.pushGateClass = pushGateClass;\n }\n if (Array.isArray(o.auditFindings)) {\n ctx.auditFindings = o.auditFindings\n .filter((x): x is string => typeof x === \"string\" && x.trim().length > 0)\n .slice(0, 20)\n .map((x) => x.trim().slice(0, 500));\n }\n if (o.artifactUrls && typeof o.artifactUrls === \"object\" && !Array.isArray(o.artifactUrls)) {\n const a = o.artifactUrls as Record<string, unknown>;\n const html = typeof a.htmlReport === \"string\" ? a.htmlReport.trim().slice(0, 1024) : null;\n if (html) ctx.artifactUrls = { htmlReport: html };\n }\n if (Array.isArray(o.failingTests)) {\n const tests: DevPipelineFailingTestRef[] = [];\n for (const item of o.failingTests.slice(0, FAILING_TESTS_MAX)) {\n if (!item || typeof item !== \"object\" || Array.isArray(item)) continue;\n const t = item as Record<string, unknown>;\n const name = typeof t.name === \"string\" ? t.name.trim() : \"\";\n if (!name) continue;\n tests.push({\n name: name.slice(0, 500),\n ...(typeof t.error === \"string\" ? { error: t.error.slice(0, 2000) } : {}),\n ...(typeof t.scenario === \"string\" ? { scenario: t.scenario.slice(0, 500) } : {}),\n });\n }\n if (tests.length) ctx.failingTests = tests;\n }\n const failurePhase = typeof o.failurePhase === \"string\" ? o.failurePhase.trim() : \"\";\n if (\n failurePhase === \"preflight\" ||\n failurePhase === \"auth_setup\" ||\n failurePhase === \"bddgen\" ||\n failurePhase === \"tests\" ||\n failurePhase === \"artifacts\" ||\n failurePhase === \"unknown\"\n ) {\n ctx.failurePhase = failurePhase;\n }\n if (Array.isArray(o.hints)) {\n ctx.hints = o.hints\n .filter((x): x is string => typeof x === \"string\" && x.trim().length > 0)\n .slice(0, 8)\n .map((x) => x.trim().slice(0, 500));\n }\n return ctx;\n}\n\nexport function formatFailureContextForAgent(ctx: DevPipelineFailureContext): string {\n const lines: string[] = [\n `失败类型: ${ctx.kind}`,\n `发生阶段: ${ctx.fromPhase}`,\n `时间: ${ctx.at}`,\n `摘要: ${ctx.summary}`,\n ];\n if (ctx.releaseTaskCode) lines.push(`发布任务: ${ctx.releaseTaskCode}`);\n if (ctx.buildJobName) lines.push(`构建 Job: ${ctx.buildJobName}`);\n if (ctx.argoAppName) {\n lines.push(\n `Argo 应用: ${ctx.argoAppName} (sync=${ctx.argoSyncStatus ?? \"?\"}, health=${ctx.argoHealthStatus ?? \"?\"})`,\n );\n }\n if (ctx.argoMessage) lines.push(`Argo 详情:\\n${ctx.argoMessage}`);\n if (ctx.validationJobCode) lines.push(`验证 Job: ${ctx.validationJobCode}`);\n if (ctx.failurePhase) lines.push(`验证失败阶段: ${ctx.failurePhase}`);\n if (ctx.securityJobCode) lines.push(`安全验证 Job: ${ctx.securityJobCode}`);\n if (ctx.failingTests?.length) {\n lines.push(\"失败用例:\");\n for (const t of ctx.failingTests) {\n lines.push(`- ${t.name}${t.scenario ? ` (${t.scenario})` : \"\"}`);\n if (t.error) lines.push(` ${t.error}`);\n }\n }\n if (ctx.artifactUrls?.htmlReport) lines.push(`报告: ${ctx.artifactUrls.htmlReport}`);\n if (ctx.stderrTail) lines.push(`stderr 尾部:\\n${ctx.stderrTail}`);\n if (ctx.buildFailedDockerfile) {\n lines.push(`失败 Dockerfile: ${ctx.buildFailedDockerfile}`);\n }\n if (ctx.buildErrorExcerpt) {\n lines.push(`构建错误摘录:\\n${ctx.buildErrorExcerpt}`);\n }\n if (ctx.buildLogTail) lines.push(`构建/发布日志尾部:\\n${ctx.buildLogTail}`);\n if (ctx.rawError && ctx.rawError !== ctx.summary) lines.push(`原始错误:\\n${ctx.rawError}`);\n if (ctx.hints?.length) {\n lines.push(\"操作建议:\");\n for (const h of ctx.hints.slice(0, 6)) lines.push(`- ${h}`);\n }\n if (ctx.pushGateKind) lines.push(`Push 门禁: ${ctx.pushGateKind}`);\n if (ctx.pushGateClass) lines.push(`Push 门禁分类: ${pushGateFailureClassLabel(ctx.pushGateClass)}`);\n if (ctx.auditFindings?.length) {\n lines.push(\"Audit 摘要:\");\n for (const line of ctx.auditFindings.slice(0, 10)) lines.push(`- ${line}`);\n }\n return lines.join(\"\\n\");\n}\n\nexport function pushGateFailureClassLabel(pushGateClass: PushGateFailureClass): string {\n switch (pushGateClass) {\n case \"transient_npm\":\n return \"npm 瞬时故障\";\n case \"baseline_bun_audit\":\n return \"基线依赖漏洞\";\n case \"lockfile_drift\":\n return \"lockfile 不一致\";\n case \"code_other\":\n return \"代码/门禁\";\n default:\n return pushGateClass;\n }\n}\n\nexport function buildFixJobChatContext(\n failure: DevPipelineFailureContext | null | undefined,\n agentBrief: string,\n): string {\n const parts: string[] = [];\n if (failure) {\n parts.push(\"【开发流水线 · 失败上下文】\", formatFailureContextForAgent(failure), \"\");\n }\n if (agentBrief.trim()) {\n parts.push(\"【修复指令】\", agentBrief.trim());\n }\n return parts.join(\"\\n\").trim().slice(0, 24_000);\n}\n\nexport function isInfraDeployFailureHeuristic(text: string): boolean {\n const hay = text.toLowerCase();\n return (\n hay.includes(\"ingress\") ||\n hay.includes(\"rfc 1123\") ||\n hay.includes(\"invalid value\") ||\n hay.includes(\"failed to apply\") ||\n hay.includes(\"gitops\") ||\n hay.includes(\"helm\") ||\n hay.includes(\"manifest\") ||\n hay.includes(\"outofsync\") ||\n hay.includes(\"feature_app_unhealthy\")\n );\n}\n\n/** Playwright / feature-env transient failures that should retry P5 without consuming fixAttemptCount. */\nexport function isTransientValidationFailureHeuristic(text: string): boolean {\n const hay = text.toLowerCase();\n\n if (\n hay.includes(\"expect(\") ||\n hay.includes(\"expected:\") ||\n hay.includes(\"received:\") ||\n hay.includes(\"undefined step\") ||\n hay.includes(\"step definition\") ||\n hay.includes(\"gherkin\") ||\n hay.includes(\"bddgen\") ||\n hay.includes(\"spec/behaviors\") ||\n hay.includes(\"tobevisible\") ||\n hay.includes(\"tobehidden\") ||\n ((hay.includes(\"selector\") || hay.includes(\"data-testid\")) &&\n (hay.includes(\"timeout\") || hay.includes(\"not found\")))\n ) {\n return false;\n }\n\n if (isInfraDeployFailureHeuristic(hay)) return true;\n\n return (\n hay.includes(\"503\") ||\n hay.includes(\"502 service\") ||\n hay.includes(\"504 gateway\") ||\n hay.includes(\"net::err_\") ||\n hay.includes(\"econnrefused\") ||\n hay.includes(\"econnreset\") ||\n hay.includes(\"etimedout\") ||\n hay.includes(\"enotfound\") ||\n hay.includes(\"socket hang up\") ||\n hay.includes(\"connection refused\") ||\n hay.includes(\"page.goto\") ||\n hay.includes(\"navigation timeout\") ||\n hay.includes(\"target page, context or browser has been closed\") ||\n hay.includes(\"browser has been closed\") ||\n hay.includes(\"feature deploy not ready\") ||\n hay.includes(\"feature application not found\") ||\n hay.includes(\"deploy not ready\") ||\n hay.includes(\"not synced\") ||\n (hay.includes(\"unhealthy\") && hay.includes(\"argo\")) ||\n (hay.includes(\"baseurl\") && hay.includes(\"unreachable\")) ||\n hay.includes(\"world_state_skip\") ||\n hay.includes(\"active_validation_job\")\n );\n}\n\nexport function isTransientValidationFailure(failure: DevPipelineFailureContext): boolean {\n const hay = failureContextHaystack(failure);\n if (failure.kind === \"deploy_runtime\") {\n return isInfraDeployFailureHeuristic(hay) || isTransientValidationFailureHeuristic(hay);\n }\n if (failure.kind !== \"validation\" && failure.fromPhase !== \"VALIDATE\") {\n return false;\n }\n return isTransientValidationFailureHeuristic(hay);\n}\n\n/** BuildKit / bun install errors that require committing bun.lock in the business repo. */\nexport function isTransientNpmTarballFailure(text: string): boolean {\n const hay = text.toLowerCase();\n if (hay.includes(\"lockfile had changes\") || hay.includes(\"lockfile is frozen\")) return false;\n if (hay.includes(\"missing in workspace\")) return false;\n return (\n hay.includes(\"fail extracting tarball\") ||\n hay.includes(\"failed to download\") ||\n (hay.includes(\"registry.npmjs.org\") && hay.includes(\"fail\"))\n );\n}\n\nexport function isPushGateBunAuditFailure(text: string): boolean {\n const hay = text.toLowerCase();\n return (\n hay.includes(\"push_gate:bun_audit\") ||\n hay.includes(\"bun audit failed before push\") ||\n isCompileGateBunAuditFailure(text)\n );\n}\n\n/** COMPILE_GATE `bun run audit` failure in local-check Job logs. */\nexport function isCompileGateBunAuditFailure(text: string): boolean {\n const hay = stripLocalVerifyLogTailForHeuristics(text).toLowerCase();\n if (isLocalCheckEntrypointInfraFailureHeuristic(hay)) return false;\n return (\n (hay.includes(\"bun audit\") || hay.includes(\"error: script \\\"audit\\\"\")) &&\n (hay.includes(\"vulnerabilit\") ||\n hay.includes(\"ghsa-\") ||\n hay.includes(\"dompurify\") ||\n hay.includes(\"moderate:\") ||\n hay.includes(\"high:\") ||\n hay.includes(\"critical:\"))\n );\n}\n\nexport function isLockfileDriftFailure(text: string): boolean {\n if (isTransientNpmTarballFailure(text)) return false;\n const hay = text.toLowerCase();\n return (\n hay.includes(\"lockfile had changes\") ||\n hay.includes(\"missing in workspace\") ||\n (hay.includes(\"docker-parity\") && hay.includes(\"frozen-lockfile\"))\n );\n}\n\nexport function isLockfileBuildFailureHeuristic(text: string): boolean {\n if (isTransientNpmTarballFailure(text)) return false;\n return isLockfileDriftFailure(text) || (() => {\n const hay = text.toLowerCase();\n return (\n hay.includes(\"frozen-lockfile\") ||\n hay.includes(\"lockfile is frozen\") ||\n (hay.includes(\"bun install\") && hay.includes(\"lockfile\"))\n );\n })();\n}\n\nexport function parsePushGateKind(text: string): PushGateFailureKind | null {\n const prefixed = /push_gate:([a-z_]+):/.exec(text);\n if (prefixed?.[1] === \"docker_parity\") return \"docker_parity\";\n if (prefixed?.[1] === \"frozen_lockfile\") return \"frozen_lockfile\";\n if (prefixed?.[1] === \"bun_audit\") return \"bun_audit\";\n if (prefixed?.[1] === \"check_behaviors\") return \"check_behaviors\";\n const hay = text.toLowerCase();\n if (hay.includes(\"docker-parity\")) return \"docker_parity\";\n if (hay.includes(\"check:behaviors failed before push\")) return \"check_behaviors\";\n if (hay.includes(\"bun audit failed before push\")) return \"bun_audit\";\n if (hay.includes(\"frozen-lockfile\") && hay.includes(\"before push\")) return \"frozen_lockfile\";\n return null;\n}\n\nexport function classifyAgentPushGateFailure(\n failure: DevPipelineFailureContext,\n): PushGateFailureClass | null {\n if (failure.kind !== \"agent_job\" || failure.fromPhase !== \"IMPLEMENTATION\") return null;\n const hay = stripLocalVerifyLogTailForHeuristics(failureContextHaystack(failure));\n const hasPushGateSignal =\n hay.includes(\"push_gate:\") ||\n hay.includes(\"before push\") ||\n hay.includes(\"docker-parity\") ||\n hay.includes(\"bun audit failed\");\n if (!hasPushGateSignal) return null;\n\n if (isTransientNpmTarballFailure(hay)) return \"transient_npm\";\n if (isPushGateBunAuditFailure(hay)) {\n const branchDepsClue =\n hay.includes(\"package.json\") || hay.includes(\"bun.lock\") || hay.includes(\"bun update\");\n return branchDepsClue ? \"code_other\" : \"baseline_bun_audit\";\n }\n if (isLockfileDriftFailure(hay)) return \"lockfile_drift\";\n return \"code_other\";\n}\n\n/** Classify COMPILE_GATE audit / deps failures for fix-attempt accounting. */\nexport function classifyCompileGateFailure(\n failure: DevPipelineFailureContext,\n): PushGateFailureClass | null {\n if (failure.kind !== \"compile_gate\" && failure.fromPhase !== \"COMPILE_GATE\") return null;\n const hay = stripLocalVerifyLogTailForHeuristics(failureContextHaystack(failure));\n if (isCompileGateBunAuditFailure(hay)) {\n const branchDepsClue =\n hay.includes(\"override\") ||\n hay.includes(\"bun update\") ||\n (hay.includes(\"package.json\") && hay.includes(\"dompurify\"));\n return branchDepsClue ? \"code_other\" : \"baseline_bun_audit\";\n }\n return null;\n}\n\nexport function classifyDevPipelineFixFailureClass(\n failure: DevPipelineFailureContext,\n): PushGateFailureClass | null {\n return (\n failure.pushGateClass ??\n classifyAgentPushGateFailure(failure) ??\n classifyCompileGateFailure(failure)\n );\n}\n\nexport function enrichCompileGateFailureContext(\n failure: DevPipelineFailureContext,\n): DevPipelineFailureContext {\n const compileGateClass = classifyCompileGateFailure(failure);\n if (!compileGateClass) return failure;\n return {\n ...failure,\n pushGateClass: failure.pushGateClass ?? compileGateClass,\n };\n}\n\nexport function enrichPushGateFailureContext(\n failure: DevPipelineFailureContext,\n): DevPipelineFailureContext {\n const withCompile = enrichCompileGateFailureContext(failure);\n const hay = failureContextHaystack(withCompile);\n const pushGateClass =\n withCompile.pushGateClass ?? classifyDevPipelineFixFailureClass(withCompile);\n const pushGateKind = withCompile.pushGateKind ?? parsePushGateKind(hay) ?? undefined;\n if (!pushGateClass && !pushGateKind) return withCompile;\n return {\n ...withCompile,\n ...(pushGateClass ? { pushGateClass } : {}),\n ...(pushGateKind ? { pushGateKind } : {}),\n };\n}\n\nexport const TRANSIENT_PUSH_GATE_AGENT_BRIEF =\n \"无需修改业务代码:上一次失败为 Agent Pod push 门禁瞬时故障(npm tarball 下载/解压)。请重试 push 门禁;若 check/parity 已通过,确保 commit 已 push 后继续流水线。\";\n\nexport const BASELINE_BUN_AUDIT_AGENT_BRIEF =\n \"bun audit 失败且为仓库基线依赖漏洞(非本需求引入)。请在 dev/main 添加 package.json overrides 并更新 bun.lock,或在本分支仅做 deps 修复后 push;与功能代码无关。\";\n\nexport const LOCKFILE_FIX_AGENT_BRIEF =\n \"在 feature 分支根目录运行 `bun install`,将更新后的 bun.lock 一并 commit 并 push;若新增了 workspace package,同步更新 apps/server/Dockerfile 与 apps/web/Dockerfile 中的 COPY package.json 列表。若 build 失败来自平台 Dockerfile 漏项,先从 main/dev rebase 同步平台修复,再继续本卡功能实现。\";\n\nexport const BUILD_DOCKERFILE_FIX_AGENT_BRIEF_PREFIX =\n \"DEPLOY 镜像构建失败。优先根据「失败 Dockerfile / 构建错误摘录」修复对应 Dockerfile、build-runtime externals 或源码;本地用 `bun run build:runtime-images` 与 `bun run check:runtime-images:docker-context` 验证。勿将 test.skip、spec drift、dompurify warn 等交付债当作 build 根因。\";\n\nexport const LOCAL_SECURITY_FIX_AGENT_BRIEF =\n \"STATIC_SECURITY 静态安全扫描失败。按扫描器类型修复 feature 分支:deps — 运行 `bun audit`,升级有 high/critical advisory 的依赖并 commit 更新后的 bun.lock;secrets — 从仓库移除 token/密钥(改用 env/Secret,勿提交 .env);sast — 修复 semgrep finding,或仅在合理时在 nvwa.semgrep.yml / 扫描排除中调整。修复后 push,流水线将重跑 STATIC_SECURITY。\";\n\nexport function failureContextHaystack(ctx: DevPipelineFailureContext): string {\n return [\n ctx.summary,\n ctx.buildFailedDockerfile ?? \"\",\n ctx.buildErrorExcerpt ?? \"\",\n ctx.failurePhase ?? \"\",\n ctx.hints?.join(\"\\n\") ?? \"\",\n ctx.buildLogTail ?? \"\",\n ctx.rawError ?? \"\",\n ctx.argoMessage ?? \"\",\n ].join(\"\\n\");\n}\n\n/** Drop unit-test harness lines so LOCAL_VERIFY log tails do not false-trigger infra heuristics. */\nexport function stripLocalVerifyLogTailForHeuristics(haystack: string): string {\n return haystack\n .split(\"\\n\")\n .filter((line) => {\n const t = line.trim();\n if (!t) return false;\n if (/^\\(pass\\)\\s/.test(t) || /^\\(fail\\)\\s/.test(t)) return false;\n // tail -c truncation can drop the \"(pass) suite\" prefix and leave \"suite > test …\" fragments.\n if (/ > /.test(t) && !/^\\[/.test(t)) return false;\n if (/\\.test\\.ts:/.test(t)) return false;\n if (/^bun test v/.test(t)) return false;\n if (/^Ran \\d+ tests/.test(t)) return false;\n if (/^\\d+ pass$/.test(t) || /^\\d+ fail$/.test(t)) return false;\n return true;\n })\n .join(\"\\n\");\n}\n\nfunction isExplicitLocalCheckPlatformHaystack(hay: string): boolean {\n return (\n hay.includes(\"imagemap\") ||\n hay.includes(\"nvwa-os-local-check\") ||\n hay.includes(\"dockerfile.local-check\") ||\n hay.includes(\"/usr/local/bin/nvwa-local-security\") ||\n (hay.includes(\"镜像\") &&\n (hay.includes(\"local-check\") || hay.includes(\"local-security\") || hay.includes(\"builder\")))\n );\n}\n\n/** local-check entrypoint / callback orphan failures (platform, not feature codegen). */\nexport function isLocalCheckEntrypointInfraFailureHeuristic(haystack: string): boolean {\n const hay = stripLocalVerifyLogTailForHeuristics(haystack).toLowerCase();\n return (\n hay.includes(\"illegal number\") ||\n hay.includes(\"nvwa-local-verify-entrypoint\") ||\n hay.includes(\"invalid literal for int\") ||\n hay.includes(\"completed but no callback received\")\n );\n}\n\n/** K8s reconcile without callback — often entrypoint crash; treat as infra when repeated. */\nexport function isReconciledBackoffInfraFailureHeuristic(haystack: string): boolean {\n const hay = stripLocalVerifyLogTailForHeuristics(haystack).toLowerCase();\n if (!hay.includes(\"reconciled:\")) return false;\n return (\n hay.includes(\"backoff limit\") ||\n hay.includes(\"no callback received\") ||\n hay.includes(\"completed but no callback\")\n );\n}\n\n/** True when BEHAVIORS_GATE failure looks like Gherkin/bddgen, not platform infra. */\nexport function isBehaviorsGateCodegenFailureHeuristic(haystack: string): boolean {\n const hay = stripLocalVerifyLogTailForHeuristics(haystack).toLowerCase();\n if (isLocalCheckEntrypointInfraFailureHeuristic(hay)) return false;\n if (isExplicitLocalCheckPlatformHaystack(hay)) return false;\n return (\n hay.includes(\"undefined step\") ||\n hay.includes(\"step definition\") ||\n hay.includes(\"bddgen\") ||\n hay.includes(\"gherkin\") ||\n hay.includes(\"check-gherkin\") ||\n hay.includes(\"spec/behaviors\") ||\n hay.includes(\"e2e/steps\") ||\n hay.includes(\"no tests found\") ||\n (hay.includes(\"check:behaviors\") &&\n (hay.includes(\"fail\") || hay.includes(\"error\")) &&\n !hay.includes(\"[compile-gate]\"))\n );\n}\n\n/** LOCAL_VERIFY security failures caused by platform local-check image / imageMap (not feature repo fixes). */\nexport function isLocalSecurityInfraFailureHeuristic(\n haystack: string,\n failure?: DevPipelineFailureContext | null,\n opts?: { allowWeakScannerSignals?: boolean },\n): boolean {\n const hay = stripLocalVerifyLogTailForHeuristics(haystack).toLowerCase();\n\n if (isExplicitLocalCheckPlatformHaystack(hay)) {\n return true;\n }\n\n if (isLocalCheckEntrypointInfraFailureHeuristic(hay)) {\n return true;\n }\n\n if (opts?.allowWeakScannerSignals !== true) {\n return false;\n }\n\n if (failure?.kind !== \"local_security\" && failure?.kind !== \"local_verify\") {\n return false;\n }\n\n const scannerSignal =\n hay.includes(\"bun audit\") ||\n hay.includes(\"bun pm audit\") ||\n hay.includes(\"scanner deps\") ||\n hay.includes(\"[local-security]\") ||\n hay.includes(\"local security scan\");\n\n if (!scannerSignal) return false;\n\n const repoCveFixClue =\n hay.includes(\"cve-\") ||\n hay.includes(\"vulnerable\") ||\n (hay.includes(\"bun audit\") && (hay.includes(\"upgrade\") || hay.includes(\"update \")));\n\n if (repoCveFixClue) return false;\n\n return (\n hay.includes(\"nvwa-local-security\") ||\n hay.includes(\"nvwa-os-local-check\") ||\n hay.includes(\"dockerfile.local-check\") ||\n hay.includes(\"imagemap\")\n );\n}\n\nexport type ResolveLocalSecurityInfraBlockedInput = {\n haystack: string;\n failure?: DevPipelineFailureContext | null;\n security?: LocalSecurityCallbackResult | null;\n /** Same failure fingerprint as previous attempt — allows weaker log heuristics. */\n repeatedFailure?: boolean;\n};\n\n/** Decide whether LOCAL_VERIFY failure should stop at fix_infra_blocked (wait for platform). */\nexport function resolveLocalSecurityInfraBlocked(\n input: ResolveLocalSecurityInfraBlockedInput,\n): boolean {\n if (input.security?.scanners?.length) {\n return isLocalSecurityInfraFromScanners(input.security);\n }\n return isLocalSecurityInfraFailureHeuristic(input.haystack, input.failure, {\n allowWeakScannerSignals: input.repeatedFailure === true,\n });\n}\n\nexport type InfraWaitPipelineSlice = {\n lastTriage?: { fixCategory?: string } | null;\n};\n\n/**\n * Whether a repeated failure should stop at fix_infra_blocked (platform wait).\n */\nexport function isInfraWaitFailure(\n failure: DevPipelineFailureContext,\n pipeline?: InfraWaitPipelineSlice | null,\n): boolean {\n const hay = stripLocalVerifyLogTailForHeuristics(failureContextHaystack(failure));\n const hayLower = hay.toLowerCase();\n\n if (failure.kind === \"build\") {\n if (isLockfileBuildFailureHeuristic(hay)) return false;\n return (\n isExplicitLocalCheckPlatformHaystack(hayLower) ||\n hayLower.includes(\"imagemap\") ||\n isLocalSecurityInfraFailureHeuristic(hay, failure, { allowWeakScannerSignals: true })\n );\n }\n\n if (failure.kind === \"deploy_runtime\") {\n return pipeline?.lastTriage?.fixCategory === \"infra\";\n }\n\n if (\n failure.kind === \"static_security\" ||\n failure.kind === \"local_security\" ||\n failure.kind === \"local_verify\"\n ) {\n return resolveLocalSecurityInfraBlocked({ haystack: hay, failure, repeatedFailure: true });\n }\n\n if (pipeline?.lastTriage?.fixCategory === \"code\") {\n return false;\n }\n\n if (failure.kind === \"validation\") {\n return false;\n }\n\n if (\n failure.kind === \"compile_gate\" ||\n failure.fromPhase === \"COMPILE_GATE\" ||\n failure.fromPhase === \"BEHAVIORS_GATE\"\n ) {\n if (\n isLocalCheckEntrypointInfraFailureHeuristic(hay) ||\n isExplicitLocalCheckPlatformHaystack(hayLower) ||\n isReconciledBackoffInfraFailureHeuristic(hay)\n ) {\n return true;\n }\n }\n\n return false;\n}\n\nconst LOCAL_SECURITY_INFRA_SUFFIX =\n \"(服务端纠偏:local-check 镜像/平台问题,非 feature 代码修复)\";\n\n/** Server-side guard: build/lockfile failures must not stop at infra wait. */\nexport function normalizeTriageDecision(\n failure: DevPipelineFailureContext | null | undefined,\n decision: DevPipelineTriageDecision,\n): DevPipelineTriageDecision {\n if (!failure) return decision;\n\n const pushGateClass = classifyAgentPushGateFailure(failure);\n if (pushGateClass === \"transient_npm\" && decision.fixCategory === \"code\") {\n return {\n targetPhase: \"IMPLEMENTATION\",\n fixCategory: \"retry_only\",\n rationale: `${decision.rationale}(服务端纠偏:npm registry 瞬时故障,重试 push 门禁)`.slice(\n 0,\n 2000,\n ),\n agentBrief: decision.agentBrief.includes(\"重试\")\n ? decision.agentBrief\n : TRANSIENT_PUSH_GATE_AGENT_BRIEF,\n };\n }\n\n const hay = stripLocalVerifyLogTailForHeuristics(failureContextHaystack(failure));\n\n if (\n (failure.kind === \"validation\" || failure.fromPhase === \"VALIDATE\") &&\n isTransientValidationFailureHeuristic(hay) &&\n decision.fixCategory === \"code\"\n ) {\n return {\n targetPhase: \"VALIDATE\",\n fixCategory: \"retry_only\",\n rationale: `${decision.rationale}(服务端纠偏:验证环境瞬时故障,仅重跑 Playwright)`.slice(\n 0,\n 2000,\n ),\n agentBrief: decision.agentBrief.includes(\"重试\")\n ? decision.agentBrief\n : \"仅重跑集成验证(INTEGRATION_VERIFY),勿改业务代码或 Gherkin。\",\n };\n }\n\n if (\n decision.fixCategory === \"code\" &&\n isLocalSecurityInfraFailureHeuristic(hay, failure, { allowWeakScannerSignals: true })\n ) {\n const targetPhase =\n failure.fromPhase === \"STATIC_SECURITY\" ||\n failure.kind === \"local_security\" ||\n failure.kind === \"static_security\"\n ? \"STATIC_SECURITY\"\n : failure.fromPhase === \"LOCAL_VERIFY\" || failure.fromPhase === \"COMPILE_GATE\"\n ? \"COMPILE_GATE\"\n : decision.targetPhase;\n return {\n targetPhase,\n fixCategory: \"infra\",\n rationale: `${decision.rationale}${LOCAL_SECURITY_INFRA_SUFFIX}`.slice(0, 2000),\n agentBrief: decision.agentBrief,\n };\n }\n\n const lockfile = isLockfileBuildFailureHeuristic(hay);\n const buildMisInfra = failure.kind === \"build\" && decision.fixCategory === \"infra\";\n\n if (failure.kind === \"build\") {\n if (decision.fixCategory === \"none\") return decision;\n\n const dockerfile = failure.buildFailedDockerfile?.trim();\n const excerpt = failure.buildErrorExcerpt?.trim();\n const buildBriefParts = [BUILD_DOCKERFILE_FIX_AGENT_BRIEF_PREFIX];\n if (dockerfile) buildBriefParts.push(`失败 Dockerfile: ${dockerfile}`);\n if (excerpt) buildBriefParts.push(`错误: ${excerpt.split(\"\\n\")[0]?.slice(0, 300) ?? excerpt}`);\n const buildBrief = buildBriefParts.join(\"\\n\");\n const agentBrief =\n decision.agentBrief.includes(\"失败 Dockerfile\") || decision.agentBrief.includes(\"build-runtime\")\n ? decision.agentBrief\n : `${buildBrief}\\n\\n${decision.agentBrief}`.slice(0, 8000);\n\n if (buildMisInfra || lockfile) {\n const suffix = \"(服务端纠偏:镜像/构建失败不应归类为 infra,需先代码修复)\";\n let brief = agentBrief;\n if (lockfile && !brief.includes(\"bun.lock\")) {\n brief = `${LOCKFILE_FIX_AGENT_BRIEF}\\n\\n${brief}`.slice(0, 8000);\n }\n return {\n targetPhase: \"IMPLEMENTATION\",\n fixCategory: \"code\",\n rationale: `${decision.rationale}${suffix}`.slice(0, 2000),\n agentBrief: brief,\n };\n }\n\n if (decision.fixCategory === \"code\" && decision.targetPhase === \"IMPLEMENTATION\") {\n return { ...decision, agentBrief };\n }\n\n return {\n targetPhase: \"IMPLEMENTATION\",\n fixCategory: \"code\",\n rationale: decision.rationale.slice(0, 2000),\n agentBrief,\n };\n }\n\n if (!buildMisInfra && !lockfile) return decision;\n if (decision.fixCategory === \"none\") return decision;\n\n const suffix = \"(服务端纠偏:镜像/构建失败不应归类为 infra,需先代码修复)\";\n let agentBrief = decision.agentBrief;\n if (lockfile && !agentBrief.includes(\"bun.lock\")) {\n agentBrief = `${LOCKFILE_FIX_AGENT_BRIEF}\\n\\n${agentBrief}`.slice(0, 8000);\n }\n\n return {\n targetPhase: \"IMPLEMENTATION\",\n fixCategory: \"code\",\n rationale: `${decision.rationale}${suffix}`.slice(0, 2000),\n agentBrief,\n };\n}\n\nexport function parseDevPipelineTriageDecision(raw: unknown): DevPipelineTriageDecision | null {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return null;\n const o = raw as Record<string, unknown>;\n const targetPhase = typeof o.targetPhase === \"string\" ? o.targetPhase.trim() : \"\";\n const fixCategory = typeof o.fixCategory === \"string\" ? o.fixCategory.trim() : \"\";\n const rationale = typeof o.rationale === \"string\" ? o.rationale.trim() : \"\";\n const agentBrief = typeof o.agentBrief === \"string\" ? o.agentBrief.trim() : \"\";\n if (\n !(DEV_PIPELINE_TRIAGE_TARGET_PHASES as readonly string[]).includes(targetPhase) ||\n !(DEV_PIPELINE_FIX_CATEGORIES as readonly string[]).includes(fixCategory) ||\n !rationale ||\n !agentBrief\n ) {\n return null;\n }\n return {\n targetPhase: targetPhase as DevPipelineTriageTargetPhase,\n fixCategory: fixCategory as DevPipelineFixCategory,\n rationale: rationale.slice(0, 2000),\n agentBrief: agentBrief.slice(0, 8000),\n };\n}\n",
|
|
12
|
+
"import { formatIntakeDisplayLabel } from \"./requirement-intake\";\n\n/** Prompt block for Agent optional Read of requirement intake images. */\n\nexport type MaterializedIntakeImageRef = {\n id: string;\n fileName: string;\n intakeIndex: number;\n localPath: string;\n};\n\nexport function formatRequirementIntakeImagesPromptBlock(opts: {\n materialized: MaterializedIntakeImageRef[];\n callbackBaseUrl?: string | null;\n}): string {\n if (opts.materialized.length === 0) return \"\";\n const lines = opts.materialized.map((m) => {\n const label = formatIntakeDisplayLabel(m.intakeIndex, m.fileName);\n return `- ${label} → ${m.localPath}`;\n });\n const fallback =\n opts.callbackBaseUrl?.trim()\n ? [\n \"\",\n \"Fallback fetch (same Job only; do not use Studio project URLs):\",\n `GET ${opts.callbackBaseUrl.trim()}/<attachmentId>/content`,\n \"Header: X-Nvwa-Callback-Secret: (from NVWA_CALLBACK_SECRET env)\",\n ].join(\"\\n\")\n : \"\";\n return [\n \"## Requirement intake images (optional Read)\",\n \"Server pre-analysis is in requirementRawInput under \\\"## 图片理解(图N)\\\".\",\n \"Refer to images as 图1 / 图2 — same labels as rawInput headings.\",\n \"Use Read on local files only when UI details, colors, or layout matter:\",\n ...lines,\n fallback,\n ]\n .filter(Boolean)\n .join(\"\\n\");\n}\n\n/** Append intake block to chat context; prefer keeping the intake block when truncating. */\nexport function appendIntakeImagesToChatContext(\n chatContext: string,\n block: string,\n maxLen = 24_000,\n): string {\n const trimmedBlock = block.trim();\n if (!trimmedBlock) return chatContext;\n const head = chatContext.trim();\n const combined = head ? `${head}\\n\\n${trimmedBlock}` : trimmedBlock;\n if (combined.length <= maxLen) return combined;\n const budget = maxLen - trimmedBlock.length - 16;\n if (budget < 64) return trimmedBlock.slice(0, maxLen);\n const truncatedHead =\n head.length > budget ? `…(truncated)\\n\\n${head.slice(head.length - budget + 16)}` : head;\n return truncatedHead ? `${truncatedHead}\\n\\n${trimmedBlock}` : trimmedBlock;\n}\n",
|
|
13
|
+
"import { mkdirSync } from \"node:fs\";\n\n/** Persistent workspace + Cursor home for per-requirement Deployment workers. */\n\nexport const AGENT_WORKSPACE_DIR =\n (process.env.NVWA_AGENT_WORKSPACE_DIR ?? \"\").trim() || \"/workspace/repo\";\n\n/** PVC-mounted Cursor home (source for fork copy). */\nexport const AGENT_CURSOR_HOME_DIR =\n (process.env.NVWA_AGENT_CURSOR_HOME_DIR ?? \"\").trim() || \"/var/nvwa/cursor-home\";\n\nexport const AGENT_OUTPUT_ROOT =\n (process.env.NVWA_AGENT_OUTPUT_ROOT ?? \"\").trim() || \"/var/nvwa/agent-out\";\n\nlet activeCursorHomeDir: string | null = null;\n\nexport function setActiveCursorHomeDir(dir: string): void {\n activeCursorHomeDir = dir;\n}\n\nexport function resetActiveCursorHomeDir(): void {\n activeCursorHomeDir = null;\n}\n\nexport function getActiveCursorHomeDir(): string {\n return activeCursorHomeDir ?? AGENT_CURSOR_HOME_DIR;\n}\n\nexport function applyAgentWorkerPathsEnv(): void {\n const cursorHome = getActiveCursorHomeDir();\n mkdirSync(cursorHome, { recursive: true });\n mkdirSync(AGENT_OUTPUT_ROOT, { recursive: true });\n mkdirSync(AGENT_WORKSPACE_DIR, { recursive: true });\n process.env.HOME = cursorHome;\n}\n",
|
|
14
|
+
"import { execFileSync } from \"node:child_process\";\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport {\n parseRewriteGateResult,\n rewriteGateAllowsSkip,\n type RewriteGateDecision,\n type RewriteGateResult,\n} from \"../common/src/rewrite-gate.ts\";\n\nconst SPEC_PREFIXES = [\n \"spec/foundation/\",\n \"spec/capabilities/\",\n \"spec/behaviors/\",\n \"spec/ui-contracts/\",\n];\n\nconst GATE_STUB_ENV = \"NVWA_E2E_REWRITE_GATE_STUB\";\nconst GATE_FORCE_FULL_ENV = \"NVWA_E2E_REWRITE_GATE_FORCE_FULL\";\n\nexport type RewriteGateRunInput = {\n dir: string;\n integrationBranch: string;\n deltaText: string;\n title: string;\n rawInput: string;\n rewriteForceFull?: boolean;\n llmBaseUrl?: string | null;\n llmModel?: string | null;\n llmApiKey?: string | null;\n specRefsHint?: {\n l2CapabilityPath?: string;\n suggestedBehaviorPaths?: string[];\n };\n outputPath: string;\n};\n\nfunction runGit(args: string[], cwd: string): string {\n return execFileSync(\"git\", args, { cwd, encoding: \"utf-8\", maxBuffer: 4 * 1024 * 1024 }).trim();\n}\n\nfunction listSpecBaselinePaths(dir: string, integrationBranch: string): string[] {\n try {\n const out = runGit(\n [\"diff\", \"--name-only\", `origin/${integrationBranch}...HEAD`, \"--\", \"spec/\"],\n dir,\n );\n return out\n .split(/\\r?\\n/)\n .map((l) => l.trim())\n .filter((p) => SPEC_PREFIXES.some((pref) => p.startsWith(pref)) && !p.includes(\"/drafts/\"));\n } catch {\n return [];\n }\n}\n\nfunction readFileExcerpt(dir: string, relPath: string, maxChars: number): string {\n const full = join(dir, relPath);\n if (!existsSync(full)) return \"\";\n try {\n const text = readFileSync(full, \"utf-8\");\n return text.length <= maxChars ? text : `${text.slice(0, maxChars)}\\n…(truncated)`;\n } catch {\n return \"\";\n }\n}\n\nfunction buildBaselineSummary(dir: string, paths: string[], hint: RewriteGateRunInput[\"specRefsHint\"]): string {\n const ordered = [...paths];\n if (hint?.l2CapabilityPath && !ordered.includes(hint.l2CapabilityPath)) {\n ordered.unshift(hint.l2CapabilityPath);\n }\n for (const p of hint?.suggestedBehaviorPaths ?? []) {\n if (!ordered.includes(p)) ordered.push(p);\n }\n const unique = [...new Set(ordered)].slice(0, 8);\n const blocks: string[] = [];\n for (const rel of unique) {\n const excerpt = readFileExcerpt(dir, rel, 4000);\n if (excerpt) blocks.push(`### ${rel}\\n${excerpt}`);\n }\n return blocks.join(\"\\n\\n\");\n}\n\nfunction gateSystemPrompt(): string {\n return [\n \"你是 Nvwa rewrite gate 助手。\",\n \"任务:判断用户本次补充(delta)相对 feature 分支已有 spec 是否改变行为边界、验收标准或操作流。\",\n \"输出 exactly one JSON object,无 Markdown 围栏。\",\n 'Schema: { \"decision\": \"skip\"|\"l3_only\"|\"l2_l3\"|\"full\", \"confidence\": \"high\"|\"medium\"|\"low\", \"reason\": \"中文一句话\", \"touchedDimensions\": string[], \"baselinePaths\": string[] }',\n \"规则:\",\n \"- 仅举例/澄清/措辞且与 L2 验收一致 → skip + high\",\n \"- 与 spec 矛盾 → full + medium,不得 skip\",\n \"- 新验收/新能力域/新 testid 流程 → full 或 l2_l3/l3_only\",\n \"- confidence 非 high 时 decision 不得为 skip\",\n \"- 无 spec 基线时 decision 必须为 full\",\n ].join(\"\\n\");\n}\n\nfunction buildGateUserPrompt(input: RewriteGateRunInput, baselinePaths: string[], baselineSummary: string): string {\n const delta = input.deltaText.trim() || input.rawInput.trim();\n return [\n `需求标题:${input.title}`,\n \"\",\n \"## 本次 delta(补充对话/变更)\",\n delta.slice(0, 12000),\n \"\",\n \"## feature 分支已有 spec 路径\",\n baselinePaths.length ? baselinePaths.join(\"\\n\") : \"(无 — 首次 rewrite,必须 full)\",\n \"\",\n \"## spec 摘要\",\n baselineSummary || \"(无可读 spec 文件)\",\n ].join(\"\\n\");\n}\n\nasync function callFlashGate(\n input: RewriteGateRunInput,\n userPrompt: string,\n): Promise<RewriteGateResult | null> {\n const baseUrl = input.llmBaseUrl?.trim();\n const model = input.llmModel?.trim() || \"nvwa-flash-model\";\n const apiKey = input.llmApiKey?.trim();\n if (!baseUrl || !apiKey) return null;\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), 15_000);\n try {\n const res = await fetch(`${baseUrl.replace(/\\/$/, \"\")}/chat/completions`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n model,\n temperature: 0.2,\n messages: [\n { role: \"system\", content: gateSystemPrompt() },\n { role: \"user\", content: userPrompt },\n ],\n }),\n signal: controller.signal,\n });\n if (!res.ok) return null;\n const json = (await res.json()) as {\n choices?: Array<{ message?: { content?: string } }>;\n };\n const content = json.choices?.[0]?.message?.content ?? \"\";\n const objectText = extractJsonObject(content);\n if (!objectText) return null;\n return parseRewriteGateResult(JSON.parse(objectText));\n } catch {\n return null;\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction extractJsonObject(text: string): string | null {\n const start = text.indexOf(\"{\");\n const end = text.lastIndexOf(\"}\");\n if (start < 0 || end <= start) return null;\n return text.slice(start, end + 1);\n}\n\nfunction stubFromEnv(): RewriteGateResult | null {\n const raw = process.env[GATE_STUB_ENV]?.trim();\n if (!raw) return null;\n if (raw === \"skip\") {\n return {\n decision: \"skip\",\n confidence: \"high\",\n reason: \"E2E stub:与已有 spec 一致\",\n touchedDimensions: [],\n baselinePaths: [\"spec/capabilities/stub.md\"],\n };\n }\n if (raw === \"full\") {\n return {\n decision: \"full\",\n confidence: \"high\",\n reason: \"E2E stub:需要全量 rewrite\",\n touchedDimensions: [\"acceptance\"],\n baselinePaths: [],\n };\n }\n return parseRewriteGateResult(JSON.parse(raw));\n}\n\nexport function fallbackRewriteGateResult(reason: string): RewriteGateResult {\n return {\n decision: \"full\",\n confidence: \"low\",\n reason,\n touchedDimensions: [],\n baselinePaths: [],\n lastError: reason,\n };\n}\n\nexport async function runRewriteGate(input: RewriteGateRunInput): Promise<RewriteGateResult> {\n if (input.rewriteForceFull || process.env[GATE_FORCE_FULL_ENV] === \"1\") {\n const result: RewriteGateResult = {\n decision: \"full\",\n confidence: \"high\",\n reason: \"用户或环境要求强制全量分析\",\n touchedDimensions: [],\n baselinePaths: [],\n };\n writeFileSync(input.outputPath, JSON.stringify(result, null, 2), \"utf-8\");\n return result;\n }\n\n const stub = stubFromEnv();\n if (stub) {\n writeFileSync(input.outputPath, JSON.stringify(stub, null, 2), \"utf-8\");\n return stub;\n }\n\n const baselinePaths = listSpecBaselinePaths(input.dir, input.integrationBranch);\n if (baselinePaths.length === 0) {\n const result: RewriteGateResult = {\n decision: \"full\",\n confidence: \"high\",\n reason: \"feature 分支尚无 spec 产出,执行全量 L1–L3\",\n touchedDimensions: [],\n baselinePaths: [],\n };\n writeFileSync(input.outputPath, JSON.stringify(result, null, 2), \"utf-8\");\n return result;\n }\n\n const baselineSummary = buildBaselineSummary(input.dir, baselinePaths, input.specRefsHint);\n const userPrompt = buildGateUserPrompt(input, baselinePaths, baselineSummary);\n const parsed = await callFlashGate(input, userPrompt);\n const result =\n parsed ??\n fallbackRewriteGateResult(\"LLM gate 不可用或解析失败,回退全量 rewrite\");\n\n if (result.decision === \"skip\" && !rewriteGateAllowsSkip(result)) {\n result.decision = \"full\";\n result.reason = `${result.reason}(置信度不足,改为全量)`;\n }\n\n writeFileSync(input.outputPath, JSON.stringify(result, null, 2), \"utf-8\");\n return result;\n}\n\nexport function readRewriteGateJson(path: string): RewriteGateResult | null {\n if (!existsSync(path)) return null;\n try {\n return parseRewriteGateResult(JSON.parse(readFileSync(path, \"utf-8\")));\n } catch {\n return null;\n }\n}\n\nexport function effectiveRewritePhases(decision: RewriteGateDecision): (\"l1\" | \"l2\" | \"l3\")[] {\n switch (decision) {\n case \"skip\":\n return [];\n case \"l3_only\":\n return [\"l3\"];\n case \"l2_l3\":\n return [\"l2\", \"l3\"];\n case \"full\":\n return [\"l1\", \"l2\", \"l3\"];\n }\n}\n",
|
|
15
|
+
"/** SSOT shapes for rewrite gate — see spec/capabilities/rewrite-gate.md */\n\nexport const REWRITE_GATE_DECISIONS = [\"skip\", \"l3_only\", \"l2_l3\", \"full\"] as const;\nexport type RewriteGateDecision = (typeof REWRITE_GATE_DECISIONS)[number];\n\nexport const REWRITE_GATE_CONFIDENCE = [\"high\", \"medium\", \"low\"] as const;\nexport type RewriteGateConfidence = (typeof REWRITE_GATE_CONFIDENCE)[number];\n\nexport type RewriteGateResult = {\n decision: RewriteGateDecision;\n confidence: RewriteGateConfidence;\n reason: string;\n touchedDimensions: string[];\n baselinePaths: string[];\n lastError?: string;\n};\n\nexport type RewriteGateArtifactEntry = RewriteGateResult & {\n lastJobCode: string;\n updatedAt: string;\n};\n\nexport type RewriteGateArtifact = {\n lastJobCode: string;\n updatedAt: string;\n decision: RewriteGateDecision;\n confidence: RewriteGateConfidence;\n reason: string;\n touchedDimensions: string[];\n baselinePaths: string[];\n lastError?: string;\n history: RewriteGateArtifactEntry[];\n};\n\nexport function isRewriteGateDecision(v: string): v is RewriteGateDecision {\n return (REWRITE_GATE_DECISIONS as readonly string[]).includes(v);\n}\n\nexport function isRewriteGateConfidence(v: string): v is RewriteGateConfidence {\n return (REWRITE_GATE_CONFIDENCE as readonly string[]).includes(v);\n}\n\nexport function parseRewriteGateResult(raw: unknown): RewriteGateResult | null {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return null;\n const o = raw as Record<string, unknown>;\n const decision = typeof o.decision === \"string\" ? o.decision.trim() : \"\";\n const confidence = typeof o.confidence === \"string\" ? o.confidence.trim() : \"\";\n const reason = typeof o.reason === \"string\" ? o.reason.trim() : \"\";\n if (!isRewriteGateDecision(decision) || !isRewriteGateConfidence(confidence) || !reason) {\n return null;\n }\n const touchedDimensions = Array.isArray(o.touchedDimensions)\n ? o.touchedDimensions.filter((x): x is string => typeof x === \"string\" && x.trim() !== \"\")\n : [];\n const baselinePaths = Array.isArray(o.baselinePaths)\n ? o.baselinePaths.filter((x): x is string => typeof x === \"string\" && x.trim() !== \"\")\n : [];\n const lastError = typeof o.lastError === \"string\" ? o.lastError.trim() : undefined;\n return {\n decision,\n confidence,\n reason,\n touchedDimensions,\n baselinePaths,\n ...(lastError ? { lastError } : {}),\n };\n}\n\nexport function rewriteGateDecisionToPhases(decision: RewriteGateDecision): (\"l1\" | \"l2\" | \"l3\")[] {\n switch (decision) {\n case \"skip\":\n return [];\n case \"l3_only\":\n return [\"l3\"];\n case \"l2_l3\":\n return [\"l2\", \"l3\"];\n case \"full\":\n return [\"l1\", \"l2\", \"l3\"];\n }\n}\n\n/** Gate may skip only when high confidence and explicit skip decision. */\nexport function rewriteGateAllowsSkip(result: RewriteGateResult): boolean {\n return result.decision === \"skip\" && result.confidence === \"high\";\n}\n",
|
|
16
|
+
"import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, rmSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\nimport {\n AGENT_CURSOR_SESSION_MODE_FORK,\n AGENT_CURSOR_SESSION_MODE_MAIN,\n parseAgentCursorSessionMode,\n type AgentCursorSessionMode,\n type AgentJobConfigV1,\n} from \"../common/src/agent-job-config.ts\";\n\nconst DEFAULT_CURSOR_WORK_ROOT = \"/tmp/nvwa-cursor-work\";\n\nexport type CursorSessionLayout = {\n mode: AgentCursorSessionMode;\n pvcHomeDir: string;\n activeHomeDir: string;\n workDirToCleanup: string | null;\n copiedFromPvc: boolean;\n};\n\nfunction pvcHomeDirFromEnv(): string {\n return (process.env.NVWA_AGENT_CURSOR_HOME_DIR ?? \"\").trim() || \"/var/nvwa/cursor-home\";\n}\n\nfunction cursorWorkRootFromEnv(): string {\n return (process.env.NVWA_AGENT_CURSOR_WORK_ROOT ?? \"\").trim() || DEFAULT_CURSOR_WORK_ROOT;\n}\n\nfunction dirHasEntries(dir: string): boolean {\n try {\n return readdirSync(dir).length > 0;\n } catch {\n return false;\n }\n}\n\nfunction resolveSessionMode(spec: AgentJobConfigV1): AgentCursorSessionMode {\n return parseAgentCursorSessionMode(spec.cursorSessionMode);\n}\n\n/** Skip sockets/FIFOs/devices — cpSync on Cursor home often hits ENXIO on Unix sockets. */\nfunction isCopyableCursorHomeEntry(path: string): boolean {\n try {\n const st = lstatSync(path);\n if (st.isSocket() || st.isFIFO() || st.isCharacterDevice() || st.isBlockDevice()) {\n return false;\n }\n if (st.isSymbolicLink()) {\n return false;\n }\n return st.isFile() || st.isDirectory();\n } catch {\n return false;\n }\n}\n\nfunction copyCursorHomeSafe(src: string, dest: string): void {\n if (!isCopyableCursorHomeEntry(src)) {\n return;\n }\n const st = lstatSync(src);\n if (st.isDirectory()) {\n mkdirSync(dest, { recursive: true });\n for (const name of readdirSync(src)) {\n copyCursorHomeSafe(join(src, name), join(dest, name));\n }\n return;\n }\n if (st.isFile()) {\n mkdirSync(dirname(dest), { recursive: true });\n cpSync(src, dest);\n }\n}\n\nexport function resolveCursorSessionLayout(spec: AgentJobConfigV1): CursorSessionLayout {\n const pvcHomeDir = pvcHomeDirFromEnv();\n const mode = resolveSessionMode(spec);\n\n if (mode === AGENT_CURSOR_SESSION_MODE_MAIN) {\n mkdirSync(pvcHomeDir, { recursive: true });\n console.error(\n \"[nvwa-agent] cursor_session\",\n JSON.stringify({\n mode,\n pvcHomeDir,\n activeHomeDir: pvcHomeDir,\n copiedFromPvc: false,\n cursorResume: spec.cursorResume === true,\n }),\n );\n return {\n mode,\n pvcHomeDir,\n activeHomeDir: pvcHomeDir,\n workDirToCleanup: null,\n copiedFromPvc: false,\n };\n }\n\n const workRoot = cursorWorkRootFromEnv();\n const jobKey = (spec.jobCode ?? spec.jobId).trim() || spec.jobId;\n const workDir = join(workRoot, jobKey);\n if (existsSync(workDir)) {\n rmSync(workDir, { recursive: true, force: true });\n }\n mkdirSync(workDir, { recursive: true });\n\n let copiedFromPvc = false;\n if (spec.cursorResume && existsSync(pvcHomeDir) && dirHasEntries(pvcHomeDir)) {\n try {\n copyCursorHomeSafe(pvcHomeDir, workDir);\n copiedFromPvc = true;\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n console.error(\n \"[nvwa-agent] cursor_session_copy_failed\",\n JSON.stringify({ pvcHomeDir, workDir, error: msg.slice(0, 500) }),\n );\n }\n }\n\n console.error(\n \"[nvwa-agent] cursor_session\",\n JSON.stringify({\n mode,\n pvcHomeDir,\n activeHomeDir: workDir,\n copiedFromPvc,\n cursorResume: spec.cursorResume === true,\n }),\n );\n\n return {\n mode,\n pvcHomeDir,\n activeHomeDir: workDir,\n workDirToCleanup: workDir,\n copiedFromPvc,\n };\n}\n\nexport function cleanupCursorSessionWorkDir(layout: CursorSessionLayout | null): void {\n const dir = layout?.workDirToCleanup;\n if (!dir) return;\n try {\n rmSync(dir, { recursive: true, force: true });\n } catch {\n // best-effort\n }\n}\n",
|
|
17
|
+
"import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\nimport type { AgentJobConfigV1 } from \"../common/src/agent-job-config.ts\";\n\nexport const INTEGRATION_SIM_TEMPLATE_ROOT =\n process.env.NVWA_INTEGRATION_SIM_TEMPLATE_ROOT?.trim() || \"/opt/nvwa/integration-sim-template\";\n\nconst TEMPLATE_FILES: { template: string; dest: string }[] = [\n { template: \"scaffold-package.json\", dest: \"package.json\" },\n { template: \"Dockerfile\", dest: \"Dockerfile\" },\n { template: \"scaffold-server.ts\", dest: \"src/server.ts\" },\n { template: \"openapi/openapi.yaml\", dest: \"openapi/openapi.yaml\" },\n { template: \"vendor/profile.json\", dest: \"src/vendor/profile.json\" },\n { template: \"vendor/common-errors.json\", dest: \"src/vendor/common-errors.json\" },\n { template: \"test/contract/health.test.ts\", dest: \"test/contract/health.test.ts\" },\n { template: \"test/contract/vendor-errors.example.test.ts\", dest: \"test/contract/vendor-errors.example.test.ts\" },\n];\n\nexport type IntegrationSimSeedMeta = {\n contractId: string;\n realBaseUrl: string;\n advanceStates?: string[];\n};\n\nexport function buildContractYaml(meta: IntegrationSimSeedMeta): string {\n const states = meta.advanceStates?.length ? meta.advanceStates : [\"pending\", \"paid\"];\n return [\n `contractId: ${meta.contractId}`,\n `realBaseUrl: ${meta.realBaseUrl}`,\n \"advanceStates:\",\n ...states.map((s) => ` - ${s}`),\n \"webhookPaths: []\",\n \"\",\n ].join(\"\\n\");\n}\n\n/** Copy bundled template into project workspace (idempotent overwrite of template files). */\nexport function seedIntegrationSimFromTemplate(\n workspaceDir: string,\n repoSubpath: string,\n meta: IntegrationSimSeedMeta,\n): string | null {\n const root = INTEGRATION_SIM_TEMPLATE_ROOT;\n if (!existsSync(root)) {\n return `integration sim template root missing: ${root}`;\n }\n const base = join(workspaceDir, repoSubpath);\n mkdirSync(join(base, \"src\"), { recursive: true });\n mkdirSync(join(base, \"openapi\"), { recursive: true });\n mkdirSync(join(base, \"src/vendor\"), { recursive: true });\n mkdirSync(join(base, \"src/generated/errors\"), { recursive: true });\n mkdirSync(join(base, \"test/contract\"), { recursive: true });\n\n for (const { template, dest } of TEMPLATE_FILES) {\n const src = join(root, template);\n if (!existsSync(src)) return `template file missing: ${template}`;\n const out = join(base, dest);\n mkdirSync(dirname(out), { recursive: true });\n copyFileSync(src, out);\n }\n\n writeFileSync(join(base, \"contract.yaml\"), buildContractYaml(meta), \"utf8\");\n return null;\n}\n\nexport function buildIntegrationSimAgentPrompt(opts: {\n spec: AgentJobConfigV1;\n mode: \"scaffold\" | \"regen\" | \"skeleton\" | \"api_batch\";\n indexSample: string;\n resultJsonPath: string;\n}): string {\n const sub = opts.spec.integrationSimRepoSubpath?.trim() || \"unknown/\";\n const urls = opts.spec.integrationSimDocumentUrls ?? [];\n const apiIds = opts.spec.integrationSimApiIds ?? [];\n const docList = urls.length > 0 ? urls.map((u, i) => `${i + 1}. ${u}`).join(\"\\n\") : \"(none)\";\n const apiBatchNote =\n opts.mode === \"api_batch\"\n ? [\n `API_BATCH: implement only apis: ${apiIds.join(\", \") || \"(from brief)\"}; merge into existing openapi paths.`,\n \"\",\n \"Error-code simulation (Phase 1 — mandatory):\",\n \"- Read compile api detail via `nvwa-os integration-docs api --contract CODE --api-id ID` (includes errorCodes + vendorProfile)\",\n \"- Write src/vendor/profile.json from compile manifest vendorProfile (contract-level)\",\n \"- Write src/vendor/common-errors.json (deduped scope=common codes from compile)\",\n \"- For each apiId in this batch: src/generated/errors/{apiId}.json (api errorCodes + referenced common codes)\",\n \"- Handlers MUST use @nvwa/integration-sim-sdk: loadVendorProfile, vendorOk, vendorError, resolveCommonError, assertRequired\",\n \"- Do NOT hardcode ad-hoc codes like 40101; use resolveCommonError(catalog, hint) for missing_access_token / invalid_json_body / missing_required_param\",\n \"- Alipay OpenAPI v3 (codeField=code, successCode=10000): NEVER write WeChat codes 41001/47001/40013 in common-errors.json; use 40001/20001 + sub_code from vendor docs for auth errors\",\n \"- On success return vendorOk(profile, { ...payload }) with HTTP 200\",\n \"- On validation errors return vendorError(code, message, profile) with HTTP 400 (or vendor-appropriate status)\",\n \"- Add test/contract/{apiId}.errors.test.ts covering: success errcode, missing required param or access_token\",\n \"- Sync x-nvwa-error-codes on openapi operation responses when adding paths\",\n \"- Add x-nvwa-capability: domain.action on EVERY operation (e.g. oauth.login); used to generate src/generated/capabilities.json\",\n \"- After paths change, capabilities.json must stay in sync (platform regenerates from openapi x-nvwa-capability)\",\n ].join(\"\\n\")\n : \"\";\n const regenNote =\n opts.mode === \"regen\"\n ? \"This is a REGEN run: preserve working handlers; update openapi, vendor JSON, and tests from compile artifacts.\\n\"\n : opts.mode === \"skeleton\"\n ? \"SKELETON: seed contract.yaml, openapi security/components shell, handler dirs, src/vendor/* placeholders; read compile guides+apis list via integration-docs CLI.\\n\"\n : opts.mode === \"api_batch\"\n ? apiBatchNote\n : \"\";\n\n return [\n \"You are implementing an HTTP integration SIMULATOR for Nvwa (not the business app).\",\n regenNote,\n `ONLY modify files under: ${sub}`,\n \"Do NOT change files outside that directory.\",\n \"\",\n \"Goals:\",\n \"- Use nvwa-os integration-docs guides/apis (compile artifacts) as source of truth\",\n \"- Merge vendor API knowledge into openapi/openapi.yaml (OpenAPI 3)\",\n \"- Implement/adjust Bun+Hono handlers in src/ to match openapi\",\n \"- src/server.ts: export default { port, fetch }; do NOT call Bun.serve in import.meta.main (runtime imports the module once)\",\n \"- Keep test/contract/ passing (run bun test in the contract directory)\",\n \"\",\n `Contract id: ${opts.spec.integrationContractCode ?? \"unknown\"}`,\n `Vendor document URLs:\\n${docList}`,\n \"\",\n opts.spec.requirementRawInput.slice(0, 6000),\n \"\",\n `Repo index sample:\\n${opts.indexSample.slice(0, 2000)}`,\n \"\",\n `Optional: write summary JSON to ${opts.resultJsonPath} with keys: summary, contractCode.`,\n ].join(\"\\n\");\n}\n\nexport function readTemplateFile(name: string): string {\n return readFileSync(join(INTEGRATION_SIM_TEMPLATE_ROOT, name), \"utf8\");\n}\n",
|
|
18
|
+
"import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport type { AgentJobConfigV1 } from \"../common/src/agent-job-config.ts\";\nimport type { IntegrationDocCompilePhase } from \"../common/src/integration-doc-compile-catalog.ts\";\nimport {\n formatIntegrationDocCompileCatalog,\n type IntegrationDocCompileDocumentEntry,\n} from \"../common/src/integration-doc-compile-catalog.ts\";\nimport { AGENT_PLAYBOOK_PATHS } from \"./agent-playbook-paths.ts\";\n\nfunction resolveCompileDocuments(\n spec: AgentJobConfigV1,\n): IntegrationDocCompileDocumentEntry[] {\n if (spec.integrationDocCompileDocuments?.length) {\n return spec.integrationDocCompileDocuments;\n }\n return [];\n}\n\nfunction resolveCompilePhase(spec: AgentJobConfigV1): IntegrationDocCompilePhase {\n const phase = spec.integrationDocCompilePhase;\n if (phase === \"classify\" || phase === \"extract\" || phase === \"full\") return phase;\n return \"full\";\n}\n\nfunction catalogSection(spec: AgentJobConfigV1, documents: IntegrationDocCompileDocumentEntry[]): string {\n const docIds = spec.integrationDocCompileDocumentIds ?? documents.map((d) => d.documentId);\n const catalog = formatIntegrationDocCompileCatalog(documents);\n if (documents.length === 0) {\n return [\n \"## Registered documents\",\n \"(missing integrationDocCompileDocuments in job.json — fall back to brief URLs if any)\",\n `Document ids: ${docIds.join(\", \") || \"(none)\"}`,\n ].join(\"\\n\");\n }\n return [\n \"## Registered documents (authoritative URL catalog)\",\n \"Use ONLY these URLs for fetchAll (SSRF guard). Do not rely on requirementRawInput for URLs.\",\n `Also available in /etc/nvwa/job.json → integrationDocCompileDocuments (${documents.length} rows).`,\n `Document ids: ${docIds.join(\", \")}`,\n catalog,\n ].join(\"\\n\");\n}\n\nfunction batchSection(spec: AgentJobConfigV1): string {\n const batch = spec.integrationDocCompileBatch;\n if (!batch) return \"\";\n return `\\nBatch: ${batch.index + 1} / ${batch.total} (zero-based index ${batch.index}).`;\n}\n\nfunction classifyManifestSection(spec: AgentJobConfigV1): string {\n const key = spec.integrationDocClassifyManifestKey?.trim();\n if (!key) return \"\";\n return [\n \"\",\n \"## Pre-classified manifest\",\n `Read merged classify manifest from MinIO key: ${key}`,\n \"Do NOT re-classify pageKind; use it to decide extractGuides vs extractApis.\",\n ].join(\"\\n\");\n}\n\nexport function buildIntegrationDocClassifyPrompt(opts: {\n spec: AgentJobConfigV1;\n resultJsonPath: string;\n playbook: string;\n}): string {\n const contractCode = opts.spec.integrationContractCode ?? \"unknown\";\n const documents = resolveCompileDocuments(opts.spec);\n return [\n \"You are classifying vendor integration documentation pages for Nvwa (pageKind only — no API extract).\",\n `Contract: ${contractCode}`,\n batchSection(opts.spec),\n \"\",\n \"Phases (post progress via callback between phases):\",\n \"1. fetchAll — curl/read each URL in the Registered documents catalog\",\n \"2. classifyAll — pageKind: guide | api | mixed | noise | pending + reason\",\n \"3. emitResult — write compileResult JSON with guides:[] and apis:[]\",\n \"\",\n `Write JSON to ${opts.resultJsonPath}:`,\n `{ \"compileResult\": { \"manifest\": {...}, \"guides\": [], \"apis\": [], \"noise\": [...] } }`,\n \"\",\n catalogSection(opts.spec, documents),\n \"\",\n \"## Task brief (instructions only; URLs are in catalog above)\",\n opts.spec.requirementRawInput.slice(0, 8000),\n \"\",\n opts.playbook ? `## Skill playbook\\n${opts.playbook.slice(0, 12000)}` : \"\",\n ].join(\"\\n\");\n}\n\nexport function buildIntegrationDocExtractPrompt(opts: {\n spec: AgentJobConfigV1;\n resultJsonPath: string;\n playbook: string;\n}): string {\n const contractCode = opts.spec.integrationContractCode ?? \"unknown\";\n const documents = resolveCompileDocuments(opts.spec);\n return [\n \"You are extracting structured guides and APIs from pre-classified vendor integration docs for Nvwa.\",\n `Contract: ${contractCode}`,\n batchSection(opts.spec),\n \"\",\n \"Phases (post progress via callback between phases):\",\n \"1. fetchAll — read pre-fetched pages from MinIO when available\",\n \"2. extractGuides — guide/mixed pages only\",\n \"3. extractApis — api/mixed pages only; inject guide summaries as context\",\n \"4. followCommonErrors — one-hop same-domain common error tables\",\n \"5. inferVendorProfile — from JSON examples\",\n \"6. emitResult — write compileResult JSON\",\n \"\",\n `Write JSON to ${opts.resultJsonPath}:`,\n `{ \"compileResult\": { \"manifest\": {...}, \"guides\": [...], \"apis\": [...], \"noise\": [...] } }`,\n \"\",\n catalogSection(opts.spec, documents),\n classifyManifestSection(opts.spec),\n \"\",\n \"## Task brief (instructions only; URLs are in catalog above)\",\n opts.spec.requirementRawInput.slice(0, 8000),\n \"\",\n opts.playbook ? `## Skill playbook\\n${opts.playbook.slice(0, 12000)}` : \"\",\n ].join(\"\\n\");\n}\n\nexport function buildIntegrationDocCompilePrompt(opts: {\n spec: AgentJobConfigV1;\n resultJsonPath: string;\n playbook: string;\n}): string {\n const phase = resolveCompilePhase(opts.spec);\n if (phase === \"classify\") {\n return buildIntegrationDocClassifyPrompt(opts);\n }\n if (phase === \"extract\") {\n return buildIntegrationDocExtractPrompt(opts);\n }\n\n const contractCode = opts.spec.integrationContractCode ?? \"unknown\";\n const documents = resolveCompileDocuments(opts.spec);\n return [\n \"You are compiling vendor integration documentation for Nvwa (LLM structured extract).\",\n `Contract: ${contractCode}`,\n \"\",\n \"Phases (post progress via callback between phases):\",\n \"1. fetchAll — curl each URL in the Registered documents catalog; simplify HTML to text\",\n \"2. classifyAll — pageKind: guide | api | mixed | noise | pending + reason\",\n \"3. extractGuides — guides/*.json structure for guide/mixed pages\",\n \"4. extractApis — apis/*.json with parameters; inject guide summaries as context\",\n \"5. emitResult — write compileResult JSON\",\n \"\",\n `Write JSON to ${opts.resultJsonPath}:`,\n `{ \"compileResult\": { \"manifest\": {...}, \"guides\": [...], \"apis\": [...], \"noise\": [...] } }`,\n \"\",\n catalogSection(opts.spec, documents),\n \"\",\n \"## Task brief (instructions only; URLs are in catalog above)\",\n opts.spec.requirementRawInput.slice(0, 8000),\n \"\",\n opts.playbook ? `## Skill playbook\\n${opts.playbook.slice(0, 12000)}` : \"\",\n ].join(\"\\n\");\n}\n\nexport function readCompileSkillPlaybookForPhase(phase: IntegrationDocCompilePhase): string {\n const path =\n phase === \"classify\"\n ? AGENT_PLAYBOOK_PATHS.integrationDocClassify\n : phase === \"extract\"\n ? AGENT_PLAYBOOK_PATHS.integrationDocExtract\n : AGENT_PLAYBOOK_PATHS.integrationDocCompile;\n try {\n if (!existsSync(path)) return \"\";\n return readFileSync(path, \"utf-8\");\n } catch {\n return \"\";\n }\n}\n\nexport function readCompileSkillPlaybook(): string {\n return readCompileSkillPlaybookForPhase(\"full\");\n}\n\nexport function parseCompileResultFromFile(\n resultJsonPath: string,\n): Record<string, unknown> | null {\n if (!existsSync(resultJsonPath)) return null;\n try {\n const parsed = JSON.parse(readFileSync(resultJsonPath, \"utf-8\")) as Record<string, unknown>;\n const cr = parsed.compileResult;\n if (cr && typeof cr === \"object\" && !Array.isArray(cr)) {\n return cr as Record<string, unknown>;\n }\n if (parsed.manifest) return parsed;\n return null;\n } catch {\n return null;\n }\n}\n\nexport function validateCompileResultShape(\n result: Record<string, unknown>,\n phase: IntegrationDocCompilePhase,\n): string | null {\n const guides = result.guides;\n const apis = result.apis;\n if (!Array.isArray(guides) || !Array.isArray(apis)) {\n return \"compileResult missing guides[] or apis[]\";\n }\n if (phase === \"classify\" && (guides.length > 0 || apis.length > 0)) {\n return \"classify job must emit empty guides[] and apis[]\";\n }\n return null;\n}\n\nexport function ensureCompileWorkspace(dir: string): void {\n mkdirSync(join(dir, \"compile-work\"), { recursive: true });\n}\n\nexport function writeCompileStubResult(\n resultJsonPath: string,\n contractCode: string,\n jobCode: string,\n): void {\n const extractedAt = new Date().toISOString();\n writeFileSync(\n resultJsonPath,\n JSON.stringify(\n {\n compileResult: {\n manifest: {\n contractCode,\n extractedAt,\n compileJobCode: jobCode,\n stats: { documents: 0, guides: 0, apis: 0, noise: 0 },\n documents: [],\n guideIds: [],\n apiIds: [],\n },\n guides: [],\n apis: [],\n noise: [],\n },\n },\n null,\n 2,\n ),\n \"utf-8\",\n );\n}\n",
|
|
19
|
+
"export const AGENT_PLAYBOOK_ROOT = \"/opt/nvwa/skills\";\n\nexport const AGENT_PLAYBOOK_PATHS = {\n jobDeployOps: `${AGENT_PLAYBOOK_ROOT}/nvwa-job-deploy-ops/SKILL.md`,\n integrationDocs: `${AGENT_PLAYBOOK_ROOT}/nvwa-integration-docs/SKILL.md`,\n integrationClient: `${AGENT_PLAYBOOK_ROOT}/nvwa-integration-client/SKILL.md`,\n integrationDocCompile: `${AGENT_PLAYBOOK_ROOT}/nvwa-integration-doc-compile/SKILL.md`,\n integrationDocClassify: `${AGENT_PLAYBOOK_ROOT}/nvwa-integration-doc-classify/SKILL.md`,\n integrationDocExtract: `${AGENT_PLAYBOOK_ROOT}/nvwa-integration-doc-extract/SKILL.md`,\n requirementIntakeImages: `${AGENT_PLAYBOOK_ROOT}/nvwa-requirement-intake-images/SKILL.md`,\n opsStructuralPort: `${AGENT_PLAYBOOK_ROOT}/nvwa-ops-structural-port/SKILL.md`,\n} as const;\n",
|
|
20
|
+
"import { existsSync, readFileSync } from \"node:fs\";\n\nimport type { AgentJobConfigV1 } from \"../common/src/agent-job-config.ts\";\nimport { resolveIntegrationDocsClientConfig } from \"../common/src/integration-docs-client.ts\";\nimport { logAgentToolTrace, type AgentTraceFields } from \"../common/src/agent-tool-trace.ts\";\nimport { AGENT_PLAYBOOK_PATHS } from \"./agent-playbook-paths.ts\";\n\nexport type AgentSkillContext = {\n jobCode: string;\n pipeline: string;\n integrationDocs: { enabled: boolean; projectCode?: string; reason?: string };\n jobOps: {\n enabled: boolean;\n projectCode?: string;\n defaultEnv?: string;\n featureAppName?: string;\n reason?: string;\n };\n playbooks: {\n jobDeployOps: boolean;\n integrationDocs: boolean;\n integrationClient: boolean;\n integrationDocCompile: boolean;\n };\n};\n\nfunction playbookReadable(path: string): boolean {\n try {\n return existsSync(path) && readFileSync(path, \"utf-8\").trim().length > 0;\n } catch {\n return false;\n }\n}\n\nexport function buildAgentSkillContext(spec: AgentJobConfigV1): AgentSkillContext {\n const jobCode = spec.jobCode?.trim() || spec.jobId;\n const pipeline = spec.pipeline;\n\n const integrationToken = (process.env.NVWA_INTEGRATION_DOCS_TOKEN ?? \"\").trim();\n const integrationHints = spec.integrationDocsHints;\n const resolvedConfig = resolveIntegrationDocsClientConfig();\n let integrationDocs: AgentSkillContext[\"integrationDocs\"];\n if (integrationHints?.projectCode && integrationHints.apiBaseUrl && integrationToken) {\n integrationDocs = { enabled: true, projectCode: integrationHints.projectCode };\n } else if (resolvedConfig) {\n integrationDocs = {\n enabled: true,\n projectCode: resolvedConfig.projectCode ?? integrationHints?.projectCode,\n };\n } else if (!integrationToken) {\n integrationDocs = { enabled: false, reason: \"no_token\" };\n } else if (!integrationHints?.apiBaseUrl) {\n integrationDocs = { enabled: false, reason: \"no_hints\" };\n } else {\n integrationDocs = { enabled: false, reason: \"not_configured\" };\n }\n\n const callbackSecret = (process.env.NVWA_CALLBACK_SECRET ?? \"\").trim();\n const opsHints = spec.opsHints;\n let jobOps: AgentSkillContext[\"jobOps\"];\n if (opsHints?.projectCode && callbackSecret) {\n jobOps = {\n enabled: true,\n projectCode: opsHints.projectCode,\n defaultEnv: opsHints.defaultEnv,\n featureAppName: opsHints.featureAppName ?? undefined,\n };\n } else if (!callbackSecret) {\n jobOps = { enabled: false, reason: \"no_callback_secret\" };\n } else if (!opsHints) {\n jobOps = { enabled: false, reason: \"no_ops_hints\" };\n } else {\n jobOps = { enabled: false, reason: \"not_configured\" };\n }\n\n return {\n jobCode,\n pipeline,\n integrationDocs,\n jobOps,\n playbooks: {\n jobDeployOps: playbookReadable(AGENT_PLAYBOOK_PATHS.jobDeployOps),\n integrationDocs: playbookReadable(AGENT_PLAYBOOK_PATHS.integrationDocs),\n integrationClient: playbookReadable(AGENT_PLAYBOOK_PATHS.integrationClient),\n integrationDocCompile: playbookReadable(AGENT_PLAYBOOK_PATHS.integrationDocCompile),\n },\n };\n}\n\nexport function skillContextTraceFields(ctx: AgentSkillContext): AgentTraceFields {\n const fields: AgentTraceFields = {\n jobCode: ctx.jobCode,\n pipeline: ctx.pipeline,\n integrationDocs: ctx.integrationDocs.enabled ? \"enabled\" : \"disabled\",\n jobOps: ctx.jobOps.enabled ? \"enabled\" : \"disabled\",\n playbookJobDeployOps: ctx.playbooks.jobDeployOps,\n playbookIntegrationDocs: ctx.playbooks.integrationDocs,\n playbookIntegrationClient: ctx.playbooks.integrationClient,\n playbookIntegrationDocCompile: ctx.playbooks.integrationDocCompile,\n };\n if (ctx.integrationDocs.projectCode) fields.integrationDocsProjectCode = ctx.integrationDocs.projectCode;\n if (ctx.integrationDocs.reason) fields.integrationDocsReason = ctx.integrationDocs.reason;\n if (ctx.jobOps.projectCode) fields.jobOpsProjectCode = ctx.jobOps.projectCode;\n if (ctx.jobOps.defaultEnv) fields.jobOpsDefaultEnv = ctx.jobOps.defaultEnv;\n if (ctx.jobOps.featureAppName) fields.jobOpsFeatureAppName = ctx.jobOps.featureAppName;\n if (ctx.jobOps.reason) fields.jobOpsReason = ctx.jobOps.reason;\n return fields;\n}\n\nexport function logAgentSkillContext(spec: AgentJobConfigV1): AgentSkillContext {\n const ctx = buildAgentSkillContext(spec);\n logAgentToolTrace(\"skill_context\", skillContextTraceFields(ctx));\n return ctx;\n}\n\nexport function logSkillPlaybookInjected(\n spec: AgentJobConfigV1,\n playbook:\n | \"nvwa-job-deploy-ops\"\n | \"nvwa-integration-docs\"\n | \"nvwa-integration-client\"\n | \"nvwa-integration-doc-compile\"\n | \"nvwa-integration-doc-classify\"\n | \"nvwa-integration-doc-extract\"\n | \"nvwa-requirement-intake-images\",\n bytes: number,\n injected: boolean,\n): void {\n logAgentToolTrace(\"skill_playbook\", {\n jobCode: spec.jobCode?.trim() || spec.jobId,\n pipeline: spec.pipeline,\n playbook,\n bytes,\n injected,\n });\n}\n",
|
|
21
|
+
"/**\n * Project-scoped integration vendor docs HTTP client (Agent Pod + external CLI/MCP).\n */\n\nimport { readFileSync } from \"node:fs\";\n\nimport { AGENT_JOB_CONFIG_MOUNT_PATH } from \"./agent-job-config\";\nimport type { AgentJobIntegrationDocsHints } from \"./integration-docs-types\";\nimport { resolveNvwaCliCredential } from \"./nvwa-cli-config\";\n\nexport type IntegrationDocsClientConfig = {\n apiBaseUrl: string;\n token: string;\n projectCode?: string;\n};\n\nfunction trimSlash(url: string): string {\n return url.replace(/\\/$/, \"\");\n}\n\nexport function buildIntegrationDocsApiBaseUrlFromParts(\n apiBaseUrl: string,\n projectCode: string,\n): string {\n const base = trimSlash(apiBaseUrl.trim());\n const code = projectCode.trim();\n if (!base || !code) return \"\";\n return `${base}/api/projects/${encodeURIComponent(code)}/integration-docs`;\n}\n\nfunction parseJobJsonHints(jobConfigMountPath: string): AgentJobIntegrationDocsHints | null {\n try {\n const raw = readFileSync(jobConfigMountPath, \"utf-8\");\n const j = JSON.parse(raw) as { integrationDocsHints?: unknown };\n const h = j.integrationDocsHints;\n if (h && typeof h === \"object\" && !Array.isArray(h)) {\n const o = h as Record<string, unknown>;\n const projectCode = typeof o.projectCode === \"string\" ? o.projectCode.trim() : \"\";\n const apiBaseUrl = typeof o.apiBaseUrl === \"string\" ? o.apiBaseUrl.trim() : \"\";\n if (projectCode && apiBaseUrl) return { projectCode, apiBaseUrl };\n }\n } catch {\n // ignore missing job.json (local / external CLI)\n }\n return null;\n}\n\nexport function resolveIntegrationDocsClientConfig(opts?: {\n jobConfigMountPath?: string;\n cwd?: string;\n}): IntegrationDocsClientConfig | null {\n const envToken = (process.env.NVWA_INTEGRATION_DOCS_TOKEN ?? \"\").trim();\n\n const explicitBase = trimSlash(process.env.NVWA_INTEGRATION_DOCS_API_BASE_URL ?? \"\");\n if (envToken && explicitBase) {\n const projectCode = (process.env.NVWA_PROJECT_CODE ?? \"\").trim() || undefined;\n return { apiBaseUrl: explicitBase, token: envToken, projectCode };\n }\n\n const platformBase = trimSlash(process.env.NVWA_API_BASE_URL ?? \"\");\n const envProjectCode = (process.env.NVWA_PROJECT_CODE ?? \"\").trim();\n if (envToken && platformBase && envProjectCode) {\n const apiBaseUrl = buildIntegrationDocsApiBaseUrlFromParts(platformBase, envProjectCode);\n if (apiBaseUrl) return { apiBaseUrl, token: envToken, projectCode: envProjectCode };\n }\n\n if (envToken) {\n const hints = parseJobJsonHints(opts?.jobConfigMountPath ?? AGENT_JOB_CONFIG_MOUNT_PATH);\n if (hints?.apiBaseUrl) {\n return {\n apiBaseUrl: trimSlash(hints.apiBaseUrl),\n token: envToken,\n projectCode: hints.projectCode,\n };\n }\n }\n\n const fileCred = resolveNvwaCliCredential({\n cwd: opts?.cwd ?? process.cwd(),\n projectCode: envProjectCode || undefined,\n });\n if (fileCred) {\n const apiBaseUrl = buildIntegrationDocsApiBaseUrlFromParts(\n fileCred.studioUrl,\n fileCred.projectCode,\n );\n if (apiBaseUrl) {\n return {\n apiBaseUrl,\n token: fileCred.integrationDocsToken,\n projectCode: fileCred.projectCode,\n };\n }\n }\n\n return null;\n}\n\nasync function integrationDocsFetch(\n cfg: IntegrationDocsClientConfig,\n path: string,\n): Promise<{ ok: boolean; status: number; body: unknown }> {\n const headers = new Headers({ \"X-Nvwa-Integration-Docs-Token\": cfg.token });\n const res = await fetch(`${cfg.apiBaseUrl}${path}`, { method: \"GET\", headers });\n let body: unknown = null;\n try {\n body = await res.json();\n } catch {\n body = null;\n }\n return { ok: res.ok, status: res.status, body };\n}\n\nfunction integrationDocsError(r: { status: number; body: unknown }): Error {\n const b = r.body as { message?: string; error?: string } | null;\n const msg = b?.message ?? b?.error ?? `HTTP ${r.status}`;\n return new Error(msg);\n}\n\nexport async function integrationDocsContracts(cfg: IntegrationDocsClientConfig): Promise<unknown> {\n const r = await integrationDocsFetch(cfg, \"/contracts\");\n if (!r.ok) throw integrationDocsError(r);\n return r.body;\n}\n\nexport async function integrationDocsDocuments(\n cfg: IntegrationDocsClientConfig,\n contractCode: string,\n): Promise<unknown> {\n const r = await integrationDocsFetch(\n cfg,\n `/contracts/${encodeURIComponent(contractCode)}/documents`,\n );\n if (!r.ok) throw integrationDocsError(r);\n return r.body;\n}\n\nexport async function integrationDocsApis(\n cfg: IntegrationDocsClientConfig,\n contractCode: string,\n): Promise<unknown> {\n const r = await integrationDocsFetch(cfg, `/contracts/${encodeURIComponent(contractCode)}/apis`);\n if (!r.ok) throw integrationDocsError(r);\n return r.body;\n}\n\nexport async function integrationDocsApi(\n cfg: IntegrationDocsClientConfig,\n contractCode: string,\n apiId: string,\n): Promise<unknown> {\n const r = await integrationDocsFetch(\n cfg,\n `/contracts/${encodeURIComponent(contractCode)}/apis/${encodeURIComponent(apiId)}`,\n );\n if (!r.ok) throw integrationDocsError(r);\n return r.body;\n}\n\nexport async function integrationDocsGuides(\n cfg: IntegrationDocsClientConfig,\n contractCode: string,\n): Promise<unknown> {\n const r = await integrationDocsFetch(\n cfg,\n `/contracts/${encodeURIComponent(contractCode)}/guides`,\n );\n if (!r.ok) throw integrationDocsError(r);\n return r.body;\n}\n\nexport async function integrationDocsGuide(\n cfg: IntegrationDocsClientConfig,\n contractCode: string,\n guideId: string,\n): Promise<unknown> {\n const r = await integrationDocsFetch(\n cfg,\n `/contracts/${encodeURIComponent(contractCode)}/guides/${encodeURIComponent(guideId)}`,\n );\n if (!r.ok) throw integrationDocsError(r);\n return r.body;\n}\n",
|
|
22
|
+
"/**\n * Local Nvwa CLI config (~/.nvwa/config.json + repo .nvwa/config.json).\n */\n\nimport { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nexport const NVWA_CLI_CONFIG_VERSION = 1;\n\nexport type NvwaCliProjectCredential = {\n integrationDocsToken?: string;\n connectedAt?: string;\n connectedBy?: string;\n /** Reserved for Phase 3 scoped keys */\n scopes?: string[];\n};\n\nexport type NvwaCliConfig = {\n version: number;\n studioUrl?: string;\n defaultProjectCode?: string;\n projects?: Record<string, NvwaCliProjectCredential>;\n};\n\nexport type LoadedNvwaCliConfig = {\n merged: NvwaCliConfig;\n globalPath: string;\n projectPath: string | null;\n};\n\nfunction trimSlash(url: string): string {\n return url.replace(/\\/$/, \"\");\n}\n\nexport function getGlobalNvwaConfigDir(): string {\n const override = (process.env.NVWA_CLI_CONFIG_DIR ?? \"\").trim();\n if (override) return override;\n return join(homedir(), \".nvwa\");\n}\n\nexport function getGlobalNvwaConfigPath(): string {\n return join(getGlobalNvwaConfigDir(), \"config.json\");\n}\n\nfunction parseConfigJson(raw: string): NvwaCliConfig | null {\n try {\n const parsed = JSON.parse(raw) as NvwaCliConfig;\n if (!parsed || typeof parsed !== \"object\") return null;\n return {\n version: typeof parsed.version === \"number\" ? parsed.version : NVWA_CLI_CONFIG_VERSION,\n studioUrl:\n typeof parsed.studioUrl === \"string\" && parsed.studioUrl.trim()\n ? trimSlash(parsed.studioUrl.trim())\n : undefined,\n defaultProjectCode:\n typeof parsed.defaultProjectCode === \"string\" && parsed.defaultProjectCode.trim()\n ? parsed.defaultProjectCode.trim()\n : undefined,\n projects:\n parsed.projects && typeof parsed.projects === \"object\" && !Array.isArray(parsed.projects)\n ? parsed.projects\n : {},\n };\n } catch {\n return null;\n }\n}\n\nfunction readConfigFile(path: string): NvwaCliConfig | null {\n if (!existsSync(path)) return null;\n try {\n return parseConfigJson(readFileSync(path, \"utf-8\"));\n } catch {\n return null;\n }\n}\n\nfunction findGitRoot(startDir: string): string | null {\n let dir = startDir;\n for (let i = 0; i < 64; i++) {\n if (existsSync(join(dir, \".git\"))) return dir;\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\nexport function findProjectNvwaConfigPath(cwd: string): string | null {\n let dir = cwd;\n for (let i = 0; i < 64; i++) {\n const candidate = join(dir, \".nvwa\", \"config.json\");\n if (existsSync(candidate)) return candidate;\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\nexport function getProjectNvwaConfigPathForRepo(cwd: string): string {\n const root = findGitRoot(cwd) ?? cwd;\n return join(root, \".nvwa\", \"config.json\");\n}\n\nfunction mergeConfigs(globalCfg: NvwaCliConfig | null, projectCfg: NvwaCliConfig | null): NvwaCliConfig {\n const g = globalCfg ?? { version: NVWA_CLI_CONFIG_VERSION, projects: {} };\n const p = projectCfg ?? { version: NVWA_CLI_CONFIG_VERSION, projects: {} };\n return {\n version: NVWA_CLI_CONFIG_VERSION,\n studioUrl: p.studioUrl ?? g.studioUrl,\n defaultProjectCode: p.defaultProjectCode ?? g.defaultProjectCode,\n projects: { ...(g.projects ?? {}), ...(p.projects ?? {}) },\n };\n}\n\nexport function loadNvwaCliConfig(cwd: string = process.cwd()): LoadedNvwaCliConfig {\n const globalPath = getGlobalNvwaConfigPath();\n const projectPath = findProjectNvwaConfigPath(cwd);\n const merged = mergeConfigs(readConfigFile(globalPath), projectPath ? readConfigFile(projectPath) : null);\n return { merged, globalPath, projectPath };\n}\n\nexport type NvwaCliCredentialResolution = {\n studioUrl: string;\n projectCode: string;\n integrationDocsToken: string;\n};\n\nexport function resolveNvwaCliCredential(opts?: {\n cwd?: string;\n projectCode?: string;\n}): NvwaCliCredentialResolution | null {\n const cwd = opts?.cwd ?? process.cwd();\n const { merged } = loadNvwaCliConfig(cwd);\n const projectCode = (opts?.projectCode ?? merged.defaultProjectCode ?? \"\").trim();\n if (!projectCode) return null;\n const entry = merged.projects?.[projectCode];\n const token = (entry?.integrationDocsToken ?? \"\").trim();\n const studioUrl = (merged.studioUrl ?? \"\").trim();\n if (!token || !studioUrl) return null;\n return { studioUrl: trimSlash(studioUrl), projectCode, integrationDocsToken: token };\n}\n\nfunction writeConfigFile(path: string, config: NvwaCliConfig): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, `${JSON.stringify(config, null, 2)}\\n`, { encoding: \"utf-8\", mode: 0o600 });\n try {\n chmodSync(path, 0o600);\n } catch {\n // best effort on platforms without chmod\n }\n}\n\nexport function writeNvwaCliProjectCredential(input: {\n cwd?: string;\n studioUrl: string;\n projectCode: string;\n integrationDocsToken: string;\n connectedBy?: string;\n /** When true, also write project-local .nvwa/config.json in git root */\n writeProjectFile?: boolean;\n}): { globalPath: string; projectPath: string | null } {\n const cwd = input.cwd ?? process.cwd();\n const code = input.projectCode.trim();\n const studioUrl = trimSlash(input.studioUrl.trim());\n const token = input.integrationDocsToken.trim();\n const now = new Date().toISOString();\n const cred: NvwaCliProjectCredential = {\n integrationDocsToken: token,\n connectedAt: now,\n connectedBy: input.connectedBy?.trim() || undefined,\n };\n\n const globalPath = getGlobalNvwaConfigPath();\n const globalCfg = readConfigFile(globalPath) ?? {\n version: NVWA_CLI_CONFIG_VERSION,\n projects: {},\n };\n globalCfg.version = NVWA_CLI_CONFIG_VERSION;\n globalCfg.studioUrl = studioUrl;\n globalCfg.defaultProjectCode = code;\n globalCfg.projects = { ...(globalCfg.projects ?? {}), [code]: cred };\n writeConfigFile(globalPath, globalCfg);\n\n let projectPath: string | null = null;\n if (input.writeProjectFile !== false && findGitRoot(cwd)) {\n projectPath = getProjectNvwaConfigPathForRepo(cwd);\n const projectCfg = readConfigFile(projectPath) ?? {\n version: NVWA_CLI_CONFIG_VERSION,\n projects: {},\n };\n projectCfg.version = NVWA_CLI_CONFIG_VERSION;\n projectCfg.studioUrl = studioUrl;\n projectCfg.defaultProjectCode = code;\n projectCfg.projects = { ...(projectCfg.projects ?? {}), [code]: cred };\n writeConfigFile(projectPath, projectCfg);\n }\n\n return { globalPath, projectPath };\n}\n\nexport function removeNvwaCliProjectCredential(input: {\n cwd?: string;\n projectCode: string;\n removeFromProjectFile?: boolean;\n}): void {\n const code = input.projectCode.trim();\n const globalPath = getGlobalNvwaConfigPath();\n const globalCfg = readConfigFile(globalPath);\n if (globalCfg?.projects?.[code]) {\n delete globalCfg.projects[code];\n if (globalCfg.defaultProjectCode === code) delete globalCfg.defaultProjectCode;\n writeConfigFile(globalPath, globalCfg);\n }\n\n if (input.removeFromProjectFile !== false) {\n const cwd = input.cwd ?? process.cwd();\n const projectPath = findProjectNvwaConfigPath(cwd);\n if (projectPath) {\n const projectCfg = readConfigFile(projectPath);\n if (projectCfg?.projects?.[code]) {\n delete projectCfg.projects[code];\n if (projectCfg.defaultProjectCode === code) delete projectCfg.defaultProjectCode;\n writeConfigFile(projectPath, projectCfg);\n }\n }\n }\n}\n\nexport function formatNvwaCliWhoami(cwd: string = process.cwd()): {\n globalPath: string;\n projectPath: string | null;\n studioUrl: string | null;\n projectCode: string | null;\n hasToken: boolean;\n connectedAt: string | null;\n} {\n const loaded = loadNvwaCliConfig(cwd);\n const code = loaded.merged.defaultProjectCode?.trim() ?? \"\";\n const entry = code ? loaded.merged.projects?.[code] : undefined;\n return {\n globalPath: loaded.globalPath,\n projectPath: loaded.projectPath,\n studioUrl: loaded.merged.studioUrl ?? null,\n projectCode: code || null,\n hasToken: !!(entry?.integrationDocsToken ?? \"\").trim(),\n connectedAt: entry?.connectedAt ?? null,\n };\n}\n",
|
|
23
|
+
"/** Structured agent / worker / callback trace lines (stderr). Never pass secrets or tokens. */\nexport type AgentTraceFields = Record<string, string | number | boolean | null | undefined>;\n\nconst SENSITIVE_KEY =\n /secret|token|password|authorization|callbacksecret|x-nvwa|rawinput|requirementrawinput|logs$/i;\n\nexport function isAgentToolTraceEnabled(): boolean {\n const raw = (process.env.NVWA_AGENT_TOOL_TRACE ?? \"1\").trim();\n return raw !== \"0\" && raw.toLowerCase() !== \"false\";\n}\n\nexport function formatAgentTraceLine(event: string, fields: AgentTraceFields): string {\n const parts: string[] = [`event=${event}`];\n for (const [key, value] of Object.entries(fields)) {\n if (value === undefined) continue;\n if (SENSITIVE_KEY.test(key)) continue;\n const v = value === null ? \"null\" : String(value);\n const safe = v.includes(\" \") ? JSON.stringify(v) : v;\n parts.push(`${key}=${safe}`);\n }\n return `[agent-trace] ${parts.join(\" \")}`;\n}\n\nexport function logAgentTrace(event: string, fields: AgentTraceFields = {}): void {\n console.error(formatAgentTraceLine(event, fields));\n}\n\n/** Agent Pod skill/tool traces; disable with NVWA_AGENT_TOOL_TRACE=0. */\nexport function logAgentToolTrace(event: string, fields: AgentTraceFields = {}): void {\n if (!isAgentToolTraceEnabled()) return;\n logAgentTrace(event, fields);\n}\n\nexport type SkillToolTraceArgs = Record<string, string | number | boolean | null | undefined>;\n",
|
|
24
|
+
"/**\n * Integration vendor-docs + runtime client playbook suffixes for Agent prompts.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport type { AgentJobConfigV1 } from \"../common/src/agent-job-config.ts\";\nimport {\n INTEGRATION_CLIENT_PACKAGE,\n INTEGRATION_CLIENT_VERSION_RANGE,\n} from \"../common/src/integration-client-package.ts\";\nimport { resolveIntegrationDocsClientConfig } from \"../common/src/integration-docs-client.ts\";\nimport { AGENT_PLAYBOOK_PATHS } from \"./agent-playbook-paths.ts\";\nimport { logSkillPlaybookInjected } from \"./agent-skill-context.ts\";\n\nconst PLAYBOOK_MAX_CHARS = 4096;\n\nfunction resolvePlaybookPath(imagePath: string): string {\n if (existsSync(imagePath)) return imagePath;\n const parts = imagePath.replace(/\\\\/g, \"/\").split(\"/\");\n const skillDir = parts[parts.length - 2];\n const file = parts[parts.length - 1];\n if (skillDir && file) {\n const repoPath = join(import.meta.dir, \"skills\", skillDir, file);\n if (existsSync(repoPath)) return repoPath;\n }\n return imagePath;\n}\n\nfunction readSkillPlaybook(path: string): string {\n const resolved = resolvePlaybookPath(path);\n try {\n if (!existsSync(resolved)) return \"\";\n return readFileSync(resolved, \"utf-8\").slice(0, PLAYBOOK_MAX_CHARS);\n } catch {\n return \"\";\n }\n}\n\nexport function integrationDocsPromptSuffix(spec: AgentJobConfigV1): string {\n const resolved = resolveIntegrationDocsClientConfig();\n const base =\n spec.integrationDocsHints?.apiBaseUrl?.trim() || resolved?.apiBaseUrl || \"\";\n if (!base) return \"\";\n const pb = readSkillPlaybook(AGENT_PLAYBOOK_PATHS.integrationDocs);\n logSkillPlaybookInjected(spec, \"nvwa-integration-docs\", pb.length, pb.length > 0);\n return pb\n ? `\\n\\n## Integration vendor docs\\nAPI base: ${base}\\nUse \\`/usr/local/bin/nvwa-os integration-docs …\\` (token in NVWA_INTEGRATION_DOCS_TOKEN). Prefer cached artifacts; fallback to sourceUrl from responses only when needed.\\n${pb}\\n`\n : `\\n\\n## Integration vendor docs\\nAPI base: ${base}\\nUse nvwa-os integration-docs CLI.\\n`;\n}\n\nconst E2E_INTEGRATION_NOTE = `\n### E2E / Playwright\n- Reuse e2e/support/integration-sim.ts (resolveIntegrationBaseUrl from ${INTEGRATION_CLIENT_PACKAGE}).\n- Validation Job extras include platform-injected INTEGRATION_*_BASE_URL; steps only read those env keys.\n- Do not add E2E_INTEGRATION_*_TIER to validation profiles (rejected).\n`;\n\nexport function integrationClientPromptSuffix(\n spec: AgentJobConfigV1,\n opts?: { e2e?: boolean },\n): string {\n const pb = readSkillPlaybook(AGENT_PLAYBOOK_PATHS.integrationClient);\n const e2eBlock = opts?.e2e ? E2E_INTEGRATION_NOTE : \"\";\n const intro =\n `\\n\\n## Integration runtime (business app)\\nUse \\`${INTEGRATION_CLIENT_PACKAGE}\\` to read \\`INTEGRATION_*_BASE_URL\\` (platform chooses sim vs real). Add npm dependency \\`\"${INTEGRATION_CLIENT_PACKAGE}\": \"${INTEGRATION_CLIENT_VERSION_RANGE}\"\\` — do not copy or inline URL helpers. Do not branch on E2E or tier env to pick URL.\\n`;\n logSkillPlaybookInjected(\n spec,\n \"nvwa-integration-client\",\n pb.length + intro.length + e2eBlock.length,\n true,\n );\n return `${intro}${e2eBlock}${pb ? `\\n${pb}\\n` : \"\"}`;\n}\n\n/** Business-repo pipelines: runtime client + optional vendor-docs (when hints configured). */\nexport function integrationBusinessPromptSuffix(\n spec: AgentJobConfigV1,\n opts?: { e2e?: boolean },\n): string {\n return integrationClientPromptSuffix(spec, opts) + integrationDocsPromptSuffix(spec);\n}\n",
|
|
25
|
+
"/**\n * Published npm coordinates for @nvwa-os/integration-client.\n * Keep in sync with packages/integration-client/package.json when releasing.\n * @see spec/foundation/integration-client.md\n */\n\nexport const INTEGRATION_CLIENT_PACKAGE = \"@nvwa-os/integration-client\";\n\nexport const INTEGRATION_CLIENT_VERSION_RANGE = \"^0.0.1\";\n\nexport const INTEGRATION_CLIENT_DEPENDENCY = {\n [INTEGRATION_CLIENT_PACKAGE]: INTEGRATION_CLIENT_VERSION_RANGE,\n} as const;\n",
|
|
26
|
+
"import { mkdirSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport type { AgentJobConfigV1 } from \"../common/src/agent-job-config.ts\";\nimport {\n intakeAttachmentContentUrlFromCallback,\n intakeMaterializedLocalFileName,\n} from \"../common/src/requirement-intake.ts\";\nimport { AGENT_OUTPUT_ROOT } from \"./agent-worker-paths.ts\";\n\nexport function requirementIntakeWorkspaceDir(): string {\n const root = (process.env.NVWA_AGENT_OUTPUT_ROOT ?? \"\").trim() || AGENT_OUTPUT_ROOT;\n return join(root, \"requirement-intake\");\n}\n\nexport type MaterializedIntakeImage = {\n id: string;\n fileName: string;\n intakeIndex: number;\n localPath: string;\n};\n\nlet fetchImpl: typeof fetch = fetch;\n\nexport function __setFetchImplForTests(fn: typeof fetch | null): void {\n fetchImpl = fn ?? fetch;\n}\n\nexport async function materializeRequirementIntakeImages(\n spec: AgentJobConfigV1,\n): Promise<MaterializedIntakeImage[]> {\n const items = spec.requirementIntakeAttachments ?? [];\n if (items.length === 0) return [];\n\n const secret = (process.env.NVWA_CALLBACK_SECRET ?? \"\").trim();\n if (!secret) {\n console.warn(\"[nvwa-agent] skip intake materialize: missing NVWA_CALLBACK_SECRET\");\n return [];\n }\n\n mkdirSync(requirementIntakeWorkspaceDir(), { recursive: true });\n const out: MaterializedIntakeImage[] = [];\n\n for (let i = 0; i < items.length; i++) {\n const item = items[i]!;\n const intakeIndex =\n typeof item.intakeIndex === \"number\" && item.intakeIndex >= 1\n ? Math.floor(item.intakeIndex)\n : i + 1;\n const url = intakeAttachmentContentUrlFromCallback(spec.callbackUrl, item.id);\n if (!url) {\n console.warn(`[nvwa-agent] skip intake ${item.id}: invalid callbackUrl`);\n continue;\n }\n try {\n const res = await fetchImpl(url, {\n headers: { \"X-Nvwa-Callback-Secret\": secret },\n });\n if (!res.ok) {\n console.warn(`[nvwa-agent] intake fetch failed ${item.id}: HTTP ${res.status}`);\n continue;\n }\n const buf = new Uint8Array(await res.arrayBuffer());\n const localName = intakeMaterializedLocalFileName(intakeIndex, item.id, item.mimeType);\n const localPath = join(requirementIntakeWorkspaceDir(), localName);\n writeFileSync(localPath, buf);\n out.push({\n id: item.id,\n fileName: item.fileName,\n intakeIndex,\n localPath,\n });\n } catch (e) {\n console.warn(`[nvwa-agent] intake materialize error ${item.id}`, e);\n }\n }\n\n return out;\n}\n",
|
|
27
|
+
"/** Repo paths agents must not delete (platform security contracts). */\n\nexport const SECURITY_PROTECTED_PATH_PREFIXES = [\n \"nvwa.semgrep.yml\",\n \"nvwa.validation.yml\",\n \"spec/behaviors/01-auth/api-unauthenticated.feature\",\n \"spec/api-contracts/nvwa-os/openapi.yaml\",\n \"spec/api-contracts/nvwa-os/auth-regression-paths.json\",\n \"spec/api-contracts/nvwa-os/excluded-routes.json\",\n \"spec/api-contracts/nvwa-os/paths/\",\n] as const;\n\nexport function isSecurityProtectedRepoPath(relPath: string): boolean {\n const p = relPath.replace(/\\\\/g, \"/\").replace(/^\\.\\//, \"\").trim();\n if (!p) return false;\n for (const prefix of SECURITY_PROTECTED_PATH_PREFIXES) {\n if (p === prefix || p.startsWith(prefix)) return true;\n }\n return false;\n}\n\n/** Git `name-status` lines (`D\\tpath`) for deleted protected paths. */\nexport function findDeletedProtectedPaths(nameStatusLines: string[]): string[] {\n const out: string[] = [];\n for (const line of nameStatusLines) {\n const t = line.trim();\n if (!t.startsWith(\"D\")) continue;\n const parts = t.split(/\\s+/);\n const rel = parts.length >= 2 ? parts.slice(1).join(\" \") : \"\";\n if (rel && isSecurityProtectedRepoPath(rel) && !out.includes(rel)) out.push(rel);\n }\n return out;\n}\n",
|
|
28
|
+
"import { spawnSync } from \"node:child_process\";\nimport {\n cpSync,\n existsSync,\n mkdirSync,\n mkdtempSync,\n readFileSync,\n rmSync,\n} from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport type PushGateFailureKind =\n | \"docker_parity\"\n | \"frozen_lockfile\"\n | \"bun_audit\"\n | \"check_behaviors\";\n\nexport type PushGateCheckResult =\n | { ok: true }\n | { ok: false; kind: PushGateFailureKind; error: string; auditFindings?: string[] };\n\nconst OUTPUT_TAIL_MAX = 2500;\n\nexport function formatPushGateCallbackError(kind: PushGateFailureKind, detail: string): string {\n const trimmed = detail.trim();\n return trimmed.startsWith(`push_gate:${kind}:`)\n ? trimmed\n : `push_gate:${kind}: ${trimmed}`;\n}\n\nexport function extractAuditAdvisoryLines(output: string): string[] {\n const lines: string[] = [];\n for (const raw of output.split(/\\r?\\n/)) {\n const line = raw.trim();\n if (!line) continue;\n const lower = line.toLowerCase();\n if (\n /cve-\\d{4}-\\d+/i.test(line) ||\n /ghsa-[a-z0-9-]+/i.test(line) ||\n /^\\s*(critical|high|moderate|low):/i.test(line) ||\n lower.includes(\"vulnerabilit\")\n ) {\n lines.push(line.slice(0, 500));\n }\n }\n return lines.slice(0, 20);\n}\n\nfunction formatOutputTail(output: string, advisoryLines?: string[]): string {\n const advisories = advisoryLines ?? extractAuditAdvisoryLines(output);\n if (advisories.length > 0) {\n const body = advisories.join(\"\\n\");\n return body.length <= OUTPUT_TAIL_MAX ? body : `${body.slice(0, OUTPUT_TAIL_MAX - 20)}\\n…(truncated)`;\n }\n const trimmed = output.trim();\n if (!trimmed) return \"\";\n return trimmed.length <= OUTPUT_TAIL_MAX\n ? trimmed\n : `${trimmed.slice(-OUTPUT_TAIL_MAX)}`;\n}\n\nfunction spawnCheck(\n args: string[],\n cwd: string,\n timeout: number,\n): { status: number | null; stdout: string; stderr: string } {\n const result = spawnSync(\"bun\", args, { cwd, encoding: \"utf8\", timeout });\n return {\n status: result.status,\n stdout: result.stdout ?? \"\",\n stderr: result.stderr ?? \"\",\n };\n}\n\nexport function verifyBehaviorsPushGate(dir: string): PushGateCheckResult {\n const result = spawnCheck([\"run\", \"check:behaviors\"], dir, 300_000);\n if (result.status === 0) return { ok: true };\n const combined = `${result.stdout}\\n${result.stderr}`;\n const tail = formatOutputTail(combined);\n return {\n ok: false,\n kind: \"check_behaviors\",\n error: formatPushGateCallbackError(\n \"check_behaviors\",\n `check:behaviors failed before push${tail ? `:\\n${tail}` : \"\"}`,\n ),\n };\n}\n\nexport function verifyFrozenLockfilePushGate(dir: string): PushGateCheckResult {\n const result = spawnCheck([\"install\", \"--frozen-lockfile\"], dir, 180_000);\n if (result.status === 0) return { ok: true };\n const combined = `${result.stdout}\\n${result.stderr}`;\n const tail = formatOutputTail(combined);\n return {\n ok: false,\n kind: \"frozen_lockfile\",\n error: formatPushGateCallbackError(\n \"frozen_lockfile\",\n `bun install --frozen-lockfile failed before push${tail ? `:\\n${tail}` : \"\"}`,\n ),\n };\n}\n\nexport function verifyBunAuditPushGate(dir: string): PushGateCheckResult {\n const result = spawnCheck([\"audit\"], dir, 120_000);\n if (result.status === 0) return { ok: true };\n const combined = `${result.stdout}\\n${result.stderr}`;\n const auditFindings = extractAuditAdvisoryLines(combined);\n const tail = formatOutputTail(combined, auditFindings);\n return {\n ok: false,\n kind: \"bun_audit\",\n error: formatPushGateCallbackError(\n \"bun_audit\",\n `bun audit failed before push${tail ? `:\\n${tail}` : \"\"}`,\n ),\n auditFindings,\n };\n}\n\nexport function verifyDockerParityPushGate(dir: string): PushGateCheckResult {\n const targets = [\n { label: \"apps/server/Dockerfile\", path: join(dir, \"apps/server/Dockerfile\") },\n { label: \"apps/web/Dockerfile\", path: join(dir, \"apps/web/Dockerfile\") },\n ];\n for (const target of targets) {\n if (!existsSync(target.path)) {\n return {\n ok: false,\n kind: \"docker_parity\",\n error: formatPushGateCallbackError(\n \"docker_parity\",\n `docker-parity check requires ${target.label} in workspace`,\n ),\n };\n }\n const dockerfile = readFileSync(target.path, \"utf-8\");\n const copyPaths = packageJsonCopyPathsFromDockerfile(dockerfile);\n const installResult = verifyFrozenLockfileInCopySandbox(dir, copyPaths, target.label);\n if (!installResult.ok) return installResult;\n }\n return { ok: true };\n}\n\nfunction packageJsonCopyPathsFromDockerfile(dockerfile: string): Set<string> {\n const copied = new Set<string>();\n const PACKAGE_JSON_COPY_RE =\n /^COPY\\s+packages\\/([a-z0-9-]+)\\/package\\.json\\s+\\.\\/packages\\/\\1\\//gm;\n const APP_PACKAGE_JSON_COPY_RE =\n /^COPY\\s+apps\\/([a-z0-9-]+)\\/package\\.json\\s+\\.\\/apps\\/\\1\\//gm;\n for (const re of [PACKAGE_JSON_COPY_RE, APP_PACKAGE_JSON_COPY_RE]) {\n re.lastIndex = 0;\n for (const m of dockerfile.matchAll(re)) {\n const line = m[0] ?? \"\";\n const name = m[1]?.trim();\n if (!name) continue;\n copied.add(line.startsWith(\"COPY packages/\") ? `packages/${name}` : `apps/${name}`);\n }\n }\n return copied;\n}\n\nfunction verifyFrozenLockfileInCopySandbox(\n dir: string,\n copyPaths: Set<string>,\n label: string,\n): PushGateCheckResult {\n let tmpDir: string | null = null;\n try {\n tmpDir = mkdtempSync(join(tmpdir(), \"nvwa-docker-parity-\"));\n cpSync(join(dir, \"package.json\"), join(tmpDir, \"package.json\"));\n cpSync(join(dir, \"bun.lock\"), join(tmpDir, \"bun.lock\"));\n for (const rel of copyPaths) {\n const src = join(dir, rel, \"package.json\");\n if (!existsSync(src)) {\n return {\n ok: false,\n kind: \"docker_parity\",\n error: formatPushGateCallbackError(\n \"docker_parity\",\n `${label}: ${rel}/package.json is in Dockerfile COPY list but missing in workspace`,\n ),\n };\n }\n mkdirSync(join(tmpDir, rel), { recursive: true });\n cpSync(src, join(tmpDir, rel, \"package.json\"));\n }\n const result = spawnCheck([\"install\", \"--frozen-lockfile\"], tmpDir, 180_000);\n if (result.status === 0) return { ok: true };\n const combined = `${result.stdout}\\n${result.stderr}`;\n const tail = formatOutputTail(combined);\n return {\n ok: false,\n kind: \"docker_parity\",\n error: formatPushGateCallbackError(\n \"docker_parity\",\n `${label} docker-parity bun install --frozen-lockfile failed${tail ? `:\\n${tail}` : \"\"}`,\n ),\n };\n } finally {\n if (tmpDir) {\n try {\n rmSync(tmpDir, { recursive: true, force: true });\n } catch {\n /* ignore */\n }\n }\n }\n}\n\n/** Run IMPLEMENTATION code-task push gates in pipeline order. Stops at first failure. */\nexport function runFeaturePushGates(dir: string): PushGateCheckResult {\n for (const check of [\n verifyDockerParityPushGate,\n verifyFrozenLockfilePushGate,\n verifyBunAuditPushGate,\n ]) {\n const result = check(dir);\n if (!result.ok) return result;\n }\n return { ok: true };\n}\n\n/** Legacy string-only wrappers (tests / callers expecting old shape). */\nexport function verifyBehaviorsBeforePush(\n dir: string,\n): { ok: true } | { ok: false; error: string } {\n const result = verifyBehaviorsPushGate(dir);\n return result.ok ? { ok: true } : { ok: false, error: result.error };\n}\n\nexport function verifyFrozenLockfileBeforePush(\n dir: string,\n): { ok: true } | { ok: false; error: string } {\n const result = verifyFrozenLockfilePushGate(dir);\n return result.ok ? { ok: true } : { ok: false, error: result.error };\n}\n\nexport function verifyBunAuditBeforePush(\n dir: string,\n): { ok: true } | { ok: false; error: string } {\n const result = verifyBunAuditPushGate(dir);\n return result.ok ? { ok: true } : { ok: false, error: result.error };\n}\n\nexport function verifyDockerParityLockfile(\n dir: string,\n): { ok: true } | { ok: false; error: string } {\n const result = verifyDockerParityPushGate(dir);\n return result.ok ? { ok: true } : { ok: false, error: result.error };\n}\n",
|
|
29
|
+
"import YAML from \"yaml\";\n\nexport const DECLARED_BUILD_FILE = \"nvwa.build.yml\" as const;\n\nexport const DEFAULT_WORKSPACE_INSTALL_COMMAND = \"bun install --frozen-lockfile\";\nexport const DEFAULT_WORKSPACE_LOCK_FILE = \"bun.lock\";\nexport const DEFAULT_WORKSPACE_MODULES_DIR = \"node_modules\";\n\nexport type DeclaredCompileGateConfig = {\n imageFromBuild: string;\n commands?: string[];\n lockFile?: string;\n modulesDir?: string;\n timeoutSeconds?: number;\n};\n\nexport type ResolvedWorkspaceToolchain = {\n installCommand: string;\n lockFile: string;\n modulesDir: string;\n};\n\nfunction nvwaBlockFromDoc(doc: unknown): Record<string, unknown> | null {\n if (!doc || typeof doc !== \"object\" || Array.isArray(doc)) return null;\n const nvwa = (doc as Record<string, unknown>).nvwa;\n if (!nvwa || typeof nvwa !== \"object\" || Array.isArray(nvwa)) return null;\n return nvwa as Record<string, unknown>;\n}\n\nfunction parseCommands(raw: unknown): string[] | undefined {\n if (raw == null) return undefined;\n if (!Array.isArray(raw)) {\n throw new Error(\"compile gate: nvwa.compileGate.commands must be a list of strings\");\n }\n const out: string[] = [];\n for (const item of raw) {\n if (typeof item !== \"string\" || item.trim() === \"\") {\n throw new Error(\"compile gate: nvwa.compileGate.commands entries must be non-empty strings\");\n }\n out.push(item.trim());\n }\n return out.length > 0 ? out : undefined;\n}\n\nfunction parseOptionalPathField(\n raw: unknown,\n field: \"lockFile\" | \"modulesDir\",\n): string | undefined {\n if (raw == null) return undefined;\n if (typeof raw !== \"string\" || !raw.trim()) {\n throw new Error(`compile gate: nvwa.compileGate.${field} must be a non-empty string`);\n }\n return raw.trim();\n}\n\nfunction parseCompileGateBlock(block: Record<string, unknown>): DeclaredCompileGateConfig {\n const imageFromBuild =\n typeof block.imageFromBuild === \"string\" ? block.imageFromBuild.trim() : \"\";\n if (!imageFromBuild) {\n throw new Error(\n \"compile gate: nvwa.compileGate.imageFromBuild is required when nvwa.compileGate is present\",\n );\n }\n\n const commands = parseCommands(block.commands);\n const lockFile = parseOptionalPathField(block.lockFile, \"lockFile\");\n const modulesDir = parseOptionalPathField(block.modulesDir, \"modulesDir\");\n\n let timeoutSeconds: number | undefined;\n if (block.timeoutSeconds != null) {\n const n = Number(block.timeoutSeconds);\n if (!Number.isFinite(n) || n <= 0) {\n throw new Error(\"compile gate: nvwa.compileGate.timeoutSeconds must be a positive number\");\n }\n timeoutSeconds = Math.floor(n);\n }\n\n return {\n imageFromBuild,\n ...(commands ? { commands } : {}),\n ...(lockFile ? { lockFile } : {}),\n ...(modulesDir ? { modulesDir } : {}),\n ...(timeoutSeconds != null ? { timeoutSeconds } : {}),\n };\n}\n\n/** Parse `nvwa.compileGate` from `nvwa.build.yml` text. Returns null when block absent. */\nexport function parseDeclaredCompileGateFromText(content: string): DeclaredCompileGateConfig | null {\n const t = content.trim();\n if (t === \"\") return null;\n\n let doc: unknown;\n try {\n doc = YAML.parse(t) as unknown;\n } catch {\n throw new Error(\"compile gate: invalid YAML\");\n }\n\n const nvwa = nvwaBlockFromDoc(doc);\n if (!nvwa) return null;\n\n const compileGate = nvwa.compileGate;\n if (compileGate && typeof compileGate === \"object\" && !Array.isArray(compileGate)) {\n return parseCompileGateBlock(compileGate as Record<string, unknown>);\n }\n\n return null;\n}\n\nexport function resolveWorkspaceToolchain(\n cfg: DeclaredCompileGateConfig,\n): ResolvedWorkspaceToolchain {\n return {\n installCommand: cfg.commands?.[0]?.trim() || DEFAULT_WORKSPACE_INSTALL_COMMAND,\n lockFile: cfg.lockFile?.trim() || DEFAULT_WORKSPACE_LOCK_FILE,\n modulesDir: cfg.modulesDir?.trim() || DEFAULT_WORKSPACE_MODULES_DIR,\n };\n}\n",
|
|
30
|
+
"/**\n * Playwright parallel worker resolution for Validation Job / local BDD.\n * Pure env parsing — no Playwright or e2e step imports.\n *\n * Validation Job with E2E_WORKERS>1 runs two phases (runner.ts):\n * 1. `@parallel-safe` scenarios — N workers, shared E2E_PROJECT_CODE\n * 2. all other scenarios — workers=1, same E2E_PROJECT_CODE\n */\n\nexport const PLAYWRIGHT_WORKERS_MAX = 8;\n\nexport const E2E_WORKERS_ENV = \"E2E_WORKERS\";\nexport const NVWA_VALIDATION_AUTH_DIR_ENV = \"NVWA_VALIDATION_AUTH_DIR\";\nexport const NVWA_VALIDATION_PARALLEL_PHASE_ENV = \"NVWA_VALIDATION_PARALLEL_PHASE\";\nexport const PARALLEL_SAFE_TAG = \"@parallel-safe\";\n\n/** Shared authoring rules for L3 / P2 agents and Cursor rules (keep in sync with spec/behaviors/root.md). */\nexport const PARALLEL_SAFE_AUTHORING_RULES = `\n## Gherkin parallel declaration (Validation Job \\`E2E_WORKERS\\`>1)\n- **Default serial**: scenarios without a tag run in Phase 2 (workers=1). No tag required for factory/scan/merge/board writes.\n- **Opt-in \\`@parallel-safe\\`**: add on feature or scenario only when read-only UI shell or unauthenticated API; no scan world-state; no bulk factory, git merge, or board mutations; not \\`@tier:guided\\` / \\`@tier:pipeline\\`.\n- **Allowed world-state with \\`@parallel-safe\\`**: \\`nvwa.auth.logged_out\\` only (per-browser session).\n- **Do not** combine \\`@parallel-safe\\` with \\`@serial\\`. \\`@serial\\` is optional legacy documentation — prefer leaving untagged for serial.\n- Gate: \\`bun run check:behaviors\\` (\\`scripts/check-parallel-safe.ts\\`). See \\`spec/behaviors/root.md\\`.\n`.trim();\n\nconst PROJECT_CODE_RE = /^[a-zA-Z0-9][a-zA-Z0-9-]{1,29}$/;\n\nexport type PlaywrightParallelEnv = Record<string, string | undefined>;\nexport type ValidationParallelPhase = \"safe\" | \"serial\" | \"all\";\n\nfunction trimEnv(env: PlaywrightParallelEnv, name: string): string {\n return env[name]?.trim() ?? \"\";\n}\n\nfunction escapeRegExp(tag: string): string {\n return tag.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/** Parse `E2E_WORKERS`; invalid / missing → 1. Clamps to [1, PLAYWRIGHT_WORKERS_MAX]. */\nexport function resolvePlaywrightWorkersFromEnv(\n env: PlaywrightParallelEnv = process.env,\n): number {\n const raw = trimEnv(env, E2E_WORKERS_ENV);\n if (!raw) return 1;\n const n = Number.parseInt(raw, 10);\n if (!Number.isFinite(n) || n < 1) return 1;\n return Math.min(n, PLAYWRIGHT_WORKERS_MAX);\n}\n\n/** Runner phase: `safe` | `serial` | `all` (single run, E2E_WORKERS=1). */\nexport function resolveValidationParallelPhase(\n env: PlaywrightParallelEnv = process.env,\n): ValidationParallelPhase {\n const raw = trimEnv(env, NVWA_VALIDATION_PARALLEL_PHASE_ENV);\n if (raw === \"safe\") return \"safe\";\n if (raw === \"serial\") return \"serial\";\n return \"all\";\n}\n\n/** Effective Playwright workers for the current run / phase. */\nexport function resolvePlaywrightWorkersForRun(\n env: PlaywrightParallelEnv = process.env,\n): number {\n const phase = resolveValidationParallelPhase(env);\n const workers = resolvePlaywrightWorkersFromEnv(env);\n if (phase === \"serial\") return 1;\n if (phase === \"safe\") return workers;\n return workers;\n}\n\nfunction resolvePrimaryProjectCode(env: PlaywrightParallelEnv): string | null {\n const raw = trimEnv(env, \"E2E_PROJECT_CODE\");\n if (raw && PROJECT_CODE_RE.test(raw) && !raw.includes(\"-----\")) return raw;\n return null;\n}\n\n/** Shared fixture project for Validation Job (all workers / both phases). */\nexport function resolveProjectCodeFromEnv(\n env: PlaywrightParallelEnv = process.env,\n): string | null {\n return resolvePrimaryProjectCode(env);\n}\n\n/** @deprecated Use {@link resolveProjectCodeFromEnv}; kept for call-site compat. */\nexport function resolveProjectCodeForWorkerFromEnv(\n _workerIndex: number,\n env: PlaywrightParallelEnv = process.env,\n): string | null {\n return resolveProjectCodeFromEnv(env);\n}\n\nexport function resolveAuthDirFromEnv(env: PlaywrightParallelEnv = process.env): string {\n const fromDir = trimEnv(env, NVWA_VALIDATION_AUTH_DIR_ENV);\n if (fromDir) return fromDir;\n const legacyFile = trimEnv(env, \"NVWA_VALIDATION_AUTH_STATE_PATH\");\n if (legacyFile) {\n const lastSlash = legacyFile.lastIndexOf(\"/\");\n return lastSlash >= 0 ? legacyFile.slice(0, lastSlash) : legacyFile;\n }\n return \".features-gen/.auth\";\n}\n\n/** Per-worker admin storageState path (worker 0 → admin-worker-0.json). */\nexport function resolveAuthStatePathForWorker(\n workerIndex: number,\n env: PlaywrightParallelEnv = process.env,\n): string {\n const dir = resolveAuthDirFromEnv(env);\n const idx = Math.max(0, Math.floor(workerIndex));\n return `${dir}/admin-worker-${idx}.json`;\n}\n\n/** Legacy single-file path (worker 0 compat when workers=1). */\nexport function resolveLegacyAuthStatePath(env: PlaywrightParallelEnv = process.env): string {\n const legacy = trimEnv(env, \"NVWA_VALIDATION_AUTH_STATE_PATH\");\n if (legacy) return legacy;\n return `${resolveAuthDirFromEnv(env)}/admin.json`;\n}\n\n/** Per-worker auth only during parallel-safe phase with workers>1. */\nexport function usesPerWorkerAuth(env: PlaywrightParallelEnv = process.env): boolean {\n const phase = resolveValidationParallelPhase(env);\n const workers = resolvePlaywrightWorkersFromEnv(env);\n if (phase === \"safe\") return workers > 1;\n return false;\n}\n\n/**\n * Inject shared `admin.json` via BDD Before hook (playwright-bdd `use.storageState` gap).\n * - Phase `all` + workers=1: default single-run Validation Job / local BDD\n * - Phase `serial` + workers>1: multi-worker Phase 2\n */\nexport function usesSerialLegacyAuthInjection(env: PlaywrightParallelEnv = process.env): boolean {\n const phase = resolveValidationParallelPhase(env);\n const workers = resolvePlaywrightWorkersFromEnv(env);\n if (phase === \"all\" && workers <= 1) return true;\n return phase === \"serial\" && workers > 1;\n}\n\n/** Register BDD Before auth hook whenever per-worker or shared admin.json injection is required. */\nexport function shouldRegisterAuthBeforeHook(env: PlaywrightParallelEnv = process.env): boolean {\n if (usesPerWorkerAuth(env)) return true;\n if (usesSerialLegacyAuthInjection(env)) return true;\n return false;\n}\n\nexport function resolveFullyParallelForRun(env: PlaywrightParallelEnv = process.env): boolean {\n return resolvePlaywrightWorkersForRun(env) > 1;\n}\n\nexport function tagsToGrepRegExp(tags: string[]): RegExp | undefined {\n if (tags.length === 0) return undefined;\n if (tags.length === 1) return new RegExp(escapeRegExp(tags[0]!));\n return new RegExp(tags.map((tag) => `(?=.*${escapeRegExp(tag)})`).join(\"\"));\n}\n\nexport function tagsToGrepInvertRegExp(tags: string[]): RegExp | undefined {\n if (tags.length === 0) return undefined;\n return new RegExp(tags.map((tag) => escapeRegExp(tag)).join(\"|\"));\n}\n\nexport type ValidationGrepConfigInput = {\n grepRaw?: string;\n grepInvertRaw?: string;\n env?: PlaywrightParallelEnv;\n};\n\n/**\n * Build Playwright grep / grepInvert for validation runner or local BDD.\n * - Phase `safe`: only `@parallel-safe` (+ optional scope grep)\n * - Phase `serial`: exclude `@parallel-safe` (+ default @wip / @tier:pipeline)\n * - Phase `all` with workers>1 (local): only `@parallel-safe` (partial fast run)\n */\nexport function buildValidationGrepConfig(input: ValidationGrepConfigInput = {}): {\n grep?: RegExp;\n grepInvert?: RegExp;\n} {\n const env = input.env ?? process.env;\n const phase = resolveValidationParallelPhase(env);\n const workers = resolvePlaywrightWorkersFromEnv(env);\n\n const grepInvertRaw = (input.grepInvertRaw ?? \"\").trim();\n const grepRaw = (input.grepRaw ?? \"\").trim();\n const grepInvertTags = grepInvertRaw\n ? grepInvertRaw.split(\",\").map((t) => t.trim()).filter(Boolean)\n : [\"@wip\", \"@tier:pipeline\"];\n const scopeGrepTags = grepRaw\n ? grepRaw.split(\",\").map((t) => t.trim()).filter(Boolean)\n : [];\n\n if (phase === \"safe\" || (phase === \"all\" && workers > 1)) {\n const includeTags = [...scopeGrepTags, PARALLEL_SAFE_TAG];\n return { grep: tagsToGrepRegExp(includeTags) };\n }\n\n if (phase === \"serial\" && workers > 1) {\n const invertTags = [...grepInvertTags];\n if (!invertTags.includes(PARALLEL_SAFE_TAG)) invertTags.push(PARALLEL_SAFE_TAG);\n return {\n ...(scopeGrepTags.length > 0 ? { grep: tagsToGrepRegExp(scopeGrepTags) } : {}),\n grepInvert: tagsToGrepInvertRegExp(invertTags),\n };\n }\n\n if (scopeGrepTags.length > 0) {\n return { grep: tagsToGrepRegExp(scopeGrepTags) };\n }\n if (grepInvertTags.length > 0) {\n return { grepInvert: tagsToGrepInvertRegExp(grepInvertTags) };\n }\n return {};\n}\n",
|
|
31
|
+
"import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { spawnSync } from \"node:child_process\";\n\nimport { PARALLEL_SAFE_AUTHORING_RULES } from \"../common/src/e2e-playwright-parallel.ts\";\n\n/** Ephemeral job output under the clone (excluded from git commit). */\nconst AGENT_OUT_REL = \"agent-out\";\n\nconst SPEC_CHANGE_PREFIXES = [\n \"spec/foundation/\",\n \"spec/capabilities/\",\n \"spec/behaviors/\",\n \"spec/ui-contracts/\",\n] as const;\n\nexport type RewriteClarification = {\n id: string;\n prompt: string;\n options: { id: string; label: string }[];\n defaultOptionId: string;\n};\n\nexport type SpecBootstrapL1 = {\n entitiesMd: string;\n rulesMd: string;\n runtimeYaml: string;\n};\n\nexport type SpecBootstrapL2 = {\n relativePathSuggestion: string;\n markdown: string;\n};\n\nexport type SpecBootstrapAcceptanceHint = {\n featurePath: string;\n scenarioTitle: string;\n suggestedRequirementTag?: string;\n};\n\nexport type SpecBootstrapPayload = {\n l1: SpecBootstrapL1;\n l2: SpecBootstrapL2;\n clarifications: RewriteClarification[];\n suggestedBehaviorPaths?: string[];\n acceptanceScenarioHints?: SpecBootstrapAcceptanceHint[];\n};\n\nexport type RewritePayload = {\n title: string;\n body: string;\n clarifications: RewriteClarification[];\n};\n\nexport type RewriteCallbackMeta = {\n title?: string;\n /** Studio card requirement body (Markdown); written in L3 to callback meta, not a separate file under spec/. */\n body?: string;\n clarifications?: RewriteClarification[];\n suggestedBehaviorPaths?: string[];\n acceptanceScenarioHints?: SpecBootstrapAcceptanceHint[];\n /** Repo-relative path to L2 capability doc, e.g. spec/capabilities/my-feature.md */\n l2RelativePath?: string;\n};\n\nexport type RewriteWorkspacePaths = {\n l1Entities: string;\n l1Rules: string;\n l1Runtime: string;\n capabilitiesRoot: string;\n callbackMeta: string;\n};\n\nexport type RewriteChangeSummary = {\n files: string[];\n summary: string;\n};\n\nexport function slugFromRequirementTitle(title: string): string {\n const t = title.trim().slice(0, 56) || \"requirement\";\n const slug = t\n .replace(/[^\\p{L}\\p{N}]+/gu, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .toLowerCase();\n return slug || \"requirement\";\n}\n\nexport function normalizeRepoRelativePath(p: string): string | null {\n const t = p.trim().replace(/\\\\/g, \"/\");\n if (!t || t.startsWith(\"/\") || /^[a-zA-Z]:/.test(t) || t.split(\"/\").includes(\"..\")) {\n return null;\n }\n return t;\n}\n\nfunction isSpecCuratedPath(rel: string): boolean {\n const n = rel.replace(/\\\\/g, \"/\");\n return SPEC_CHANGE_PREFIXES.some((p) => n === p.slice(0, -1) || n.startsWith(p));\n}\n\n/**\n * L1–L3 rewrite 在目标仓库中的路径(与 spec/root.md 策展树一致)。\n * L2 由 Agent 选择能力名:`spec/capabilities/{能力名}.md` + `spec/capabilities/root.md` 索引。\n */\nexport function rewriteWorkspacePaths(_slug?: string): RewriteWorkspacePaths {\n return {\n l1Entities: \"spec/foundation/entities.md\",\n l1Rules: \"spec/foundation/rules.md\",\n l1Runtime: \"spec/foundation/runtime.yaml\",\n capabilitiesRoot: \"spec/capabilities/root.md\",\n callbackMeta: `${AGENT_OUT_REL}/rewrite-callback-meta.json`,\n };\n}\n\nfunction readRepoFile(dir: string, rel: string): string {\n const p = join(dir, rel);\n if (!existsSync(p)) return \"\";\n return readFileSync(p, \"utf-8\");\n}\n\nfunction firstNonDraftCapabilityPath(changes: string[]): string | null {\n for (const f of changes) {\n if (f.startsWith(\"spec/capabilities/\") && !f.includes(\"/drafts/\") && f.endsWith(\".md\")) {\n return f;\n }\n }\n return null;\n}\n\nexport function readRewriteCallbackMeta(dir: string, slug: string): RewriteCallbackMeta {\n const p = join(dir, rewriteWorkspacePaths(slug).callbackMeta);\n if (!existsSync(p)) return {};\n try {\n const raw = readFileSync(p, \"utf-8\");\n const o = JSON.parse(raw) as Record<string, unknown>;\n return {\n ...(typeof o.title === \"string\" ? { title: o.title } : {}),\n ...(typeof o.body === \"string\" ? { body: o.body } : {}),\n ...(Array.isArray(o.clarifications) ? { clarifications: o.clarifications as RewriteClarification[] } : {}),\n ...(Array.isArray(o.suggestedBehaviorPaths)\n ? { suggestedBehaviorPaths: o.suggestedBehaviorPaths.filter((x): x is string => typeof x === \"string\") }\n : {}),\n ...(Array.isArray(o.acceptanceScenarioHints)\n ? { acceptanceScenarioHints: o.acceptanceScenarioHints as SpecBootstrapAcceptanceHint[] }\n : {}),\n ...(typeof o.l2RelativePath === \"string\" ? { l2RelativePath: o.l2RelativePath } : {}),\n };\n } catch {\n return {};\n }\n}\n\n/** Spec files changed in working tree and/or vs integration branch. */\nexport function listSpecChangesInWorkspace(dir: string, integrationBranch?: string | null): string[] {\n const seen = new Set<string>();\n\n const addLines = (stdout: string) => {\n for (const line of stdout.split(\"\\n\")) {\n const t = line.trim().replace(/\\\\/g, \"/\");\n if (t && isSpecCuratedPath(t)) seen.add(t);\n }\n };\n\n for (const args of [\n [\"diff\", \"--name-only\"],\n [\"diff\", \"--name-only\", \"--cached\"],\n [\"ls-files\", \"--others\", \"--exclude-standard\"],\n ] as const) {\n const r = spawnSync(\"git\", [\"-C\", dir, ...args], { encoding: \"utf-8\" });\n if (r.status === 0 && r.stdout) addLines(r.stdout);\n }\n\n const base = integrationBranch?.trim();\n if (base) {\n const r = spawnSync(\"git\", [\"-C\", dir, \"diff\", \"--name-only\", `${base}...HEAD`], { encoding: \"utf-8\" });\n if (r.status === 0 && r.stdout) addLines(r.stdout);\n }\n\n return [...seen].sort();\n}\n\nexport function resolveL2CapabilityPath(meta: RewriteCallbackMeta): string | null {\n const fromMeta = normalizeRepoRelativePath(meta.l2RelativePath ?? \"\");\n if (fromMeta?.startsWith(\"spec/capabilities/\") && !fromMeta.includes(\"/drafts/\")) {\n return fromMeta;\n }\n return null;\n}\n\nexport function l2PhaseSatisfied(dir: string, meta: RewriteCallbackMeta, _slug?: string): boolean {\n const l2Rel = resolveL2CapabilityPath(meta);\n if (l2Rel && readRepoFile(dir, l2Rel).trim()) return true;\n const changed = listSpecChangesInWorkspace(dir);\n return changed.some((f) => f.startsWith(\"spec/capabilities/\") && !f.includes(\"/drafts/\"));\n}\n\nexport function l3PhaseSatisfied(dir: string, meta: RewriteCallbackMeta, _slug?: string): boolean {\n if ((meta.body ?? \"\").trim()) return true;\n const changed = listSpecChangesInWorkspace(dir);\n return changed.some(\n (f) => f.startsWith(\"spec/behaviors/\") || f.startsWith(\"spec/ui-contracts/\"),\n );\n}\n\nexport function buildChangeSummary(\n dir: string,\n integrationBranch: string | null | undefined,\n meta: RewriteCallbackMeta,\n built: { spec: SpecBootstrapPayload; rewrite: RewritePayload } | null,\n): RewriteChangeSummary {\n const files = listSpecChangesInWorkspace(dir, integrationBranch);\n const l2 = built?.spec.l2.relativePathSuggestion ?? meta.l2RelativePath ?? \"\";\n const parts: string[] = [];\n if (files.length > 0) {\n parts.push(`更新了 ${files.length} 个 spec 文件`);\n }\n if (l2) parts.push(`L2:${l2}`);\n if (built?.rewrite.body.trim()) {\n parts.push(`需求正文已写入 callback meta(${built.rewrite.body.trim().length} 字)`);\n }\n const summary =\n parts.length > 0 ? parts.join(\";\") : \"本次 rewrite 未检测到 spec 树变更(请检查 Agent 是否已写文件)\";\n return { files, summary };\n}\n\n/** Assemble server callback payload from repo + callback meta (emit_result phase). */\nexport function buildRewriteResultFromWorkspace(\n dir: string,\n fallbackTitle: string,\n meta?: RewriteCallbackMeta,\n opts?: { integrationBranch?: string | null },\n): { spec: SpecBootstrapPayload; rewrite: RewritePayload } | null {\n const paths = rewriteWorkspacePaths();\n const l2Rel = resolveL2CapabilityPath(meta ?? {});\n\n const entitiesMd = readRepoFile(dir, paths.l1Entities);\n const rulesMd = readRepoFile(dir, paths.l1Rules);\n const runtimeYaml = readRepoFile(dir, paths.l1Runtime);\n\n const specChanges = listSpecChangesInWorkspace(dir, opts?.integrationBranch);\n const l2PathFromChanges = firstNonDraftCapabilityPath(specChanges);\n const l2PathForSpec = l2Rel ?? l2PathFromChanges ?? \"\";\n const l2markdown = l2PathForSpec ? readRepoFile(dir, l2PathForSpec) : \"\";\n\n const body = (meta?.body ?? \"\").trim();\n\n const hasContent = Boolean(body || l2markdown.trim() || specChanges.length > 0);\n\n if (!hasContent) {\n return null;\n }\n\n const spec: SpecBootstrapPayload = {\n l1: { entitiesMd, rulesMd, runtimeYaml },\n l2: {\n relativePathSuggestion: l2PathForSpec,\n markdown: l2markdown.trim() || body.trim().slice(0, 8000),\n },\n clarifications: meta?.clarifications ?? [],\n ...(meta?.suggestedBehaviorPaths?.length ? { suggestedBehaviorPaths: meta.suggestedBehaviorPaths } : {}),\n ...(meta?.acceptanceScenarioHints?.length\n ? { acceptanceScenarioHints: meta.acceptanceScenarioHints }\n : {}),\n };\n\n const rewrite: RewritePayload = {\n title: (meta?.title ?? fallbackTitle).trim() || fallbackTitle,\n body: body.trim() || l2markdown.trim(),\n clarifications: meta?.clarifications ?? [],\n };\n\n return { spec, rewrite };\n}\n\nexport type DevelopmentGoalImplementationPlanDraft = {\n needsPhasedImplementation: boolean;\n reason?: string;\n subtasks?: Array<{ title: string; description: string; guidance: string }>;\n};\n\nexport type DevelopmentGoalDraft = {\n summary: string;\n body: string;\n acceptanceHints: string[];\n specRefs: {\n l2CapabilityPath?: string | null;\n /** Optional primary behavior feature path from L3 */\n l3RequirementPath?: string | null;\n suggestedBehaviorPaths?: string[];\n };\n phaseGuidance: {\n UI_CONTRACT: string;\n VALIDATION_CODE: string;\n IMPLEMENTATION: string;\n };\n implementationPlan?: DevelopmentGoalImplementationPlanDraft;\n};\n\nfunction extractJsonObjectText(raw: string): string | null {\n const t = raw.trim();\n const start = t.indexOf(\"{\");\n const end = t.lastIndexOf(\"}\");\n if (start < 0 || end <= start) return null;\n return t.slice(start, end + 1);\n}\n\nexport function readDevelopmentGoalJson(agentOutDir: string): DevelopmentGoalDraft | null {\n const p = join(agentOutDir, \"development-goal.json\");\n if (!existsSync(p)) return null;\n try {\n const raw = readFileSync(p, \"utf-8\");\n const text = extractJsonObjectText(raw) ?? raw.trim();\n const o = JSON.parse(text) as Record<string, unknown>;\n const body = typeof o.body === \"string\" ? o.body.trim() : \"\";\n if (!body) return null;\n const summary = typeof o.summary === \"string\" ? o.summary.trim() : body.slice(0, 120);\n const acceptanceHints: string[] = [];\n if (Array.isArray(o.acceptanceHints)) {\n for (const x of o.acceptanceHints) {\n if (typeof x === \"string\" && x.trim()) acceptanceHints.push(x.trim());\n }\n }\n const specRefs: DevelopmentGoalDraft[\"specRefs\"] = {};\n if (o.specRefs && typeof o.specRefs === \"object\" && !Array.isArray(o.specRefs)) {\n const s = o.specRefs as Record<string, unknown>;\n if (typeof s.l2CapabilityPath === \"string\" && s.l2CapabilityPath.trim()) {\n specRefs.l2CapabilityPath = s.l2CapabilityPath.trim();\n }\n if (typeof s.l3RequirementPath === \"string\" && s.l3RequirementPath.trim()) {\n specRefs.l3RequirementPath = s.l3RequirementPath.trim();\n }\n if (Array.isArray(s.suggestedBehaviorPaths)) {\n specRefs.suggestedBehaviorPaths = s.suggestedBehaviorPaths.filter(\n (x): x is string => typeof x === \"string\" && x.trim() !== \"\",\n );\n }\n }\n const defaultPhases = {\n UI_CONTRACT:\n \"P1:在 spec/ui-contracts/ 产出或更新本需求的 L4 Web UI 契约 JSON;不要实现业务页面代码。\",\n VALIDATION_CODE:\n `P2:在 spec/behaviors/ 与 e2e/ 编写或更新验证骨架;不要完成 P3 级业务 UI 实现。${PARALLEL_SAFE_AUTHORING_RULES}`,\n IMPLEMENTATION:\n \"P3:在 apps/* 实现可交付业务功能;必须产生可 git commit 的仓库变更。修改业务逻辑时须同步新增或更新 colocated unit tests(*.test.ts 或项目约定路径);纯 UI 布局可主要依赖 E2E,但不得破坏现有 bun test。\",\n };\n let phaseGuidance = defaultPhases;\n if (o.phaseGuidance && typeof o.phaseGuidance === \"object\" && !Array.isArray(o.phaseGuidance)) {\n const p = o.phaseGuidance as Record<string, unknown>;\n phaseGuidance = {\n UI_CONTRACT:\n typeof p.UI_CONTRACT === \"string\" && p.UI_CONTRACT.trim()\n ? p.UI_CONTRACT.trim()\n : defaultPhases.UI_CONTRACT,\n VALIDATION_CODE:\n typeof p.VALIDATION_CODE === \"string\" && p.VALIDATION_CODE.trim()\n ? p.VALIDATION_CODE.trim()\n : defaultPhases.VALIDATION_CODE,\n IMPLEMENTATION:\n typeof p.IMPLEMENTATION === \"string\" && p.IMPLEMENTATION.trim()\n ? p.IMPLEMENTATION.trim()\n : defaultPhases.IMPLEMENTATION,\n };\n }\n let implementationPlan: DevelopmentGoalImplementationPlanDraft | undefined;\n const planRaw = o.implementationPlan;\n if (planRaw && typeof planRaw === \"object\" && !Array.isArray(planRaw)) {\n const p = planRaw as Record<string, unknown>;\n const needsPhasedImplementation = p.needsPhasedImplementation === true;\n const reason = typeof p.reason === \"string\" ? p.reason.trim() : undefined;\n const subtasks: DevelopmentGoalImplementationPlanDraft[\"subtasks\"] = [];\n if (Array.isArray(p.subtasks)) {\n for (const row of p.subtasks) {\n if (!row || typeof row !== \"object\" || Array.isArray(row)) continue;\n const r = row as Record<string, unknown>;\n const title = typeof r.title === \"string\" ? r.title.trim() : \"\";\n const description = typeof r.description === \"string\" ? r.description.trim() : \"\";\n const guidance = typeof r.guidance === \"string\" ? r.guidance.trim() : \"\";\n if (!title) continue;\n subtasks.push({ title, description, guidance });\n }\n }\n implementationPlan = {\n needsPhasedImplementation,\n ...(reason ? { reason } : {}),\n ...(subtasks.length ? { subtasks } : {}),\n };\n }\n return {\n summary,\n body,\n acceptanceHints,\n specRefs,\n phaseGuidance,\n ...(implementationPlan ? { implementationPlan } : {}),\n };\n } catch {\n return null;\n }\n}\n\nexport function buildDegradedDevelopmentGoalDraft(input: {\n body: string;\n title: string;\n rawInput: string;\n meta?: RewriteCallbackMeta;\n spec?: SpecBootstrapPayload;\n l2CapabilityPath?: string | null;\n primaryBehaviorPath?: string | null;\n}): DevelopmentGoalDraft {\n const hints: string[] = [];\n for (const h of input.meta?.acceptanceScenarioHints ?? []) {\n hints.push(`${h.featurePath}: ${h.scenarioTitle}`);\n }\n const l2Path =\n input.l2CapabilityPath ??\n input.spec?.l2.relativePathSuggestion ??\n input.meta?.l2RelativePath ??\n null;\n const behaviorPaths =\n input.meta?.suggestedBehaviorPaths ?? input.spec?.suggestedBehaviorPaths ?? [];\n return {\n summary: input.title.slice(0, 120),\n body: input.body.trim(),\n acceptanceHints: hints,\n specRefs: {\n l2CapabilityPath: l2Path,\n l3RequirementPath: input.primaryBehaviorPath ?? behaviorPaths[0] ?? null,\n suggestedBehaviorPaths: behaviorPaths,\n },\n phaseGuidance: {\n UI_CONTRACT:\n \"P1:在 spec/ui-contracts/ 产出或更新本需求的 L4 Web UI 契约 JSON;不要实现业务页面代码。\",\n VALIDATION_CODE:\n `P2:在 spec/behaviors/ 与 e2e/ 编写或更新验证骨架;不要完成 P3 级业务 UI 实现。${PARALLEL_SAFE_AUTHORING_RULES}`,\n IMPLEMENTATION:\n \"P3:在 apps/* 实现可交付业务功能;必须产生可 git commit 的仓库变更。修改业务逻辑时须同步新增或更新 colocated unit tests(*.test.ts 或项目约定路径);纯 UI 布局可主要依赖 E2E,但不得破坏现有 bun test。\",\n },\n };\n}\n",
|
|
32
|
+
"/**\n * Job-scoped deploy ops HTTP client (Creator Server /api/jobs/:jobCode/ops/*).\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { AGENT_JOB_CONFIG_MOUNT_PATH } from \"../common/src/agent-job-config.ts\";\n\nexport type JobOpsClientConfig = {\n opsBaseUrl: string;\n callbackSecret: string;\n};\n\nexport function opsBaseUrlFromCallbackUrl(callbackUrl: string): string | null {\n const t = callbackUrl.trim();\n if (!t) return null;\n const suffix = \"/callback\";\n if (!t.endsWith(suffix)) return null;\n return `${t.slice(0, -suffix.length)}/ops`;\n}\n\nexport function resolveJobOpsClientConfig(): JobOpsClientConfig | null {\n const secret = (process.env.NVWA_CALLBACK_SECRET ?? \"\").trim();\n if (!secret) return null;\n\n let callbackUrl = (process.env.NVWA_CALLBACK_URL ?? \"\").trim();\n if (!callbackUrl) {\n try {\n const raw = readFileSync(AGENT_JOB_CONFIG_MOUNT_PATH, \"utf-8\");\n const j = JSON.parse(raw) as { callbackUrl?: unknown };\n if (typeof j.callbackUrl === \"string\") callbackUrl = j.callbackUrl.trim();\n } catch {\n // ignore\n }\n }\n const opsBaseUrl = opsBaseUrlFromCallbackUrl(callbackUrl);\n if (!opsBaseUrl) return null;\n return { opsBaseUrl, callbackSecret: secret };\n}\n\nasync function opsFetch(\n cfg: JobOpsClientConfig,\n path: string,\n init?: RequestInit,\n): Promise<{ ok: boolean; status: number; body: unknown }> {\n const headers = new Headers(init?.headers);\n headers.set(\"X-Nvwa-Callback-Secret\", cfg.callbackSecret);\n const res = await fetch(`${cfg.opsBaseUrl}${path}`, { ...init, headers });\n let body: unknown = null;\n try {\n body = await res.json();\n } catch {\n body = null;\n }\n return { ok: res.ok, status: res.status, body };\n}\n\nexport async function opsDeployStatus(cfg: JobOpsClientConfig): Promise<unknown> {\n const r = await opsFetch(cfg, \"/deploy/status\", { method: \"GET\" });\n if (!r.ok) {\n throw opsError(r);\n }\n return r.body;\n}\n\nexport async function opsDeployTree(\n cfg: JobOpsClientConfig,\n query: { env: string; featureAppName?: string },\n): Promise<unknown> {\n const q = new URLSearchParams({ env: query.env });\n if (query.featureAppName?.trim()) q.set(\"featureAppName\", query.featureAppName.trim());\n const r = await opsFetch(cfg, `/deploy/tree?${q.toString()}`, { method: \"GET\" });\n if (!r.ok) throw opsError(r);\n return r.body;\n}\n\nexport async function opsDeployLogs(\n cfg: JobOpsClientConfig,\n body: Record<string, unknown>,\n): Promise<unknown> {\n const r = await opsFetch(cfg, \"/deploy/logs\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n if (!r.ok) throw opsError(r);\n return r.body;\n}\n\nexport async function opsReleaseBuildLog(\n cfg: JobOpsClientConfig,\n query: Record<string, string | string[] | undefined>,\n): Promise<unknown> {\n const q = new URLSearchParams();\n for (const [k, v] of Object.entries(query)) {\n if (v === undefined) continue;\n if (Array.isArray(v)) {\n for (const item of v) q.append(k, item);\n } else if (v.trim()) {\n q.set(k, v.trim());\n }\n }\n const r = await opsFetch(cfg, `/release/build-log?${q.toString()}`, { method: \"GET\" });\n if (!r.ok) throw opsError(r);\n return r.body;\n}\n\nfunction opsError(r: { status: number; body: unknown }): Error {\n const b = r.body as { error?: string; message?: string } | null;\n const code = b?.error ?? \"ops_error\";\n const msg = b?.message ?? `HTTP ${r.status}`;\n return new Error(`${code}: ${msg}`);\n}\n\nexport function formatOpsDeployStatus(data: unknown): string {\n const d = data as { projectCode?: string; items?: Array<{ env: string; name: string; healthStatus?: string | null; syncStatus?: string | null; message?: string | null }> };\n const lines: string[] = [`project: ${d.projectCode ?? \"?\"}`];\n for (const item of d.items ?? []) {\n lines.push(\n `- [${item.env}] ${item.name} health=${item.healthStatus ?? \"?\"} sync=${item.syncStatus ?? \"?\"}${\n item.message ? ` — ${item.message}` : \"\"\n }`,\n );\n }\n return lines.join(\"\\n\");\n}\n\nexport function formatOpsDeployLogs(data: unknown): string {\n const d = data as {\n logs?: string;\n podName?: string;\n matchedLineCount?: number;\n truncated?: boolean;\n };\n const header = `pod: ${d.podName ?? \"?\"} matched=${d.matchedLineCount ?? \"?\"} truncated=${d.truncated === true}`;\n return `${header}\\n${d.logs ?? \"\"}`;\n}\n",
|
|
33
|
+
"import { spawnSync } from \"node:child_process\";\nimport { createInterface } from \"node:readline/promises\";\nimport { stdin as input, stdout as output } from \"node:process\";\n\nimport {\n formatNvwaCliWhoami,\n loadNvwaCliConfig,\n removeNvwaCliProjectCredential,\n writeNvwaCliProjectCredential,\n} from \"@nvwa-os/common/nvwa-cli-config\";\nimport { resolvePlatformWebOrigin } from \"@nvwa-os/common/platform-web-origin\";\n\nfunction parseFlag(args: string[], name: string): string | undefined {\n const eq = `--${name}=`;\n for (let i = 0; i < args.length; i++) {\n if (args[i] === `--${name}`) return args[i + 1];\n if (args[i]?.startsWith(eq)) return args[i]!.slice(eq.length);\n }\n return undefined;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction openBrowser(url: string): void {\n const platform = process.platform;\n if (platform === \"darwin\") {\n spawnSync(\"open\", [url], { stdio: \"ignore\" });\n return;\n }\n if (platform === \"linux\") {\n spawnSync(\"xdg-open\", [url], { stdio: \"ignore\" });\n return;\n }\n if (platform === \"win32\") {\n spawnSync(\"cmd\", [\"/c\", \"start\", \"\", url], { stdio: \"ignore\", shell: true });\n }\n}\n\nasync function resolveProjectCode(args: string[]): Promise<string> {\n const fromFlag = parseFlag(args, \"project\")?.trim();\n if (fromFlag) return fromFlag;\n const { merged } = loadNvwaCliConfig();\n const fromConfig = merged.defaultProjectCode?.trim();\n if (fromConfig) return fromConfig;\n const rl = createInterface({ input, output });\n try {\n const answer = (await rl.question(\"Project code: \")).trim();\n if (!answer) throw new Error(\"project code is required\");\n return answer;\n } finally {\n rl.close();\n }\n}\n\nasync function resolveStudioUrl(args: string[]): Promise<string> {\n const fromFlag = parseFlag(args, \"studio\")?.trim();\n if (fromFlag) return fromFlag.replace(/\\/$/, \"\");\n const { merged } = loadNvwaCliConfig();\n const fromConfig = merged.studioUrl?.trim();\n if (fromConfig) return fromConfig.replace(/\\/$/, \"\");\n const rl = createInterface({ input, output });\n try {\n const answer = (await rl.question(\"Studio URL (e.g. https://studio.example.com): \")).trim();\n if (!answer) throw new Error(\"studio URL is required\");\n return answer.replace(/\\/$/, \"\");\n } finally {\n rl.close();\n }\n}\n\nexport async function runLoginCommand(args: string[]): Promise<void> {\n const projectCode = await resolveProjectCode(args);\n const studioUrl = await resolveStudioUrl(args);\n const apiBase = `${studioUrl}/api/cli/device-codes`;\n\n const createRes = await fetch(apiBase, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ projectCode, clientName: \"nvwa-cli\", studioUrl }),\n });\n const createBody = (await createRes.json()) as {\n deviceCode?: string;\n userCode?: string;\n verificationUri?: string;\n interval?: number;\n expiresIn?: number;\n message?: string;\n error?: string;\n };\n if (!createRes.ok || !createBody.deviceCode || !createBody.verificationUri) {\n throw new Error(createBody.message ?? createBody.error ?? `login start failed (${createRes.status})`);\n }\n\n console.log(`User code: ${createBody.userCode}`);\n console.log(`Open: ${createBody.verificationUri}`);\n openBrowser(createBody.verificationUri);\n\n const intervalMs = (createBody.interval ?? 5) * 1000;\n const deadline = Date.now() + (createBody.expiresIn ?? 900) * 1000;\n\n while (Date.now() < deadline) {\n await sleep(intervalMs);\n const pollRes = await fetch(`${studioUrl}/api/cli/device-codes/token`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ deviceCode: createBody.deviceCode }),\n });\n const pollBody = (await pollRes.json()) as {\n status?: string;\n studioUrl?: string;\n projectCode?: string;\n integrationDocsToken?: string;\n };\n if (pollBody.status === \"pending\") continue;\n if (pollBody.status === \"rejected\") throw new Error(\"authorization rejected in Studio\");\n if (pollBody.status === \"expired\") throw new Error(\"device session expired\");\n if (pollBody.status === \"authorized\" && pollBody.integrationDocsToken && pollBody.projectCode) {\n const paths = writeNvwaCliProjectCredential({\n studioUrl: pollBody.studioUrl ?? studioUrl,\n projectCode: pollBody.projectCode,\n integrationDocsToken: pollBody.integrationDocsToken,\n });\n console.log(`Logged in to project ${pollBody.projectCode}`);\n console.log(`Config: ${paths.globalPath}${paths.projectPath ? `, ${paths.projectPath}` : \"\"}`);\n return;\n }\n }\n throw new Error(\"timed out waiting for Studio authorization\");\n}\n\nexport async function runLogoutCommand(args: string[]): Promise<void> {\n const projectCode = parseFlag(args, \"project\")?.trim() ?? loadNvwaCliConfig().merged.defaultProjectCode?.trim();\n if (!projectCode) throw new Error(\"--project is required (no defaultProjectCode in config)\");\n removeNvwaCliProjectCredential({ projectCode });\n console.log(`Removed credentials for project ${projectCode}`);\n}\n\nexport function runWhoamiCommand(): void {\n const info = formatNvwaCliWhoami();\n console.log(JSON.stringify(info, null, 2));\n}\n\nexport function runConfigPathCommand(): void {\n const loaded = loadNvwaCliConfig();\n console.log(\n JSON.stringify(\n {\n globalPath: loaded.globalPath,\n projectPath: loaded.projectPath,\n defaultProjectCode: loaded.merged.defaultProjectCode ?? null,\n studioUrl: loaded.merged.studioUrl ?? null,\n },\n null,\n 2,\n ),\n );\n}\n\nexport function resolveDefaultStudioUrlForLogin(fallback?: string): string {\n return resolvePlatformWebOrigin(fallback ?? loadNvwaCliConfig().merged.studioUrl ?? null);\n}\n",
|
|
34
|
+
"import { readFileSync, existsSync } from \"node:fs\";\n\nimport { AGENT_JOB_CONFIG_MOUNT_PATH } from \"../common/src/agent-job-config.ts\";\nimport {\n logAgentToolTrace,\n type SkillToolTraceArgs,\n} from \"../common/src/agent-tool-trace.ts\";\n\nexport function resolveTraceJobCode(): string | null {\n try {\n if (!existsSync(AGENT_JOB_CONFIG_MOUNT_PATH)) return null;\n const raw = readFileSync(AGENT_JOB_CONFIG_MOUNT_PATH, \"utf-8\");\n const j = JSON.parse(raw) as { jobCode?: unknown; jobId?: unknown };\n const code = typeof j.jobCode === \"string\" ? j.jobCode.trim() : \"\";\n if (code) return code;\n const id = typeof j.jobId === \"string\" ? j.jobId.trim() : \"\";\n return id || null;\n } catch {\n return null;\n }\n}\n\nexport async function withSkillToolTrace<T>(\n tool: \"ops\" | \"integration-docs\",\n action: string,\n args: SkillToolTraceArgs,\n fn: () => Promise<T>,\n summarizeResult?: (result: T) => SkillToolTraceArgs,\n): Promise<T> {\n const jobCode = resolveTraceJobCode();\n const started = Date.now();\n logAgentToolTrace(\"skill_tool_invoke\", {\n jobCode: jobCode ?? undefined,\n tool,\n action,\n ...args,\n });\n try {\n const result = await fn();\n const extra = summarizeResult?.(result) ?? {};\n logAgentToolTrace(\"skill_tool_result\", {\n jobCode: jobCode ?? undefined,\n tool,\n action,\n ok: true,\n durationMs: Date.now() - started,\n ...extra,\n });\n return result;\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n const errorCode = msg.includes(\":\") ? msg.split(\":\")[0]?.trim() : \"error\";\n logAgentToolTrace(\"skill_tool_result\", {\n jobCode: jobCode ?? undefined,\n tool,\n action,\n ok: false,\n durationMs: Date.now() - started,\n errorCode,\n });\n throw e;\n }\n}\n",
|
|
35
|
+
"import {\n runRepoRewrite,\n type AgentProviderMode,\n type AgentRuntimeValidationResult,\n validateAgentRuntime,\n} from \"../../agent/run-repo-rewrite.ts\";\nimport {\n formatOpsDeployLogs,\n formatOpsDeployStatus,\n opsDeployLogs,\n opsDeployStatus,\n opsDeployTree,\n opsReleaseBuildLog,\n resolveJobOpsClientConfig,\n} from \"../../agent/job-ops-client.ts\";\nimport {\n integrationDocsApi,\n integrationDocsApis,\n integrationDocsContracts,\n integrationDocsDocuments,\n integrationDocsGuide,\n integrationDocsGuides,\n resolveIntegrationDocsClientConfig,\n} from \"@nvwa-os/common/integration-docs-client\";\nimport {\n runConfigPathCommand,\n runLoginCommand,\n runLogoutCommand,\n runWhoamiCommand,\n} from \"./cli-login.ts\";\nimport { withSkillToolTrace } from \"../../agent/skill-tool-trace.ts\";\n\nconst MODES: AgentProviderMode[] = [\"cursor\", \"claude\", \"opencode\"];\n\nfunction printRunUsage(): void {\n console.error(\n [\n \"Usage:\",\n \" nvwa-os run [--mode <cursor|claude|opencode>]\",\n \" nvwa-os login [--project CODE] [--studio URL]\",\n \" nvwa-os logout [--project CODE]\",\n \" nvwa-os whoami\",\n \" nvwa-os config path\",\n \" nvwa-os ops <deploy-status|deploy-tree|deploy-logs|release-build-log> [options]\",\n \" nvwa-os integration-docs <contracts|documents|guides|guide|apis|api> [options]\",\n \"\",\n \"Run options:\",\n \" --mode <value> Provider mode, default: cursor\",\n \"\",\n \"Ops examples:\",\n \" nvwa-os ops deploy-status\",\n \" nvwa-os ops deploy-tree --env feature --feature-app NAME\",\n \" nvwa-os ops deploy-logs --env feature --kind deployment --name app --namespace ns --grep Error\",\n \" nvwa-os ops release-build-log --grep failed\",\n \"\",\n \" nvwa-os integration-docs contracts\",\n \" nvwa-os integration-docs documents --contract CODE\",\n \" nvwa-os integration-docs apis --contract CODE\",\n \" nvwa-os integration-docs guides --contract CODE\",\n \" nvwa-os integration-docs guide --contract CODE --guide-id ID\",\n \" nvwa-os integration-docs api --contract CODE --api-id ID\",\n \"\",\n \" --json Ops commands: print raw JSON\",\n \" --help Show this help\",\n ].join(\"\\n\"),\n );\n}\n\nfunction parseFlag(args: string[], name: string): string | undefined {\n const eq = `--${name}=`;\n for (let i = 0; i < args.length; i++) {\n if (args[i] === `--${name}`) return args[i + 1];\n if (args[i]?.startsWith(eq)) return args[i]!.slice(eq.length);\n }\n return undefined;\n}\n\nfunction hasFlag(args: string[], name: string): boolean {\n return args.includes(`--${name}`);\n}\n\nfunction parseGrepFlags(args: string[]): string[] {\n const out: string[] = [];\n for (let i = 0; i < args.length; i++) {\n if (args[i] === \"--grep\" && args[i + 1]) {\n out.push(args[i + 1]!);\n i++;\n } else if (args[i]?.startsWith(\"--grep=\")) {\n out.push(args[i]!.slice(\"--grep=\".length));\n }\n }\n return out;\n}\n\nfunction parseMode(args: string[]): AgentProviderMode {\n let mode: AgentProviderMode = \"cursor\";\n for (let i = 0; i < args.length; i++) {\n const token = args[i];\n if (token === \"--mode\") {\n const v = args[i + 1];\n if (!v) throw new Error(\"Missing value for --mode\");\n if (!MODES.includes(v as AgentProviderMode)) throw new Error(`Unsupported mode: ${v}`);\n mode = v as AgentProviderMode;\n i++;\n continue;\n }\n if (token.startsWith(\"--mode=\")) {\n const v = token.slice(\"--mode=\".length);\n if (!MODES.includes(v as AgentProviderMode)) throw new Error(`Unsupported mode: ${v}`);\n mode = v as AgentProviderMode;\n continue;\n }\n if (token === \"--help\" || token === \"-h\") {\n printRunUsage();\n process.exit(0);\n }\n if (token.startsWith(\"--\")) continue;\n throw new Error(`Unknown option: ${token}`);\n }\n return mode;\n}\n\nfunction assertRuntime(result: AgentRuntimeValidationResult): void {\n if (!result.ok) {\n const lines = [\n `[nvwa-os] mode '${result.mode}' runtime check failed`,\n ...(result.missingBinaries.length > 0\n ? [`missing binaries: ${result.missingBinaries.join(\", \")}`]\n : []),\n ...(result.missingEnv.length > 0 ? [`missing env: ${result.missingEnv.join(\", \")}`] : []),\n ];\n throw new Error(lines.join(\"\\n\"));\n }\n}\n\nasync function runOpsCommand(sub: string, args: string[]): Promise<void> {\n const cfg = resolveJobOpsClientConfig();\n if (!cfg) {\n throw new Error(\n \"Job ops unavailable: set NVWA_CALLBACK_SECRET and NVWA_CALLBACK_URL or mount /etc/nvwa/job.json\",\n );\n }\n const asJson = hasFlag(args, \"json\");\n\n if (sub === \"deploy-status\") {\n const data = await withSkillToolTrace(\"ops\", \"deploy-status\", {}, () => opsDeployStatus(cfg));\n console.log(asJson ? JSON.stringify(data, null, 2) : formatOpsDeployStatus(data));\n return;\n }\n\n if (sub === \"deploy-tree\") {\n const env = parseFlag(args, \"env\");\n if (!env) throw new Error(\"--env is required\");\n const featureAppName = parseFlag(args, \"feature-app\");\n const data = await withSkillToolTrace(\n \"ops\",\n \"deploy-tree\",\n { env, featureAppName: featureAppName ?? undefined },\n () => opsDeployTree(cfg, { env, featureAppName }),\n (result) => {\n const nodes = (result as { nodes?: unknown[] }).nodes;\n return { nodeCount: Array.isArray(nodes) ? nodes.length : 0 };\n },\n );\n console.log(asJson ? JSON.stringify(data, null, 2) : JSON.stringify(data, null, 2));\n return;\n }\n\n if (sub === \"deploy-logs\") {\n const env = parseFlag(args, \"env\");\n const kind = parseFlag(args, \"kind\");\n const name = parseFlag(args, \"name\");\n const namespace = parseFlag(args, \"namespace\");\n if (!env || !kind || !name || !namespace) {\n throw new Error(\"--env, --kind, --name, --namespace are required\");\n }\n const grep = parseGrepFlags(args);\n const tailRaw = parseFlag(args, \"tail\");\n const body: Record<string, unknown> = { env, kind, name, namespace };\n const container = parseFlag(args, \"container\");\n if (container) body.container = container;\n if (grep.length) body.grep = grep;\n const grepRegex = parseFlag(args, \"grep-regex\");\n if (grepRegex) body.grepRegex = grepRegex;\n if (tailRaw) body.tailLines = Number.parseInt(tailRaw, 10);\n const data = await withSkillToolTrace(\n \"ops\",\n \"deploy-logs\",\n { env, kind, name, namespace },\n () => opsDeployLogs(cfg, body),\n (result) => {\n const r = result as { matchedLineCount?: number; truncated?: boolean; podName?: string };\n return {\n matchedLineCount: r.matchedLineCount,\n truncated: r.truncated,\n podName: r.podName,\n };\n },\n );\n console.log(asJson ? JSON.stringify(data, null, 2) : formatOpsDeployLogs(data));\n return;\n }\n\n if (sub === \"release-build-log\") {\n const grep = parseGrepFlags(args);\n const q: Record<string, string | string[] | undefined> = {};\n if (grep.length) q.grep = grep;\n const grepRegex = parseFlag(args, \"grep-regex\");\n if (grepRegex) q.grepRegex = grepRegex;\n const releaseTaskCode = parseFlag(args, \"release-task\");\n if (releaseTaskCode) q.releaseTaskCode = releaseTaskCode;\n const tail = parseFlag(args, \"tail\");\n if (tail) q.tailLines = tail;\n const data = await withSkillToolTrace(\n \"ops\",\n \"release-build-log\",\n { releaseTaskCode: releaseTaskCode ?? undefined },\n () => opsReleaseBuildLog(cfg, q),\n (result) => {\n const r = result as { matchedLineCount?: number; truncated?: boolean; source?: string };\n return {\n matchedLineCount: r.matchedLineCount,\n truncated: r.truncated,\n source: r.source,\n };\n },\n );\n console.log(asJson ? JSON.stringify(data, null, 2) : formatOpsDeployLogs({ logs: (data as { logs?: string }).logs }));\n return;\n }\n\n throw new Error(`Unknown ops subcommand: ${sub}`);\n}\n\nasync function runIntegrationDocsCommand(sub: string, args: string[]): Promise<void> {\n const cfg = resolveIntegrationDocsClientConfig({ cwd: process.cwd() });\n if (!cfg) {\n throw new Error(\n \"Integration docs unavailable: run `nvwa-os login`, or set NVWA_INTEGRATION_DOCS_TOKEN and NVWA_API_BASE_URL + NVWA_PROJECT_CODE (or NVWA_INTEGRATION_DOCS_API_BASE_URL, or job.json integrationDocsHints)\",\n );\n }\n const asJson = hasFlag(args, \"json\");\n const contract = parseFlag(args, \"contract\");\n const apiId = parseFlag(args, \"api-id\");\n const guideId = parseFlag(args, \"guide-id\");\n\n if (sub === \"contracts\") {\n const data = await withSkillToolTrace(\"integration-docs\", \"contracts\", {}, () =>\n integrationDocsContracts(cfg),\n );\n console.log(asJson ? JSON.stringify(data, null, 2) : JSON.stringify(data, null, 2));\n return;\n }\n if (sub === \"documents\") {\n if (!contract) throw new Error(\"--contract is required\");\n const data = await withSkillToolTrace(\"integration-docs\", \"documents\", { contract }, () =>\n integrationDocsDocuments(cfg, contract),\n );\n console.log(asJson ? JSON.stringify(data, null, 2) : JSON.stringify(data, null, 2));\n return;\n }\n if (sub === \"apis\") {\n if (!contract) throw new Error(\"--contract is required\");\n const data = await withSkillToolTrace(\"integration-docs\", \"apis\", { contract }, () =>\n integrationDocsApis(cfg, contract),\n );\n console.log(asJson ? JSON.stringify(data, null, 2) : JSON.stringify(data, null, 2));\n return;\n }\n if (sub === \"guides\") {\n if (!contract) throw new Error(\"--contract is required\");\n const data = await withSkillToolTrace(\"integration-docs\", \"guides\", { contract }, () =>\n integrationDocsGuides(cfg, contract),\n );\n console.log(asJson ? JSON.stringify(data, null, 2) : JSON.stringify(data, null, 2));\n return;\n }\n if (sub === \"guide\") {\n if (!contract || !guideId) throw new Error(\"--contract and --guide-id are required\");\n const data = await withSkillToolTrace(\n \"integration-docs\",\n \"guide\",\n { contract, guideId },\n () => integrationDocsGuide(cfg, contract, guideId),\n );\n console.log(asJson ? JSON.stringify(data, null, 2) : JSON.stringify(data, null, 2));\n return;\n }\n if (sub === \"api\") {\n if (!contract || !apiId) throw new Error(\"--contract and --api-id are required\");\n const data = await withSkillToolTrace(\n \"integration-docs\",\n \"api\",\n { contract, apiId },\n () => integrationDocsApi(cfg, contract, apiId),\n );\n console.log(asJson ? JSON.stringify(data, null, 2) : JSON.stringify(data, null, 2));\n return;\n }\n throw new Error(`Unknown integration-docs subcommand: ${sub}`);\n}\n\nexport async function main(argv: string[]): Promise<void> {\n const [command, ...rest] = argv;\n if (!command || command === \"--help\" || command === \"-h\") {\n printRunUsage();\n return;\n }\n if (command === \"login\") {\n await runLoginCommand(rest);\n return;\n }\n if (command === \"logout\") {\n await runLogoutCommand(rest);\n return;\n }\n if (command === \"whoami\") {\n runWhoamiCommand();\n return;\n }\n if (command === \"config\") {\n const [sub] = rest;\n if (sub === \"path\") {\n runConfigPathCommand();\n return;\n }\n printRunUsage();\n return;\n }\n if (command === \"ops\") {\n const [sub, ...opsRest] = rest;\n if (!sub || sub === \"--help\" || sub === \"-h\") {\n printRunUsage();\n return;\n }\n await runOpsCommand(sub, opsRest);\n return;\n }\n if (command === \"integration-docs\") {\n const [sub, ...idRest] = rest;\n if (!sub || sub === \"--help\" || sub === \"-h\") {\n printRunUsage();\n return;\n }\n await runIntegrationDocsCommand(sub, idRest);\n return;\n }\n if (command !== \"run\") {\n throw new Error(`Unknown command: ${command}`);\n }\n const mode = parseMode(rest);\n const runtime = validateAgentRuntime(mode);\n assertRuntime(runtime);\n await runRepoRewrite({ mode });\n}\n"
|
|
36
|
+
],
|
|
37
|
+
"mappings": ";;;;;;AAAA,6BAAgB;AAChB;AAAA,gBAEE;AAAA,eACA;AAAA,iBAEA;AAAA,kBACA;AAAA,YACA;AAAA;AAAA,mBAEA;AAAA;AAGF,oBAAS,kBAAS;;;ACXlB,IAAM,8BAA8B;AACpC,IAAM,6BAA6B;AACnC,IAAM,+BAA+B;AAErC,SAAS,gBAAgB,CAAC,KAAyB,UAA0B;AAAA,EAC3E,MAAM,IAAI,OAAO,UAAU,OAAO,IAAI,KAAK,GAAG,EAAE;AAAA,EAChD,IAAI,CAAC,OAAO,SAAS,CAAC,KAAK,IAAI;AAAA,IAAG,OAAO;AAAA,EACzC,OAAO,KAAK,IAAI,GAAG,GAAG;AAAA;AAGjB,SAAS,+BAA+B,GAAW;AAAA,EACxD,OAAO,iBAAiB,QAAQ,IAAI,0CAA0C,2BAA2B;AAAA;AAGpG,SAAS,8BAA8B,GAAW;AAAA,EACvD,OAAO,iBAAiB,QAAQ,IAAI,yCAAyC,0BAA0B;AAAA;AAGlG,SAAS,sCAAsC,GAAY;AAAA,EAChE,QAAQ,QAAQ,IAAI,4CAA4C,IAAI,KAAK,MAAM;AAAA;AAG1E,SAAS,+BAA+B,GAAW;AAAA,EACxD,OAAO;AAAA;;;ACGT,IAAM,yBAAyB,IAAI,IAA8B,CAAC,OAAO,SAAS,OAAO,CAAC;AAEnF,SAAS,6BAA6B,CAC3C,MACA,SACiC;AAAA,EACjC,MAAM,SAAS;AAAA,EACf,MAAM,YAAY;AA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