oxe-cc 1.16.0 → 1.22.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/.cursor/commands/oxe-alm.md +47 -0
- package/.cursor/commands/oxe-ask.md +1 -1
- package/.cursor/commands/oxe-capabilities.md +1 -1
- package/.cursor/commands/oxe-checkpoint.md +1 -1
- package/.cursor/commands/oxe-compact.md +1 -1
- package/.cursor/commands/oxe-dashboard.md +1 -1
- package/.cursor/commands/oxe-debug.md +1 -1
- package/.cursor/commands/oxe-discuss.md +45 -45
- package/.cursor/commands/oxe-execute.md +52 -50
- package/.cursor/commands/oxe-forensics.md +1 -1
- package/.cursor/commands/oxe-help.md +44 -44
- package/.cursor/commands/oxe-loop.md +1 -1
- package/.cursor/commands/oxe-milestone.md +1 -1
- package/.cursor/commands/oxe-next.md +44 -44
- package/.cursor/commands/oxe-obs.md +1 -1
- package/.cursor/commands/oxe-plan-agent.md +1 -1
- package/.cursor/commands/oxe-plan.md +49 -47
- package/.cursor/commands/oxe-project.md +1 -1
- package/.cursor/commands/oxe-quick.md +49 -47
- package/.cursor/commands/oxe-research.md +1 -1
- package/.cursor/commands/oxe-retro.md +1 -1
- package/.cursor/commands/oxe-review-pr.md +47 -47
- package/.cursor/commands/oxe-route.md +1 -1
- package/.cursor/commands/oxe-scan.md +47 -47
- package/.cursor/commands/oxe-security.md +1 -1
- package/.cursor/commands/oxe-session.md +1 -1
- package/.cursor/commands/oxe-ship.md +47 -47
- package/.cursor/commands/oxe-skill.md +1 -1
- package/.cursor/commands/oxe-spec.md +49 -47
- package/.cursor/commands/oxe-ui-review.md +1 -1
- package/.cursor/commands/oxe-ui-spec.md +1 -1
- package/.cursor/commands/oxe-update.md +1 -1
- package/.cursor/commands/oxe-validate-gaps.md +1 -1
- package/.cursor/commands/oxe-verify-audit.md +1 -1
- package/.cursor/commands/oxe-verify.md +50 -50
- package/.cursor/commands/oxe-workflow-authoring.md +1 -1
- package/.cursor/commands/oxe-workstream.md +1 -1
- package/.cursor/commands/oxe.md +51 -49
- package/.github/copilot-instructions.md +3 -3
- package/.github/prompts/oxe-alm.prompt.md +47 -0
- package/.github/prompts/oxe-ask.prompt.md +47 -47
- package/.github/prompts/oxe-capabilities.prompt.md +47 -47
- package/.github/prompts/oxe-checkpoint.prompt.md +47 -47
- package/.github/prompts/oxe-compact.prompt.md +46 -46
- package/.github/prompts/oxe-dashboard.prompt.md +47 -47
- package/.github/prompts/oxe-debug.prompt.md +47 -47
- package/.github/prompts/oxe-discuss.prompt.md +47 -47
- package/.github/prompts/oxe-execute.prompt.md +52 -50
- package/.github/prompts/oxe-forensics.prompt.md +47 -47
- package/.github/prompts/oxe-help.prompt.md +46 -46
- package/.github/prompts/oxe-loop.prompt.md +47 -47
- package/.github/prompts/oxe-milestone.prompt.md +47 -47
- package/.github/prompts/oxe-next.prompt.md +46 -46
- package/.github/prompts/oxe-obs.prompt.md +47 -47
- package/.github/prompts/oxe-plan-agent.prompt.md +46 -46
- package/.github/prompts/oxe-plan.prompt.md +49 -47
- package/.github/prompts/oxe-project.prompt.md +47 -47
- package/.github/prompts/oxe-quick.prompt.md +49 -47
- package/.github/prompts/oxe-research.prompt.md +47 -47
- package/.github/prompts/oxe-retro.prompt.md +47 -47
- package/.github/prompts/oxe-review-pr.prompt.md +47 -47
- package/.github/prompts/oxe-route.prompt.md +47 -47
- package/.github/prompts/oxe-scan.prompt.md +47 -47
- package/.github/prompts/oxe-security.prompt.md +47 -47
- package/.github/prompts/oxe-session.prompt.md +47 -47
- package/.github/prompts/oxe-ship.prompt.md +47 -47
- package/.github/prompts/oxe-skill.prompt.md +47 -47
- package/.github/prompts/oxe-spec.prompt.md +49 -47
- package/.github/prompts/oxe-ui-review.prompt.md +47 -47
- package/.github/prompts/oxe-ui-spec.prompt.md +47 -47
- package/.github/prompts/oxe-update.prompt.md +46 -46
- package/.github/prompts/oxe-validate-gaps.prompt.md +47 -47
- package/.github/prompts/oxe-verify-audit.prompt.md +1 -1
- package/.github/prompts/oxe-verify.prompt.md +50 -50
- package/.github/prompts/oxe-workflow-authoring.prompt.md +1 -1
- package/.github/prompts/oxe-workstream.prompt.md +47 -47
- package/.github/prompts/oxe.prompt.md +51 -49
- package/.github/workflows/ci.yml +26 -5
- package/.github/workflows/release.yml +15 -14
- package/AGENTS.md +15 -9
- package/CHANGELOG.md +1027 -10
- package/LICENSE +21 -21
- package/QUICKSTART.md +99 -99
- package/README.md +120 -17
- package/assets/readme-banner.svg +19 -19
- package/bin/banner.txt +5 -5
- package/bin/lib/oxe-acceptance-audit.cjs +195 -0
- package/bin/lib/oxe-adr.cjs +145 -0
- package/bin/lib/oxe-agent-install.cjs +31 -29
- package/bin/lib/oxe-alm-admin.cjs +215 -0
- package/bin/lib/oxe-alm-metrics.cjs +143 -0
- package/bin/lib/oxe-alm-prs.cjs +274 -0
- package/bin/lib/oxe-alm-refine.cjs +1003 -0
- package/bin/lib/oxe-alm.cjs +1289 -0
- package/bin/lib/oxe-anchor-copy.cjs +218 -0
- package/bin/lib/oxe-api-surface.cjs +96 -0
- package/bin/lib/oxe-artifact-refs.cjs +72 -0
- package/bin/lib/oxe-attention.cjs +97 -0
- package/bin/lib/oxe-autoresume.cjs +448 -0
- package/bin/lib/oxe-azure.cjs +1445 -1445
- package/bin/lib/oxe-budget.cjs +154 -0
- package/bin/lib/oxe-change-folder.cjs +130 -0
- package/bin/lib/oxe-change.cjs +389 -0
- package/bin/lib/oxe-channels.cjs +82 -0
- package/bin/lib/oxe-cited-paths.cjs +180 -0
- package/bin/lib/oxe-cli-errors.cjs +76 -0
- package/bin/lib/oxe-cli-output.cjs +111 -0
- package/bin/lib/oxe-commit-convention.cjs +104 -0
- package/bin/lib/oxe-complexity.cjs +106 -0
- package/bin/lib/oxe-console-decode.cjs +23 -0
- package/bin/lib/oxe-coordinator-queue.cjs +67 -0
- package/bin/lib/oxe-core-command-handlers.cjs +10 -8
- package/bin/lib/oxe-criteria-ids.cjs +87 -0
- package/bin/lib/oxe-criterion-coverage.cjs +93 -0
- package/bin/lib/oxe-cross-card-conflicts.cjs +639 -0
- package/bin/lib/oxe-customize.cjs +146 -0
- package/bin/lib/oxe-dashboard.cjs +1 -1
- package/bin/lib/oxe-decisions.cjs +211 -0
- package/bin/lib/oxe-deferred.cjs +80 -0
- package/bin/lib/oxe-deps-audit.cjs +136 -0
- package/bin/lib/oxe-diff-reviewer.cjs +105 -0
- package/bin/lib/oxe-dir-info.cjs +138 -0
- package/bin/lib/oxe-docs-check.cjs +124 -0
- package/bin/lib/oxe-docs-publish.cjs +81 -0
- package/bin/lib/oxe-dom-hooks.cjs +902 -0
- package/bin/lib/oxe-dossier.cjs +355 -0
- package/bin/lib/oxe-e2e-ready.cjs +360 -0
- package/bin/lib/oxe-env-sanitize.cjs +155 -0
- package/bin/lib/oxe-event-bus.cjs +118 -118
- package/bin/lib/oxe-failure-cost.cjs +144 -0
- package/bin/lib/oxe-file-size-guard.cjs +849 -0
- package/bin/lib/oxe-findings.cjs +86 -0
- package/bin/lib/oxe-grill-cases.cjs +148 -0
- package/bin/lib/oxe-grill.cjs +444 -0
- package/bin/lib/oxe-grooming.cjs +115 -0
- package/bin/lib/oxe-guard.cjs +180 -0
- package/bin/lib/oxe-handoff.cjs +97 -0
- package/bin/lib/oxe-install-resolve.cjs +28 -0
- package/bin/lib/oxe-integration-checks.cjs +285 -0
- package/bin/lib/oxe-intent-context.cjs +101 -0
- package/bin/lib/oxe-journey.cjs +403 -0
- package/bin/lib/oxe-known-failures.cjs +138 -0
- package/bin/lib/oxe-local-config.cjs +77 -0
- package/bin/lib/oxe-memory-kernel.cjs +190 -188
- package/bin/lib/oxe-merge-train.cjs +277 -0
- package/bin/lib/oxe-model-resolve.cjs +74 -0
- package/bin/lib/oxe-model-tiers.cjs +65 -0
- package/bin/lib/oxe-nfr.cjs +125 -0
- package/bin/lib/oxe-npm-version.cjs +1 -1
- package/bin/lib/oxe-open-defects.cjs +121 -0
- package/bin/lib/oxe-operational.cjs +14339 -1066
- package/bin/lib/oxe-origin-guard.cjs +102 -0
- package/bin/lib/oxe-origin.cjs +377 -0
- package/bin/lib/oxe-pack-removed.cjs +208 -0
- package/bin/lib/oxe-parallel-run.cjs +81 -0
- package/bin/lib/oxe-parallel.cjs +234 -0
- package/bin/lib/oxe-phase-extras.cjs +185 -0
- package/bin/lib/oxe-phase-gates.cjs +551 -0
- package/bin/lib/oxe-plan-build.cjs +1520 -0
- package/bin/lib/oxe-plan-json.cjs +1107 -0
- package/bin/lib/oxe-plan-merge.cjs +253 -0
- package/bin/lib/oxe-plan-mutate.cjs +214 -0
- package/bin/lib/oxe-plan-repair.cjs +479 -0
- package/bin/lib/oxe-plan-review.cjs +256 -0
- package/bin/lib/oxe-plan-skeleton.cjs +494 -0
- package/bin/lib/oxe-plan-staleness.cjs +125 -0
- package/bin/lib/oxe-plugin-cli.cjs +3 -1
- package/bin/lib/oxe-policy-rules.cjs +144 -0
- package/bin/lib/oxe-prd.cjs +129 -0
- package/bin/lib/oxe-preflight.cjs +378 -0
- package/bin/lib/oxe-process.cjs +11 -11
- package/bin/lib/oxe-program-members.cjs +97 -0
- package/bin/lib/oxe-program.cjs +245 -0
- package/bin/lib/oxe-progress-run.cjs +80 -0
- package/bin/lib/oxe-project-env.cjs +273 -0
- package/bin/lib/oxe-project-health.cjs +619 -41
- package/bin/lib/oxe-promote-helpers.cjs +1561 -0
- package/bin/lib/oxe-provider-antigravity.cjs +114 -0
- package/bin/lib/oxe-provider-grok.cjs +48 -0
- package/bin/lib/oxe-questions.cjs +115 -0
- package/bin/lib/oxe-quick.cjs +537 -0
- package/bin/lib/oxe-ratchets.cjs +132 -0
- package/bin/lib/oxe-rationality.cjs +587 -532
- package/bin/lib/oxe-real-regression.cjs +97 -0
- package/bin/lib/oxe-recovery.cjs +160 -0
- package/bin/lib/oxe-release-ops.cjs +325 -0
- package/bin/lib/oxe-release.cjs +622 -551
- package/bin/lib/oxe-repair.cjs +153 -0
- package/bin/lib/oxe-repo-map.cjs +136 -0
- package/bin/lib/oxe-repo-rules.cjs +121 -0
- package/bin/lib/oxe-research-provenance.cjs +96 -0
- package/bin/lib/oxe-resume.cjs +406 -0
- package/bin/lib/oxe-review.cjs +403 -0
- package/bin/lib/oxe-rfc.cjs +192 -0
- package/bin/lib/oxe-risk-decision.cjs +141 -0
- package/bin/lib/oxe-runtime-semantics.cjs +8 -1
- package/bin/lib/oxe-scorecard.cjs +234 -0
- package/bin/lib/oxe-scratch.cjs +81 -0
- package/bin/lib/oxe-seams.cjs +159 -0
- package/bin/lib/oxe-security.cjs +289 -289
- package/bin/lib/oxe-semver.cjs +83 -0
- package/bin/lib/oxe-ship-pr.cjs +204 -0
- package/bin/lib/oxe-signal.cjs +173 -0
- package/bin/lib/oxe-skill-loader.cjs +131 -131
- package/bin/lib/oxe-spec-check.cjs +217 -0
- package/bin/lib/oxe-spec-ears.cjs +98 -0
- package/bin/lib/oxe-spec-edit.cjs +411 -0
- package/bin/lib/oxe-spec-freeze.cjs +378 -0
- package/bin/lib/oxe-spec-probe.cjs +146 -0
- package/bin/lib/oxe-spec-stress.cjs +146 -0
- package/bin/lib/oxe-spike.cjs +98 -0
- package/bin/lib/oxe-state.cjs +87 -0
- package/bin/lib/oxe-stub-check.cjs +355 -0
- package/bin/lib/oxe-suite-impact.cjs +1145 -0
- package/bin/lib/oxe-sync.cjs +250 -0
- package/bin/lib/oxe-system-design.cjs +138 -0
- package/bin/lib/oxe-task-gates.cjs +139 -0
- package/bin/lib/oxe-telemetry.cjs +201 -0
- package/bin/lib/oxe-test-precheck.cjs +508 -0
- package/bin/lib/oxe-test-rigor.cjs +663 -0
- package/bin/lib/oxe-test-scope.cjs +883 -0
- package/bin/lib/oxe-trace.cjs +168 -0
- package/bin/lib/oxe-turns.cjs +64 -0
- package/bin/lib/oxe-ui-evidence.cjs +187 -0
- package/bin/lib/oxe-ui-verify.cjs +55 -0
- package/bin/lib/oxe-unsafe-commands.cjs +94 -0
- package/bin/lib/oxe-verdicts.cjs +131 -0
- package/bin/lib/oxe-verify-dryrun.cjs +541 -0
- package/bin/lib/oxe-verify-remote.cjs +208 -0
- package/bin/lib/oxe-vitest-batch.cjs +142 -0
- package/bin/lib/oxe-workflow-budget.cjs +99 -0
- package/bin/lib/oxe-workflow-eval.cjs +118 -0
- package/bin/lib/oxe-workflows.cjs +3 -1
- package/bin/lib/oxe-worktree-deps.cjs +241 -0
- package/bin/lib/oxe-worktree-gc.cjs +170 -0
- package/bin/oxe-cc.js +4934 -94
- package/commands/oxe/alm.md +54 -0
- package/commands/oxe/ask.md +55 -55
- package/commands/oxe/capabilities.md +50 -50
- package/commands/oxe/checkpoint.md +53 -53
- package/commands/oxe/compact.md +47 -47
- package/commands/oxe/dashboard.md +51 -51
- package/commands/oxe/debug.md +58 -58
- package/commands/oxe/discuss.md +58 -58
- package/commands/oxe/execute.md +63 -61
- package/commands/oxe/forensics.md +53 -53
- package/commands/oxe/help.md +48 -48
- package/commands/oxe/loop.md +54 -54
- package/commands/oxe/milestone.md +53 -53
- package/commands/oxe/next.md +49 -49
- package/commands/oxe/obs.md +53 -53
- package/commands/oxe/oxe.md +55 -53
- package/commands/oxe/plan-agent.md +57 -57
- package/commands/oxe/plan.md +59 -57
- package/commands/oxe/project.md +53 -53
- package/commands/oxe/quick.md +53 -53
- package/commands/oxe/research.md +53 -53
- package/commands/oxe/retro.md +53 -53
- package/commands/oxe/review-pr.md +53 -53
- package/commands/oxe/route.md +48 -48
- package/commands/oxe/scan.md +58 -58
- package/commands/oxe/security.md +53 -53
- package/commands/oxe/session.md +53 -53
- package/commands/oxe/ship.md +53 -53
- package/commands/oxe/skill.md +53 -53
- package/commands/oxe/spec.md +59 -56
- package/commands/oxe/ui-review.md +53 -53
- package/commands/oxe/ui-spec.md +53 -53
- package/commands/oxe/update.md +53 -53
- package/commands/oxe/validate-gaps.md +53 -53
- package/commands/oxe/verify-audit.md +50 -50
- package/commands/oxe/verify.md +60 -60
- package/commands/oxe/workflow-authoring.md +50 -50
- package/commands/oxe/workstream.md +53 -53
- package/docs/ADLC-COVERAGE.md +55 -0
- package/docs/CONTENT-MIGRATION-AUDIT.md +49 -49
- package/docs/HAPPY-PATH.md +106 -0
- package/docs/INCIDENT-PLAYBOOK.md +181 -181
- package/docs/RELEASE-READINESS.md +1 -0
- package/docs/ROLES.md +129 -129
- package/docs/TEAM-ADOPTION.md +153 -153
- package/docs/WALKTHROUGH.md +241 -241
- package/docs/adr/D-1-isolamento-read-only-e-sanitizacao-centralizada-de-env-vars.md +29 -0
- package/docs/adr/D-2-junction-segura-de-node-modules-condicionada-a-sha-256-de-pa.md +29 -0
- package/docs/adr/D-3-preflight-local-5s-impacto-estatico-e2e-e-leitura-explicita.md +29 -0
- package/docs/adr/D-4-governanca-de-release-unificada-retomada-idempotente-pos-rei.md +29 -0
- package/docs/adr/README.md +15 -0
- package/docs/cli-errors.md +20 -0
- package/docs/oxespace-1.5/BACKLOG.md +2056 -0
- package/docs/oxespace-1.5/HANDOFF-1.21.2.md +140 -0
- package/docs/oxevoice/BACKLOG.md +244 -0
- package/lib/runtime/compiler/graph-compiler.d.ts +15 -0
- package/lib/runtime/compiler/graph-compiler.js +49 -3
- package/lib/runtime/delivery/promotion-pipeline.d.ts +1 -0
- package/lib/runtime/delivery/promotion-pipeline.js +59 -2
- package/lib/runtime/events/catalog.d.ts +1 -1
- package/lib/runtime/events/catalog.js +29 -0
- package/lib/runtime/executor/action-tool-map.d.ts +3 -1
- package/lib/runtime/executor/action-tool-map.js +4 -1
- package/lib/runtime/executor/adapters/antigravity-cli.d.ts +103 -0
- package/lib/runtime/executor/adapters/antigravity-cli.js +530 -0
- package/lib/runtime/executor/adapters/claude-cli.d.ts +92 -0
- package/lib/runtime/executor/adapters/claude-cli.js +328 -0
- package/lib/runtime/executor/adapters/grok-cli.d.ts +89 -0
- package/lib/runtime/executor/adapters/grok-cli.js +351 -0
- package/lib/runtime/executor/adapters/http-openai.d.ts +9 -0
- package/lib/runtime/executor/adapters/http-openai.js +18 -0
- package/lib/runtime/executor/adapters/registry.d.ts +18 -0
- package/lib/runtime/executor/adapters/registry.js +49 -0
- package/lib/runtime/executor/adapters/types.d.ts +21 -0
- package/lib/runtime/executor/adapters/types.js +2 -0
- package/lib/runtime/executor/built-in-tools.d.ts +64 -0
- package/lib/runtime/executor/built-in-tools.js +257 -24
- package/lib/runtime/executor/index.d.ts +19 -2
- package/lib/runtime/executor/index.js +50 -1
- package/lib/runtime/executor/llm-task-executor.d.ts +108 -2
- package/lib/runtime/executor/llm-task-executor.js +598 -39
- package/lib/runtime/executor/node-context.d.ts +94 -0
- package/lib/runtime/executor/node-context.js +126 -0
- package/lib/runtime/executor/node-prompt-builder.d.ts +2 -0
- package/lib/runtime/executor/node-prompt-builder.js +4 -0
- package/lib/runtime/executor/quota-patterns.d.ts +7 -0
- package/lib/runtime/executor/quota-patterns.js +39 -0
- package/lib/runtime/executor/shell-argv.d.ts +41 -0
- package/lib/runtime/executor/shell-argv.js +144 -0
- package/lib/runtime/executor/stream-completion.d.ts +27 -0
- package/lib/runtime/executor/stream-completion.js +82 -5
- package/lib/runtime/index.d.ts +5 -2
- package/lib/runtime/index.js +10 -1
- package/lib/runtime/models/failure.d.ts +1 -1
- package/lib/runtime/models/run.d.ts +1 -1
- package/lib/runtime/program/index.d.ts +1 -0
- package/lib/runtime/program/index.js +17 -0
- package/lib/runtime/program/program-model.d.ts +92 -0
- package/lib/runtime/program/program-model.js +262 -0
- package/lib/runtime/projection/projection-engine.d.ts +16 -1
- package/lib/runtime/projection/projection-engine.js +55 -3
- package/lib/runtime/reducers/run-state-reducer.js +48 -5
- package/lib/runtime/scheduler/run-journal.d.ts +27 -1
- package/lib/runtime/scheduler/run-journal.js +40 -1
- package/lib/runtime/scheduler/scheduler.d.ts +239 -0
- package/lib/runtime/scheduler/scheduler.js +1157 -97
- package/lib/runtime/verification/contract-exports.d.ts +24 -0
- package/lib/runtime/verification/contract-exports.js +201 -0
- package/lib/runtime/verification/index.d.ts +1 -0
- package/lib/runtime/verification/index.js +1 -0
- package/lib/runtime/verification/runner-timeout.d.ts +7 -0
- package/lib/runtime/verification/runner-timeout.js +17 -0
- package/lib/runtime/verification/test-report-parsers.d.ts +38 -0
- package/lib/runtime/verification/test-report-parsers.js +188 -0
- package/lib/runtime/verification/verification-compiler.d.ts +101 -2
- package/lib/runtime/verification/verification-compiler.js +491 -82
- package/lib/runtime/verification/verification-manifest.d.ts +12 -0
- package/lib/runtime/verification/verification-manifest.js +33 -4
- package/lib/runtime/workspace/index.d.ts +2 -1
- package/lib/runtime/workspace/index.js +3 -1
- package/lib/runtime/workspace/strategies/ephemeral-container.d.ts +9 -0
- package/lib/runtime/workspace/strategies/ephemeral-container.js +37 -10
- package/lib/runtime/workspace/strategies/git-worktree.d.ts +24 -1
- package/lib/runtime/workspace/strategies/git-worktree.js +134 -1
- package/lib/sdk/README.md +21 -21
- package/lib/sdk/index.cjs +27 -9
- package/oxe/agents/oxe-assumptions-analyzer.md +136 -136
- package/oxe/agents/oxe-codebase-mapper.md +142 -142
- package/oxe/agents/oxe-debugger.md +145 -145
- package/oxe/agents/oxe-executor.md +139 -139
- package/oxe/agents/oxe-integration-checker.md +142 -142
- package/oxe/agents/oxe-plan-checker.md +143 -143
- package/oxe/agents/oxe-planner.md +151 -151
- package/oxe/agents/oxe-research-synthesizer.md +146 -146
- package/oxe/agents/oxe-researcher.md +163 -163
- package/oxe/agents/oxe-ui-auditor.md +151 -151
- package/oxe/agents/oxe-ui-checker.md +157 -157
- package/oxe/agents/oxe-ui-researcher.md +179 -179
- package/oxe/agents/oxe-validation-auditor.md +154 -154
- package/oxe/agents/oxe-verifier.md +132 -132
- package/oxe/migrations/config-migrations.json +15 -0
- package/oxe/personas/README.md +91 -91
- package/oxe/personas/architect.md +149 -149
- package/oxe/personas/db-specialist.md +149 -149
- package/oxe/personas/debugger.md +155 -155
- package/oxe/personas/executor.md +164 -164
- package/oxe/personas/planner.md +165 -165
- package/oxe/personas/researcher.md +148 -148
- package/oxe/personas/ui-specialist.md +164 -164
- package/oxe/personas/verifier.md +174 -174
- package/oxe/schemas/plan-agents.schema.json +122 -122
- package/oxe/schemas/plan.schema.json +101 -0
- package/oxe/schemas/role-plan.schema.json +50 -0
- package/oxe/schemas/swarm-run.schema.json +130 -130
- package/oxe/templates/ACTIVE-RUN.template.json +32 -32
- package/oxe/templates/CAPABILITIES.template.md +7 -7
- package/oxe/templates/CAPABILITY.template.md +45 -45
- package/oxe/templates/CHECKPOINT.template.md +37 -37
- package/oxe/templates/CHECKPOINTS.template.md +7 -7
- package/oxe/templates/CODEBASE-DELTA.template.md +33 -33
- package/oxe/templates/CONFIG.md +172 -0
- package/oxe/templates/DISCUSS.template.md +1 -0
- package/oxe/templates/DOCS_BROWNFIELD_LAYOUT.md +55 -55
- package/oxe/templates/FIXTURE-PACK.template.json +18 -18
- package/oxe/templates/FIXTURE-PACK.template.md +19 -19
- package/oxe/templates/GIT_HOOKS_OXE.md +52 -52
- package/oxe/templates/GLOSSARY.template.md +9 -0
- package/oxe/templates/HYPOTHESES.template.md +33 -33
- package/oxe/templates/IMPLEMENTATION-PACK.template.json +26 -26
- package/oxe/templates/IMPLEMENTATION-PACK.template.md +32 -32
- package/oxe/templates/INVESTIGATION.template.md +38 -38
- package/oxe/templates/LESSONS-METRICS.template.json +13 -13
- package/oxe/templates/LESSONS.template.md +43 -43
- package/oxe/templates/MEMORY.template.md +49 -49
- package/oxe/templates/MILESTONES.template.md +17 -17
- package/oxe/templates/NOTES.template.md +16 -16
- package/oxe/templates/OBSERVATIONS.template.md +18 -18
- package/oxe/templates/PLAN-REVIEW.template.md +31 -31
- package/oxe/templates/PLAN.template.md +87 -87
- package/oxe/templates/PRD.template.md +53 -0
- package/oxe/templates/REFERENCE-ANCHORS.template.md +30 -26
- package/oxe/templates/RESEARCH.template.md +8 -0
- package/oxe/templates/RESUME.template.md +49 -49
- package/oxe/templates/RFC.template.md +43 -0
- package/oxe/templates/ROADMAP.template.md +44 -44
- package/oxe/templates/SECURITY.template.md +72 -72
- package/oxe/templates/SESSION.template.md +34 -34
- package/oxe/templates/SKILL.template.md +26 -26
- package/oxe/templates/SPEC.template.md +65 -65
- package/oxe/templates/SUMMARY.template.md +50 -50
- package/oxe/templates/VISUAL-INPUTS.template.json +27 -27
- package/oxe/templates/VISUAL-INPUTS.template.md +36 -36
- package/oxe/templates/WORKFLOW_AUTHORING.md +93 -93
- package/oxe/templates/finding-rules.json +22 -0
- package/oxe/templates/plan-agent-messages-README.template.md +9 -9
- package/oxe/templates/plan-agents.template.json +30 -30
- package/oxe/templates/quick-agents.template.json +24 -24
- package/oxe/templates/stress-methods.md +33 -0
- package/oxe/workflows/agent-mode.md +150 -150
- package/oxe/workflows/alm.md +50 -0
- package/oxe/workflows/ask.md +96 -96
- package/oxe/workflows/capabilities.md +25 -25
- package/oxe/workflows/checkpoint.md +37 -37
- package/oxe/workflows/compact/plan.md +149 -0
- package/oxe/workflows/compact/spec.md +114 -0
- package/oxe/workflows/compact.md +1 -0
- package/oxe/workflows/conduct.md +149 -149
- package/oxe/workflows/dashboard.md +33 -33
- package/oxe/workflows/debug.md +9 -9
- package/oxe/workflows/discuss.md +15 -3
- package/oxe/workflows/distill.md +164 -164
- package/oxe/workflows/execute.md +30 -26
- package/oxe/workflows/forensics.md +5 -5
- package/oxe/workflows/help.md +10 -4
- package/oxe/workflows/lean/execute.md +42 -0
- package/oxe/workflows/lean/plan.md +60 -0
- package/oxe/workflows/lean/spec.md +61 -0
- package/oxe/workflows/loop.md +67 -67
- package/oxe/workflows/memory.md +163 -163
- package/oxe/workflows/milestone.md +95 -95
- package/oxe/workflows/next.md +10 -8
- package/oxe/workflows/obs.md +167 -167
- package/oxe/workflows/oxe.md +33 -14
- package/oxe/workflows/plan-agent.md +143 -143
- package/oxe/workflows/plan.md +49 -40
- package/oxe/workflows/project.md +55 -55
- package/oxe/workflows/quick.md +19 -5
- package/oxe/workflows/references/adaptive-discovery.md +27 -27
- package/oxe/workflows/references/alm-refine.md +55 -0
- package/oxe/workflows/references/azure-in-plan.md +5 -0
- package/oxe/workflows/references/change-management.md +48 -0
- package/oxe/workflows/references/grill.md +74 -0
- package/oxe/workflows/references/legacy-brownfield.md +136 -136
- package/oxe/workflows/references/next-step-footer.md +33 -0
- package/oxe/workflows/references/plan-agent-chat-protocol.md +99 -99
- package/oxe/workflows/references/plan-json-acceptance-program.md +174 -0
- package/oxe/workflows/references/product-docs-alm.md +51 -0
- package/oxe/workflows/references/reasoning-discovery.md +28 -28
- package/oxe/workflows/references/reasoning-execution.md +29 -29
- package/oxe/workflows/references/reasoning-planning.md +32 -32
- package/oxe/workflows/references/reasoning-review.md +29 -29
- package/oxe/workflows/references/reasoning-status.md +24 -24
- package/oxe/workflows/references/robustness-elevation.md +295 -295
- package/oxe/workflows/references/session-path-resolution.md +71 -71
- package/oxe/workflows/references/workflow-runtime-contracts.json +1167 -1151
- package/oxe/workflows/research.md +1 -0
- package/oxe/workflows/retro.md +117 -117
- package/oxe/workflows/review-pr.md +53 -53
- package/oxe/workflows/route.md +1 -1
- package/oxe/workflows/scan.md +356 -355
- package/oxe/workflows/security.md +67 -67
- package/oxe/workflows/session.md +213 -213
- package/oxe/workflows/ship.md +74 -125
- package/oxe/workflows/size-budget.json +62 -0
- package/oxe/workflows/skill.md +44 -44
- package/oxe/workflows/spec.md +92 -93
- package/oxe/workflows/swarm/board.md +119 -119
- package/oxe/workflows/swarm/scout.md +170 -170
- package/oxe/workflows/swarm-mode.md +280 -280
- package/oxe/workflows/ui-review.md +5 -5
- package/oxe/workflows/ui-spec.md +7 -7
- package/oxe/workflows/update.md +35 -35
- package/oxe/workflows/validate-gaps.md +45 -45
- package/oxe/workflows/verify-audit.md +73 -73
- package/oxe/workflows/verify.md +35 -14
- package/oxe/workflows/workflow-authoring.md +34 -34
- package/oxe/workflows/workstream.md +97 -97
- package/package.json +8 -3
- package/packages/runtime/package.json +1 -1
- package/packages/runtime/src/audit/audit-trail.ts +243 -243
- package/packages/runtime/src/audit/index.ts +2 -2
- package/packages/runtime/src/audit/policy-pack.ts +62 -62
- package/packages/runtime/src/compiler/graph-compiler.ts +67 -3
- package/packages/runtime/src/compiler/index.ts +1 -1
- package/packages/runtime/src/context/context-pack-store.ts +197 -197
- package/packages/runtime/src/context/context-profiles.ts +60 -60
- package/packages/runtime/src/context/index.ts +3 -3
- package/packages/runtime/src/decision/decision-engine.ts +174 -174
- package/packages/runtime/src/decision/decision-memo.ts +211 -211
- package/packages/runtime/src/decision/index.ts +2 -2
- package/packages/runtime/src/delivery/branch-manager.ts +91 -91
- package/packages/runtime/src/delivery/ci-checks.ts +285 -285
- package/packages/runtime/src/delivery/delivery-records.ts +75 -75
- package/packages/runtime/src/delivery/index.ts +5 -5
- package/packages/runtime/src/delivery/pr-manager.ts +112 -112
- package/packages/runtime/src/delivery/promotion-pipeline.ts +65 -2
- package/packages/runtime/src/events/bus.ts +92 -92
- package/packages/runtime/src/events/catalog.ts +29 -0
- package/packages/runtime/src/events/envelope.ts +14 -14
- package/packages/runtime/src/events/index.ts +3 -3
- package/packages/runtime/src/evidence/evidence-store.ts +130 -130
- package/packages/runtime/src/evidence/index.ts +1 -1
- package/packages/runtime/src/executor/action-tool-map.ts +52 -50
- package/packages/runtime/src/executor/adapters/antigravity-cli.ts +619 -0
- package/packages/runtime/src/executor/adapters/claude-cli.ts +367 -0
- package/packages/runtime/src/executor/adapters/grok-cli.ts +392 -0
- package/packages/runtime/src/executor/adapters/http-openai.ts +16 -0
- package/packages/runtime/src/executor/adapters/registry.ts +53 -0
- package/packages/runtime/src/executor/adapters/types.ts +24 -0
- package/packages/runtime/src/executor/built-in-tools.ts +525 -305
- package/packages/runtime/src/executor/index.ts +23 -6
- package/packages/runtime/src/executor/llm-task-executor.ts +854 -236
- package/packages/runtime/src/executor/node-context.ts +226 -0
- package/packages/runtime/src/executor/node-prompt-builder.ts +69 -62
- package/packages/runtime/src/executor/quota-patterns.ts +41 -0
- package/packages/runtime/src/executor/shell-argv.ts +144 -0
- package/packages/runtime/src/executor/stream-completion.ts +230 -145
- package/packages/runtime/src/gate/gate-manager.ts +289 -289
- package/packages/runtime/src/gate/index.ts +1 -1
- package/packages/runtime/src/index.ts +12 -0
- package/packages/runtime/src/models/attempt.ts +19 -19
- package/packages/runtime/src/models/evidence.ts +21 -21
- package/packages/runtime/src/models/failure.ts +22 -13
- package/packages/runtime/src/models/gate-decision.ts +25 -25
- package/packages/runtime/src/models/index.ts +8 -8
- package/packages/runtime/src/models/run.ts +1 -0
- package/packages/runtime/src/models/session.ts +11 -11
- package/packages/runtime/src/models/verification-result.ts +10 -10
- package/packages/runtime/src/models/work-item.ts +25 -25
- package/packages/runtime/src/models/workspace.ts +31 -31
- package/packages/runtime/src/plugins/capability-matrix.ts +126 -126
- package/packages/runtime/src/plugins/index.ts +5 -5
- package/packages/runtime/src/plugins/plugin-manifest.ts +118 -118
- package/packages/runtime/src/policy/index.ts +1 -1
- package/packages/runtime/src/policy/policy-engine.ts +330 -330
- package/packages/runtime/src/program/index.ts +1 -0
- package/packages/runtime/src/program/program-model.ts +293 -0
- package/packages/runtime/src/projection/index.ts +1 -1
- package/packages/runtime/src/projection/projection-engine.ts +61 -3
- package/packages/runtime/src/reducers/debug-reducer.ts +36 -36
- package/packages/runtime/src/reducers/index.ts +2 -2
- package/packages/runtime/src/reducers/run-state-reducer.ts +44 -5
- package/packages/runtime/src/scheduler/agent-registry.ts +132 -132
- package/packages/runtime/src/scheduler/agent-roles.ts +109 -109
- package/packages/runtime/src/scheduler/index.ts +4 -4
- package/packages/runtime/src/scheduler/run-journal.ts +47 -2
- package/packages/runtime/src/scheduler/scheduler.ts +1242 -99
- package/packages/runtime/src/verification/contract-exports.ts +203 -0
- package/packages/runtime/src/verification/index.ts +1 -0
- package/packages/runtime/src/verification/runner-timeout.ts +17 -0
- package/packages/runtime/src/verification/test-report-parsers.ts +204 -0
- package/packages/runtime/src/verification/verification-compiler.ts +508 -40
- package/packages/runtime/src/verification/verification-manifest.ts +44 -4
- package/packages/runtime/src/workspace/index.ts +2 -1
- package/packages/runtime/src/workspace/strategies/ephemeral-container.ts +44 -11
- package/packages/runtime/src/workspace/strategies/git-worktree.ts +104 -1
- package/packages/runtime/src/workspace/strategies/inplace.ts +38 -38
- package/packages/runtime/src/workspace/workspace-manager.ts +16 -16
- package/vscode-extension/LICENSE +21 -21
- package/vscode-extension/package.json +1 -1
- package/vscode-extension/src/shared/contextLoader.js +137 -137
- package/vscode-extension/src/shared/contractBuilder.js +159 -159
- package/vscode-extension/src/shared/stateReader.js +101 -101
- package/docs/oxe-artifact-map.html +0 -1172
|
@@ -0,0 +1,1289 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 1.21.2 — ALM (Jira / Azure DevOps) end to end: the PRD's user stories and the plan's tasks become work items, and
|
|
5
|
+
* the OXE lifecycle moves them — task started → in progress, PR opened → in review, merge train → queued / back to
|
|
6
|
+
* review with the reason, merged → merged, deploy → released (and the Jira version released), a defect after the
|
|
7
|
+
* deploy → a bug item linked to its origin.
|
|
8
|
+
*
|
|
9
|
+
* Config (.oxe/config.json):
|
|
10
|
+
* "alm": {
|
|
11
|
+
* "provider": "jira" | "azure-devops" | "none",
|
|
12
|
+
* "transport": "rest" | "mcp", // mcp: no token; writes go to alm-mcp-queue.json for the agent's MCP tools
|
|
13
|
+
* "dry_run": false, // show, never write (also --dry-run on every command)
|
|
14
|
+
* "auto": true, // sync at the lifecycle points (start-task, execute, promote, deploy, close)
|
|
15
|
+
* "program": "152code", // idempotency label ref-<program>-<ref> (default: the project folder name)
|
|
16
|
+
* "epic": "OXE-4", // parent of the stories (optional; per phase: { "F1": "OXE-4" })
|
|
17
|
+
* "labels": ["area-oxecode"], // added to the task's own labels, never replacing them
|
|
18
|
+
* "fix_version": "1.5.2", // or per phase: { "F1": "1.5.2", "F3": "1.5.3" }
|
|
19
|
+
* "release_version": false, // release the version at the deploy (off when a tag pipeline does it)
|
|
20
|
+
* "adopt_prefixes": ["CODE", "VIS", "BRD"], // a task carrying CODE-8 adopts the item labeled ref-CODE-8
|
|
21
|
+
* "states": { "in_progress": "Em andamento", "in_review": "Em revisão", "queued": "Na fila",
|
|
22
|
+
* "merged": "Na main", "released": "Lançado" }, // by NAME; the transition id is resolved live
|
|
23
|
+
* "track": ["in_progress", "in_review", "merged", "released"], // stages the OXE moves (default: all)
|
|
24
|
+
* "jira": { "project": "OXE", "site_env": "JIRA_SITE", "email_env": "JIRA_EMAIL", "token_env": "JIRA_API_TOKEN",
|
|
25
|
+
* "types": { "story": "Story", "task": "Task", "bug": "Task" }, "bug_label": "bug" },
|
|
26
|
+
* "azure_devops": { "project": "…", "org_env": "AZURE_DEVOPS_ORG", "token_env": "AZURE_DEVOPS_EXT_PAT",
|
|
27
|
+
* "types": { "story": "User Story", "task": "Task", "bug": "Bug" }, "area_path": "…", "iteration_path": "…" }
|
|
28
|
+
* }
|
|
29
|
+
* Credentials come ONLY from the environment variables named there; their values are never printed or written.
|
|
30
|
+
*
|
|
31
|
+
* State: .oxe/program/alm-links.ndjson (append-only: OXE id → key/url), .oxe/program/alm-state.json (the event cursor,
|
|
32
|
+
* the stage each item reached, and the failed writes waiting for a retry). An ALM failure never fails the OXE
|
|
33
|
+
* command that triggered it: it is recorded and retried on the next sync.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
const fs = require('fs');
|
|
37
|
+
const path = require('path');
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The canonical stages of a card, in order. Each project maps them to its own board's column names (alm.states); a
|
|
41
|
+
* stage with no column is skipped. The OXE moves only the stages in alm.track (the ones it owns: grill → grooming,
|
|
42
|
+
* refine → refinement / ready, task start → in_progress); a repository workflow may own the rest.
|
|
43
|
+
*/
|
|
44
|
+
const STAGES = ['intake', 'grooming', 'refinement', 'ready', 'in_progress', 'review', 'verified', 'queued', 'integrated', 'staging', 'accepted', 'released'];
|
|
45
|
+
/** The names of 1.21.2 before the 12 stages, still accepted in states / track / move. */
|
|
46
|
+
const STAGE_ALIASES = { todo: 'intake', in_review: 'review', merged: 'integrated' };
|
|
47
|
+
const canonStage = (s) => STAGE_ALIASES[s] || s;
|
|
48
|
+
/** Who moves each stage by default, and what proves a card may enter it (documentation and metrics). */
|
|
49
|
+
const STAGE_INFO = {
|
|
50
|
+
intake: { owner: 'human', proof: null },
|
|
51
|
+
grooming: { owner: 'oxe', proof: 'grill / perguntas do refine' },
|
|
52
|
+
refinement: { owner: 'oxe', proof: 'alm refine em curso' },
|
|
53
|
+
ready: { owner: 'oxe', proof: 'spec-v1 + lint OK + sem needs-info' },
|
|
54
|
+
in_progress: { owner: 'oxe', proof: 'tarefa iniciada (com ready_gate: spec-v1)' },
|
|
55
|
+
review: { owner: 'ci', proof: 'PR aberto' },
|
|
56
|
+
verified: { owner: 'ci', proof: 'pr:ready (CI verde)' },
|
|
57
|
+
queued: { owner: 'ci', proof: 'no trem de merge' },
|
|
58
|
+
integrated: { owner: 'ci', proof: 'merge na main' },
|
|
59
|
+
staging: { owner: 'ci', proof: 'branch release/X.Y.Z ou stage homologacao' },
|
|
60
|
+
accepted: { owner: 'human', proof: 'relatório de homologação' },
|
|
61
|
+
released: { owner: 'ci', proof: 'release verify / deploy' },
|
|
62
|
+
};
|
|
63
|
+
const DEFAULT_STATES = {
|
|
64
|
+
jira: { intake: 'To Do', in_progress: 'In Progress', review: 'In Review', integrated: 'Done', released: 'Done' },
|
|
65
|
+
'azure-devops': { intake: 'New', in_progress: 'Active', review: 'Resolved', integrated: 'Resolved', released: 'Closed' },
|
|
66
|
+
};
|
|
67
|
+
const canonStates = (st) => Object.fromEntries(Object.entries(st || {}).map(([k, v]) => [canonStage(k), v]));
|
|
68
|
+
|
|
69
|
+
// ── config ───────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
70
|
+
|
|
71
|
+
function almConfig(config, options = {}) {
|
|
72
|
+
const a = config && config.alm;
|
|
73
|
+
if (!a || typeof a !== 'object') return null;
|
|
74
|
+
const provider = String(a.provider || 'none').toLowerCase().replace('_', '-');
|
|
75
|
+
if (provider === 'none' || provider === 'false') return null;
|
|
76
|
+
if (!['jira', 'azure-devops'].includes(provider)) throw new Error(`alm.provider "${a.provider}" desconhecido (jira | azure-devops | none)`);
|
|
77
|
+
const p = provider === 'jira' ? (a.jira || {}) : (a.azure_devops || a['azure-devops'] || {});
|
|
78
|
+
const transport = String(a.transport || 'rest').toLowerCase();
|
|
79
|
+
if (!['rest', 'mcp'].includes(transport)) throw new Error(`alm.transport "${a.transport}" desconhecido (rest | mcp)`);
|
|
80
|
+
return {
|
|
81
|
+
provider,
|
|
82
|
+
// rest: the oxe-cc talks to the API (token in the environment). mcp: the oxe-cc decides WHAT to do and queues it;
|
|
83
|
+
// the agent runs the queue with the session's MCP tools (the user's own login) and reports back (alm ack).
|
|
84
|
+
transport,
|
|
85
|
+
dry_run: a.dry_run === true,
|
|
86
|
+
// OXB-G13: write only with an explicit --apply; without it every writing command is a simulation
|
|
87
|
+
require_apply: a.require_apply === true,
|
|
88
|
+
// the intake label: ref-<program>-<ref> (default; push refs like F2-T5 repeat across programs) or, with "plain",
|
|
89
|
+
// ref-<ref> for intake ids that are unique by themselves (ref-TOKENS-1-CAMADA, the board convention)
|
|
90
|
+
ref_label: a.ref_label === "plain" ? "plain" : "program",
|
|
91
|
+
auto: a.auto !== false,
|
|
92
|
+
// The program name in the idempotency label (ref-<program>-<ref>): refs like F2-T5 repeat across programs.
|
|
93
|
+
program: String(a.program || options.defaultProgram || 'oxe').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'oxe',
|
|
94
|
+
epic: a.epic || null,
|
|
95
|
+
labels: Array.isArray(a.labels) ? a.labels.map(String) : [],
|
|
96
|
+
// one version, or one per phase ({ "F1": "1.5.2", "F3": "1.5.3" }) like the epic
|
|
97
|
+
fix_version: a.fix_version && typeof a.fix_version === 'object' ? a.fix_version : (a.fix_version ? String(a.fix_version) : null),
|
|
98
|
+
// old codes a task may carry (refs: ["CODE-8"] or "CODE-8" in its text): an item labeled ref-CODE-8 is adopted
|
|
99
|
+
adopt_prefixes: Array.isArray(a.adopt_prefixes) ? a.adopt_prefixes.map(String) : [],
|
|
100
|
+
// Jira's label search can take MINUTES to see a new item: with ledger_guard, a missing local record refuses any
|
|
101
|
+
// create until `alm push --rebuild-ledger` rebuilt it from the search (no creates in that mode).
|
|
102
|
+
ledger_guard: a.ledger_guard === true,
|
|
103
|
+
search_settle_ms: Number.isFinite(Number(a.search_settle_ms)) && Number(a.search_settle_ms) >= 0 ? Number(a.search_settle_ms) : (a.ledger_guard === true ? 60_000 : 5000),
|
|
104
|
+
release_version: a.release_version === true,
|
|
105
|
+
// One writer per program: with alm.writer set, only the session that exports OXE_ALM_WRITER=<that name> creates
|
|
106
|
+
// or moves items; the others read and comment (two sessions creating the same batch duplicated 19 items).
|
|
107
|
+
writer: a.writer ? String(a.writer) : null,
|
|
108
|
+
// where the stories come from: "prd" (new project: the push creates them) or "alm" (the cards already exist: the
|
|
109
|
+
// push only links a PRD story to the card its row names, and never creates a story or an epic)
|
|
110
|
+
stories_source: a.stories_source === 'alm' ? 'alm' : 'prd',
|
|
111
|
+
// Definition of Ready: an item goes to in_progress only with the refined-spec label (alm refine → spec-v1)
|
|
112
|
+
ready_gate: a.ready_gate === true ? 'spec-v1' : (typeof a.ready_gate === 'string' && a.ready_gate ? a.ready_gate : null),
|
|
113
|
+
// The stages the OXE moves. A repository that already moves PR / train / tag (e.g. a GitHub Action) keeps only
|
|
114
|
+
// what it does not cover: "track": ["in_progress"].
|
|
115
|
+
track: Array.isArray(a.track) ? a.track.map((s) => canonStage(String(s))).filter((s) => STAGES.includes(s)) : STAGES.slice(),
|
|
116
|
+
states: { ...DEFAULT_STATES[provider], ...canonStates(a.states) },
|
|
117
|
+
// optional WIP limits per stage (warning only, in alm metrics): { "in_progress": 5 }
|
|
118
|
+
wip: a.wip && typeof a.wip === 'object' ? canonStates(a.wip) : {},
|
|
119
|
+
p,
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Missing settings / environment variables (names only). */
|
|
124
|
+
/** Is this process the program's ALM writer? (no alm.writer → everyone writes, as before) */
|
|
125
|
+
function isWriter(cfg, env = process.env) {
|
|
126
|
+
return !cfg || !cfg.writer || String(env.OXE_ALM_WRITER || '') === cfg.writer;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function writerError(cfg) {
|
|
130
|
+
return Object.assign(new Error(`ALM só leitura nesta sessão: o escritor do programa é "${cfg.writer}" (alm.writer). Daqui só se lê e comenta (oxe-cc alm comment); para escrever, rode na sessão escritora (OXE_ALM_WRITER=${cfg.writer})`), { readOnly: true });
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* A local lock while a session writes (push/sync/defect): a second writer on the same machine waits for nothing and
|
|
135
|
+
* is refused. A lock older than 15 minutes, or of a dead process, is taken over.
|
|
136
|
+
*/
|
|
137
|
+
function withWriteLock(programDir, fn) {
|
|
138
|
+
const file = path.join(programDir, 'alm-write.lock');
|
|
139
|
+
fs.mkdirSync(programDir, { recursive: true });
|
|
140
|
+
try {
|
|
141
|
+
const cur = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
142
|
+
let alive = false;
|
|
143
|
+
try { process.kill(cur.pid, 0); alive = true; } catch { alive = false; }
|
|
144
|
+
if (alive && cur.pid !== process.pid && Date.now() - Date.parse(cur.at) < 15 * 60_000) {
|
|
145
|
+
throw Object.assign(new Error(`outra sessão está escrevendo no ALM agora (pid ${cur.pid}, desde ${cur.at}) — rode de novo quando ela terminar; nada foi escrito`), { locked: true });
|
|
146
|
+
}
|
|
147
|
+
} catch (err) { if (err.locked) throw err; }
|
|
148
|
+
fs.writeFileSync(file, JSON.stringify({ pid: process.pid, at: new Date().toISOString() }));
|
|
149
|
+
const release = () => { try { const cur = JSON.parse(fs.readFileSync(file, 'utf8')); if (cur.pid === process.pid) fs.unlinkSync(file); } catch { /* */ } };
|
|
150
|
+
let out;
|
|
151
|
+
try { out = fn(); } catch (err) { release(); throw err; }
|
|
152
|
+
if (out && typeof out.then === 'function') return out.finally(release);
|
|
153
|
+
release();
|
|
154
|
+
return out;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function checkConfig(cfg, env = process.env) {
|
|
158
|
+
const problems = [];
|
|
159
|
+
if (!cfg) return ['alm não configurado (alm.provider: "jira" | "azure-devops" no .oxe/config.json)'];
|
|
160
|
+
if (!cfg.p.project) problems.push(`alm.${cfg.provider === 'jira' ? 'jira' : 'azure_devops'}.project ausente`);
|
|
161
|
+
if (cfg.transport === 'mcp') return problems; // the MCP server holds the login: no variable needed
|
|
162
|
+
const vars = cfg.provider === 'jira'
|
|
163
|
+
? [cfg.p.site_env || 'JIRA_SITE', cfg.p.email_env || 'JIRA_EMAIL', cfg.p.token_env || 'JIRA_API_TOKEN']
|
|
164
|
+
: [cfg.p.org_env || 'AZURE_DEVOPS_ORG', cfg.p.token_env || 'AZURE_DEVOPS_EXT_PAT'];
|
|
165
|
+
for (const v of vars) if (!env[v]) problems.push(`variável de ambiente ${v} não definida`);
|
|
166
|
+
return problems;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// ── http with retry and backoff ──────────────────────────────────────────────────────────────────────────────────
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* 8e 22/11: a token renewed in the Windows User env var does not reach processes started before the renewal; they
|
|
173
|
+
* keep the revoked one and Jira answers 404. Names (never values) of the credential vars whose process value differs
|
|
174
|
+
* from the User-scope one. Only for the real process env on Windows (or an injected `userEnv(name)` reader).
|
|
175
|
+
*/
|
|
176
|
+
function staleCredentialNames(credEnv) {
|
|
177
|
+
if (!credEnv || !Array.isArray(credEnv.names)) return [];
|
|
178
|
+
const reader = typeof credEnv.userEnv === 'function'
|
|
179
|
+
? credEnv.userEnv
|
|
180
|
+
: process.platform === 'win32' && credEnv.env === process.env
|
|
181
|
+
? (name) => {
|
|
182
|
+
const r = require('child_process').spawnSync('reg', ['query', 'HKCU\\Environment', '/v', name], { encoding: 'utf8', windowsHide: true, timeout: 5000 });
|
|
183
|
+
if (r.status !== 0) return null;
|
|
184
|
+
const m = new RegExp(`^\\s*${name}\\s+REG_(?:EXPAND_)?SZ\\s+(.*)$`, 'mi').exec(String(r.stdout || ''));
|
|
185
|
+
return m ? m[1].trim() : null;
|
|
186
|
+
}
|
|
187
|
+
: null;
|
|
188
|
+
if (!reader) return [];
|
|
189
|
+
const out = [];
|
|
190
|
+
for (const name of credEnv.names) {
|
|
191
|
+
let user = null;
|
|
192
|
+
try { user = reader(name); } catch { user = null; }
|
|
193
|
+
if (user != null && user !== '' && String(user) !== String((credEnv.env || {})[name] ?? '')) out.push(name);
|
|
194
|
+
}
|
|
195
|
+
return out;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Default transport: global fetch. Tests inject { http } with the same contract. */
|
|
199
|
+
async function fetchHttp(method, url, headers, body) {
|
|
200
|
+
const res = await fetch(url, { method, headers, body: body == null ? undefined : (typeof body === 'string' ? body : JSON.stringify(body)) });
|
|
201
|
+
const text = await res.text();
|
|
202
|
+
let json = null;
|
|
203
|
+
try { json = text ? JSON.parse(text) : null; } catch { json = null; }
|
|
204
|
+
return { status: res.status, json, text, headers: { retryAfter: res.headers.get('retry-after') } };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** A read-only POST (Azure WIQL query): allowed in a dry run. Everything else that is not GET writes. */
|
|
208
|
+
const isReadOnlyCall = (method, url) => method === 'GET' || (method === 'POST' && /\/wit\/wiql\?/.test(url));
|
|
209
|
+
|
|
210
|
+
async function request(ctx, method, url, body, extraHeaders = {}) {
|
|
211
|
+
// OXB-G13: a dry run (or a read-only session) never reaches a write endpoint, whatever the command does above
|
|
212
|
+
if (ctx.readOnly && !isReadOnlyCall(method, url)) {
|
|
213
|
+
throw Object.assign(new Error(`simulação: ${method} ${url.replace(/\?.*$/, '')} bloqueado (--dry-run nunca grava no ALM)`), { fatal: true, dryRunBlocked: true });
|
|
214
|
+
}
|
|
215
|
+
const attempts = ctx.retries ?? 3;
|
|
216
|
+
let last = null;
|
|
217
|
+
for (let i = 0; i < attempts; i += 1) {
|
|
218
|
+
try {
|
|
219
|
+
const r = await ctx.http(method, url, { ...ctx.headers, ...extraHeaders }, body);
|
|
220
|
+
if (r.status === 429 || r.status >= 500) {
|
|
221
|
+
last = new Error(`HTTP ${r.status}`);
|
|
222
|
+
const wait = Math.min(Number(r.headers && r.headers.retryAfter) * 1000 || (1000 * 3 ** i), 30_000);
|
|
223
|
+
await ctx.sleep(wait);
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
if (r.status === 401) throw Object.assign(new Error('HTTP 401: credencial recusada (confira as variáveis de ambiente do ALM)'), { fatal: true });
|
|
227
|
+
if (r.status === 403) throw Object.assign(new Error(`HTTP 403: sem permissão para ${method} ${url.replace(/\?.*$/, '')}`), { fatal: true });
|
|
228
|
+
// OXB-C28-9: a 404 names the call (quick start: comment or transition?) — the bare body did not say which write
|
|
229
|
+
if (r.status === 404) {
|
|
230
|
+
// 8e 22/11 (C28-9 again): Jira answers an unauthenticated call with 404 on every issue, never 401. Ask
|
|
231
|
+
// /myself once: a 401 there means the credential is the problem, not the card.
|
|
232
|
+
let anonymous = false;
|
|
233
|
+
const jira = /^(https?:\/\/[^/]+)\/rest\/api\/\d\//.exec(String(url));
|
|
234
|
+
if (jira && !/\/myself$/.test(String(url))) {
|
|
235
|
+
try { const me = await ctx.http('GET', `${jira[1]}/rest/api/3/myself`, { ...ctx.headers }, undefined); anonymous = Boolean(me && me.status === 401); } catch { anonymous = false; }
|
|
236
|
+
}
|
|
237
|
+
const where = `${method} ${String(url).replace(/^https?:\/\/[^/]+/, '').replace(/\?.*$/, '')}`;
|
|
238
|
+
if (anonymous) {
|
|
239
|
+
const stale = staleCredentialNames(ctx.credEnv);
|
|
240
|
+
const fix = stale.length
|
|
241
|
+
? `o valor de ${stale.join(', ')} neste processo difere da variável de usuário (renovada depois que este terminal/processo abriu): reabra o terminal ou recarregue as variáveis de usuário e rode de novo`
|
|
242
|
+
: 'renove o token (JIRA_API_TOKEN ou o token_env do bloco "alm") e confira o e-mail (JIRA_EMAIL)';
|
|
243
|
+
throw Object.assign(new Error(`HTTP 404 em ${where}: a credencial foi recusada (GET /rest/api/3/myself → 401), e o Jira responde 404 para todo card a um acesso anônimo — ${fix}`), { fatal: true, status: 404, auth: true, stale_env: stale });
|
|
244
|
+
}
|
|
245
|
+
throw Object.assign(new Error(`HTTP 404 em ${where}: ${String(r.text || '').slice(0, 300)} — o card existe e é visível para esta credencial (site e projeto do bloco "alm")?`), { fatal: true, status: 404 });
|
|
246
|
+
}
|
|
247
|
+
if (r.status >= 400) throw Object.assign(new Error(`HTTP ${r.status}: ${String(r.text || '').slice(0, 300)}`), { fatal: true });
|
|
248
|
+
return r.json;
|
|
249
|
+
} catch (err) {
|
|
250
|
+
if (err.fatal) throw err;
|
|
251
|
+
last = err;
|
|
252
|
+
await ctx.sleep(1000 * 3 ** i);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
throw last || new Error('falha de rede');
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// ── providers (one interface) ────────────────────────────────────────────────────────────────────────────────────
|
|
259
|
+
|
|
260
|
+
const adf = (text) => ({ type: 'doc', version: 1, content: String(text || '').split(/\n{2,}/).filter(Boolean).map((p) => ({ type: 'paragraph', content: [{ type: 'text', text: p.replace(/\n/g, ' ') }] })) });
|
|
261
|
+
|
|
262
|
+
function jiraProvider(cfg, env, ctx) {
|
|
263
|
+
const site = String(env[cfg.p.site_env || 'JIRA_SITE'] || '').replace(/\/+$/, '');
|
|
264
|
+
const auth = Buffer.from(`${env[cfg.p.email_env || 'JIRA_EMAIL']}:${env[cfg.p.token_env || 'JIRA_API_TOKEN']}`).toString('base64');
|
|
265
|
+
const c = { ...ctx, credEnv: { env, names: [cfg.p.email_env || 'JIRA_EMAIL', cfg.p.token_env || 'JIRA_API_TOKEN'], userEnv: ctx.userEnv }, headers: { Authorization: `Basic ${auth}`, Accept: 'application/json', 'Content-Type': 'application/json' } };
|
|
266
|
+
const types = { epic: 'Epic', story: 'Story', task: 'Task', bug: 'Task', ...(cfg.p.types || {}) };
|
|
267
|
+
let bugTypeResolved = false;
|
|
268
|
+
const project = cfg.p.project;
|
|
269
|
+
const keyUrl = (key) => `${site}/browse/${key}`;
|
|
270
|
+
return {
|
|
271
|
+
name: 'jira',
|
|
272
|
+
keyText: (key) => key,
|
|
273
|
+
url: keyUrl,
|
|
274
|
+
// alm list (OxeSpace 15/11): the cards in the given board states, every page (nextPageToken)
|
|
275
|
+
async searchByStates(states) {
|
|
276
|
+
const quoted = states.map((s) => `"${String(s).replace(/"/g, '\\"')}"`).join(', ');
|
|
277
|
+
const jql = `project = "${project}" AND status in (${quoted}) ORDER BY key ASC`;
|
|
278
|
+
const out = [];
|
|
279
|
+
let token = null;
|
|
280
|
+
for (let page = 0; page < 50; page += 1) {
|
|
281
|
+
const r = await request(c, 'GET', `${site}/rest/api/3/search/jql?jql=${encodeURIComponent(jql)}&fields=summary,status&maxResults=100${token ? `&nextPageToken=${encodeURIComponent(token)}` : ''}`);
|
|
282
|
+
for (const i of (r && r.issues) || []) out.push({ key: i.key, summary: i.fields && i.fields.summary ? i.fields.summary : '', status: i.fields && i.fields.status ? i.fields.status.name : null, url: keyUrl(i.key) });
|
|
283
|
+
token = r && r.nextPageToken ? r.nextPageToken : null;
|
|
284
|
+
if (!token || (r && r.isLast)) break;
|
|
285
|
+
}
|
|
286
|
+
return out;
|
|
287
|
+
},
|
|
288
|
+
async findByLabel(label) {
|
|
289
|
+
const jql = `project = "${project}" AND labels = "${label}"`;
|
|
290
|
+
const r = await request(c, 'GET', `${site}/rest/api/3/search/jql?jql=${encodeURIComponent(jql)}&fields=summary,status&maxResults=2`);
|
|
291
|
+
const issue = r && Array.isArray(r.issues) ? r.issues[0] : null;
|
|
292
|
+
return issue ? { key: issue.key, id: issue.id, status: issue.fields && issue.fields.status ? issue.fields.status.name : null } : null;
|
|
293
|
+
},
|
|
294
|
+
async create(item) {
|
|
295
|
+
// OXE-292: a bug uses the project's Bug type when it has one and the config does not map it (once per provider)
|
|
296
|
+
if (item.kind === 'bug' && !(cfg.p.types && cfg.p.types.bug) && !bugTypeResolved) {
|
|
297
|
+
bugTypeResolved = true;
|
|
298
|
+
try {
|
|
299
|
+
const pj = await request(c, 'GET', `${site}/rest/api/3/project/${encodeURIComponent(project)}`);
|
|
300
|
+
const hit = ((pj && pj.issueTypes) || []).filter((t) => t && !t.subtask && t.name).map((t) => t.name).find((n) => /^(bug|defeito|erro)$/i.test(String(n || '').trim()));
|
|
301
|
+
if (hit) types.bug = hit;
|
|
302
|
+
} catch { /* keep the map */ }
|
|
303
|
+
}
|
|
304
|
+
const fields = {
|
|
305
|
+
project: { key: project },
|
|
306
|
+
issuetype: { name: types[item.kind] || types.task },
|
|
307
|
+
summary: item.title.slice(0, 250),
|
|
308
|
+
description: adf(item.description),
|
|
309
|
+
labels: [...new Set([...(item.labels || [])])].map((l) => l.replace(/\s+/g, '-')),
|
|
310
|
+
...(item.parent ? { parent: { key: item.parent } } : {}),
|
|
311
|
+
...(item.fixVersion ? { fixVersions: [{ name: item.fixVersion }] } : {}),
|
|
312
|
+
};
|
|
313
|
+
// No retry on the POST itself: a create that timed out may have landed; the caller records the key at once and
|
|
314
|
+
// confirms with read() (GET by key — the label search takes minutes to see a new item).
|
|
315
|
+
const r = await request({ ...c, retries: 1 }, 'POST', `${site}/rest/api/3/issue`, { fields });
|
|
316
|
+
return { key: r.key, id: r.id };
|
|
317
|
+
},
|
|
318
|
+
async read(key) {
|
|
319
|
+
const back = await request(c, 'GET', `${site}/rest/api/3/issue/${key}?fields=summary,status,labels`);
|
|
320
|
+
return back ? { key: back.key, id: back.id, status: back.fields && back.fields.status ? back.fields.status.name : null } : null;
|
|
321
|
+
},
|
|
322
|
+
async status(key) {
|
|
323
|
+
const r = await request(c, 'GET', `${site}/rest/api/3/issue/${key}?fields=status`);
|
|
324
|
+
return r && r.fields && r.fields.status ? r.fields.status.name : null;
|
|
325
|
+
},
|
|
326
|
+
async transition(key, stateName) {
|
|
327
|
+
const now = await this.status(key);
|
|
328
|
+
if (now && now.toLowerCase() === stateName.toLowerCase()) return { changed: false, status: now };
|
|
329
|
+
const r = await request(c, 'GET', `${site}/rest/api/3/issue/${key}/transitions`);
|
|
330
|
+
const ts = (r && r.transitions) || [];
|
|
331
|
+
const t = ts.find((x) => x.to && String(x.to.name).toLowerCase() === stateName.toLowerCase()) || ts.find((x) => String(x.name).toLowerCase() === stateName.toLowerCase());
|
|
332
|
+
if (!t) throw Object.assign(new Error(`${key}: nenhuma transição leva a "${stateName}" (disponíveis: ${ts.map((x) => x.to ? x.to.name : x.name).join(', ') || '—'})`), { fatal: true });
|
|
333
|
+
await request(c, 'POST', `${site}/rest/api/3/issue/${key}/transitions`, { transition: { id: t.id } });
|
|
334
|
+
const after = await this.status(key);
|
|
335
|
+
return { changed: true, status: after };
|
|
336
|
+
},
|
|
337
|
+
async comment(key, text) { await request(c, 'POST', `${site}/rest/api/3/issue/${key}/comment`, { body: adf(text) }); },
|
|
338
|
+
async link(key, otherKey, type = 'Relates') { await request(c, 'POST', `${site}/rest/api/3/issueLink`, { type: { name: type }, inwardIssue: { key }, outwardIssue: { key: otherKey } }); },
|
|
339
|
+
/** OxeSpace 15/11 (alm supersede): the link types the site has, the issue's links and the close transition. */
|
|
340
|
+
async linkTypes() {
|
|
341
|
+
const r = await request(c, 'GET', `${site}/rest/api/3/issueLinkType`);
|
|
342
|
+
return ((r && r.issueLinkTypes) || []).map((t) => ({ name: t.name, inward: t.inward, outward: t.outward }));
|
|
343
|
+
},
|
|
344
|
+
async links(key) {
|
|
345
|
+
const r = await request(c, 'GET', `${site}/rest/api/3/issue/${key}?fields=issuelinks,status`);
|
|
346
|
+
const f = (r && r.fields) || {};
|
|
347
|
+
return {
|
|
348
|
+
status: f.status ? f.status.name : null,
|
|
349
|
+
done: Boolean(f.status && f.status.statusCategory && f.status.statusCategory.key === 'done'),
|
|
350
|
+
linked: (f.issuelinks || []).map((l) => (l.inwardIssue || l.outwardIssue || {}).key).filter(Boolean),
|
|
351
|
+
};
|
|
352
|
+
},
|
|
353
|
+
async linkDirected(type, inwardKey, outwardKey) { await request(c, 'POST', `${site}/rest/api/3/issueLink`, { type: { name: type }, inwardIssue: { key: inwardKey }, outwardIssue: { key: outwardKey } }); },
|
|
354
|
+
/** The transition to a done-category status (cancel / won't do / superseded first) and its resolution, if any. */
|
|
355
|
+
async closeTransition(key, opts = {}) {
|
|
356
|
+
const r = await request(c, 'GET', `${site}/rest/api/3/issue/${key}/transitions?expand=transitions.fields`);
|
|
357
|
+
const all = (r && r.transitions) || [];
|
|
358
|
+
const ts = all.filter((t) => t.to && t.to.statusCategory && t.to.statusCategory.key === 'done');
|
|
359
|
+
// OxeSpace 15/11: on a workflow whose only done status is the release one ("Lançado"), a superseded card would
|
|
360
|
+
// read as shipped. A release status is never picked unless named with --close-to.
|
|
361
|
+
const RELEASE = /lan[cç]ad|released?|deploy|entregue|em produ[cç][aã]o|publicad|shipped/i;
|
|
362
|
+
let t = null;
|
|
363
|
+
if (opts.closeTo) {
|
|
364
|
+
t = all.find((x) => x.to && String(x.to.name).toLowerCase() === String(opts.closeTo).toLowerCase()) || null;
|
|
365
|
+
if (!t) return { none: true, why: `nenhuma transição leva a "${opts.closeTo}" a partir de agora (disponíveis: ${all.map((x) => x.to && x.to.name).filter(Boolean).join(', ') || '—'})` };
|
|
366
|
+
} else {
|
|
367
|
+
const pref = /cancel|won.?t|superse|descart|desist|n[aã]o (ser[aá] )?feit|obsolet|duplic/i;
|
|
368
|
+
const usable = ts.filter((x) => !RELEASE.test(x.to.name) && !RELEASE.test(x.name));
|
|
369
|
+
t = usable.find((x) => pref.test(x.name) || pref.test(x.to.name)) || usable[0] || null;
|
|
370
|
+
if (!t && ts.length) return { none: true, why: `o fluxo só tem status done de release (${ts.map((x) => x.to.name).join(', ')}): fechar ali leria como entregue — use --close-to <status> ou --no-close` };
|
|
371
|
+
}
|
|
372
|
+
if (!t) return null;
|
|
373
|
+
const resField = t.fields && t.fields.resolution;
|
|
374
|
+
const values = (resField && resField.allowedValues) || [];
|
|
375
|
+
const res = values.find((v) => /won.?t|superse|duplic|n[aã]o ser[aá]|descart|obsolet|cancel/i.test(v.name)) || null;
|
|
376
|
+
return { id: t.id, name: t.name, to: t.to.name, resolution: res ? res.name : null, resolution_required: Boolean(resField && resField.required) };
|
|
377
|
+
},
|
|
378
|
+
async applyTransition(key, tr) {
|
|
379
|
+
await request(c, 'POST', `${site}/rest/api/3/issue/${key}/transitions`, { transition: { id: tr.id }, ...(tr.resolution ? { fields: { resolution: { name: tr.resolution } } } : {}) });
|
|
380
|
+
return this.status(key);
|
|
381
|
+
},
|
|
382
|
+
async remoteLink(key, url, title) {
|
|
383
|
+
// globalId makes it idempotent: the same PR posted again updates the link instead of adding a second one
|
|
384
|
+
await request(c, 'POST', `${site}/rest/api/3/issue/${key}/remotelink`, { globalId: `oxe-pr:${url}`, object: { url, title, icon: { url16x16: 'https://github.com/favicon.ico', title: 'GitHub' } } });
|
|
385
|
+
return { linked: true };
|
|
386
|
+
},
|
|
387
|
+
async labels(key) {
|
|
388
|
+
const r = await request(c, 'GET', `${site}/rest/api/3/issue/${key}?fields=labels`);
|
|
389
|
+
return (r && r.fields && r.fields.labels) || [];
|
|
390
|
+
},
|
|
391
|
+
async addLabels(key, labels) {
|
|
392
|
+
await request(c, 'PUT', `${site}/rest/api/3/issue/${key}`, { update: { labels: labels.map((l) => ({ add: l })) } });
|
|
393
|
+
},
|
|
394
|
+
async removeLabels(key, labels) {
|
|
395
|
+
await request(c, 'PUT', `${site}/rest/api/3/issue/${key}`, { update: { labels: labels.map((l) => ({ remove: l })) } });
|
|
396
|
+
},
|
|
397
|
+
/** The fix versions of an item (names). */
|
|
398
|
+
async fixVersions(key) {
|
|
399
|
+
const r = await request(c, 'GET', `${site}/rest/api/3/issue/${key}?fields=fixVersions`);
|
|
400
|
+
return ((r && r.fields && r.fields.fixVersions) || []).map((v) => v.name);
|
|
401
|
+
},
|
|
402
|
+
/**
|
|
403
|
+
* Sets the fix version of an existing item. A PUT of `fields.fixVersions` came back empty on Jira Cloud; what works
|
|
404
|
+
* is `update.fixVersions[].set` with the version id.
|
|
405
|
+
*/
|
|
406
|
+
async setFixVersion(key, name) {
|
|
407
|
+
const vs = await request(c, 'GET', `${site}/rest/api/3/project/${project}/versions`);
|
|
408
|
+
const v = (vs || []).find((x) => x.name === name);
|
|
409
|
+
if (!v) throw Object.assign(new Error(`versão ${name} não existe no projeto ${project}`), { fatal: true });
|
|
410
|
+
await request(c, 'PUT', `${site}/rest/api/3/issue/${key}`, { update: { fixVersions: [{ set: [{ id: String(v.id) }] }] } });
|
|
411
|
+
const now = await this.fixVersions(key);
|
|
412
|
+
return { changed: true, ok: now.includes(name), versions: now };
|
|
413
|
+
},
|
|
414
|
+
/** The card's summary line (OxeSpace 14/11, OXE-160: refine narrowed the scope, the title still named it). */
|
|
415
|
+
async setSummary(key, summary) {
|
|
416
|
+
await request(c, 'PUT', `${site}/rest/api/3/issue/${key}`, { fields: { summary } });
|
|
417
|
+
const r = await request(c, 'GET', `${site}/rest/api/3/issue/${key}?fields=summary`);
|
|
418
|
+
return { ok: Boolean(r && r.fields && r.fields.summary === summary), summary: r && r.fields ? r.fields.summary : null };
|
|
419
|
+
},
|
|
420
|
+
/** No fix version at all (OxeSpace 15/11: a superseded card keeps no version). */
|
|
421
|
+
async clearFixVersions(key) {
|
|
422
|
+
await request(c, 'PUT', `${site}/rest/api/3/issue/${key}`, { update: { fixVersions: [{ set: [] }] } });
|
|
423
|
+
const now = await this.fixVersions(key);
|
|
424
|
+
return { changed: true, ok: now.length === 0, versions: now };
|
|
425
|
+
},
|
|
426
|
+
async releaseVersion(name) {
|
|
427
|
+
const vs = await request(c, 'GET', `${site}/rest/api/3/project/${project}/versions`);
|
|
428
|
+
const v = (vs || []).find((x) => x.name === name);
|
|
429
|
+
if (!v) throw Object.assign(new Error(`versão ${name} não existe no projeto ${project}`), { fatal: true });
|
|
430
|
+
if (v.released) return { changed: false };
|
|
431
|
+
await request(c, 'PUT', `${site}/rest/api/3/version/${v.id}`, { released: true, releaseDate: new Date().toISOString().slice(0, 10) });
|
|
432
|
+
return { changed: true };
|
|
433
|
+
},
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
function azureProvider(cfg, env, ctx) {
|
|
438
|
+
const org = String(env[cfg.p.org_env || 'AZURE_DEVOPS_ORG'] || '').replace(/\/+$/, '');
|
|
439
|
+
const orgUrl = /^https?:\/\//.test(org) ? org : `https://dev.azure.com/${org}`;
|
|
440
|
+
const project = cfg.p.project;
|
|
441
|
+
const base = `${orgUrl}/${encodeURIComponent(project)}/_apis`;
|
|
442
|
+
const auth = Buffer.from(`:${env[cfg.p.token_env || 'AZURE_DEVOPS_EXT_PAT']}`).toString('base64');
|
|
443
|
+
const c = { ...ctx, headers: { Authorization: `Basic ${auth}`, Accept: 'application/json', 'Content-Type': 'application/json' } };
|
|
444
|
+
const types = { epic: 'Epic', story: 'User Story', task: 'Task', bug: 'Bug', ...(cfg.p.types || {}) };
|
|
445
|
+
const api = 'api-version=7.1';
|
|
446
|
+
const html = (t) => String(t || '').split(/\n{2,}/).map((p) => `<p>${p.replace(/&/g, '&').replace(/</g, '<').replace(/\n/g, '<br>')}</p>`).join('');
|
|
447
|
+
return {
|
|
448
|
+
name: 'azure-devops',
|
|
449
|
+
keyText: (id) => `AB#${id}`,
|
|
450
|
+
url: (id) => `${orgUrl}/${encodeURIComponent(project)}/_workitems/edit/${id}`,
|
|
451
|
+
async findByLabel(label) {
|
|
452
|
+
const r = await request(c, 'POST', `${base}/wit/wiql?${api}`, { query: `SELECT [System.Id] FROM WorkItems WHERE [System.TeamProject] = @project AND [System.Tags] CONTAINS '${label.replace(/'/g, "''")}'` });
|
|
453
|
+
const id = r && Array.isArray(r.workItems) && r.workItems[0] ? r.workItems[0].id : null;
|
|
454
|
+
return id ? { key: String(id), id: String(id), status: await this.status(String(id)) } : null;
|
|
455
|
+
},
|
|
456
|
+
async create(item) {
|
|
457
|
+
const ops = [
|
|
458
|
+
{ op: 'add', path: '/fields/System.Title', value: item.title.slice(0, 250) },
|
|
459
|
+
{ op: 'add', path: '/fields/System.Description', value: html(item.description) },
|
|
460
|
+
{ op: 'add', path: '/fields/System.Tags', value: [...new Set(item.labels || [])].join('; ') },
|
|
461
|
+
...(cfg.p.area_path ? [{ op: 'add', path: '/fields/System.AreaPath', value: cfg.p.area_path }] : []),
|
|
462
|
+
...(cfg.p.iteration_path ? [{ op: 'add', path: '/fields/System.IterationPath', value: cfg.p.iteration_path }] : []),
|
|
463
|
+
...(item.parent ? [{ op: 'add', path: '/relations/-', value: { rel: 'System.LinkTypes.Hierarchy-Reverse', url: `${orgUrl}/_apis/wit/workItems/${item.parent}` } }] : []),
|
|
464
|
+
];
|
|
465
|
+
const r = await request({ ...c, retries: 1 }, 'POST', `${base}/wit/workitems/$${encodeURIComponent(types[item.kind] || types.task)}?${api}`, ops, { 'Content-Type': 'application/json-patch+json' });
|
|
466
|
+
return { key: String(r.id), id: String(r.id) };
|
|
467
|
+
},
|
|
468
|
+
async read(id) {
|
|
469
|
+
const back = await request(c, 'GET', `${base}/wit/workitems/${id}?${api}`);
|
|
470
|
+
return back ? { key: String(back.id), id: String(back.id), status: back.fields ? back.fields['System.State'] : null } : null;
|
|
471
|
+
},
|
|
472
|
+
async status(id) {
|
|
473
|
+
const r = await request(c, 'GET', `${base}/wit/workitems/${id}?fields=System.State&${api}`);
|
|
474
|
+
return r && r.fields ? r.fields['System.State'] : null;
|
|
475
|
+
},
|
|
476
|
+
async transition(id, stateName) {
|
|
477
|
+
const now = await this.status(id);
|
|
478
|
+
if (now && now.toLowerCase() === stateName.toLowerCase()) return { changed: false, status: now };
|
|
479
|
+
await request(c, 'PATCH', `${base}/wit/workitems/${id}?${api}`, [{ op: 'add', path: '/fields/System.State', value: stateName }], { 'Content-Type': 'application/json-patch+json' });
|
|
480
|
+
return { changed: true, status: await this.status(id) };
|
|
481
|
+
},
|
|
482
|
+
async comment(id, text) { await request(c, 'POST', `${base}/wit/workItems/${id}/comments?api-version=7.1-preview.4`, { text: html(text) }); },
|
|
483
|
+
async link(id, otherId) {
|
|
484
|
+
await request(c, 'PATCH', `${base}/wit/workitems/${id}?${api}`, [{ op: 'add', path: '/relations/-', value: { rel: 'System.LinkTypes.Related', url: `${orgUrl}/_apis/wit/workItems/${otherId}` } }], { 'Content-Type': 'application/json-patch+json' });
|
|
485
|
+
},
|
|
486
|
+
async remoteLink(id, url, title) {
|
|
487
|
+
await request(c, 'PATCH', `${base}/wit/workitems/${id}?${api}`, [{ op: 'add', path: '/relations/-', value: { rel: 'Hyperlink', url, attributes: { comment: title } } }], { 'Content-Type': 'application/json-patch+json' });
|
|
488
|
+
return { linked: true };
|
|
489
|
+
},
|
|
490
|
+
async releaseVersion() { return { changed: false, note: 'Azure DevOps não tem versão de release no item; use iteration_path' }; },
|
|
491
|
+
};
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* transport "mcp": nothing leaves the oxe-cc. Every write becomes an operation in .oxe/program/alm-mcp-queue.json; the
|
|
496
|
+
* agent runs them in order with the MCP tools of its session and reports each one with `oxe-cc alm ack`.
|
|
497
|
+
*/
|
|
498
|
+
function queueProvider(cfg) {
|
|
499
|
+
return { name: cfg.provider, deferred: true, url: () => null };
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/** A raw Jira REST context ({ request(method, url, body), site }) with the same auth, retries and backoff. */
|
|
503
|
+
function jiraRest(cfg, options = {}) {
|
|
504
|
+
const env = options.env || process.env;
|
|
505
|
+
const site = String(env[cfg.p.site_env || 'JIRA_SITE'] || '').replace(/\/+$/, '');
|
|
506
|
+
const auth = Buffer.from(`${env[cfg.p.email_env || 'JIRA_EMAIL']}:${env[cfg.p.token_env || 'JIRA_API_TOKEN']}`).toString('base64');
|
|
507
|
+
const c = { http: options.http || fetchHttp, sleep: options.sleep || ((ms) => new Promise((r) => setTimeout(r, ms))), retries: options.retries, readOnly: isDry(cfg, options), credEnv: { env, names: [cfg.p.email_env || 'JIRA_EMAIL', cfg.p.token_env || 'JIRA_API_TOKEN'], userEnv: options.userEnv }, headers: { Authorization: `Basic ${auth}`, Accept: 'application/json', 'Content-Type': 'application/json' } };
|
|
508
|
+
return { site, readOnly: c.readOnly, request: (method, url, body) => request(c, method, url, body) };
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/** Is this call a simulation? --dry-run, alm.dry_run, or an explicit read-only context. */
|
|
512
|
+
/**
|
|
513
|
+
* Deprecation (coordination 14/11): today a writing command without --apply still writes; the next minor makes
|
|
514
|
+
* alm.require_apply true by default. Said once per process, on stderr, so a JSON output stays clean.
|
|
515
|
+
*/
|
|
516
|
+
let applyWarned = false;
|
|
517
|
+
function warnApply(cfg, options = {}) {
|
|
518
|
+
if (applyWarned || !cfg || cfg.require_apply || options.apply || isDry(cfg, options) || options.quietApply) return false;
|
|
519
|
+
applyWarned = true;
|
|
520
|
+
process.stderr.write(' ! isto grava no ALM sem --apply; na próxima versão vai exigir --apply (alm.require_apply passa a true)\n');
|
|
521
|
+
return true;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
const isDry = (cfg, options = {}) => Boolean(options.dryRun || options.readOnly || (cfg && cfg.dry_run) || (cfg && cfg.require_apply && !options.apply));
|
|
525
|
+
|
|
526
|
+
function provider(cfg, options = {}) {
|
|
527
|
+
if (cfg.transport === 'mcp') return queueProvider(cfg);
|
|
528
|
+
const env = options.env || process.env;
|
|
529
|
+
const ctx = { http: options.http || fetchHttp, sleep: options.sleep || ((ms) => new Promise((r) => setTimeout(r, ms))), retries: options.retries, readOnly: isDry(cfg, options), userEnv: options.userEnv };
|
|
530
|
+
return cfg.provider === 'jira' ? jiraProvider(cfg, env, ctx) : azureProvider(cfg, env, ctx);
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
// ── ledger and state ─────────────────────────────────────────────────────────────────────────────────────────────
|
|
534
|
+
|
|
535
|
+
const linksFile = (programDir) => path.join(programDir, 'alm-links.ndjson');
|
|
536
|
+
const stateFile = (programDir) => path.join(programDir, 'alm-state.json');
|
|
537
|
+
|
|
538
|
+
function links(programDir) {
|
|
539
|
+
const out = new Map();
|
|
540
|
+
let raw = '';
|
|
541
|
+
try { raw = fs.readFileSync(linksFile(programDir), 'utf8'); } catch { return out; }
|
|
542
|
+
for (const line of raw.split(/\r?\n/)) { try { const r = JSON.parse(line); if (r && r.ref && r.key) out.set(r.ref, r); } catch { /* */ } }
|
|
543
|
+
return out;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
function addLink(programDir, rec) {
|
|
547
|
+
fs.mkdirSync(programDir, { recursive: true });
|
|
548
|
+
fs.appendFileSync(linksFile(programDir), `${JSON.stringify({ ...rec, at: new Date().toISOString() })}\n`, 'utf8');
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
function readState(programDir) {
|
|
552
|
+
try { return JSON.parse(fs.readFileSync(stateFile(programDir), 'utf8')); } catch { return { cursor: 0, stages: {}, pending: [] }; }
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
function writeState(programDir, st) {
|
|
556
|
+
fs.mkdirSync(programDir, { recursive: true });
|
|
557
|
+
fs.writeFileSync(stateFile(programDir), JSON.stringify(st, null, 2), 'utf8');
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
// ── MCP queue (transport "mcp") ──────────────────────────────────────────────────────────────────────────────────
|
|
561
|
+
|
|
562
|
+
const REF_MARK = '@ref:'; // an item still queued, named by its ref where a key would go
|
|
563
|
+
const queueFile = (programDir) => path.join(programDir, 'alm-mcp-queue.json');
|
|
564
|
+
|
|
565
|
+
function readQueue(programDir) {
|
|
566
|
+
try { const q = JSON.parse(fs.readFileSync(queueFile(programDir), 'utf8')); return Array.isArray(q.ops) ? q : { ops: [] }; } catch { return { ops: [] }; }
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
function writeQueue(programDir, q) {
|
|
570
|
+
fs.mkdirSync(programDir, { recursive: true });
|
|
571
|
+
fs.writeFileSync(queueFile(programDir), JSON.stringify({ ...q, updated_at: new Date().toISOString() }, null, 2), 'utf8');
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/** The search the agent runs BEFORE creating (an item already there is adopted, never duplicated). */
|
|
575
|
+
function searchFor(cfg, labels) {
|
|
576
|
+
if (cfg.provider === 'jira') return { jql: `project = "${cfg.p.project}" AND labels in (${labels.map((l) => `"${l}"`).join(', ')})` };
|
|
577
|
+
return { wiql: `SELECT [System.Id] FROM WorkItems WHERE [System.TeamProject] = '${String(cfg.p.project).replace(/'/g, "''")}' AND (${labels.map((l) => `[System.Tags] CONTAINS '${l.replace(/'/g, "''")}'`).join(' OR ')})` };
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/**
|
|
581
|
+
* Adds (or replaces, by id) operations, keeping the order a parent needs: an ensure keeps its first position. A newer
|
|
582
|
+
* transition of the same item replaces the older one (the state is set by name, the last one wins) and keeps the
|
|
583
|
+
* comments of both. Ops whose item is already linked carry its key; the others name the parent by `parent_ref`.
|
|
584
|
+
*/
|
|
585
|
+
function enqueue(programDir, ops) {
|
|
586
|
+
const q = readQueue(programDir);
|
|
587
|
+
for (const op of ops) {
|
|
588
|
+
const i = q.ops.findIndex((o) => o.id === op.id);
|
|
589
|
+
if (i < 0) { q.ops.push({ ...op, queued_at: new Date().toISOString() }); continue; }
|
|
590
|
+
const prev = q.ops[i];
|
|
591
|
+
const comments = [...new Set([...(prev.comments || []), ...(op.comments || [])])];
|
|
592
|
+
q.ops[i] = { ...prev, ...op, ...(comments.length ? { comments } : {}), queued_at: prev.queued_at };
|
|
593
|
+
}
|
|
594
|
+
writeQueue(programDir, q);
|
|
595
|
+
return q;
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/** The queue with the keys known since (a parent created by an earlier op) filled in. */
|
|
599
|
+
function pendingOps(programDir) {
|
|
600
|
+
const known = links(programDir);
|
|
601
|
+
return readQueue(programDir).ops.map((o) => {
|
|
602
|
+
const out = { ...o };
|
|
603
|
+
if (o.parent_ref && known.has(o.parent_ref)) out.parent = known.get(o.parent_ref).key;
|
|
604
|
+
if (o.ref && !o.key && known.has(o.ref) && o.op !== 'ensure') out.key = known.get(o.ref).key;
|
|
605
|
+
if (o.other_ref && known.has(o.other_ref)) out.other_key = known.get(o.other_ref).key;
|
|
606
|
+
return out;
|
|
607
|
+
});
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* The agent reports one operation: done (an ensure needs the key it created or found), or failed (it stays queued,
|
|
612
|
+
* with the error). An id or, for convenience, the item ref (US-3, F1-T2: its ensure first, else its transition).
|
|
613
|
+
*/
|
|
614
|
+
function ack(programDir, cfg, idOrRef, input = {}) {
|
|
615
|
+
const q = readQueue(programDir);
|
|
616
|
+
const op = q.ops.find((o) => o.id === idOrRef) || q.ops.find((o) => o.ref === idOrRef && o.op === 'ensure') || q.ops.find((o) => o.ref === idOrRef);
|
|
617
|
+
if (!op) throw new Error(`${idOrRef}: nenhuma operação na fila do ALM (oxe-cc alm queue)`);
|
|
618
|
+
if (input.error) {
|
|
619
|
+
op.attempts = (op.attempts || 0) + 1;
|
|
620
|
+
op.last_error = String(input.error).slice(0, 300);
|
|
621
|
+
writeQueue(programDir, q);
|
|
622
|
+
return { id: op.id, failed: true, attempts: op.attempts };
|
|
623
|
+
}
|
|
624
|
+
if (op.op === 'ensure') {
|
|
625
|
+
if (!input.key) throw new Error(`${op.id}: informe a chave criada ou encontrada (--key OXE-12 / --key 123)`);
|
|
626
|
+
const key = String(input.key).replace(/^AB#/i, '');
|
|
627
|
+
addLink(programDir, { ref: op.ref, key, url: input.url || null, kind: op.kind, provider: cfg.provider, via: 'mcp', ...(input.adopted ? { adopted: input.adopted } : {}), ...(op.cr ? { cr: op.cr } : {}) });
|
|
628
|
+
} else if (op.op === 'transition') {
|
|
629
|
+
const st = readState(programDir);
|
|
630
|
+
st.stages[op.ref] = op.stage;
|
|
631
|
+
writeState(programDir, st);
|
|
632
|
+
} else if (op.op === 'release_version') {
|
|
633
|
+
const st = readState(programDir);
|
|
634
|
+
st.versions_released = [...new Set([...(st.versions_released || []), op.version])];
|
|
635
|
+
writeState(programDir, st);
|
|
636
|
+
}
|
|
637
|
+
q.ops = q.ops.filter((o) => o !== op);
|
|
638
|
+
writeQueue(programDir, q);
|
|
639
|
+
return { id: op.id, done: true, remaining: q.ops.length };
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
/** `alm link` by hand settles the ensure of that ref too. */
|
|
643
|
+
function dropEnsure(programDir, ref) {
|
|
644
|
+
const q = readQueue(programDir);
|
|
645
|
+
const n = q.ops.length;
|
|
646
|
+
q.ops = q.ops.filter((o) => !(o.op === 'ensure' && o.ref === ref));
|
|
647
|
+
if (q.ops.length !== n) writeQueue(programDir, q);
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/**
|
|
651
|
+
* The idempotency label: ref-<program>-<ref> (ref-152code-US-3, ref-152code-F2-T5). The project's own convention
|
|
652
|
+
* (ref-CODE-8, ref-BRD-nn) and never confused with the item keys (OXE-n) in a search.
|
|
653
|
+
*/
|
|
654
|
+
const refLabel = (ref, cfg) => `ref-${(cfg && cfg.program) || 'oxe'}-${ref}`;
|
|
655
|
+
const taskRef = (phase, taskId) => (phase ? `${phase}-${taskId}` : taskId);
|
|
656
|
+
const perPhase = (v, phase) => (v && typeof v === 'object' ? v[phase] || null : v || null);
|
|
657
|
+
|
|
658
|
+
/** Old codes a task carries: its `refs`, plus <PREFIX>-<n> in its text for the configured prefixes. */
|
|
659
|
+
function oldRefs(cfg, t) {
|
|
660
|
+
const out = new Set((Array.isArray(t.refs) ? t.refs : []).map(String));
|
|
661
|
+
if (cfg.adopt_prefixes.length) {
|
|
662
|
+
const re = new RegExp(`\\b(?:${cfg.adopt_prefixes.map((p) => p.replace(/[^A-Za-z0-9]/g, '')).join('|')})-\\d+\\b`, 'g');
|
|
663
|
+
for (const m of `${t.title || ''} ${t.description || ''}`.match(re) || []) out.add(m);
|
|
664
|
+
}
|
|
665
|
+
return [...out];
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
// ── push (stories, tasks) ────────────────────────────────────────────────────────────────────────────────────────
|
|
669
|
+
|
|
670
|
+
/**
|
|
671
|
+
* Creates the missing items: each PRD story (parent = alm.epic), then each pending plan task (parent = the story whose
|
|
672
|
+
* criteria it delivers, else the epic). Idempotent: an item already linked, or found by its oxe-… label, is reused.
|
|
673
|
+
* @param {{ stories: object[], tasks: object[], phase: string|null, dryRun: boolean }} input
|
|
674
|
+
*/
|
|
675
|
+
async function push(programDir, cfg, input, options = {}) {
|
|
676
|
+
const prov = options.provider || provider(cfg, options);
|
|
677
|
+
const known = links(programDir);
|
|
678
|
+
const result = { created: [], reused: [], planned: [], failed: [] };
|
|
679
|
+
const ledgerExists = fs.existsSync(linksFile(programDir));
|
|
680
|
+
if (cfg.ledger_guard && !ledgerExists && !input.dryRun && !input.rebuild && !input.firstPush) {
|
|
681
|
+
throw new Error(`registro local do ALM ausente (${path.relative(process.cwd(), linksFile(programDir)) || linksFile(programDir)}): com alm.ledger_guard, nada é criado no escuro — rode oxe-cc alm push --rebuild-ledger (refaz o registro pela busca, sem criar) ou, se é o primeiro push deste programa, --first-push`);
|
|
682
|
+
}
|
|
683
|
+
if (input.rebuild) result.missing = [];
|
|
684
|
+
let createdEpic = null;
|
|
685
|
+
const epicFor = (phase) => perPhase(cfg.epic, phase) || createdEpic;
|
|
686
|
+
const fixVersion = perPhase(cfg.fix_version, input.phase);
|
|
687
|
+
// Dry run with credentials: READS only (what exists, what would be adopted); no credentials: nothing leaves.
|
|
688
|
+
const canRead = !prov.deferred && (!input.dryRun || options.readOnlyLookup === true);
|
|
689
|
+
let settled = false;
|
|
690
|
+
// transport "mcp": an item not linked yet becomes an `ensure` op (search by label → adopt or create → alm ack); the
|
|
691
|
+
// children name it by ref until the agent reports its key.
|
|
692
|
+
// The target version on an item that exists (adopted, or created without it): set by id via update.set — never
|
|
693
|
+
// trusted to the create alone. A failure here is a warning, not a lost item.
|
|
694
|
+
const ensureVersion = async (key, version) => {
|
|
695
|
+
if (!version || input.dryRun || typeof prov.fixVersions !== 'function') return;
|
|
696
|
+
try {
|
|
697
|
+
const have = await prov.fixVersions(key);
|
|
698
|
+
if (have.includes(version)) return;
|
|
699
|
+
const r = await prov.setFixVersion(key, version);
|
|
700
|
+
(result.versions = result.versions || []).push({ key, version, ok: r.ok });
|
|
701
|
+
} catch (err) { (result.versions = result.versions || []).push({ key, version, ok: false, error: err.message }); }
|
|
702
|
+
};
|
|
703
|
+
const deferred = prov.deferred && !input.dryRun && !input.rebuild;
|
|
704
|
+
const ops = [];
|
|
705
|
+
if (deferred) result.queued = [];
|
|
706
|
+
const TYPES = cfg.provider === 'jira' ? { epic: 'Epic', story: 'Story', task: 'Task', bug: 'Task' } : { epic: 'Epic', story: 'User Story', task: 'Task', bug: 'Bug' };
|
|
707
|
+
const parentField = (p) => (typeof p === 'string' && p.startsWith(REF_MARK) ? { parent_ref: p.slice(REF_MARK.length) } : (p ? { parent: p } : {}));
|
|
708
|
+
const keyRe = new RegExp(`^${String(cfg.p.project || '[A-Z][A-Z0-9]+').replace(/[^A-Za-z0-9]/g, '')}-\\d+$`);
|
|
709
|
+
const ensure = async (ref, item, adopt = [], hints = {}) => {
|
|
710
|
+
if (known.has(ref)) { result.reused.push({ ref, key: known.get(ref).key }); return known.get(ref).key; }
|
|
711
|
+
// the item names its card (OXE-48 in the PRD row, "(OXE-20)" in the task): that card is it, confirmed by key
|
|
712
|
+
const cardKey = (hints.keys || []).find((k) => keyRe.test(k)) || null;
|
|
713
|
+
if (cardKey && !deferred && (canRead || !input.dryRun)) {
|
|
714
|
+
try {
|
|
715
|
+
const got = await prov.read(cardKey);
|
|
716
|
+
if (got) {
|
|
717
|
+
if (input.dryRun) { result.reused.push({ ref, key: got.key, by_key: true, dry_run: true }); return got.key; }
|
|
718
|
+
addLink(programDir, { ref, key: got.key, url: prov.url(got.key), kind: item.kind, provider: prov.name, by_key: true });
|
|
719
|
+
known.set(ref, { ref, key: got.key });
|
|
720
|
+
result.reused.push({ ref, key: got.key, by_key: true });
|
|
721
|
+
return got.key;
|
|
722
|
+
}
|
|
723
|
+
} catch { /* not found by key: the usual path below */ }
|
|
724
|
+
}
|
|
725
|
+
if (hints.noCreate) {
|
|
726
|
+
(result.missing = result.missing || []).push({ ref, kind: item.kind, title: item.title, why: cardKey ? `o card ${cardKey} não foi encontrado` : 'alm.stories_source "alm": a história não cita o card — ponha a chave na linha da US no PRD (ex.: "OXE-48") ou rode oxe-cc alm link ' + ref + ' <chave>' });
|
|
727
|
+
return null;
|
|
728
|
+
}
|
|
729
|
+
if (deferred) {
|
|
730
|
+
ops.push({
|
|
731
|
+
id: `ensure:${ref}`, op: 'ensure', ref, kind: item.kind,
|
|
732
|
+
type: { ...TYPES, ...(cfg.p.types || {}) }[item.kind] || TYPES.task,
|
|
733
|
+
project: cfg.p.project, title: item.title, description: item.description, labels: item.labels,
|
|
734
|
+
...parentField(item.parent), ...(item.fixVersion ? { fix_version: item.fixVersion } : {}),
|
|
735
|
+
...(cfg.provider === 'azure-devops' && cfg.p.area_path ? { area_path: cfg.p.area_path } : {}),
|
|
736
|
+
...(cfg.provider === 'azure-devops' && cfg.p.iteration_path ? { iteration_path: cfg.p.iteration_path } : {}),
|
|
737
|
+
...(adopt.length ? { adopt } : {}),
|
|
738
|
+
...(cardKey ? { adopt_key: cardKey } : {}),
|
|
739
|
+
search: searchFor(cfg, [refLabel(ref, cfg), ...adopt.map((o) => `ref-${o}`)]),
|
|
740
|
+
});
|
|
741
|
+
result.queued.push({ ref, kind: item.kind, title: item.title });
|
|
742
|
+
return `${REF_MARK}${ref}`;
|
|
743
|
+
}
|
|
744
|
+
try {
|
|
745
|
+
let found = canRead ? await prov.findByLabel(refLabel(ref, cfg)) : null;
|
|
746
|
+
let adopted = null;
|
|
747
|
+
for (const old of adopt) {
|
|
748
|
+
if (found || !canRead) break;
|
|
749
|
+
found = await prov.findByLabel(`ref-${old}`);
|
|
750
|
+
if (found) adopted = old;
|
|
751
|
+
}
|
|
752
|
+
if (input.dryRun) {
|
|
753
|
+
if (found) result.reused.push({ ref, key: found.key, ...(adopted ? { adopted } : {}), dry_run: true });
|
|
754
|
+
else result.planned.push({ ref, kind: item.kind, title: item.title, parent: item.parent || null, labels: item.labels, fix_version: item.fixVersion || null });
|
|
755
|
+
return found ? found.key : null;
|
|
756
|
+
}
|
|
757
|
+
// The label search lags behind a create (minutes, measured on Jira Cloud): with no local record, absence is only
|
|
758
|
+
// trusted after a second search, spaced (alm.search_settle_ms, default 5 s).
|
|
759
|
+
if (!found) {
|
|
760
|
+
// one wait per push is enough: the lag concerns items created BEFORE this push
|
|
761
|
+
if (!settled) { settled = true; await (options.sleep || ((ms) => new Promise((r) => setTimeout(r, ms))))(cfg.search_settle_ms); }
|
|
762
|
+
found = await prov.findByLabel(refLabel(ref, cfg));
|
|
763
|
+
}
|
|
764
|
+
if (found) {
|
|
765
|
+
addLink(programDir, { ref, key: found.key, url: prov.url(found.key), kind: item.kind, provider: prov.name, ...(adopted ? { adopted } : {}) });
|
|
766
|
+
known.set(ref, { ref, key: found.key });
|
|
767
|
+
result.reused.push({ ref, key: found.key, ...(adopted ? { adopted } : {}) });
|
|
768
|
+
await ensureVersion(found.key, item.fixVersion);
|
|
769
|
+
return found.key;
|
|
770
|
+
}
|
|
771
|
+
// --rebuild-ledger: only what the search finds is recorded; nothing is created in this mode
|
|
772
|
+
if (input.rebuild) { result.missing.push({ ref, kind: item.kind, title: item.title }); return null; }
|
|
773
|
+
const it = await prov.create(item);
|
|
774
|
+
// the key goes to the local record BEFORE any other write — a lost read-back must never cause a duplicate
|
|
775
|
+
addLink(programDir, { ref, key: it.key, url: prov.url(it.key), kind: item.kind, provider: prov.name });
|
|
776
|
+
known.set(ref, { ref, key: it.key });
|
|
777
|
+
let confirmed = true;
|
|
778
|
+
try { confirmed = Boolean(await prov.read(it.key)); } catch { confirmed = false; }
|
|
779
|
+
result.created.push({ ref, key: it.key, ...(confirmed ? {} : { unconfirmed: true }) });
|
|
780
|
+
if (confirmed) await ensureVersion(it.key, item.fixVersion);
|
|
781
|
+
return it.key;
|
|
782
|
+
} catch (err) {
|
|
783
|
+
result.failed.push({ ref, error: err.message });
|
|
784
|
+
return null;
|
|
785
|
+
}
|
|
786
|
+
};
|
|
787
|
+
const refineLib = require('./oxe-alm-refine.cjs');
|
|
788
|
+
const inferredRoot = input.projectRoot || (() => {
|
|
789
|
+
const p = path.resolve(programDir);
|
|
790
|
+
if (path.basename(p) === 'program') {
|
|
791
|
+
const parent = path.dirname(p);
|
|
792
|
+
if (path.basename(parent) === '.oxe') return path.dirname(parent);
|
|
793
|
+
if (path.basename(path.dirname(parent)) === 'sessions') return path.dirname(path.dirname(path.dirname(parent)));
|
|
794
|
+
}
|
|
795
|
+
return null;
|
|
796
|
+
})();
|
|
797
|
+
const artifacts = input.artifacts || (inferredRoot ? refineLib.discoverProjectArtifacts(inferredRoot, input.activeSession || null) : null);
|
|
798
|
+
const epicArtifactBlock = artifacts && artifacts.has_any ? `Artefatos OXE:\n${refineLib.formatArtifactRefs(artifacts).join('\n')}` : '';
|
|
799
|
+
const taskRefParts = artifacts ? [artifacts.spec && artifacts.spec.path, artifacts.system_design && artifacts.system_design.path].filter(Boolean) : [];
|
|
800
|
+
// Spec approved → the epic, when the config names none (one per program, or per phase with input.phase).
|
|
801
|
+
if (cfg.stories_source !== 'alm' && !epicFor(input.phase) && input.epicTitle && (input.stories || []).length) {
|
|
802
|
+
// one epic per spec (program); per phase only when the config already maps epics per phase
|
|
803
|
+
const ref = cfg.epic && typeof cfg.epic === 'object' && input.phase ? `EPIC-${input.phase}` : 'EPIC';
|
|
804
|
+
const epicDesc = [input.epicDescription || 'Criado pelo OXE a partir do PRD.md.', epicArtifactBlock].filter(Boolean).join('\n\n');
|
|
805
|
+
createdEpic = await ensure(ref, { kind: 'epic', title: input.epicTitle, description: epicDesc, labels: [...cfg.labels, refLabel(ref, cfg)], fixVersion });
|
|
806
|
+
}
|
|
807
|
+
const storyKeyByCriterion = new Map();
|
|
808
|
+
const storyRefByCriterion = new Map();
|
|
809
|
+
for (const s of input.stories || []) for (const a of s.criteria) if (!storyRefByCriterion.has(a)) storyRefByCriterion.set(a, s.id);
|
|
810
|
+
for (const s of input.stories || []) {
|
|
811
|
+
const storyArtifactBlock = artifacts && artifacts.has_any
|
|
812
|
+
? `Artefatos & Arquitetura:\n${refineLib.formatArtifactRefs(artifacts, { storyId: s.id }).join('\n')}`
|
|
813
|
+
: '';
|
|
814
|
+
const key = await ensure(s.id, {
|
|
815
|
+
kind: 'story',
|
|
816
|
+
title: `${s.id}: ${s.want}`,
|
|
817
|
+
description: [
|
|
818
|
+
`Como ${s.persona}, quero ${s.want}, para ${s.benefit}.`,
|
|
819
|
+
s.criteria.length ? `Critérios de aceite: ${s.criteria.join(', ')}` : '',
|
|
820
|
+
s.requirements.length ? `Requisitos: ${s.requirements.join(', ')}` : '',
|
|
821
|
+
Array.isArray(s.business_rules) && s.business_rules.length ? `Regras de negócio: ${s.business_rules.join('; ')}` : '',
|
|
822
|
+
s.flow ? `Fluxo: ${s.flow}` : '',
|
|
823
|
+
storyArtifactBlock,
|
|
824
|
+
'Criado pelo OXE (PRD.md).',
|
|
825
|
+
].filter(Boolean).join('\n\n'),
|
|
826
|
+
labels: [...cfg.labels, refLabel(s.id, cfg)],
|
|
827
|
+
parent: epicFor(input.phase),
|
|
828
|
+
fixVersion,
|
|
829
|
+
}, [], { keys: s.cards || [], noCreate: cfg.stories_source === 'alm' });
|
|
830
|
+
for (const a of s.criteria) if (!storyKeyByCriterion.has(a)) storyKeyByCriterion.set(a, key || (input.dryRun ? s.id : null));
|
|
831
|
+
}
|
|
832
|
+
for (const t of input.tasks || []) {
|
|
833
|
+
if (t.done) continue;
|
|
834
|
+
const ref = taskRef(input.phase, t.id);
|
|
835
|
+
const crit = [...(t.acceptance || t.aceite || [])];
|
|
836
|
+
const story = crit.map((a) => storyKeyByCriterion.get(a)).find(Boolean) || null;
|
|
837
|
+
// Jira: a task cannot be the child of a story in a team-managed project unless it is a subtask; parent = the epic,
|
|
838
|
+
// and the story is linked. Azure DevOps: Task under User Story is the native hierarchy.
|
|
839
|
+
const parent = cfg.provider === 'azure-devops' ? (story || epicFor(input.phase)) : epicFor(input.phase);
|
|
840
|
+
const key = await ensure(ref, {
|
|
841
|
+
kind: 'task',
|
|
842
|
+
title: `${t.id}: ${t.title || 'tarefa'}`,
|
|
843
|
+
description: [
|
|
844
|
+
t.description || '',
|
|
845
|
+
(t.files || []).length ? `Arquivos: ${t.files.join(', ')}` : '',
|
|
846
|
+
crit.length ? `Critérios: ${crit.join(', ')}` : '',
|
|
847
|
+
taskRefParts.length ? `Referências OXE: ${taskRefParts.join(' · ')}` : '',
|
|
848
|
+
`Fase ${input.phase || '—'} · criado pelo OXE (PLAN.json).`,
|
|
849
|
+
].filter(Boolean).join('\n\n'),
|
|
850
|
+
// the block's labels PLUS the task's own (area-…), never replacing them
|
|
851
|
+
labels: [...new Set([...cfg.labels, ...(Array.isArray(t.labels) ? t.labels.map(String) : []), refLabel(ref, cfg)])],
|
|
852
|
+
parent,
|
|
853
|
+
fixVersion,
|
|
854
|
+
}, oldRefs(cfg, t), { keys: require('./oxe-prd.cjs').cardKeys([t.title, t.description, ...(Array.isArray(t.refs) ? t.refs : [])].join(' ')) });
|
|
855
|
+
if (key && story && cfg.provider === 'jira' && !input.dryRun && story !== key) {
|
|
856
|
+
const storyRef = crit.map((a) => storyRefByCriterion.get(a)).find(Boolean);
|
|
857
|
+
if (deferred) { if (storyRef && !known.has(ref)) ops.push({ id: `link:${ref}:${storyRef}`, op: 'link', ref, other_ref: storyRef, type: 'Relates' }); } else {
|
|
858
|
+
try { await prov.link(key, story); } catch { /* the link is a convenience */ }
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
if (deferred && ops.length) enqueue(programDir, ops);
|
|
863
|
+
if (deferred) result.queue = readQueue(programDir).ops.length;
|
|
864
|
+
return result;
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
// ── sync (lifecycle → stages) ────────────────────────────────────────────────────────────────────────────────────
|
|
868
|
+
|
|
869
|
+
/**
|
|
870
|
+
* The stage each OXE event moves an item to. Pure: tested without a network.
|
|
871
|
+
* @returns {Array<{ ref: string, stage: string, comment?: string }>}
|
|
872
|
+
*/
|
|
873
|
+
function stagesFromEvents(events, ctx = {}) {
|
|
874
|
+
const out = [];
|
|
875
|
+
const phase = ctx.phase || null;
|
|
876
|
+
const phaseOfTask = ctx.phaseOfTask || (() => phase);
|
|
877
|
+
for (const e of events) {
|
|
878
|
+
const task = e.work_item_id || (e.payload && e.payload.task) || null;
|
|
879
|
+
if (e.type === 'TaskStarted' && task) out.push({ ref: taskRef(phaseOfTask(task), task), stage: 'in_progress' });
|
|
880
|
+
else if (e.type === 'TaskPromoted' && task && e.payload && e.payload.pr) out.push({ ref: taskRef(phaseOfTask(task), task), stage: 'review', comment: `PR aberto: ${e.payload.pr}` });
|
|
881
|
+
else if (e.type === 'TaskPromoteFailed' && task) out.push({ ref: taskRef(phaseOfTask(task), task), stage: 'review', comment: `Promoção falhou: ${(e.payload && (e.payload.reason || e.payload.error)) || 'sem detalhe'}` });
|
|
882
|
+
else if (e.type === 'AlmMerged' && task) out.push({ ref: taskRef(phaseOfTask(task), task), stage: 'integrated', comment: e.payload && e.payload.pr ? `Merge: ${e.payload.pr}` : undefined });
|
|
883
|
+
else if (e.type === 'DeployAttached' && e.payload && e.payload.ok !== false && (!ctx.releasedEnv || e.payload.env === ctx.releasedEnv)) {
|
|
884
|
+
for (const ref of (ctx.refsOfPhase ? ctx.refsOfPhase(e.payload.phase) : [])) out.push({ ref, stage: 'released', comment: `Deploy ${e.payload.env || ''} ${e.payload.version || ''}`.trim() });
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
return out;
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
const RANK = Object.fromEntries(STAGES.map((s, i) => [s, i]));
|
|
891
|
+
|
|
892
|
+
/**
|
|
893
|
+
* Applies the stages of the events after the cursor, plus the writes that failed before. Never throws: failures go to
|
|
894
|
+
* `pending` and are retried next time. An item never moves backwards, except in_review after a failed promotion.
|
|
895
|
+
*/
|
|
896
|
+
async function sync(programDir, cfg, events, ctx = {}, options = {}) {
|
|
897
|
+
const prov = options.provider || provider(cfg, options);
|
|
898
|
+
const st = readState(programDir);
|
|
899
|
+
const known = links(programDir);
|
|
900
|
+
const fresh = events.slice(st.cursor || 0);
|
|
901
|
+
const moves = [...(st.pending || []), ...stagesFromEvents(fresh, ctx)];
|
|
902
|
+
const result = { moved: [], skipped: [], failed: [], planned: [], comments: 0 };
|
|
903
|
+
const pending = [];
|
|
904
|
+
const deferred = prov.deferred && !(options.dryRun || cfg.dry_run);
|
|
905
|
+
const ops = [];
|
|
906
|
+
const ensureQueued = deferred ? new Set(readQueue(programDir).ops.filter((o) => o.op === 'ensure').map((o) => o.ref)) : new Set();
|
|
907
|
+
if (deferred) result.queued = [];
|
|
908
|
+
for (const m of moves) {
|
|
909
|
+
const link = known.get(m.ref);
|
|
910
|
+
const state = cfg.states[m.stage];
|
|
911
|
+
if (!cfg.track.includes(m.stage)) { result.skipped.push({ ref: m.ref, stage: m.stage, why: 'etapa fora de alm.track (outra ferramenta move)' }); continue; }
|
|
912
|
+
if (deferred && state && (link || ensureQueued.has(m.ref))) {
|
|
913
|
+
const prev = st.stages[m.ref];
|
|
914
|
+
if (prev && RANK[m.stage] < RANK[prev] && !/^Promoção falhou/.test(m.comment || '')) { result.skipped.push({ ref: m.ref, stage: m.stage, why: `já em ${prev}` }); continue; }
|
|
915
|
+
ops.push({ id: `transition:${m.ref}`, op: 'transition', ref: m.ref, ...(link ? { key: link.key } : {}), stage: m.stage, state, ...(m.comment ? { comments: [m.comment] } : {}) });
|
|
916
|
+
result.queued.push({ ref: m.ref, stage: m.stage, state });
|
|
917
|
+
continue;
|
|
918
|
+
}
|
|
919
|
+
if (!link || !state) { result.skipped.push({ ref: m.ref, stage: m.stage, why: !link ? 'sem item no ALM (oxe-cc alm push)' : `estado de ${m.stage} não mapeado` }); continue; }
|
|
920
|
+
const prev = st.stages[m.ref];
|
|
921
|
+
const backwards = prev && RANK[m.stage] < RANK[prev] && !/^Promoção falhou/.test(m.comment || '');
|
|
922
|
+
if (backwards) { result.skipped.push({ ref: m.ref, stage: m.stage, why: `já em ${prev}` }); continue; }
|
|
923
|
+
if (options.dryRun || cfg.dry_run) { result.planned.push({ ref: m.ref, key: link.key, stage: m.stage, state }); continue; }
|
|
924
|
+
try {
|
|
925
|
+
// Another tool may own the later states (a repository workflow moving PR → train → main → release): read the
|
|
926
|
+
// live state and never pull an item back from a more advanced one.
|
|
927
|
+
// Definition of Ready, before "ready" and before development starts: the refined spec, with no open question.
|
|
928
|
+
if (cfg.ready_gate && (m.stage === 'in_progress' || m.stage === 'ready') && typeof prov.labels === 'function') {
|
|
929
|
+
const have = await prov.labels(link.key);
|
|
930
|
+
const missing = !have.includes(cfg.ready_gate) ? `sem o rótulo ${cfg.ready_gate}` : have.includes('needs-info') ? 'com needs-info (perguntas em aberto)' : null;
|
|
931
|
+
if (missing) {
|
|
932
|
+
result.skipped.push({ ref: m.ref, stage: m.stage, why: `Definition of Ready: ${link.key} ${missing} — rode oxe-cc alm refine ${link.key} e responda as perguntas antes de começar` });
|
|
933
|
+
pending.push(m);
|
|
934
|
+
continue;
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
if (typeof prov.status === 'function' && !/^Promoção falhou/.test(m.comment || '')) {
|
|
938
|
+
const live = await prov.status(link.key);
|
|
939
|
+
const liveStage = STAGES.filter((s) => cfg.states[s] && live && String(cfg.states[s]).toLowerCase() === String(live).toLowerCase()).sort((a, b) => RANK[b] - RANK[a])[0];
|
|
940
|
+
if (liveStage && RANK[liveStage] > RANK[m.stage]) {
|
|
941
|
+
st.stages[m.ref] = liveStage;
|
|
942
|
+
result.skipped.push({ ref: m.ref, stage: m.stage, why: `já em "${live}" (movido por outra ferramenta) — o OXE nunca recua um item` });
|
|
943
|
+
continue;
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
const r = await prov.transition(link.key, state);
|
|
947
|
+
if (m.comment && r.changed) { await prov.comment(link.key, m.comment); result.comments += 1; }
|
|
948
|
+
st.stages[m.ref] = m.stage;
|
|
949
|
+
result.moved.push({ ref: m.ref, key: link.key, stage: m.stage, state: r.status, changed: r.changed });
|
|
950
|
+
} catch (err) {
|
|
951
|
+
result.failed.push({ ref: m.ref, key: link.key, stage: m.stage, error: err.message });
|
|
952
|
+
if (!err.fatal) pending.push(m);
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
// Tag / deploy → the Jira version released (alm.release_version + alm.fix_version), once.
|
|
956
|
+
const deployed = fresh.some((e) => e.type === 'DeployAttached' && e.payload && e.payload.ok !== false && (!ctx.releasedEnv || e.payload.env === ctx.releasedEnv));
|
|
957
|
+
const version = perPhase(cfg.fix_version, ctx.phase);
|
|
958
|
+
if (deployed && cfg.release_version && version && cfg.track.includes('released') && !(st.versions_released || []).includes(version)) {
|
|
959
|
+
if (options.dryRun || cfg.dry_run) result.planned.push({ ref: `version:${version}`, stage: 'released' });
|
|
960
|
+
else if (deferred) { if (cfg.provider === 'jira') { ops.push({ id: `release:${version}`, op: 'release_version', project: cfg.p.project, version }); result.queued.push({ ref: `version:${version}`, stage: 'released' }); } } else {
|
|
961
|
+
try { await prov.releaseVersion(version); st.versions_released = [...(st.versions_released || []), version]; result.version_released = version; } catch (err) { result.failed.push({ ref: `version:${version}`, error: err.message }); }
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
if (deferred) { if (ops.length) enqueue(programDir, ops); result.queue = readQueue(programDir).ops.length; }
|
|
965
|
+
if (!(options.dryRun || cfg.dry_run)) {
|
|
966
|
+
st.cursor = events.length;
|
|
967
|
+
st.pending = pending;
|
|
968
|
+
st.last_sync = new Date().toISOString();
|
|
969
|
+
writeState(programDir, st);
|
|
970
|
+
}
|
|
971
|
+
return result;
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
/** A defect found after the deploy: a bug item linked to the item of its origin (story or task). */
|
|
975
|
+
async function reportDefect(programDir, cfg, input, options = {}) {
|
|
976
|
+
const prov = options.provider || provider(cfg, options);
|
|
977
|
+
const known = links(programDir);
|
|
978
|
+
const ref = input.ref;
|
|
979
|
+
if (known.has(ref)) return { key: known.get(ref).key, reused: true };
|
|
980
|
+
const origin = input.origin ? known.get(input.origin) : null;
|
|
981
|
+
if (options.dryRun || cfg.dry_run) return { planned: { ref, title: input.title, origin: origin ? origin.key : null } };
|
|
982
|
+
const labels = [...cfg.labels, refLabel(ref, cfg), ...(cfg.provider === 'jira' ? [cfg.p.bug_label || 'bug'] : [])];
|
|
983
|
+
if (prov.deferred) {
|
|
984
|
+
const type = { ...(cfg.provider === 'jira' ? { bug: 'Task' } : { bug: 'Bug' }), ...(cfg.p.types || {}) }.bug;
|
|
985
|
+
const ops = [{ id: `ensure:${ref}`, op: 'ensure', ref, kind: 'bug', type, project: cfg.p.project, title: `${ref}: ${input.title}`, description: [input.description || '', origin ? `Origem: ${origin.key}` : ''].filter(Boolean).join('\n\n'), labels, ...(perPhase(cfg.fix_version, input.phase || null) ? { fix_version: perPhase(cfg.fix_version, input.phase || null) } : {}), search: searchFor(cfg, [refLabel(ref, cfg)]), ...(input.cr ? { cr: String(input.cr) } : {}) }];
|
|
986
|
+
if (origin) ops.push({ id: `link:${ref}:${input.origin}`, op: 'link', ref, other_ref: input.origin, other_key: origin.key, type: 'Relates' });
|
|
987
|
+
enqueue(programDir, ops);
|
|
988
|
+
return { ref, queued: ops.length };
|
|
989
|
+
}
|
|
990
|
+
const it = (await prov.findByLabel(refLabel(ref, cfg))) || await prov.create({ kind: 'bug', title: `${ref}: ${input.title}`, description: [input.description || '', origin ? `Origem: ${origin.key}` : ''].filter(Boolean).join('\n\n'), labels, fixVersion: perPhase(cfg.fix_version, input.phase || null) });
|
|
991
|
+
addLink(programDir, { ref, key: it.key, url: prov.url(it.key), kind: 'bug', provider: prov.name, origin: origin ? origin.key : null, ...(input.cr ? { cr: String(input.cr) } : {}) });
|
|
992
|
+
if (origin) { try { await prov.link(it.key, origin.key); } catch { /* */ } }
|
|
993
|
+
return { key: it.key, created: true };
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
/** A manual move (the merge train's "na fila", a fix by hand): by OXE ref (US-3, F2-T5) or by the item key. */
|
|
997
|
+
async function move(programDir, cfg, refOrKey, stage, options = {}) {
|
|
998
|
+
stage = canonStage(stage);
|
|
999
|
+
if (!STAGES.includes(stage)) throw new Error(`etapa "${stage}" desconhecida (${STAGES.join(' | ')})`);
|
|
1000
|
+
const state = cfg.states[stage];
|
|
1001
|
+
if (!state) throw new Error(`alm.states.${stage} não está mapeado no .oxe/config.json`);
|
|
1002
|
+
const link = resolveItem(programDir, cfg, refOrKey);
|
|
1003
|
+
if (!link) throw new Error(`${refOrKey}: sem item no ALM (oxe-cc alm push, alm link ${refOrKey} <chave>, ou a chave do item, ex.: ${cfg.provider === 'jira' ? `${cfg.p.project}-12` : '123'})`);
|
|
1004
|
+
if (options.dryRun || cfg.dry_run) return { planned: { ref: link.ref, key: link.key, stage, state, ...(options.comment ? { comment: options.comment } : {}) } };
|
|
1005
|
+
const prov = options.provider || provider(cfg, options);
|
|
1006
|
+
if (prov.deferred) {
|
|
1007
|
+
enqueue(programDir, [{ id: `transition:${link.ref}`, op: 'transition', ref: link.ref, key: link.key, stage, state, ...(options.comment ? { comments: [options.comment] } : {}) }]);
|
|
1008
|
+
return { ref: link.ref, key: link.key, stage, state, queued: true };
|
|
1009
|
+
}
|
|
1010
|
+
const r = await prov.transition(link.key, state);
|
|
1011
|
+
if (options.comment && r.changed) await prov.comment(link.key, options.comment);
|
|
1012
|
+
// the lifecycle state is the OXE refs'; a card moved by its key alone is not one of them
|
|
1013
|
+
if (!link.direct) {
|
|
1014
|
+
const st = readState(programDir);
|
|
1015
|
+
st.stages[link.ref] = stage;
|
|
1016
|
+
writeState(programDir, st);
|
|
1017
|
+
}
|
|
1018
|
+
return { ref: link.ref, key: link.key, stage, state: r.status, changed: r.changed, ...(options.comment && r.changed ? { commented: true } : {}) };
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
/**
|
|
1022
|
+
* The item of an OXE ref (US-3, F2-T5) or of a key: the ledger first, then a key of this project used directly
|
|
1023
|
+
* (OXE-12 in Jira, 123 in Azure), the way refine and grill publish take it (OXB-G17). "US-1" is never a key.
|
|
1024
|
+
*/
|
|
1025
|
+
function resolveItem(programDir, cfg, refOrKey) {
|
|
1026
|
+
// Azure DevOps keys come as "AB#123" from PR text; the ledger and the API use "123" (R42)
|
|
1027
|
+
const s = cfg && cfg.provider === 'azure-devops' ? String(refOrKey || '').trim().replace(/^AB#/i, '') : String(refOrKey || '').trim();
|
|
1028
|
+
const all = links(programDir);
|
|
1029
|
+
const known = all.get(s) || [...all.values()].find((l) => l.key === s || l.key === s.toUpperCase());
|
|
1030
|
+
if (known) return known;
|
|
1031
|
+
const direct = cfg.provider === 'jira' ? new RegExp(`^${String(cfg.p.project || '[A-Z][A-Z0-9]+').toUpperCase()}-\\d+$`, 'i').test(s) : /^\d+$/.test(s);
|
|
1032
|
+
return direct ? { ref: s.toUpperCase(), key: s.toUpperCase(), direct: true } : null;
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
/**
|
|
1036
|
+
* A label on an item and "Relates" links between items — the umbrella card (OxeSpace 14/11: OXE-22/23 point to the
|
|
1037
|
+
* BRD items that split them). By key, idempotent (Jira adds a label once; an existing link is not repeated).
|
|
1038
|
+
*/
|
|
1039
|
+
async function labelItem(programDir, cfg, refOrKey, labels, options = {}) {
|
|
1040
|
+
const item = resolveItem(programDir, cfg, refOrKey);
|
|
1041
|
+
if (!item) throw new Error(`${refOrKey}: sem item no ALM (use a chave do item)`);
|
|
1042
|
+
const list = (v) => (Array.isArray(v) ? v : String(v || '').split(',')).map((s) => String(s).trim()).filter(Boolean);
|
|
1043
|
+
const add = list(labels);
|
|
1044
|
+
// OxeSpace 15/11 (OXE-189): an answered needs-info stayed on the card — `--remove` takes a label off
|
|
1045
|
+
const remove = list(options.remove);
|
|
1046
|
+
if (!add.length && !remove.length) throw new Error('informe o rótulo: --add <rótulo>[,<rótulo>] ou --remove <rótulo>[,<rótulo>]');
|
|
1047
|
+
if ([...add, ...remove].some((l) => /\s/.test(l))) throw new Error('rótulo do Jira não tem espaço');
|
|
1048
|
+
const both = add.filter((l) => remove.includes(l));
|
|
1049
|
+
if (both.length) throw new Error(`rótulo em --add e --remove ao mesmo tempo: ${both.join(', ')}`);
|
|
1050
|
+
if (options.dryRun || cfg.dry_run) return { planned: { key: item.key, add, remove } };
|
|
1051
|
+
const prov = options.provider || provider(cfg, options);
|
|
1052
|
+
if ((add.length && typeof prov.addLabels !== 'function') || (remove.length && typeof prov.removeLabels !== 'function')) throw new Error(`${cfg.provider}: rótulo ainda não suportado (Azure: tags)`);
|
|
1053
|
+
const have = typeof prov.labels === 'function' ? await prov.labels(item.key) : [];
|
|
1054
|
+
const missing = add.filter((l) => !have.includes(l));
|
|
1055
|
+
if (missing.length) await prov.addLabels(item.key, missing);
|
|
1056
|
+
const present = remove.filter((l) => have.includes(l));
|
|
1057
|
+
if (present.length) await prov.removeLabels(item.key, present);
|
|
1058
|
+
return { key: item.key, added: missing, existed: add.filter((l) => have.includes(l)), removed: present, absent: remove.filter((l) => !have.includes(l)) };
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
/**
|
|
1062
|
+
* Moves a card to `stage` only forward (a card already at or past it stays, with the reason). The quick's rule, shared.
|
|
1063
|
+
*/
|
|
1064
|
+
/**
|
|
1065
|
+
* Whether the card is already at or past `stage` on the board (R43). An unmapped live state ("Backlog", "Em revisão")
|
|
1066
|
+
* is NOT past it — the caller moves. A deferred provider (MCP queue) cannot read: never past.
|
|
1067
|
+
* @returns {Promise<{ past: boolean, live: string|null, liveStage: string|null }>}
|
|
1068
|
+
*/
|
|
1069
|
+
async function stageAtOrPast(programDir, cfg, key, stage, options = {}) {
|
|
1070
|
+
const prov = options.provider || provider(cfg, options);
|
|
1071
|
+
if (prov.deferred || typeof prov.status !== 'function') return { past: false, live: null, liveStage: null };
|
|
1072
|
+
const link = resolveItem(programDir, cfg, key);
|
|
1073
|
+
const live = await prov.status(link ? link.key : key);
|
|
1074
|
+
const liveStage = STAGES.find((s) => cfg.states[s] && live && String(cfg.states[s]).toLowerCase() === String(live).toLowerCase()) || null;
|
|
1075
|
+
return { past: Boolean(liveStage) && STAGES.indexOf(liveStage) >= STAGES.indexOf(stage), live, liveStage };
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
async function moveForward(programDir, cfg, key, stage, options = {}) {
|
|
1079
|
+
if (!cfg.states[stage]) return { skipped: true, why: `alm.states sem "${stage}": nada movido` };
|
|
1080
|
+
// a dry run never touches the network, not even to read the card's live state (the same rule as `push`): it says
|
|
1081
|
+
// what it would move; the "never backwards" check runs on the real write
|
|
1082
|
+
if (options.dryRun || cfg.dry_run) return move(programDir, cfg, key, stage, options);
|
|
1083
|
+
const prov = options.provider || provider(cfg, options);
|
|
1084
|
+
const live = typeof prov.status === 'function' && !prov.deferred ? await prov.status(key) : null;
|
|
1085
|
+
const liveStage = STAGES.find((s) => cfg.states[s] && live && String(cfg.states[s]).toLowerCase() === String(live).toLowerCase()) || null;
|
|
1086
|
+
const before = liveStage && STAGES.indexOf(liveStage) < STAGES.indexOf(stage);
|
|
1087
|
+
if (before || prov.deferred) return move(programDir, cfg, key, stage, { ...options, provider: prov });
|
|
1088
|
+
return { skipped: true, why: liveStage ? `o card está em "${live}" (${liveStage}): não move para trás nem para o lado` : `estado "${live}" sem etapa mapeada: nada movido` };
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
/**
|
|
1092
|
+
* G21 (OxeSpace 14/11): a session that is not the ALM writer cannot write the card, and used to just say so — the card
|
|
1093
|
+
* stayed without the mini-spec and the move. Now it records the request in `.oxe/alm/pending.ndjson`; the writer
|
|
1094
|
+
* drains it with `oxe-cc alm pending apply` (comments in order, moves only forward), and an applied request is never
|
|
1095
|
+
* applied again.
|
|
1096
|
+
*/
|
|
1097
|
+
function pendingFile(projectRoot) { return path.join(projectRoot, '.oxe', 'alm', 'pending.ndjson'); }
|
|
1098
|
+
|
|
1099
|
+
function readPendingLog(projectRoot) {
|
|
1100
|
+
try { return fs.readFileSync(pendingFile(projectRoot), 'utf8').split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean); } catch { return []; }
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
function addPending(projectRoot, req) {
|
|
1104
|
+
const entry = { id: `P-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 5)}`, at: new Date().toISOString(), ...req };
|
|
1105
|
+
fs.mkdirSync(path.dirname(pendingFile(projectRoot)), { recursive: true });
|
|
1106
|
+
fs.appendFileSync(pendingFile(projectRoot), `${JSON.stringify(entry)}\n`);
|
|
1107
|
+
return entry;
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
function listPending(projectRoot) {
|
|
1111
|
+
const log = readPendingLog(projectRoot);
|
|
1112
|
+
const done = new Set(log.filter((e) => e.applied).map((e) => e.applied));
|
|
1113
|
+
return log.filter((e) => e.op && !done.has(e.id));
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
async function applyPending(projectRoot, programDir, cfg, options = {}) {
|
|
1117
|
+
const todo = listPending(projectRoot);
|
|
1118
|
+
if (options.dryRun || cfg.dry_run) return { planned: todo, applied: [], failed: [] };
|
|
1119
|
+
const applied = [];
|
|
1120
|
+
const failed = [];
|
|
1121
|
+
for (const p of todo) {
|
|
1122
|
+
try {
|
|
1123
|
+
const r = p.op === 'comment' ? await comment(programDir, cfg, p.key, p.text, options)
|
|
1124
|
+
: p.op === 'move' ? await moveForward(programDir, cfg, p.key, p.stage, options)
|
|
1125
|
+
: (() => { throw new Error(`operação desconhecida: ${p.op}`); })();
|
|
1126
|
+
fs.appendFileSync(pendingFile(projectRoot), `${JSON.stringify({ applied: p.id, at: new Date().toISOString(), result: r && r.skipped ? 'skipped' : 'ok' })}\n`);
|
|
1127
|
+
applied.push({ ...p, result: r });
|
|
1128
|
+
} catch (err) { failed.push({ ...p, error: err.message }); }
|
|
1129
|
+
}
|
|
1130
|
+
return { applied, failed, remaining: listPending(projectRoot).length };
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
/**
|
|
1134
|
+
* OxeSpace 14/11: an existing card's fix version (OXE-10 moved to 1.5.3 and no command changed it). Jira only; the
|
|
1135
|
+
* version must exist in the project. Replaces the card's fix versions with this one.
|
|
1136
|
+
*/
|
|
1137
|
+
async function setItemVersion(programDir, cfg, refOrKey, version, options = {}) {
|
|
1138
|
+
const item = resolveItem(programDir, cfg, refOrKey);
|
|
1139
|
+
if (!item) throw new Error(`${refOrKey}: sem item no ALM (use a chave do item)`);
|
|
1140
|
+
const name = String(version || '').trim();
|
|
1141
|
+
if (!name) throw new Error('informe a versão: oxe-cc alm version <KEY> <versão>');
|
|
1142
|
+
const prov = options.provider || (options.dryRun || cfg.dry_run ? null : provider(cfg, options));
|
|
1143
|
+
if (options.dryRun || cfg.dry_run) return { planned: { key: item.key, version: name, comment: options.comment || null } };
|
|
1144
|
+
if (prov.deferred) throw new Error('alm.transport "mcp": troque a versão com a ferramenta do Jira do MCP (fixVersions) — este comando grava só por REST');
|
|
1145
|
+
if (typeof prov.setFixVersion !== 'function') throw new Error(`${cfg.provider}: versão de correção ainda não suportada (Azure: use a iteração)`);
|
|
1146
|
+
const have = typeof prov.fixVersions === 'function' ? await prov.fixVersions(item.key) : [];
|
|
1147
|
+
// `none` / `--clear`: the card keeps no fix version
|
|
1148
|
+
const clear = /^(none|nenhuma|--clear)$/i.test(name);
|
|
1149
|
+
const out = clear
|
|
1150
|
+
? (have.length ? await prov.clearFixVersions(item.key) : { changed: false, ok: true, versions: [] })
|
|
1151
|
+
: have.length === 1 && have[0] === name ? { changed: false, ok: true, versions: have } : await prov.setFixVersion(item.key, name);
|
|
1152
|
+
let commented = false;
|
|
1153
|
+
if (options.comment) { await comment(programDir, cfg, item.key, options.comment, options); commented = true; }
|
|
1154
|
+
return { key: item.key, version: name, before: have, ...out, commented };
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
/**
|
|
1158
|
+
* `alm supersede <OLD> --by <NEW>[,<NEW>] [--comment "…"]` (OxeSpace 15/11: the OxeChat redo closes 7 BRD cards as
|
|
1159
|
+
* superseded by new ones). Links OLD to each NEW with the site's "supersedes" type (else Duplicate, else Relates),
|
|
1160
|
+
* moves OLD to a done-category status (cancel / won't do / superseded first) with the matching resolution when the
|
|
1161
|
+
* workflow has one, and comments. Idempotent: an existing link is not repeated, a card already done is not moved.
|
|
1162
|
+
* A dry run only reads, and says what it would do.
|
|
1163
|
+
*/
|
|
1164
|
+
async function supersede(programDir, cfg, oldRef, newRefs, options = {}) {
|
|
1165
|
+
const old = resolveItem(programDir, cfg, oldRef);
|
|
1166
|
+
if (!old) throw new Error(`${oldRef}: sem item no ALM (use a chave do item)`);
|
|
1167
|
+
const news = (Array.isArray(newRefs) ? newRefs : String(newRefs || '').split(',')).map((s) => resolveItem(programDir, cfg, String(s).trim())).filter(Boolean);
|
|
1168
|
+
if (!news.length) throw new Error('informe o(s) card(s) novo(s): --by <KEY>[,<KEY>]');
|
|
1169
|
+
if (news.some((n) => n.key === old.key)) throw new Error(`${old.key} não substitui a si mesmo`);
|
|
1170
|
+
const prov = options.provider || provider(cfg, options);
|
|
1171
|
+
if (prov.deferred) throw new Error('alm.transport "mcp": feche com as ferramentas do Jira do MCP — este comando grava só por REST');
|
|
1172
|
+
if (typeof prov.linkTypes !== 'function') throw new Error(`${cfg.provider}: supersede ainda não suportado (só Jira)`);
|
|
1173
|
+
const types = await prov.linkTypes();
|
|
1174
|
+
const type = types.find((t) => /supersed/i.test(`${t.name} ${t.outward} ${t.inward}`)) || types.find((t) => /duplic/i.test(t.name)) || types.find((t) => /relat/i.test(t.name)) || null;
|
|
1175
|
+
if (!type) throw new Error(`nenhum tipo de link utilizável no site (tem: ${types.map((t) => t.name).join(', ') || '—'})`);
|
|
1176
|
+
const supersedesType = /supersed/i.test(`${type.name} ${type.outward}`);
|
|
1177
|
+
const state = await prov.links(old.key);
|
|
1178
|
+
const found = state.done || options.noClose ? null : await prov.closeTransition(old.key, { closeTo: options.closeTo });
|
|
1179
|
+
const tr = found && !found.none ? found : null;
|
|
1180
|
+
const plan = {
|
|
1181
|
+
key: old.key,
|
|
1182
|
+
by: news.map((n) => n.key),
|
|
1183
|
+
link_type: type.name,
|
|
1184
|
+
links: news.filter((n) => !state.linked.includes(n.key)).map((n) => n.key),
|
|
1185
|
+
already_linked: news.filter((n) => state.linked.includes(n.key)).map((n) => n.key),
|
|
1186
|
+
close: state.done ? { skipped: true, why: `já em "${state.status}" (done)` }
|
|
1187
|
+
: options.noClose ? { skipped: true, why: '--no-close: só liga e comenta' }
|
|
1188
|
+
: tr ? { transition: tr.name, to: tr.to, resolution: tr.resolution }
|
|
1189
|
+
: { skipped: true, why: (found && found.why) || 'o fluxo não tem transição para um status done a partir daqui' },
|
|
1190
|
+
comment: options.comment || `Substituído por ${news.map((n) => n.key).join(', ')}.`,
|
|
1191
|
+
};
|
|
1192
|
+
if (options.dryRun || cfg.dry_run) return { planned: plan };
|
|
1193
|
+
// no safe close (only a release status, or --close-to not reachable): nothing is written — no half-superseded card
|
|
1194
|
+
if (found && found.none) throw new Error(`${old.key}: ${found.why} — nada foi gravado`);
|
|
1195
|
+
// nothing to link and nothing to close: already superseded — no second comment
|
|
1196
|
+
if (!plan.links.length && plan.close.skipped) return { ...plan, applied: false, unchanged: true, status: state.status };
|
|
1197
|
+
if (tr && tr.resolution_required && !tr.resolution) throw new Error(`${old.key}: a transição "${tr.name}" exige resolution, e nenhuma do tipo won't do / superseded / duplicate existe — feche à mão`);
|
|
1198
|
+
// "A supersedes B": the new card is the outward side; Duplicate/Relates: the old card duplicates the new one
|
|
1199
|
+
for (const k of plan.links) await (supersedesType ? prov.linkDirected(type.name, old.key, k) : prov.linkDirected(type.name, k, old.key));
|
|
1200
|
+
await comment(programDir, cfg, old.key, plan.comment, options);
|
|
1201
|
+
const status = tr ? await prov.applyTransition(old.key, tr) : state.status;
|
|
1202
|
+
return { ...plan, applied: true, status };
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
/** `alm summary <KEY> "<título>"`: an existing card's summary line (Jira, REST). Writer only. */
|
|
1206
|
+
async function setItemSummary(programDir, cfg, refOrKey, summary, options = {}) {
|
|
1207
|
+
const item = resolveItem(programDir, cfg, refOrKey);
|
|
1208
|
+
if (!item) throw new Error(`${refOrKey}: sem item no ALM (use a chave do item)`);
|
|
1209
|
+
const text = String(summary || '').trim();
|
|
1210
|
+
if (text.length < 3) throw new Error('informe o título: oxe-cc alm summary <KEY> "<título>"');
|
|
1211
|
+
if (text.length > 255) throw new Error(`título com ${text.length} caracteres: o Jira aceita até 255`);
|
|
1212
|
+
if (options.dryRun || cfg.dry_run) return { planned: { key: item.key, summary: text, comment: options.comment || null } };
|
|
1213
|
+
const prov = options.provider || provider(cfg, options);
|
|
1214
|
+
if (prov.deferred) throw new Error('alm.transport "mcp": troque o título com a ferramenta do Jira do MCP — este comando grava só por REST');
|
|
1215
|
+
if (typeof prov.setSummary !== 'function') throw new Error(`${cfg.provider}: título ainda não suportado`);
|
|
1216
|
+
const out = await prov.setSummary(item.key, text);
|
|
1217
|
+
let commented = false;
|
|
1218
|
+
if (options.comment) { await comment(programDir, cfg, item.key, options.comment, options); commented = true; }
|
|
1219
|
+
return { key: item.key, ...out, commented };
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
async function relateItems(programDir, cfg, refOrKey, others, options = {}) {
|
|
1223
|
+
const item = resolveItem(programDir, cfg, refOrKey);
|
|
1224
|
+
if (!item) throw new Error(`${refOrKey}: sem item no ALM (use a chave do item)`);
|
|
1225
|
+
const targets = (Array.isArray(others) ? others : String(others || '').split(',')).map((s) => resolveItem(programDir, cfg, String(s).trim())).filter(Boolean);
|
|
1226
|
+
if (!targets.length) throw new Error('informe os itens: --relates <KEY>[,<KEY>]');
|
|
1227
|
+
if (options.dryRun || cfg.dry_run) return { planned: { key: item.key, relates: targets.map((t) => t.key) } };
|
|
1228
|
+
const prov = options.provider || provider(cfg, options);
|
|
1229
|
+
const linked = [];
|
|
1230
|
+
const existed = [];
|
|
1231
|
+
let current = [];
|
|
1232
|
+
if (cfg.provider === 'jira' && typeof prov.read === 'function') {
|
|
1233
|
+
try {
|
|
1234
|
+
const r = await (options.rest || jiraRest(cfg, options)).request('GET', `${String((options.env || process.env)[cfg.p.site_env || 'JIRA_SITE'] || '').replace(/\/+$/, '')}/rest/api/3/issue/${item.key}?fields=issuelinks`);
|
|
1235
|
+
current = ((r && r.fields && r.fields.issuelinks) || []).map((l) => (l.outwardIssue || l.inwardIssue || {}).key).filter(Boolean);
|
|
1236
|
+
} catch { current = []; }
|
|
1237
|
+
}
|
|
1238
|
+
for (const t of targets) {
|
|
1239
|
+
if (current.includes(t.key)) { existed.push(t.key); continue; }
|
|
1240
|
+
await prov.link(item.key, t.key, 'Relates');
|
|
1241
|
+
linked.push(t.key);
|
|
1242
|
+
}
|
|
1243
|
+
return { key: item.key, linked, existed };
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
/** A link from the item to a pull request (Jira remote link / Azure hyperlink): "entregue no #771". Idempotent. */
|
|
1247
|
+
async function linkPr(programDir, cfg, refOrKey, input, options = {}) {
|
|
1248
|
+
const item = resolveItem(programDir, cfg, refOrKey);
|
|
1249
|
+
if (!item) throw new Error(`${refOrKey}: sem item no ALM (use a chave do item, ex.: ${cfg.provider === 'jira' ? `${cfg.p.project}-12` : '123'})`);
|
|
1250
|
+
const pr = String(input.pr || '').replace(/^#/, '');
|
|
1251
|
+
if (!/^\d+$/.test(pr)) throw new Error('informe o número do PR (--pr 771)');
|
|
1252
|
+
const repo = String(input.repo || '').replace(/\.git$/, '').replace(/\/+$/, '');
|
|
1253
|
+
if (!/^https?:\/\//.test(repo)) throw new Error('o repositório do PR não está configurado: --repo https://github.com/<dono>/<repo> ou alm.docs.repo no .oxe/config.json');
|
|
1254
|
+
const url = `${repo}/pull/${pr}`;
|
|
1255
|
+
const title = input.title || `PR #${pr}`;
|
|
1256
|
+
if (options.dryRun || cfg.dry_run) return { planned: { key: item.key, pr: Number(pr), url, title } };
|
|
1257
|
+
const prov = options.provider || provider(cfg, options);
|
|
1258
|
+
if (prov.deferred) {
|
|
1259
|
+
enqueue(programDir, [{ id: `remotelink:${item.key}:${pr}`, op: 'remotelink', ref: item.ref, key: item.key, url, title }]);
|
|
1260
|
+
return { key: item.key, url, queued: true };
|
|
1261
|
+
}
|
|
1262
|
+
if (typeof prov.remoteLink !== 'function') throw new Error(`${cfg.provider}: link para PR ainda não suportado`);
|
|
1263
|
+
const r = await prov.remoteLink(item.key, url, title);
|
|
1264
|
+
return { key: item.key, pr: Number(pr), url, linked: true, ...(r && r.existed ? { existed: true } : {}) };
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
/** A comment on an item (by OXE ref or key) — allowed to reader sessions too (alm.writer). */
|
|
1268
|
+
async function comment(programDir, cfg, refOrKey, text, options = {}) {
|
|
1269
|
+
if (!text || String(text).trim().length < 2) throw new Error('informe o comentário (--text "…")');
|
|
1270
|
+
const link = resolveItem(programDir, cfg, refOrKey);
|
|
1271
|
+
if (!link) throw new Error(`${refOrKey}: sem item no ALM (oxe-cc alm push, ou use a chave do item)`);
|
|
1272
|
+
if (options.dryRun || cfg.dry_run) return { planned: { ref: link.ref, key: link.key, comment: String(text) } };
|
|
1273
|
+
const prov = options.provider || provider(cfg, options);
|
|
1274
|
+
if (prov.deferred) {
|
|
1275
|
+
enqueue(programDir, [{ id: `comment:${link.ref}:${Date.now().toString(36)}`, op: 'comment', ref: link.ref, key: link.key, comments: [String(text)] }]);
|
|
1276
|
+
return { ref: link.ref, key: link.key, queued: true };
|
|
1277
|
+
}
|
|
1278
|
+
await prov.comment(link.key, String(text));
|
|
1279
|
+
return { ref: link.ref, key: link.key, commented: true };
|
|
1280
|
+
}
|
|
1281
|
+
|
|
1282
|
+
/** "(OXE-12)" / "(AB#123)" for a task: what goes in the PR title, the commit and the branch. */
|
|
1283
|
+
function keyFor(programDir, cfg, phase, taskId) {
|
|
1284
|
+
const l = links(programDir).get(taskRef(phase, taskId));
|
|
1285
|
+
if (!l) return null;
|
|
1286
|
+
return cfg && cfg.provider === 'azure-devops' ? `AB#${l.key}` : l.key;
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1289
|
+
module.exports = { almConfig, checkConfig, jiraRest, isWriter, writerError, withWriteLock, comment, provider, readQueue, pendingOps, enqueue, ack, dropEnsure, push, sync, move, stagesFromEvents, reportDefect, links, addLink, readState, keyFor, refLabel, taskRef, oldRefs, perPhase, STAGES, STAGE_INFO, STAGE_ALIASES, canonStage, adf, request, isDry, warnApply, resolveItem, linkPr, labelItem, relateItems, setItemVersion, setItemSummary, supersede, moveForward, stageAtOrPast, addPending, listPending, applyPending, pendingFile };
|