diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..4dc611c Binary files /dev/null and b/.DS_Store differ diff --git a/SKILL.md b/SKILL.md new file mode 100644 index 0000000..634617b --- /dev/null +++ b/SKILL.md @@ -0,0 +1,309 @@ +--- +name: knowledge-one-view-cli +description: Fetch Oracle Analytics LAD Knowledge One View sales data directly through Oracle DV APIs instead of scraping the browser UI. Use when Codex needs opportunity details, pipeline and close-date data, revenue-line analysis, SR details, fiscal-year or session context, or ad hoc Oracle DV queries for the Sales Intelligence Knowledge One View workbook at `salesintelligence-dv.oracle.com`. +--- + +# Knowledge-One-View-CLI + +Use the direct API path first. Read only the smallest reference needed, run the shortest matching command, and open Chrome only when direct auth or workbook tracing requires it. + +## Quick Navigation + +- Need the complete consolidated skill documentation: + [docs/docs.html](docs/docs.html) +- Need manager, hierarchy, architect-productivity, or team-rollup business context: + [references/initial-context-catalog.md](references/initial-context-catalog.md) +- Need the explicit annual `week` lookup such as `w2`, `w43`, or `week 43`: + [references/script-catalog.md#week-reference](references/script-catalog.md#week-reference) +- Need the exact CLI surface, flags, or script contract: + [references/script-catalog.md](references/script-catalog.md) +- Need traced endpoints, workbook defaults, or view reconstruction details: + [references/api-map.md](references/api-map.md) +- Need a migration checklist for a new computer: + [portable-setup.md](portable-setup.md) + +## Core Rules + +- Use `scripts/fetch-sales-intelligence.mjs` for normal backend reads. +- Do not use REPL, browser scraping, or workbook rendering calls for routine retrieval. +- Open Chrome only when direct auth is blocked or the workbook trace must be refreshed. +- Prefer the fewest steps that still produce a correct answer. +- Choose exactly one execution mode per fetch call: `--intent`, `--view`, `--query`, or `--sql`. +- Prefer instructions already encoded in the local catalogs over re-deriving Oracle fields by hand. + +## Trigger Cues + +Use this skill when the request is about any of these: + +- LAD Knowledge One View opportunity or SR data +- close-date pipeline windows or month/day close-date asks +- pipeline, opportunity, won, close-window, territory, or owner analysis from Knowledge DV - Opportunities - V2 +- hours or hierarchy analysis from Knowledge DV - Hours - V2 +- presales coverage or involvement from Knowledge DV - Presales Involvement Aux - V1 +- Oracle DV fiscal-year/session variables used by the workbook +- ad hoc Oracle logical SQL or alias-based query mode against the workbook data +- manager hierarchy, architect productivity, or team rollups tied to these datasets + +## Fast Path + +1. Decide whether the ask is a manager or hierarchy ask. +2. If it is, read [references/initial-context-catalog.md](references/initial-context-catalog.md) first. +3. If the ask uses `week`, `wk`, or `w1`..`w5`, read [references/script-catalog.md#week-reference](references/script-catalog.md#week-reference) first. +4. If auth may be stale, run `--check-auth`. +5. Execute the shortest matching path immediately: + - recurring business ask -> `--intent` + - known extract -> `--view` + - ad hoc aliases, filters, grouping, ordering -> `--query` + - only if query mode cannot express it cleanly -> `--sql` +6. Read [references/script-catalog.md](references/script-catalog.md) or run `--catalog` only when one contract detail is still unknown. +7. Read [references/api-map.md](references/api-map.md) only when API behavior changed or a workbook view must be retraced. + +## Preferred Execution Order + +### 1. Intents + +Use intents first for recurring business asks. + +- `opportunities-default` + Use as the canonical default for generic opportunity and pipeline retrieval on Knowledge DV - Opportunities - V2. +- `opportunities-close-date` + Use for one exact close date with `--date`. +- `opportunities-close-month` + Use for one calendar month with `--month`. +- `opportunities-close-quarter` + Use for one fiscal quarter with `--quarter`, including `current-quarter`. +- `opportunities-current-team-close-window` + Use for asks that really mean current-team coverage, such as allocated-resource manager, people attached through SR work, or similar team-involvement wording. This intent keeps the full org-wide opportunity/workload window and only enriches resource fields from the current team. +- `opportunities-by-resource-close-window` + Use when the ask names one explicit resource and you need opportunities in a close-date window tied to that person through coverage data, with commercial fields coming from Knowledge DV - Opportunities - V2. +- `opportunities-by-manager-close-window` + Use when the ask names one explicit manager email and you need opportunities in a close-date window tied to that hierarchy anchor, with commercial fields coming from Knowledge DV - Opportunities - V2. +- `workloads-by-owner-current` + Use for current-state workload asks for one explicit territory owner. It defaults to `current-quarter`, `Cloud Infrastructure - Workloads`, and `WORKLOAD`. +- `workloads-by-owner-manager-current` + Use for current-state workload asks for owners under one explicit manager-of-owner. It defaults to `current-quarter`, `Cloud Infrastructure - Workloads`, and `WORKLOAD`. +- `workloads-by-manager-resource-close-window` + Use for org-wide workload revenue lines closing inside a direct date window when the ask is about opportunities that have allocated resources under one or more named managers. This intent gets manager/resource linkage only from `Knowledge DV - Presales Involvement Aux - V1`, gets commercial rows only from `Knowledge DV - Opportunities - V2`, filters on `Revenue Line Close Date`, and does not query `DV - SE Team` unless the user explicitly asks for SR details. +- `srs-by-resource` + Use for SRs by person with `--resource`. + +### 2. Views + +Use a view when the extract shape is already known. + +- `opportunity-details` +- `sr-details` +- `opportunities-close-window` +- `srs-by-resource-email` +- `sa-attach-pipeline-details` +- `sa-attach-open-pipeline` +- `sa-attach-won-pipeline` +- `sa-attach-involvement-distribution` +- `sa-attach-hours-by-opportunity` +- `sa-attach-presales-coverage` + +Read [references/script-catalog.md](references/script-catalog.md) for the full built-in script surface. + +### 3. Query Mode + +Use `--query` for general ad hoc retrieval when the ask can be expressed as aliases plus filters, grouping, and ordering. + +- Prefer `--query` over `--sql` for most non-recurring asks. +- Use field aliases instead of raw Oracle expressions whenever possible. +- Let query mode infer the safest source from the selected aliases: commercial aliases go org-wide-first on XSA datasets, while SR/session aliases stay on `DV - SE Team`. +- Use `--scope my-team` only when the user explicitly asks for the executing user's current-team view on org-wide-capable sources. + +### 4. Raw SQL + +Use `--sql` only when `--query` cannot express the ask cleanly. + +- Prefer placeholders such as `{{opportunityId}}`, `{{closeDate}}`, `{{bookingValue}}`, `{{workloadAmount}}`, `{{subjectArea}}`, and `{{securityEntryPointFilter}}`. +- Use `--render-sql` when you need to validate the final SQL locally without a backend call. +- If quoting becomes fragile in PowerShell, use `scripts/run-sales-intelligence-sql.mjs`. + +## Authentication Workflow + +1. Run `--check-auth` only when the session may be stale. +2. For normal fetch calls, if the saved session files are missing or the backend redirects to Oracle sign-in, `fetch-sales-intelligence.mjs` now opens the browser refresh flow automatically, waits for login, writes fresh session files, and retries the backend request. +3. Use `scripts/refresh-auth-state.mjs` manually only when you want to pre-refresh the browser session yourself or troubleshoot the automatic flow. +4. Use `scripts/refresh-auth-direct.mjs` when browser auth is unavailable or when you explicitly want the terminal-driven MFA flow. +5. `--check-auth` stays diagnostic-only and does not open the browser automatically. + +## Data-Specific Rules + +- For manager or hierarchy asks, start with [references/initial-context-catalog.md](references/initial-context-catalog.md) before touching the CLI catalog. +- For generic opportunity and pipeline asks, prefer `opportunities-default`. +- For close-date asks, prefer `opportunities-close-date`, `opportunities-close-month`, or `opportunities-close-window`. +- For fiscal-quarter asks, prefer `--quarter` with `FY26-Q4`, `Q4 FY26`, or `current-quarter`. +- For asks phrased as `week 1`..`week 53` or `w1`..`w53`, use the annual June-to-May week mapping in [references/script-catalog.md#week-reference](references/script-catalog.md#week-reference) and prefer `--week` plus optional `--week-year`. +- Treat wording like `agora`, `atual`, `mês corrente`, `quarter atual`, and `FY corrente` as current-period shortcuts whenever the matching flag supports it. +- For `opportunities-close-window`, close-window intents, and `sa-attach-*` commercial views, date-window flags now constrain `Revenue Line Close Date` directly, including `--week`, `--quarter`, and explicit `--from-date/--to-date`. +- For present-state workload asks about one seller or one seller-manager, prefer `workloads-by-owner-current` or `workloads-by-owner-manager-current`. +- For current-team coverage asks, prefer `opportunities-current-team-close-window`. +- For asks like `recursos do em pipe na week 2`, prefer `opportunities-by-manager-close-window --manager-email --week w2`. +- For asks like `workloads com close date nos proximos 7 dias em oportunidades com recursos abaixo de e `, prefer `workloads-by-manager-resource-close-window --manager-email-list , --from-date today --to-date +7d`. +- For that workload-by-manager-resource intent, treat `resourceEmails` as the org-wide allocated resource list from Presales Involvement Aux. The default result is involvement/allocation only; do not fetch SR details unless the user explicitly asks for SRs. +- When crossing SRs to workloads or opportunities, keep the `opportunityId` join as the confirmed linkage and also consider same-resource same-customer SRs without a usable `opportunityId` as internal-SR candidates. This is the current safe fallback because `Parent SR Number` is still not queryable through the logical SQL path. +- For SR resource lookups, default to SR Team Level `1..4` email matching and use `Lead Email` only for explicit leader intent. +- Accept short Oracle user ids through `--resource` when available. +- Use `--owner-email` for direct territory-owner filters and `--owner-manager-email` for owner-hierarchy filters on SA Attach workload reads. +- Use `--forecast-type` for natural-language asks such as `forecast`, `upside`, or `won` on SA Attach workload reads. +- Keep opportunity-linked monetary outputs consistent as `bookingValue` and `workloadAmount`. +- Treat `Knowledge DV - Opportunities - V2` as the normal source for pipeline, opportunity, won, close date, territory, owner, booking, and workload. +- Interpret user wording `vendedor`, `sales rep`, and `lider de vendas` as `territory owner` by default. +- Treat org-wide-capable XSA datasets as org-wide reads in `--scope auto`: `Knowledge DV - Opportunities - V2`, `Knowledge DV - Hours - V2`, `Knowledge DV - Presales Involvement Aux - V1`, and `Knowledge DV - Revn Lines by SE`. +- Treat `Knowledge DV - Hours - V2` as the normal source for hierarchy ownership and hours; default to org-wide unless the ask explicitly requests current-team scope. +- Treat `Knowledge DV - Presales Involvement Aux - V1` as the normal source for allocated resource, manager, and presales-coverage linkage; default to org-wide unless the ask explicitly requests current-team scope. +- Treat `Knowledge DV - Revn Lines by SE` as the normal source for detailed revenue-line extracts; default to org-wide unless the ask explicitly requests current-team scope. +- Treat `DV - SE Team` as self-scoped to the executing user, with hierarchy starting from that user and expanding only downward through their team. +- Treat `DV - SE Team` as fallback for commercial views only when the ask is explicitly about the current user's team, and as the normal source for session context and SR reads. +- When mixing org-wide commercial rows with current-team resource enrichment, preserve every org-wide opportunity/workload row and leave resource fields empty when there is no match. +- When a result mixes org-wide commercial rows with team-scoped resources, say that explicitly in the answer: `Opportunities/workloads: org-wide`, `Resources: only your current team`, and `rows without a match keep empty resource fields`. +- When a result includes any `scope.components`, prefer those component lines over a single simplified label because they identify which source is org-wide and which source is my-team-only. + +## Inputs And Outputs + +Input expectations: + +- business ask phrased in natural language, or +- a known intent/view/query/SQL request, optionally with date, month, resource, manager, or status filters + +Normal output contract from `fetch-sales-intelligence.mjs`: + +- `request` +- `scope` +- `apiMetrics` +- `columns` +- `records` +- `summary` for derived intents when relevant +- `warnings` +- `raw` for backend debugging + +User-facing answer contract: + +- Every answer that reports DV data must include a short "Context / assumptions" note near the result. Do not leave scope, defaults, or implicit DV assumptions only in the JSON. +- Always state the effective scope as one of `org-wide`, `my-team-only`, or `mixed-consistent`. If `scope.components` exists, use it as the authoritative source-by-source disclosure instead of compressing the result into one label. +- Always state the main source and execution path used: `--intent`, `--view`, `--query`, or `--sql`; the source subject area when known; and whether `--scope auto`, `--scope org-wide`, or `--scope my-team` was used. +- When defaults are applied, explicitly say so. At minimum disclose these common defaults when relevant: `cluster = Brazil`; `--scope auto`; live Oracle DV session fiscal year; current-period shortcuts such as `current-quarter`, current FY, or the current June-to-May week cycle; default status filters; default `--limit`; and SA Attach defaults for solution, product LOB, revenue type group, sales credit type, and minimum opportunity probability. +- If the user did not specify geography and the selected SA Attach/commercial path applies the traced workbook filter `cluster = Brazil`, say `Cluster default: Brazil`. If geography was overridden or no cluster filter applies, say that instead. +- If date windows, weeks, quarters, or "current" wording were interpreted, state the resolved period and the date field being filtered. For commercial SA Attach close-window answers, say that the window filters `Revenue Line Close Date`. +- If user wording required role interpretation, state it briefly, for example `vendedor`/`sales rep`/`lider de vendas` interpreted as `territory owner`, or short Oracle uid normalized to `@oracle.com`. +- If SR, resource, manager, or workload enrichment involved implicit joins, state the join assumption: `opportunityId` is the confirmed linkage; same-resource same-customer SRs without usable `opportunityId` are only fallback candidates; and current-team enrichment can leave unmatched org-wide rows with empty resource fields. +- Always include API effort and data-shape caveats: `Raw rows pulled from the API: X`; whether the result hit the requested/default limit; any `warnings`; and whether displayed monetary fields use truncated `k` values while `raw` keeps backend-native values. +- Never describe the numbers as "all company", "all Brazil", or "complete pipeline" unless the disclosed `scope`, filters, defaults, and limits actually support that statement. + +Scope disclosure rule: + +- Use the emitted `scope` object when wording the answer. +- `scope.scopeMode = org-wide` means the visible rows are org-wide. +- `scope.scopeMode = my-team-only` means the visible rows are limited to the executing user's current team. +- `scope.scopeMode = mixed-consistent` means the opportunity/workload rows remain org-wide, resource enrichment is team-scoped, and unmatched rows stay in the output with empty resource fields. +- `scope.components` is the most precise source-by-source disclosure. Use it when present, especially for mixed answers. +- For `workloads-by-manager-resource-close-window`, `scope.scopeMode = org-wide` means both workload rows and manager/resource allocation came from org-wide Knowledge DV sources. If the user explicitly asks for SR details, disclose the separate SR lookup as `DV - SE Team` / my-team-only. +- Explain in the output to the user which context was used to retrieve the information. + +API effort disclosure rule: + +- Use `apiMetrics.totalRowsPulledFromApi` as the canonical count of raw rows returned by Oracle DV for that invocation. +- Do not replace that number with final `records.length`; they mean different things. +- Do not add local-cache-only rows to this number. If the skill reused local fiscal-year/session metadata, those local reads do not count toward `apiMetrics.totalRowsPulledFromApi`. +- Prefer wording the answer with a sentence like `Raw rows pulled from the API: X.` + +Display-format rule: + +- `bookingValue` and `workloadAmount`, plus `summary.totalBookingValue` and `summary.totalWorkloadAmount`, are emitted as truncated thousands with a `k` suffix, for example `849k`. The `raw` section keeps the backend-native values. + +Read [references/script-catalog.md](references/script-catalog.md) for the full CLI contract and [references/api-map.md](references/api-map.md) for traced backend details. + +## Minimal Commands + +Codex normally invokes this skill from the current agent workspace, so the default runtime is `./knowledge-one-view-cli/runtime/`. If you run the scripts manually from the installed skill directory or any other location, pass `--runtime-home` or set `ORACLE_SI_RUNTIME_HOME` to point back to the target workspace. + +For the consolidated technical guide, testing strategy, and workspace artifact layout, read [docs/docs.html](docs/docs.html). Test definitions stay inside the installed skill `tests/` folder, while test-run artifacts go to the workspace-side `knowledge-one-view-cli/output/` and `knowledge-one-view-cli/tmp/` folders. + +Check auth: + +```powershell +node .\scripts\fetch-sales-intelligence.mjs ` + --check-auth +``` + +Generic pipeline or opportunities: + +```powershell +node .\scripts\fetch-sales-intelligence.mjs ` + --intent opportunities-default ` + --limit 200 +``` + +Exact close date: + +```powershell +node .\scripts\fetch-sales-intelligence.mjs ` + --intent opportunities-close-date ` + --date 2026-05-02 +``` + +Calendar month: + +```powershell +node .\scripts\fetch-sales-intelligence.mjs ` + --intent opportunities-close-month ` + --month 2026-04 +``` + +Annual week shortcut: + +```powershell +node .\scripts\fetch-sales-intelligence.mjs ` + --intent opportunities-by-manager-close-window ` + --manager-email ` + --week w2 ` + --week-year 2026 +``` + +Current workload by owner: + +```powershell +node .\scripts\fetch-sales-intelligence.mjs ` + --intent workloads-by-owner-current ` + --owner-email ` + --forecast-type Forecast,Upside +``` + +Current workload by owner manager: + +```powershell +node .\scripts\fetch-sales-intelligence.mjs ` + --intent workloads-by-owner-manager-current ` + --owner-manager-email ` + --quarter current-quarter ` + --forecast-type Forecast +``` + +Org-wide workload close window by manager/resource: + +```powershell +node .\scripts\fetch-sales-intelligence.mjs ` + --intent workloads-by-manager-resource-close-window ` + --manager-email-list , ` + --from-date today ` + --to-date +7d +``` + +SRs by person: + +```powershell +node .\scripts\fetch-sales-intelligence.mjs ` + --intent srs-by-resource ` + --resource +``` + +Alias-based ad hoc query: + +```powershell +node .\scripts\fetch-sales-intelligence.mjs ` + --query ` + --select opportunityId,opportunityName,closeDate,bookingValue,workloadAmount ` + --where "closeDate = DATE '2026-05-02'" +``` diff --git a/agents/openai.yaml b/agents/openai.yaml new file mode 100644 index 0000000..6491bee --- /dev/null +++ b/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Knowledge-One-View-CLI" + short_description: "Fetch LAD sales data via Oracle DV APIs." + default_prompt: "Use $knowledge-one-view-cli to retrieve LAD Knowledge One View opportunity, workload, SR, or SA Attach data directly from Oracle DV APIs." diff --git a/docs/docs.html b/docs/docs.html new file mode 100644 index 0000000..71b17aa --- /dev/null +++ b/docs/docs.html @@ -0,0 +1,2119 @@ + + + + + + Knowledge One View CLI Docs + + + +
+
+ + +
+
+
+ Oracle DV +

Skill para consultar o DV LAD Knowledge One View direto pela API.

+

Guia consolidado da skill para onboarding, operação e consulta rápida da superfície atual.

+
+
+ +
+

Casos de uso práticos

+

Pense nesta skill como um tradutor entre linguagem de negócio e Oracle DV. Você descreve o recorte desejado no Codex; a skill decide se usa intent, view, query ou SQL, resolve a autenticação e devolve uma saída utilizável.

+ +
+
+ Exemplo 1 +

Workloads com SR por manager

+
Prompt no Codex:
+
+"Me traga todos os workloads do cluster Brazil para a próxima semana fiscal da Oracle, cruzando quais têm SR na oportunidade de recursos abaixo de <manager de recurso>."
+

Esse tipo de pedido costuma cair no intent workloads-by-manager-resource-close-window. A skill resolve a semana Oracle, filtra as revenue lines e enriquece o resultado com recursos e SRs visíveis.

+
+ +
+ Exemplo 2 +

Pipeline com janela comercial

+
Prompt no Codex:
+
+"Quais oportunidades com close no mês atual têm booking acima de 500k e territory owner abaixo de <manager comercial>?"
+

A skill tende a usar intents ou views comerciais em Knowledge DV - Opportunities - V2, mantendo escopo org-wide e o vocabulário comercial consistente.

+
+ +
+ Exemplo 3 +

SRs por recurso

+
Prompt no Codex:
+
+"Liste os SRs do <recurso alocado> com status e opportunityId, em formato tabela."
+

Aqui a skill normalmente usa srs-by-resource ou uma view equivalente em DV - SE Team, respeitando o escopo do time visível ao usuário executor.

+
+ +
+ Exemplo 4 +

Formato de resposta

+
Resposta típica:
+
+- semana Oracle resolvida
+- escopo da leitura
+- total de linhas puxadas da API
+- tabela final com cliente, workload, recurso e SR
+

Se você pedir "mostre em tabela", "gere um relatório HTML", "monte um PDF executivo", "organize em planilha" ou "automatize o envio por email", o Codex pode transformar o payload final em entregáveis mais úteis para consumo e acompanhamento.

+
+
+
+ +
+

Instalação rápida e primeiro uso

+

Em uma máquina nova, a sequência ideal é: instalar a skill, confirmar a sessão Oracle DV uma vez e depois seguir browserless na rotina normal. O objetivo é gastar energia no negócio, não em setup.

+ +
+
+ Passo 1 +

Pedir a instalação no Codex

+
Prompt no Codex:
+
+"Instale a skill knowledge-one-view-cli no Codex e valide a pasta runtime/output no workspace."
+

Depois disso, a skill fica instalada em ~/.codex/skills/knowledge-one-view-cli.

+
+ +
+ Passo 2 +

Testar a autenticação no Chrome

+
Prompt no Codex:
+
+"Faça um teste de autenticação da skill via Chrome e confirme se o backend Oracle DV respondeu."
+

O helper abre o navegador só para gravar auth-state.json e session-meta.json no runtime do workspace.

+
+ +
+ Passo 3 +

Seguir browserless

+
Prompt no Codex:
+
+"Me traga todos os workloads do cluster Brazil para a próxima semana fiscal da Oracle."
+

Daí em diante, a skill normalmente segue sem browser, consultando o backend Oracle DV direto pela API.

+
+
+ +
+
+

How-to relâmpago

+
    +
  1. Peça ao Codex para instalar ou validar a skill.
  2. +
  3. Peça ao Codex para fazer um teste de autenticação da skill via Chrome.
  4. +
  5. Conclua login e MFA.
  6. +
  7. Depois disso, siga usando em linguagem natural.
  8. +
+
+ +
+

Exemplo de resposta após o primeiro uso

+
Resultado típico:
+
+"Auth validado no runtime do workspace.
+Backend Oracle DV acessível.
+Raw rows pulled from the API: 5.
+Segue a tabela com cliente, workload, close date e territory owner."
+
+
+
+ +
+

Internals - Não é necessário para usar a skill

+

A página foi reorganizada para funcionar bem tanto para onboarding quanto para troubleshooting. Se você estiver chegando agora, vale seguir esta ordem em vez de pular direto para os comandos.

+ +
+
+ Leitura 1 +

Entenda o pedido

+

Comece por Casos de uso e Papéis e linguagem. Eles mostram como transformar uma pergunta de negócio em um recorte consistente de owner, manager, recurso, workload e SR.

+
+
+ Leitura 2 +

Entenda a execução

+

Depois veja Arquitetura, Datasets e Intents. Essa parte explica de onde os dados vêm e por que a skill escolhe intent, view, query ou SQL.

+
+
+ Leitura 3 +

Entenda a operação

+

Feche com Auth e Runtime, Contrato de saída, Testes e Comandos. Aí você já consegue instalar, validar e depurar com segurança.

+
+
+ +
+

Atalho mental para usar bem

+
    +
  • Se a pergunta for recorrente, pense em intent.
  • +
  • Se você quiser um extrato conhecido, pense em view.
  • +
  • Se precisar montar um recorte sob medida sem ir para SQL, pense em query.
  • +
  • Se estiver investigando um caso raro ou depurando Oracle DV, aí sim pense em sql.
  • +
+
+
+ +
+

Papéis e linguagem

+

Este guia evita nomes pessoais e usa papéis de negócio. Isso deixa a documentação mais transferível, mais segura e mais fácil de reaproveitar em outros times.

+ +
+
+

Papéis que aparecem neste guia

+
    +
  • <territory owner>: dono comercial direto da oportunidade ou workload.
  • +
  • <manager comercial>: gestor da hierarquia de territory owners usada para recortes comerciais.
  • +
  • <manager de recurso>: gestor do lado presales/engenharia, usado para cruzar recursos alocados em oportunidades.
  • +
  • <recurso alocado>: arquiteto, engenheiro ou especialista associado à oportunidade.
  • +
  • <time atual do usuário>: escopo visível em DV - SE Team para quem executa a skill.
  • +
+
+ +
+

Tradução prática da linguagem

+
    +
  • Quando alguém pedir "vendedor", a leitura padrão deve ser <territory owner>.
  • +
  • Quando alguém pedir "recursos abaixo de um manager", a leitura costuma ser <manager de recurso> em Knowledge DV - Presales Involvement Aux - V1.
  • +
  • Quando alguém pedir SR, cobertura ou contexto de sessão, a leitura costuma envolver o escopo do <time atual do usuário>.
  • +
  • Quando o pedido mistura comercial e recurso, a skill normalmente combina fonte org-wide com enriquecimento controlado por papel.
  • +
+
+
+ +
+

Como ler os exemplos

+

Sempre que você vir um papel entre <...>, substitua pelo identificador real da sua pergunta. O papel explica qual atributo da hierarquia a skill deve usar, sem amarrar a documentação a uma pessoa específica.

+
+
+ +
+

Arquitetura

+

Estrutura simples: o fetch principal concentra a lógica de negócio e scripts/lib/runtime-paths.mjs cuida do runtime, output e bootstrap do workspace.

+ +
+

Fluxo principal

+
    +
  1. Parse de argumentos e validação do modo de execução.
  2. +
  3. Resolução de runtime-home, arquivos de sessão e cache.
  4. +
  5. Opcionalmente resolução de ano fiscal e contexto de sessão.
  6. +
  7. Montagem de SQL via intent, view, query declarativa ou SQL bruto.
  8. +
  9. Execução em sqlquery/execute com restauração de sessão se necessário.
  10. +
  11. Normalização de linhas, escopo, métricas, warnings e persistência opcional em arquivo.
  12. +
+
+ +
+

Módulos atuais

+

A skill hoje está organizada em um script principal, helpers de autenticação e utilitários internos em scripts/lib/. A lista abaixo reflete os módulos realmente presentes no código atual.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MóduloResponsabilidade
fetch-sales-intelligence.mjsCatálogo local, query engine, intents, views, orchestration e execução Oracle DV.
refresh-auth-direct.mjsLogin Oracle sem abrir Chrome, com MFA.
refresh-auth-state.mjsRefresh de auth via browser/Playwright quando o fluxo direto não basta.
run-sales-intelligence-sql.mjsAjuda para SQL longa ou sensível a quoting de shell.
lib/runtime-paths.mjsResolução canônica de runtime, output, tmp, bootstrap de workspace e fallback legado.
lib/auth-shared.mjsLeitura, persistência e refresh dos artefatos de sessão, cookies, CSRF e metadados de autenticação.
lib/cli-shared.mjsParse de argumentos, normalização de flags e helpers utilitários de entrada.
lib/date-windows.mjsResolução de janelas temporais, semanas fiscais, quarters e atalhos como today ou +7d.
lib/output-contract.mjsMontagem do payload final com apiMetrics, warnings, normalização de linhas e emissão JSON.
+
+ +
+

Endpoint e estado local

+
    +
  • Endpoint principal: POST /ui/dv/ui/api/v1/sqlquery/execute.
  • +
  • Workbook alvo: salesintelligence-dv.oracle.com no report path LAD Knowledge One View.
  • +
  • Estado persistido: auth-state.json e session-meta.json.
  • +
  • Fallback legado de leitura: ~/.codex/oracle-sales-intelligence-direct/.
  • +
+
+
+ +
+

Datasets

+

Resumo das fontes realmente usadas pela skill e do papel de cada uma. Esta seção existe para evitar o erro mais comum nesse tipo de análise: consultar a fonte certa com a leitura errada de escopo.

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
DatasetEscopoPapel principalObservações
Knowledge DV - Opportunities - V2Org-wideFonte comercial principal: pipeline, opportunities, won, close date, booking, workload, territory e owner.Base normal para opportunities-default, opportunities-close-* e views sa-attach-* comerciais.
Knowledge DV - Hours - V2Org-wide por padrão; my-team com --scope my-teamHoras, ownership e produtividade por hierarquia.Exposto em sa-attach-hours-by-opportunity; em --scope auto preserva a leitura org-wide.
Knowledge DV - Presales Involvement Aux - V1Org-wide por padrão; my-team com --scope my-teamCobertura e vínculo manager/recurso/oportunidade.Base normal para cobertura presales e linkage manager/recurso; intents de workload/manager usam essa leitura org-wide.
DV - SE TeamMy-team-onlySession context, SRs e fallback comercial só quando a pergunta é explicitamente do time atual.Não usar como fonte comercial genérica org-wide.
Knowledge DV - Revn Lines by SEOrg-wide por padrão; my-team com --scope my-teamDetalhe de revenue lines.Exposto por revenue-line-details como extrato org-wide em --scope auto.
+
+ +
+

Como escolher a fonte certa

+
    +
  • Se a pergunta é comercial e precisa preservar todas as oportunidades do recorte, a base tende a ser Knowledge DV - Opportunities - V2.
  • +
  • Se a pergunta é sobre quem está alocado, coberto ou relacionado a uma oportunidade, a base tende a ser Knowledge DV - Presales Involvement Aux - V1 e a skill tenta org-wide primeiro.
  • +
  • Se a pergunta é sobre SR, contexto da sessão ou o time visível do executor, a base tende a passar por DV - SE Team.
  • +
  • Se a pergunta é sobre horas e produtividade, a skill tende a usar Knowledge DV - Hours - V2 em org-wide, salvo pedido explícito de time atual.
  • +
  • Se a pergunta é sobre revenue line detalhada, a skill tende a olhar Knowledge DV - Revn Lines by SE em org-wide, salvo pedido explícito de time atual.
  • +
+
+ +
+
+

Defaults SA Attach

+

cluster=Brazil, sales-credit-type=QUOTA, solution=Cloud Infrastructure - Workloads, Hardware - Bookings, On-Premise Technology - Bookings, revenue-type-group=NEW,EXPANSION,WORKLOAD.

+
+
+

Aliases importantes

+

workload e workloads normalizam para WORKLOAD. license and hardware normaliza para License,Hardware.

+
+
+

Monetário

+

Outputs comerciais usam preferencialmente bookingValue e workloadAmount; a seção raw preserva o valor nativo do backend.

+
+
+
+ +
+

Intents

+

Use intent primeiro quando o pedido já parece um caso de negócio recorrente. Essa é a forma mais fácil de pedir algo no Codex sem precisar pensar em SQL, aliases ou tabelas internas.

+ +
+ + + + + + + + + + + + + + + + + + + + + + +
IntentQuando usarEntrada chaveEscopo
opportunities-defaultConsulta comercial padrão de pipeline/opportunities.--limitOrg-wide
opportunities-close-dateClose date exata.--dateOrg-wide
opportunities-close-monthMês calendário.--monthOrg-wide
opportunities-close-quarterQuarter fiscal.--quarterOrg-wide
opportunities-current-team-close-windowJanela comercial org-wide enriquecida com cobertura do time atual.janela de datasMixed-consistent
opportunities-by-resource-close-windowJanela comercial com cobertura de um recurso explícito.--resource + janelaOrg-wide
opportunities-by-manager-close-windowJanela comercial com cobertura de um manager explícito.--manager-email + janelaOrg-wide
workloads-by-owner-currentEstado atual de workloads para um territory owner.--owner-emailOrg-wide
workloads-by-owner-manager-currentEstado atual de workloads sob um manager de owners.--owner-manager-emailOrg-wide
workloads-by-manager-resource-close-windowRevenue lines workload com manager/resource allocation org-wide e SRs visíveis do time.--manager-email-list + janelaMixed-consistent
srs-by-resourceSRs por recurso Oracle.--resourceMy-team-only
+
+
+ +
+

Views

+

Use view quando você já sabe exatamente o shape do extrato que quer. Views são boas para integrações, análises repetidas e validações em cima de um contrato estável, sem precisar redescobrir campo por campo.

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
ViewFonteEscopoUso
current-fiscal-yearDV sessionMy-team-onlyAno fiscal da sessão Oracle DV.
data-quality-session-contextDV sessionMy-team-onlyEntry point e variáveis fiscais da sessão.
effort-by-se-teamDV - SE TeamMy-team-onlyHoras por membro do time.
effort-task-type-summaryDV - SE TeamMy-team-onlyHoras por task type.
opportunities-close-windowKnowledge DV - Opportunities - V2Org-wideUma linha por oportunidade em janela de close date.
opportunity-detailsKnowledge DV - Opportunities - V2Org-wideDetalhe comercial de oportunidades.
revenue-line-detailsKnowledge DV - Revn Lines by SEOrg-wideDetalhe de revenue lines.
sa-attach-hours-by-opportunityKnowledge DV - Hours - V2Org-wideHoras/cobertura por oportunidade.
sa-attach-involvement-distributionKnowledge DV - Opportunities - V2Org-wideDistribuição agregada por bucket de envolvimento.
sa-attach-open-pipelineKnowledge DV - Opportunities - V2Org-wideMétrica de pipeline aberto.
sa-attach-pipeline-detailsKnowledge DV - Opportunities - V2Org-wideExtrato comercial mais completo da skill.
sa-attach-presales-coverageKnowledge DV - Presales Involvement Aux - V1Org-wideCobertura presales por oportunidade.
sa-attach-won-pipelineKnowledge DV - Opportunities - V2Org-wideMétrica de pipeline won.
sr-detailsDV - SE TeamMy-team-onlyDetalhe de SR.
srs-by-resource-emailDV - SE TeamMy-team-onlySRs por email de recurso.
won-and-open-by-se-optyDV - SE TeamMy-team-onlyContribuição por oportunidade e membro do time.
+
+ +
+ Notas rápidas de escopo +
    +
  • org-wide: linhas comerciais visíveis para a hierarquia comercial da workbook.
  • +
  • my-team-only: visibilidade limitada ao time do usuário executor em DV - SE Team.
  • +
  • mixed-consistent: linhas comerciais org-wide preservadas, enriquecimento de recursos/SRs restrito ao escopo apropriado.
  • +
  • scope.components: detalhe fonte por fonte; prefira esse campo quando o resultado combinar escopos.
  • +
+
+
+ +
+

Superfície CLI

+

A CLI existe para quando você quer rodar a skill manualmente ou entender o que o Codex está fazendo por baixo. Cada chamada deve escolher exatamente um modo entre --intent, --view, --query e --sql.

+ +
+
+

Modos

+
    +
  • --intent: caminho preferido para perguntas recorrentes.
  • +
  • --view: extrato conhecido, contrato estável.
  • +
  • --query: aliases + filtros + grouping + ordering, com inferência de fonte e política org-wide-first por padrão.
  • +
  • --sql: SQL lógico Oracle bruto, com placeholders locais.
  • +
  • --render-sql: render local para --query ou --sql, sem backend.
  • +
+
+ +
+

Discovery

+
    +
  • --catalog
  • +
  • --list-views, --describe-view
  • +
  • --list-intents, --describe-intent
  • +
  • --list-fields, --describe-field
  • +
  • --list-parameters, --describe-parameter
  • +
  • --list-scripts, --describe-script
  • +
+
+
+ +
+
+

Janela temporal

+

--date, --month, --quarter, --week ou o par --from-date/--to-date. Nunca combine entre si.

+
+
+

Hierarquia e recurso

+

--resource, --resource-email, --manager-email, --manager-email-list, --owner-email, --owner-manager-email, --match-role.

+
+
+

Filtros SA Attach

+

--cluster, --solution, --revenue-line-status, --executive-product-lob, --revenue-type-group, --sales-credit-type, --min-opportunity-probability, --forecast-type.

+
+
+

Escopo

+

--scope auto tenta org-wide primeiro nas fontes XSA compatíveis; --scope my-team força a leitura do time atual quando a fonte suporta esse recorte.

+
+
+ +
+ Modelo de week +
    +
  • week-year é o ano de início do ciclo Junho-Maio.
  • +
  • No contexto atual, o ciclo default é 2025-06-01 até 2026-05-31.
  • +
  • Exemplos: W1 = 2025-06-01..2025-06-07, W43 = 2026-03-22..2026-03-28, W53 = 2026-05-31.
  • +
+
+ +
+

Regra prática de escolha

+
    +
  • Comece por --intent sempre que existir um intent compatível com a pergunta.
  • +
  • Use --view quando você quer consistência de colunas para export, reconciliação ou integração.
  • +
  • Use --query quando a pergunta é nova, mas ainda cabe em aliases conhecidos e filtros claros.
  • +
  • Deixe --sql para casos realmente excepcionais, porque ele exige mais cuidado com Oracle DV e aumenta a chance de drift de contrato.
  • +
+
+
+ +
+

Auth e Runtime

+

O objetivo é reutilizar sessão local e abrir browser apenas quando a sessão precisar ser refeita. Em uso normal, a skill deve parecer browserless mesmo quando houve uma autenticação inicial no Chrome.

+ +
+
+

Arquivos de sessão

+
    +
  • <workspace>/knowledge-one-view-cli/runtime/auth-state.json
  • +
  • <workspace>/knowledge-one-view-cli/runtime/session-meta.json
  • +
  • <workspace>/knowledge-one-view-cli/runtime/chrome-profile/
  • +
+

Leitura pode cair para o legado em ~/.codex/oracle-sales-intelligence-direct/ quando o runtime novo ainda está vazio.

+
+ +
+

Estratégia de autenticação

+
    +
  1. --check-auth só diagnostica.
  2. +
  3. refresh-auth-direct.mjs é o caminho preferido para MFA sem browser.
  4. +
  5. refresh-auth-state.mjs é helper de browser para troubleshooting ou refresh interativo.
  6. +
  7. Em execução normal, o fetch pode disparar refresh automático e reexecutar a consulta.
  8. +
+
+
+ +
+

Como pensar o runtime no workspace

+

A árvore operacional do workspace é a âncora da instalação migrada de máquina. É ali que a skill grava autenticação, outputs e arquivos temporários; por isso a checagem inicial deve validar esse diretório antes de qualquer teste de negócio.

+
+ +
+

Playwright / browser helper

+
    +
  • Procura runtime em módulos locais, skill compartilhada ~/.codex/skills/playwright e runtimes empacotados do Codex.
  • +
  • Útil em máquinas novas: normalmente o helper já funciona sem instalação adicional fora do ambiente Codex.
  • +
+
+
+ +
+

Contrato de saída

+

O formato JSON é estável e foi desenhado para consumo por agente e leitura humana. A ideia é que a mesma execução possa servir para responder no chat, exportar para arquivo e depurar um problema sem reinventar o payload.

+ +
+ + + + + + + + + + + + + + + + + +
CampoFunção
requestModo, flags resolvidas, escopo, SQL final e contexto da execução.
scopeDisclosure canônico de escopo com scopeMode, explicação e linhas de divulgação.
apiMetricsContagem crua de linhas puxadas do Oracle DV. Este é o número oficial de esforço de API.
columnsColunas estáveis do payload final.
recordsRegistros já normalizados.
summaryAgregados de intents derivados quando aplicável.
warningsLimite atingido, fallback, SQL custom sem alias estável, etc.
rawPayload nativo do Oracle DV para debugging.
+
+ +
+
+

Scope modes

+

org-wide, my-team-only e mixed-consistent.

+
+
+

Métricas

+

apiMetrics.totalRowsPulledFromApi nunca deve ser trocado por records.length.

+
+
+

Moedas

+

bookingValue e workloadAmount saem formatados em k; raw preserva o valor nativo.

+
+
+ +
+

Como interpretar o payload sem se perder

+
    +
  • Leia request para entender o que a skill realmente executou, mesmo que o prompt original tenha sido mais informal.
  • +
  • Leia scope antes de tirar conclusão de negócio; é ele que explica se o recorte é org-wide, my-team-only ou misto.
  • +
  • Leia records como resultado final pronto para tabela, CSV ou resumo executivo.
  • +
  • Volte para raw apenas quando precisar investigar divergência com o backend Oracle DV.
  • +
+
+
+ +
+

Hierarquia e semântica

+

Regras que evitam leituras erradas de manager, território, time atual e cobertura. Esta é a seção mais importante quando a pergunta mistura owner comercial, manager de recurso e SR no mesmo resultado.

+ +
+
+

Heurísticas úteis

+
    +
  • Em produtividade estilo SA Attach: L3 costuma ser o anchor de manager, L4 o manager direto e L5 o IC/arquiteto.
  • +
  • Não assumir que Security.Entry Point replica a hierarquia comercial desejada.
  • +
  • vendedor, sales rep e lider de vendas devem ser lidos como territory owner por padrão.
  • +
  • Para perguntas por manager/recurso, priorizar Knowledge DV - Presales Involvement Aux - V1 para cobertura e Knowledge DV - Opportunities - V2 para monetário e close date.
  • +
+
+ +
+

Papéis típicos na hierarquia

+
    +
  • Anchors altos da hierarquia costumam ser úteis para leituras executivas ou rollups amplos.
  • +
  • O nível usado como <manager comercial> costuma ser o ponto de corte para pipeline, owner e workload em leitura org-wide.
  • +
  • O nível usado como <manager de recurso> costuma ser o ponto de corte para cobertura, recursos alocados e cruzamento com SR.
  • +
  • O nível usado como <recurso alocado> costuma representar o IC, arquiteto ou engenheiro diretamente vinculado à oportunidade.
  • +
+
+
+ +
+

Regras de escopo que precisam aparecer na resposta

+
    +
  • Quando o resultado for misto: deixar explícito que oportunidades/workloads são org-wide e recursos/SRs podem ser limitados ao time atual.
  • +
  • No intent workloads-by-manager-resource-close-window, resourceDetails.srNumbers mistura SR direto confirmado com candidatos internos por mesmo customer quando não há opportunityId utilizável.
  • +
  • Linhas comerciais org-wide nunca devem sumir só porque não houve match de recurso no enriquecimento.
  • +
+
+ +
+

Leitura segura para perguntas cruzadas

+

Quando alguém pedir "quais workloads do Brasil têm SR na oportunidade de recursos abaixo de <manager de recurso>", a leitura correta não é "mostrar apenas o que existe no time". A leitura correta é preservar o conjunto comercial do recorte e, em seguida, enriquecer com a visibilidade de recursos e SR disponível para o papel consultado.

+
+
+ +
+

Estrutura de pastas

+

Separação clara entre skill instalada e árvore operacional do workspace.

+ +
+
+

Skill instalada

+
knowledge-one-view-cli/
+  SKILL.md
+  agents/
+    openai.yaml
+  portable-setup.md
+  scripts/
+    fetch-sales-intelligence.mjs
+    refresh-auth-direct.mjs
+    refresh-auth-state.mjs
+    run-sales-intelligence-sql.mjs
+    lib/
+      auth-shared.mjs
+      cli-shared.mjs
+      date-windows.mjs
+      output-contract.mjs
+      runtime-paths.mjs
+  references/
+    api-map.md
+    initial-context-catalog.md
+    script-catalog.md
+  docs/
+    docs.html
+    tests.html
+  tests/
+    README.md
+    run.mjs
+    functions.test.mjs
+    sales-prompts.test.mjs
+    helpers/
+      catalogs.mjs
+      cli.mjs
+      examples.mjs
+    prompts/
+      sales-prompts.json
+
+ +
+

Workspace-side

+
<workspace>/
+  knowledge-one-view-cli/
+    output/
+      test-runs/
+      *.json / *.csv
+    runtime/
+      auth-state.json
+      session-meta.json
+      chrome-profile/
+    tmp/
+      tmp-render-output-*.json
+
+
+
+ +
+

Testes e validação

+

A skill possui uma suíte pequena e executável em tests/, com relatório humano em docs/tests.html. Esta parte separa duas perguntas: se o contrato local continua estável e se o backend ainda responde como esperado.

+ +
+
+

Status recente

+

Offline passou com 12 pass, 0 falhas e 1 live skipped. Live passou com 13 pass e 0 falhas.

+
+
+

O que o offline cobre

+

Funções locais, SQL renderizado, escopo, contratos de CLI, prompts documentados e summaries com dados controlados.

+
+
+

O que o live cobre

+

Execução real de comandos já mapeados contra Oracle DV, com --no-cache, escopo, fonte e métricas esperadas.

+
+
+ +
+ + + + + + + + + + + + + +
SuiteObjetivo
functions.test.mjsFunções locais, janelas de data, SQL, escopo, summaries e métricas.
sales-prompts.test.mjsMapeamento documentado de prompts para comandos CLI e checks live opcionais.
tests/prompts/sales-prompts.jsonCasos de prompt com argumentos esperados e placeholders dinâmicos para pessoas.
docs/tests.htmlRelatório legível em português e espanhol com objetivos, entradas, saídas e avaliação.
+
+ +
+

Sequência recomendada de validação

+
    +
  1. Rode node tests/run.mjs para validar contrato local sem Oracle DV.
  2. +
  3. Quando houver sessão válida, rode o live com KNOWLEDGE_ONE_VIEW_LIVE=1 e ORACLE_SI_RUNTIME_HOME.
  4. +
  5. Use docs/tests.html para revisar objetivo, entrada, saída e avaliação de cada caso.
  6. +
  7. Só depois avance para um teste de negócio novo, como um workload do Brasil ou um cruzamento com SR.
  8. +
+
+
+ +
+

Comandos úteis

+

Esses exemplos ajudam a entender o que a skill faz por baixo do pedido em linguagem natural. Use-os como referência manual, não como ponto de partida obrigatório; no dia a dia, o ideal é continuar pedindo em português claro para o Codex.

+ +
+
+

Discovery e render

+
node scripts/fetch-sales-intelligence.mjs --list-intents
+
+node scripts/fetch-sales-intelligence.mjs \
+  --render-sql \
+  --query \
+  --select opportunityId,bookingValue \
+  --where "opportunityId IS NOT NULL"
+
+ +
+

Execução normal

+
node scripts/fetch-sales-intelligence.mjs \
+  --intent opportunities-default \
+  --limit 200
+
+node scripts/fetch-sales-intelligence.mjs \
+  --intent opportunities-close-date \
+  --date 2026-05-02
+
+
+ +
+
+

Janela e cobertura

+
node scripts/fetch-sales-intelligence.mjs \
+  --intent opportunities-by-manager-close-window \
+  --manager-email <manager de recurso>@oracle.com \
+  --week w2 \
+  --week-year 2026
+
+node scripts/fetch-sales-intelligence.mjs \
+  --intent workloads-by-manager-resource-close-window \
+  --manager-email-list <manager de recurso A>@oracle.com,<manager de recurso B>@oracle.com \
+  --from-date today \
+  --to-date +7d
+
+ +
+

Auth e testes

+
node scripts/fetch-sales-intelligence.mjs --check-auth
+
+node scripts/refresh-auth-direct.mjs --username <usuario oracle>@oracle.com
+
+node tests/run.mjs
+
+KNOWLEDGE_ONE_VIEW_LIVE=1 \
+ORACLE_SI_RUNTIME_HOME=/path/to/workspace/knowledge-one-view-cli/runtime \
+node tests/run.mjs
+
+
+ +
+

Quando usar cada bloco

+
    +
  • Discovery e render serve para entender o catálogo e inspecionar SQL sem tocar o backend.
  • +
  • Execução normal serve para consultas diretas de pipeline e close date.
  • +
  • Janela e cobertura serve para cruzamentos por manager, recurso e período fiscal.
  • +
  • Auth e testes serve para onboarding, migração de máquina e troubleshooting controlado.
  • +
+
+
+ +
+

Boas práticas

+

Regras curtas para manter uso e manutenção consistentes. Se a skill continuar simples de operar, a tendência é ela permanecer confiável mesmo quando o workbook ou o ambiente mudarem.

+ +
+
    +
  • Preferir --intent para perguntas recorrentes e --query para ad hoc; cair para --sql só quando necessário.
  • +
  • Usar aliases de campo locais e placeholders como {{opportunityId}} e {{securityEntryPointFilter}} em vez de adivinhar expressão Oracle.
  • +
  • Tratar DV - SE Team como fonte de time atual e SR, não como leitura comercial org-wide genérica.
  • +
  • Quando misturar org-wide com enriquecimento de recurso, preservar sempre a linha comercial original.
  • +
  • Em PowerShell, usar run-sales-intelligence-sql.mjs para SQL longa ou com quoting frágil.
  • +
  • Usar --output-file para persistir payloads finais; nomes temporários/intermediários vão para tmp/.
  • +
  • Documentação oficial da skill fica em docs/docs.html; catálogos operacionais continuam em references/.
  • +
+
+
+ + +
+
+
+
+
+ + +
+
+
+ Oracle DV +

Skill para consultar el DV LAD Knowledge One View directamente por la API.

+

Guía consolidada de la skill para onboarding, operación y consulta rápida de la superficie actual.

+
+
+ +
+

Casos de uso prácticos

+

Piense en esta skill como un traductor entre el lenguaje de negocio y Oracle DV. Usted describe el alcance deseado en Codex; la skill decide si usa intent, view, query o SQL, resuelve la autenticación y devuelve una salida utilizable.

+ +
+
+ Ejemplo 1 +

Workloads con SR por manager

+
Prompt en Codex:
+
+"Tráeme todos los workloads del cluster Brazil para la próxima semana fiscal de Oracle, cruzando cuáles tienen SR en la oportunidad con recursos bajo <manager de recursos>."
+

Este tipo de solicitud suele caer en el intent workloads-by-manager-resource-close-window. La skill resuelve la semana Oracle, filtra las revenue lines y enriquece el resultado con recursos y SRs visibles.

+
+ +
+ Ejemplo 2 +

Pipeline con ventana comercial

+
Prompt en Codex:
+
+"¿Qué oportunidades con close en el mes actual tienen booking por encima de 500k y territory owner bajo <manager comercial>?"
+

La skill tiende a usar intents o views comerciales en Knowledge DV - Opportunities - V2, manteniendo alcance org-wide y el vocabulario comercial consistente.

+
+ +
+ Ejemplo 3 +

SRs por recurso

+
Prompt en Codex:
+
+"Liste los SRs de <recurso asignado> con status y opportunityId, en formato tabla."
+

Aquí la skill normalmente usa srs-by-resource o una view equivalente en DV - SE Team, respetando el alcance del equipo visible para el usuario ejecutor.

+
+ +
+ Ejemplo 4 +

Formato de respuesta

+
Respuesta típica:
+
+- semana Oracle resuelta
+- alcance de la lectura
+- total de filas obtenidas de la API
+- tabla final con cliente, workload, recurso y SR
+

Si usted pide "muéstralo en tabla", "genera un informe HTML", "arma un PDF ejecutivo", "organiza en una planilla" o "automatiza el envío por email", Codex puede transformar el payload final en entregables más útiles para consumo y seguimiento.

+
+
+
+ +
+

Instalación rápida y primer uso

+

En una máquina nueva, la secuencia ideal es: instalar la skill, confirmar la sesión Oracle DV una vez y luego seguir browserless en la rutina normal. El objetivo es gastar energía en el negocio, no en setup.

+ +
+
+ Paso 1 +

Pedir la instalación en Codex

+
Prompt en Codex:
+
+"Instala la skill knowledge-one-view-cli en Codex y valida la carpeta runtime/output en el workspace."
+

Después de eso, la skill queda instalada en ~/.codex/skills/knowledge-one-view-cli.

+
+ +
+ Paso 2 +

Probar la autenticación en Chrome

+
Prompt en Codex:
+
+"Haz una prueba de autenticación de la skill vía Chrome y confirma si el backend Oracle DV respondió."
+

El helper abre el navegador solo para grabar auth-state.json y session-meta.json en el runtime del workspace.

+
+ +
+ Paso 3 +

Seguir browserless

+
Prompt en Codex:
+
+"Tráeme todos los workloads del cluster Brazil para la próxima semana fiscal de Oracle."
+

A partir de ahí, la skill normalmente sigue sin browser, consultando el backend Oracle DV directamente por la API.

+
+
+ +
+
+

How-to exprés

+
    +
  1. Pídale a Codex que instale o valide la skill.
  2. +
  3. Pídale a Codex que haga una prueba de autenticación de la skill vía Chrome.
  4. +
  5. Complete el login y el MFA.
  6. +
  7. Después de eso, siga usándola en lenguaje natural.
  8. +
+
+ +
+

Ejemplo de respuesta después del primer uso

+
Resultado típico:
+
+"Auth validada en el runtime del workspace.
+Backend Oracle DV accesible.
+Raw rows pulled from the API: 5.
+Aquí está la tabla con cliente, workload, close date y territory owner."
+
+
+
+ +
+

Internals - No es necesario para usar la skill

+

La página fue reorganizada para funcionar bien tanto para onboarding como para troubleshooting. Si usted está llegando ahora, conviene seguir este orden en lugar de saltar directo a los comandos.

+ +
+
+ Lectura 1 +

Entienda la solicitud

+

Empiece por Casos de uso y Roles y lenguaje. Muestran cómo transformar una pregunta de negocio en un alcance consistente de owner, manager, recurso, workload y SR.

+
+
+ Lectura 2 +

Entienda la ejecución

+

Después vea Arquitectura, Datasets e Intents. Esta parte explica de dónde vienen los datos y por qué la skill elige intent, view, query o SQL.

+
+
+ Lectura 3 +

Entienda la operación

+

Cierre con Auth y Runtime, Contrato de salida, Pruebas y Comandos. Así ya puede instalar, validar y depurar con seguridad.

+
+
+ +
+

Atajo mental para usar bien

+
    +
  • Si la pregunta es recurrente, piense en intent.
  • +
  • Si quiere un extracto conocido, piense en view.
  • +
  • Si necesita montar un alcance a medida sin ir a SQL, piense en query.
  • +
  • Si está investigando un caso raro o depurando Oracle DV, entonces sí piense en sql.
  • +
+
+
+ +
+

Roles y lenguaje

+

Esta guía evita nombres personales y usa roles de negocio. Eso hace la documentación más transferible, más segura y más fácil de reutilizar en otros equipos.

+ +
+
+

Roles que aparecen en esta guía

+
    +
  • <territory owner>: dueño comercial directo de la oportunidad o workload.
  • +
  • <manager comercial>: responsable de la jerarquía de territory owners usada para alcances comerciales.
  • +
  • <manager de recursos>: responsable del lado presales/ingeniería, usado para cruzar recursos asignados en oportunidades.
  • +
  • <recurso asignado>: arquitecto, ingeniero o especialista asociado a la oportunidad.
  • +
  • <equipo actual del usuario>: alcance visible en DV - SE Team para quien ejecuta la skill.
  • +
+
+ +
+

Traducción práctica del lenguaje

+
    +
  • Cuando alguien pida "vendedor", la lectura estándar debe ser <territory owner>.
  • +
  • Cuando alguien pida "recursos bajo un manager", la lectura suele ser <manager de recursos> en Knowledge DV - Presales Involvement Aux - V1.
  • +
  • Cuando alguien pida SR, cobertura o contexto de sesión, la lectura suele involucrar el alcance del <equipo actual del usuario>.
  • +
  • Cuando la solicitud mezcla comercial y recurso, la skill normalmente combina una fuente org-wide con enriquecimiento controlado por rol.
  • +
+
+
+ +
+

Cómo leer los ejemplos

+

Siempre que vea un rol entre <...>, sustitúyalo por el identificador real de su pregunta. El rol explica qué atributo de la jerarquía debe usar la skill, sin atar la documentación a una persona específica.

+
+
+ +
+

Arquitectura

+

Estructura simple: el fetch principal concentra la lógica de negocio y scripts/lib/runtime-paths.mjs se ocupa del runtime, output y bootstrap del workspace.

+ +
+

Flujo principal

+
    +
  1. Parse de argumentos y validación del modo de ejecución.
  2. +
  3. Resolución de runtime-home, archivos de sesión y caché.
  4. +
  5. Opcionalmente resolución de año fiscal y contexto de sesión.
  6. +
  7. Construcción de SQL vía intent, view, query declarativa o SQL bruto.
  8. +
  9. Ejecución en sqlquery/execute con restauración de sesión si es necesario.
  10. +
  11. Normalización de filas, alcance, métricas, warnings y persistencia opcional en archivo.
  12. +
+
+ +
+

Módulos actuales

+

Actualmente, la skill está organizada en un script principal, helpers de autenticación y utilitarios internos en scripts/lib/. La lista siguiente refleja los módulos realmente presentes en el código actual.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MóduloResponsabilidad
fetch-sales-intelligence.mjsCatálogo local, query engine, intents, views, orquestación y ejecución Oracle DV.
refresh-auth-direct.mjsLogin Oracle sin abrir Chrome, con MFA.
refresh-auth-state.mjsRefresh de auth vía browser/Playwright cuando el flujo directo no alcanza.
run-sales-intelligence-sql.mjsAyuda para SQL larga o sensible al quoting del shell.
lib/runtime-paths.mjsResolución canónica de runtime, output, tmp, bootstrap de workspace y fallback legado.
lib/auth-shared.mjsLectura, persistencia y refresh de los artefactos de sesión, cookies, CSRF y metadatos de autenticación.
lib/cli-shared.mjsParse de argumentos, normalización de flags y helpers utilitarios de entrada.
lib/date-windows.mjsResolución de ventanas temporales, semanas fiscales, quarters y atajos como today o +7d.
lib/output-contract.mjsConstrucción del payload final con apiMetrics, warnings, normalización de filas y emisión JSON.
+
+ +
+

Endpoint y estado local

+
    +
  • Endpoint principal: POST /ui/dv/ui/api/v1/sqlquery/execute.
  • +
  • Workbook objetivo: salesintelligence-dv.oracle.com en el report path LAD Knowledge One View.
  • +
  • Estado persistido: auth-state.json y session-meta.json.
  • +
  • Fallback legado de lectura: ~/.codex/oracle-sales-intelligence-direct/.
  • +
+
+
+ +
+

Datasets

+

Resumen de las fuentes realmente usadas por la skill y del papel de cada una. Esta sección existe para evitar el error más común en este tipo de análisis: consultar la fuente correcta con la lectura equivocada del alcance.

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
DatasetAlcancePapel principalObservaciones
Knowledge DV - Opportunities - V2Org-wideFuente comercial principal: pipeline, opportunities, won, close date, booking, workload, territory y owner.Base normal para opportunities-default, opportunities-close-* y views sa-attach-* comerciales.
Knowledge DV - Hours - V2Org-wide por defecto; my-team con --scope my-teamHoras, ownership y productividad por jerarquía.Expuesto en sa-attach-hours-by-opportunity; en --scope auto preserva la lectura org-wide.
Knowledge DV - Presales Involvement Aux - V1Org-wide por defecto; my-team con --scope my-teamCobertura y vínculo manager/recurso/oportunidad.Base normal para cobertura presales y linkage manager/recurso; intents de workload/manager usan esta lectura org-wide.
DV - SE TeamMy-team-onlySession context, SRs y fallback comercial solo cuando la pregunta es explícitamente del equipo actual.No debe usarse como fuente comercial genérica org-wide.
Knowledge DV - Revn Lines by SEOrg-wide por defecto; my-team con --scope my-teamDetalle de revenue lines.Expuesto por revenue-line-details como extracto org-wide en --scope auto.
+
+ +
+

Cómo elegir la fuente correcta

+
    +
  • Si la pregunta es comercial y necesita preservar todas las oportunidades del alcance, la base tiende a ser Knowledge DV - Opportunities - V2.
  • +
  • Si la pregunta es sobre quién está asignado, cubierto o relacionado con una oportunidad, la base tiende a ser Knowledge DV - Presales Involvement Aux - V1 y la skill intenta org-wide primero.
  • +
  • Si la pregunta es sobre SR, contexto de la sesión o el equipo visible del ejecutor, la base tiende a pasar por DV - SE Team.
  • +
  • Si la pregunta es sobre horas y productividad, la skill tiende a usar Knowledge DV - Hours - V2 en org-wide, salvo solicitud explícita de equipo actual.
  • +
  • Si la pregunta es sobre revenue line detallada, la skill tiende a consultar Knowledge DV - Revn Lines by SE en org-wide, salvo solicitud explícita de equipo actual.
  • +
+
+ +
+
+

Defaults SA Attach

+

cluster=Brazil, sales-credit-type=QUOTA, solution=Cloud Infrastructure - Workloads, Hardware - Bookings, On-Premise Technology - Bookings, revenue-type-group=NEW,EXPANSION,WORKLOAD.

+
+
+

Aliases importantes

+

workload y workloads se normalizan a WORKLOAD. license and hardware se normaliza a License,Hardware.

+
+
+

Monetario

+

Los outputs comerciales usan preferentemente bookingValue y workloadAmount; la sección raw preserva el valor nativo del backend.

+
+
+
+ +
+

Intents

+

Use intent primero cuando la solicitud ya parece un caso de negocio recurrente. Esta es la forma más fácil de pedir algo en Codex sin tener que pensar en SQL, aliases o tablas internas.

+ +
+ + + + + + + + + + + + + + + + + + + + + + +
IntentCuándo usarEntrada claveAlcance
opportunities-defaultConsulta comercial estándar de pipeline/opportunities.--limitOrg-wide
opportunities-close-dateClose date exacta.--dateOrg-wide
opportunities-close-monthMes calendario.--monthOrg-wide
opportunities-close-quarterQuarter fiscal.--quarterOrg-wide
opportunities-current-team-close-windowVentana comercial org-wide enriquecida con cobertura del equipo actual.ventana de fechasMixed-consistent
opportunities-by-resource-close-windowVentana comercial con cobertura de un recurso explícito.--resource + ventanaOrg-wide
opportunities-by-manager-close-windowVentana comercial con cobertura de un manager explícito.--manager-email + ventanaOrg-wide
workloads-by-owner-currentEstado actual de workloads para un territory owner.--owner-emailOrg-wide
workloads-by-owner-manager-currentEstado actual de workloads bajo un manager de owners.--owner-manager-emailOrg-wide
workloads-by-manager-resource-close-windowRevenue lines workload con manager/resource allocation org-wide y SRs visibles del equipo.--manager-email-list + ventanaMixed-consistent
srs-by-resourceSRs por recurso Oracle.--resourceMy-team-only
+
+
+ +
+

Views

+

Use view cuando ya sabe exactamente el shape del extracto que quiere. Las views son buenas para integraciones, análisis repetidos y validaciones sobre un contrato estable, sin tener que redescubrir campo por campo.

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
ViewFuenteAlcanceUso
current-fiscal-yearDV sessionMy-team-onlyAño fiscal de la sesión Oracle DV.
data-quality-session-contextDV sessionMy-team-onlyEntry point y variables fiscales de la sesión.
effort-by-se-teamDV - SE TeamMy-team-onlyHoras por miembro del equipo.
effort-task-type-summaryDV - SE TeamMy-team-onlyHoras por task type.
opportunities-close-windowKnowledge DV - Opportunities - V2Org-wideUna fila por oportunidad en ventana de close date.
opportunity-detailsKnowledge DV - Opportunities - V2Org-wideDetalle comercial de oportunidades.
revenue-line-detailsKnowledge DV - Revn Lines by SEOrg-wideDetalle de revenue lines.
sa-attach-hours-by-opportunityKnowledge DV - Hours - V2Org-wideHoras/cobertura por oportunidad.
sa-attach-involvement-distributionKnowledge DV - Opportunities - V2Org-wideDistribución agregada por bucket de involucramiento.
sa-attach-open-pipelineKnowledge DV - Opportunities - V2Org-wideMétrica de pipeline abierto.
sa-attach-pipeline-detailsKnowledge DV - Opportunities - V2Org-wideExtracto comercial más completo de la skill.
sa-attach-presales-coverageKnowledge DV - Presales Involvement Aux - V1Org-wideCobertura presales por oportunidad.
sa-attach-won-pipelineKnowledge DV - Opportunities - V2Org-wideMétrica de pipeline won.
sr-detailsDV - SE TeamMy-team-onlyDetalle de SR.
srs-by-resource-emailDV - SE TeamMy-team-onlySRs por email de recurso.
won-and-open-by-se-optyDV - SE TeamMy-team-onlyContribución por oportunidad y miembro del equipo.
+
+ +
+ Notas rápidas de alcance +
    +
  • org-wide: filas comerciales visibles para la jerarquía comercial del workbook.
  • +
  • my-team-only: visibilidad limitada al equipo del usuario ejecutor en DV - SE Team.
  • +
  • mixed-consistent: filas comerciales org-wide preservadas, enriquecimiento de recursos/SRs restringido al alcance apropiado.
  • +
  • scope.components: detalle fuente por fuente; prefiera ese campo cuando el resultado combine alcances.
  • +
+
+
+ +
+

Superficie CLI

+

La CLI existe para cuando quiere ejecutar la skill manualmente o entender qué está haciendo Codex por debajo. Cada llamada debe elegir exactamente un modo entre --intent, --view, --query y --sql.

+ +
+
+

Modos

+
    +
  • --intent: camino preferido para preguntas recurrentes.
  • +
  • --view: extracto conocido, contrato estable.
  • +
  • --query: aliases + filtros + grouping + ordering, con inferencia de fuente y política org-wide-first por defecto.
  • +
  • --sql: SQL lógico Oracle bruto, con placeholders locales.
  • +
  • --render-sql: render local para --query o --sql, sin backend.
  • +
+
+ +
+

Discovery

+
    +
  • --catalog
  • +
  • --list-views, --describe-view
  • +
  • --list-intents, --describe-intent
  • +
  • --list-fields, --describe-field
  • +
  • --list-parameters, --describe-parameter
  • +
  • --list-scripts, --describe-script
  • +
+
+
+ +
+
+

Ventana temporal

+

--date, --month, --quarter, --week o el par --from-date/--to-date. Nunca los combine entre sí.

+
+
+

Jerarquía y recurso

+

--resource, --resource-email, --manager-email, --manager-email-list, --owner-email, --owner-manager-email, --match-role.

+
+
+

Filtros SA Attach

+

--cluster, --solution, --revenue-line-status, --executive-product-lob, --revenue-type-group, --sales-credit-type, --min-opportunity-probability, --forecast-type.

+
+
+

Alcance

+

--scope auto intenta org-wide primero en fuentes XSA compatibles; --scope my-team fuerza la lectura del equipo actual cuando la fuente soporta ese alcance.

+
+
+ +
+ Modelo de week +
    +
  • week-year es el año de inicio del ciclo Junio-Mayo.
  • +
  • En el contexto actual, el ciclo default es 2025-06-01 hasta 2026-05-31.
  • +
  • Ejemplos: W1 = 2025-06-01..2025-06-07, W43 = 2026-03-22..2026-03-28, W53 = 2026-05-31.
  • +
+
+ +
+

Regla práctica de elección

+
    +
  • Empiece por --intent siempre que exista un intent compatible con la pregunta.
  • +
  • Use --view cuando quiera consistencia de columnas para export, reconciliación o integración.
  • +
  • Use --query cuando la pregunta es nueva, pero todavía cabe en aliases conocidos y filtros claros.
  • +
  • Deje --sql para casos realmente excepcionales, porque exige más cuidado con Oracle DV y aumenta la posibilidad de drift de contrato.
  • +
+
+
+ +
+

Auth y Runtime

+

El objetivo es reutilizar la sesión local y abrir el browser solo cuando la sesión necesite rehacerse. En uso normal, la skill debe parecer browserless incluso cuando hubo una autenticación inicial en Chrome.

+ +
+
+

Archivos de sesión

+
    +
  • <workspace>/knowledge-one-view-cli/runtime/auth-state.json
  • +
  • <workspace>/knowledge-one-view-cli/runtime/session-meta.json
  • +
  • <workspace>/knowledge-one-view-cli/runtime/chrome-profile/
  • +
+

La lectura puede caer al legado en ~/.codex/oracle-sales-intelligence-direct/ cuando el runtime nuevo todavía está vacío.

+
+ +
+

Estrategia de autenticación

+
    +
  1. --check-auth solo diagnostica.
  2. +
  3. refresh-auth-direct.mjs es el camino preferido para MFA sin browser.
  4. +
  5. refresh-auth-state.mjs es helper de browser para troubleshooting o refresh interactivo.
  6. +
  7. En ejecución normal, el fetch puede disparar refresh automático y reejecutar la consulta.
  8. +
+
+
+ +
+

Cómo pensar el runtime en el workspace

+

El árbol operativo del workspace es el ancla de la instalación migrada de máquina. Es allí donde la skill graba autenticación, outputs y archivos temporales; por eso la verificación inicial debe validar ese directorio antes de cualquier prueba de negocio.

+
+ +
+

Playwright / browser helper

+
    +
  • Busca runtime en módulos locales, skill compartida ~/.codex/skills/playwright y runtimes empaquetados de Codex.
  • +
  • Útil en máquinas nuevas: normalmente el helper ya funciona sin instalación adicional fuera del entorno Codex.
  • +
+
+
+ +
+

Contrato de salida

+

El formato JSON es estable y fue diseñado para consumo por agente y lectura humana. La idea es que la misma ejecución pueda servir para responder en el chat, exportar a archivo y depurar un problema sin reinventar el payload.

+ +
+ + + + + + + + + + + + + + + + + +
CampoFunción
requestModo, flags resueltas, alcance, SQL final y contexto de la ejecución.
scopeDisclosure canónico de alcance con scopeMode, explicación y líneas de divulgación.
apiMetricsConteo bruto de filas obtenidas de Oracle DV. Este es el número oficial de esfuerzo de API.
columnsColumnas estables del payload final.
recordsRegistros ya normalizados.
summaryAgregados de intents derivados cuando aplica.
warningsLímite alcanzado, fallback, SQL custom sin alias estable, etc.
rawPayload nativo de Oracle DV para debugging.
+
+ +
+
+

Scope modes

+

org-wide, my-team-only y mixed-consistent.

+
+
+

Métricas

+

apiMetrics.totalRowsPulledFromApi nunca debe ser reemplazado por records.length.

+
+
+

Monedas

+

bookingValue y workloadAmount salen formateados en k; raw preserva el valor nativo.

+
+
+ +
+

Cómo interpretar el payload sin perderse

+
    +
  • Lea request para entender qué ejecutó realmente la skill, incluso si el prompt original fue más informal.
  • +
  • Lea scope antes de sacar una conclusión de negocio; ese campo explica si el alcance es org-wide, my-team-only o mixto.
  • +
  • Lea records como resultado final listo para tabla, CSV o resumen ejecutivo.
  • +
  • Vuelva a raw solo cuando necesite investigar una divergencia con el backend Oracle DV.
  • +
+
+
+ +
+

Jerarquía y semántica

+

Reglas que evitan lecturas equivocadas de manager, territorio, equipo actual y cobertura. Esta es la sección más importante cuando la pregunta mezcla owner comercial, manager de recursos y SR en el mismo resultado.

+ +
+
+

Heurísticas útiles

+
    +
  • En productividad estilo SA Attach: L3 suele ser el anchor de manager, L4 el manager directo y L5 el IC/arquitecto.
  • +
  • No asumir que Security.Entry Point replica la jerarquía comercial deseada.
  • +
  • vendedor, sales rep y líder de ventas deben leerse como territory owner por defecto.
  • +
  • Para preguntas por manager/recurso, priorizar Knowledge DV - Presales Involvement Aux - V1 para cobertura y Knowledge DV - Opportunities - V2 para monetario y close date.
  • +
+
+ +
+

Roles típicos en la jerarquía

+
    +
  • Anchors altos de la jerarquía suelen ser útiles para lecturas ejecutivas o rollups amplios.
  • +
  • El nivel usado como <manager comercial> suele ser el punto de corte para pipeline, owner y workload en lectura org-wide.
  • +
  • El nivel usado como <manager de recursos> suele ser el punto de corte para cobertura, recursos asignados y cruce con SR.
  • +
  • El nivel usado como <recurso asignado> suele representar al IC, arquitecto o ingeniero directamente vinculado a la oportunidad.
  • +
+
+
+ +
+

Reglas de alcance que deben aparecer en la respuesta

+
    +
  • Cuando el resultado sea mixto: dejar explícito que oportunidades/workloads son org-wide y recursos/SRs pueden estar limitados al equipo actual.
  • +
  • En el intent workloads-by-manager-resource-close-window, resourceDetails.srNumbers mezcla SR directo confirmado con candidatos internos del mismo customer cuando no hay opportunityId utilizable.
  • +
  • Las filas comerciales org-wide nunca deben desaparecer solo porque no hubo match de recurso en el enriquecimiento.
  • +
+
+ +
+

Lectura segura para preguntas cruzadas

+

Cuando alguien pida "qué workloads de Brasil tienen SR en la oportunidad con recursos bajo <manager de recursos>", la lectura correcta no es "mostrar solo lo que existe en el equipo". La lectura correcta es preservar el conjunto comercial del alcance y, a continuación, enriquecerlo con la visibilidad de recursos y SR disponible para el rol consultado.

+
+
+ +
+

Estructura de carpetas

+

Separación clara entre la skill instalada y el árbol operativo del workspace.

+ +
+
+

Skill instalada

+
knowledge-one-view-cli/
+  SKILL.md
+  agents/
+    openai.yaml
+  portable-setup.md
+  scripts/
+    fetch-sales-intelligence.mjs
+    refresh-auth-direct.mjs
+    refresh-auth-state.mjs
+    run-sales-intelligence-sql.mjs
+    lib/
+      auth-shared.mjs
+      cli-shared.mjs
+      date-windows.mjs
+      output-contract.mjs
+      runtime-paths.mjs
+  references/
+    api-map.md
+    initial-context-catalog.md
+    script-catalog.md
+  docs/
+    docs.html
+    tests.html
+  tests/
+    README.md
+    run.mjs
+    functions.test.mjs
+    sales-prompts.test.mjs
+    helpers/
+      catalogs.mjs
+      cli.mjs
+      examples.mjs
+    prompts/
+      sales-prompts.json
+
+ +
+

Lado del workspace

+
<workspace>/
+  knowledge-one-view-cli/
+    output/
+      test-runs/
+      *.json / *.csv
+    runtime/
+      auth-state.json
+      session-meta.json
+      chrome-profile/
+    tmp/
+      tmp-render-output-*.json
+
+
+
+ +
+

Pruebas y validación

+

La skill posee una suite pequeña y ejecutable en tests/, con reporte humano en docs/tests.html. Esta parte separa dos preguntas: si el contrato local sigue estable y si el backend todavía responde como se espera.

+ +
+
+

Estado reciente

+

Offline pasó con 12 pass, 0 fallas y 1 live skipped. Live pasó con 13 pass y 0 fallas.

+
+
+

Qué cubre offline

+

Funciones locales, SQL renderizado, alcance, contratos de CLI, prompts documentados y summaries con datos controlados.

+
+
+

Qué cubre live

+

Ejecución real de comandos ya mapeados contra Oracle DV, con --no-cache, alcance, fuente y métricas esperadas.

+
+
+ +
+ + + + + + + + + + + + + +
SuiteObjetivo
functions.test.mjsFunciones locales, ventanas de fecha, SQL, alcance, summaries y métricas.
sales-prompts.test.mjsMapeo documentado de prompts a comandos CLI y checks live opcionales.
tests/prompts/sales-prompts.jsonCasos de prompt con argumentos esperados y placeholders dinámicos para personas.
docs/tests.htmlReporte legible en portugués y español con objetivos, entradas, salidas y evaluación.
+
+ +
+

Secuencia recomendada de validación

+
    +
  1. Ejecute node tests/run.mjs para validar el contrato local sin Oracle DV.
  2. +
  3. Cuando haya sesión válida, ejecute live con KNOWLEDGE_ONE_VIEW_LIVE=1 y ORACLE_SI_RUNTIME_HOME.
  4. +
  5. Use docs/tests.html para revisar objetivo, entrada, salida y evaluación de cada caso.
  6. +
  7. Solo después avance a una prueba de negocio nueva, como un workload de Brasil o un cruce con SR.
  8. +
+
+
+ +
+

Comandos útiles

+

Estos ejemplos ayudan a entender qué hace la skill detrás de una solicitud en lenguaje natural. Úselos como referencia manual, no como punto de partida obligatorio; en el día a día, lo ideal es seguir pidiendo en español claro a Codex.

+ +
+
+

Discovery y render

+
node scripts/fetch-sales-intelligence.mjs --list-intents
+
+node scripts/fetch-sales-intelligence.mjs \
+  --render-sql \
+  --query \
+  --select opportunityId,bookingValue \
+  --where "opportunityId IS NOT NULL"
+
+ +
+

Ejecución normal

+
node scripts/fetch-sales-intelligence.mjs \
+  --intent opportunities-default \
+  --limit 200
+
+node scripts/fetch-sales-intelligence.mjs \
+  --intent opportunities-close-date \
+  --date 2026-05-02
+
+
+ +
+
+

Ventana y cobertura

+
node scripts/fetch-sales-intelligence.mjs \
+  --intent opportunities-by-manager-close-window \
+  --manager-email <manager de recursos>@oracle.com \
+  --week w2 \
+  --week-year 2026
+
+node scripts/fetch-sales-intelligence.mjs \
+  --intent workloads-by-manager-resource-close-window \
+  --manager-email-list <manager de recursos A>@oracle.com,<manager de recursos B>@oracle.com \
+  --from-date today \
+  --to-date +7d
+
+ +
+

Auth y pruebas

+
node scripts/fetch-sales-intelligence.mjs --check-auth
+
+node scripts/refresh-auth-direct.mjs --username <usuario oracle>@oracle.com
+
+node tests/run.mjs
+
+KNOWLEDGE_ONE_VIEW_LIVE=1 \
+ORACLE_SI_RUNTIME_HOME=/path/to/workspace/knowledge-one-view-cli/runtime \
+node tests/run.mjs
+
+
+ +
+

Cuándo usar cada bloque

+
    +
  • Discovery y render sirve para entender el catálogo e inspeccionar SQL sin tocar el backend.
  • +
  • Ejecución normal sirve para consultas directas de pipeline y close date.
  • +
  • Ventana y cobertura sirve para cruces por manager, recurso y período fiscal.
  • +
  • Auth y pruebas sirve para onboarding, migración de máquina y troubleshooting controlado.
  • +
+
+
+ +
+

Buenas prácticas

+

Reglas cortas para mantener el uso y el mantenimiento consistentes. Si la skill sigue siendo simple de operar, la tendencia es que permanezca confiable incluso cuando el workbook o el entorno cambien.

+ +
+
    +
  • Preferir --intent para preguntas recurrentes y --query para ad hoc; caer a --sql solo cuando sea necesario.
  • +
  • Usar aliases de campo locales y placeholders como {{opportunityId}} y {{securityEntryPointFilter}} en lugar de adivinar la expresión Oracle.
  • +
  • Tratar DV - SE Team como fuente del equipo actual y SR, no como lectura comercial org-wide genérica.
  • +
  • Cuando mezcle org-wide con enriquecimiento de recurso, preservar siempre la fila comercial original.
  • +
  • En PowerShell, usar run-sales-intelligence-sql.mjs para SQL larga o con quoting frágil.
  • +
  • Usar --output-file para persistir payloads finales; nombres temporales/intermedios van a tmp/.
  • +
  • La documentación oficial de la skill queda en docs/docs.html; los catálogos operativos siguen en references/.
  • +
+
+
+ + +
+
+
+ + + diff --git a/docs/tests.html b/docs/tests.html new file mode 100644 index 0000000..4281c2d --- /dev/null +++ b/docs/tests.html @@ -0,0 +1,1073 @@ + + + + + + Knowledge One View CLI - Testes + + + +
+
+ + +
+
+
+ node:test +

O que a suíte valida antes de confiar nos dados.

+

+ O modo offline prova contratos, roteamento, SQL, escopo e transformações locais. O modo live confirma + que os comandos documentados continuam executando contra o Oracle DV com a sessão atual. +

+
+
12/12

testes offline passaram

+
13/13

testes live passaram

+
0

falhas na última execução

+
2026-04-26

data registrada

+
+
+
+ +
+

Metodologia

+

+ Os testes usam node:test. Eles leem SKILL.md, references/script-catalog.md, + references/initial-context-catalog.md e references/api-map.md como fonte da verdade, + evitando uma cópia paralela de parâmetros e regras dentro da própria suíte. +

+
+
+ Offline +

Não chama o Oracle DV. Testa se a CLI escolhe o caminho certo, monta os filtros certos e preserva o contrato de saída.

+
+
+ Live +

Chama o Oracle DV com --no-cache. O runtime de autenticação é copiado para uma área temporária de teste.

+
+
+
+ +
+

Testes offline

+

+ Estes testes respondem: "a skill monta a consulta e a resposta certas?". Eles não provam disponibilidade + do Oracle DV nem volume real de dados. +

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TesteObjetivoEntradaResultado esperadoSaída observadaStatusAvaliação
date-windowValidar atalhos de data e rejeição de combinações inválidas.resolveDateWindow com --date, --month, --quarter, --week e conflito.Ranges conforme catálogo e erro para argumentos conflitantes.single=2026-05-02; month=2026-04-01..2026-04-30; quarter=2026-03-01..2026-05-31; week=2026-03-22..2026-03-28; inválido rejeitado.PASSCorreto.
sa-attach-defaultsConfirmar defaults e aliases de SA Attach vindos do catálogo inicial.parseSaAttachDefaults, parseSaAttachAliases e resolveSaAttachFilters.Cluster, soluções, status, LOBs, tipos de receita e aliases aplicados.cluster=Brazil; solutions=3; statuses=3; aliases validados.PASSCorreto.
current-workload-defaultsVerificar os defaults dos intents de workload atual.applyCurrentWorkloadIntentDefaults para owner atual e mês explícito.current-quarter, Cloud Infrastructure - Workloads e WORKLOAD; mês explícito preservado.quarter=current-quarter; solution=Cloud Infrastructure - Workloads; revenueTypeGroup=WORKLOAD; mês preservado.PASSCorreto.
sa-attach-window-sqlEvitar regressão no campo usado para filtro de close date.buildSaAttachOpportunityWhereClauses com janela 2026-03-01..2026-05-31.Usar Revenue Line Close Date, incluir forecast/owner e não usar Revenue Line Close Year.Campo correto usado; forecast/owner incluídos; Revenue Line Close Year ausente.PASSCorreto.
scope-sqlValidar regras de escopo org-wide e my-team nos SQLs gerados.renderViewSql para Presales Aux, Hours e srs-by-resource-email.Org-wide sem SEC_ARIA; my-team com SEC_ARIA; SR por recurso usa levels 1..4; lead só quando explícito.Regras confirmadas para org-wide, my-team, SR team e lead explícito.PASSCorreto.
current-team-summaryGarantir que oportunidades sem cobertura do time continuam no resultado misto.summarizeCurrentTeamOpportunityCoverage com 2 oportunidades e 1 cobertura.2 records; 1 matched; 1 unmatched; totais comerciais preservados.records=2; matched=1; unmatched=1; totalWorkload=125000.PASSCorreto.
manager-resource-summaryValidar resumo org-wide por manager/recurso e enriquecimento opcional com SRs.summarizeOrgWideRevenueLineCoverage com cobertura Aux e cenário com SR injetado.Recursos preservados; SR omitido por padrão; SR direto e candidato interno distinguidos quando injetados.defaultResourceDetails=2; SR omitido; linkage direct-plus-candidate-internal; resourcesMatched=2.PASSCorreto.
api-metricsConfirmar que métricas contam linhas brutas do backend, não cache local.buildApiMetrics com resultados de 3 + 2 linhas e uma leitura local.totalRowsPulledFromApi=5; cache local ignorado no total.totalRowsPulledFromApi=5; queries=3; cache local ignorado.PASSCorreto.
sales prompt commandsVerificar se prompts comuns viram comandos CLI curtos, diretos e documentados.Casos de tests/prompts/sales-prompts.json.Um modo por comando; sem discovery desnecessário; flags documentadas; intents citados nas referências.Todos os prompts seguiram o contrato esperado.PASSCorreto.
people examplesEvitar e-mails fake hard-coded nos prompts de teste.Serialização dos prompts e placeholders esperados.Usar placeholders como {{resourceManagerEmail}}, {{territoryOwnerEmail}} e {{resourceMember}}.Placeholders dinâmicos encontrados; e-mails fake padrão não apareceram.PASSCorreto.
intent CLI contractGarantir que comandos de intent batem com o contrato exposto pela própria CLI.--list-parameters e --describe-intent para intents usados nos prompts.Flags existem no catálogo global e no contrato do intent; defaults atuais documentados.Contratos bateram; defaults de workload atual e descrição do intent manager/resource validados.PASSCorreto.
ad-hoc-queryConfirmar que query ad hoc renderiza como leitura org-wide de oportunidades.--query --select opportunityId,customerName,closeDate,bookingValue,workloadAmount --where "closeDate = DATE '2026-05-02'" --render-sql.Modo query; escopo org-wide; fonte comercial primária; sem SEC_ARIA; aliases documentados.Query org-wide renderizada na fonte comercial primária, sem fallback para DV - SE Team.PASSCorreto.
+
+
+ +
+

Testes live

+

+ Estes testes confirmam execução real contra o Oracle DV com --no-cache. A tabela mostra os prompts + com placeholders, porque os e-mails reais são resolvidos dinamicamente durante a execução. +

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CasoPrompt executadoObjetivoComando validadoResultado esperadoÚltima saídaStatusEscopo
generic-pipelineMe traga o pipeline de oportunidades no Knowledge One View.Validar leitura genérica de pipeline.--intent opportunities-default --limit 1000Fonte comercial primária, org-wide, sem fallback, pelo menos 100 registros.records=1000; apiRows=1000.PASSKnowledge DV - Opportunities - V2; org-wide.
exact-close-dateQuais oportunidades fecham em 2026-05-02?Validar close date exato.--intent opportunities-close-date --date 2026-05-02 --limit 1000Fonte comercial primária, org-wide, sem fallback, pelo menos 1 registro.records=11; apiRows=11.PASSKnowledge DV - Opportunities - V2; org-wide.
calendar-monthQuais oportunidades fecham em abril de 2026?Validar janela de mês calendário.--intent opportunities-close-month --month 2026-04 --limit 1000Fonte comercial primária, org-wide, sem fallback, pelo menos 11 registros.records=1000; apiRows=1000.PASSKnowledge DV - Opportunities - V2; org-wide.
manager-weekQuais oportunidades do manager {{resourceManagerEmail}} fecham na week 43?Validar oportunidades por manager de recurso em uma week.--intent opportunities-by-manager-close-window --manager-email {{resourceManagerEmail}} --week w43 --week-year 2025 --limit 10Comercial org-wide com alocação via Presales Aux; sem fallback.records=10; apiRows=11.PASSOpportunities org-wide + Presales Involvement Aux org-wide.
owner-workload-currentMe mostre os workloads em forecast agora do vendedor {{territoryOwnerEmail}}.Validar workloads em forecast para vendedor.--intent workloads-by-owner-current --owner-email {{territoryOwnerEmail}} --forecast-type Forecast --limit 10Fonte comercial primária, org-wide, sem fallback.records=1; apiRows=1.PASSKnowledge DV - Opportunities - V2; org-wide.
owner-manager-workload-currentQuais workloads em forecast agora dos owners abaixo de {{territoryManagerEmail}}?Validar workloads para owners sob manager comercial.--intent workloads-by-owner-manager-current --owner-manager-email {{territoryManagerEmail}} --forecast-type Forecast --limit 10Fonte comercial primária, org-wide, sem fallback.records=9; apiRows=9.PASSKnowledge DV - Opportunities - V2; org-wide.
manager-resource-next-7-daysWorkloads com close date nos próximos 7 dias em oportunidades com recursos abaixo de {{resourceManagerEmailA}} e {{resourceManagerEmailB}}.Validar workloads próximos por managers de recurso.--intent workloads-by-manager-resource-close-window --manager-email-list {{resourceManagerEmailList}} --from-date today --to-date +7d --limit 10Comercial org-wide, alocação org-wide por Presales Aux, sem consultas a DV - SE Team.records=4; apiRows=15.PASSOpportunities org-wide + Presales Involvement Aux org-wide.
resource-srsQuais SRs estão com {{resourceMember}} agora?Validar busca de SRs por recurso.--intent srs-by-resource --resource {{resourceMember}} --limit 10Leitura em DV - SE Team, escopo my-team-only, array de records válido.records=0; apiRows=0.PASSDV - SE Team; my-team-only.
current-team-close-windowQuais oportunidades fecham nos próximos 4 dias e têm recursos do meu time?Validar oportunidades org-wide enriquecidas com recursos do time atual.--intent opportunities-current-team-close-window --from-date today --to-date +4d --limit 10Escopo mixed-consistent; oportunidades org-wide; recursos do time atual; linhas sem match preservadas.records=10; apiRows=12.PASSOpportunities org-wide + resources current team.
+
+
+ +
+
+

Como executar

+

+ Rode a partir de /Users/marceloarbore/.codex/skills/knowledge-one-view-cli. Nesta máquina, + o shell do agente usou o Node do runtime do Codex porque node não estava no PATH. +

+
+
node tests/run.mjs
+
KNOWLEDGE_ONE_VIEW_LIVE=1 \
+ORACLE_SI_RUNTIME_HOME=/Users/marceloarbore/code/fusion/knowledge-one-view-cli/runtime \
+node tests/run.mjs
+
/Users/marceloarbore/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/bin/node tests/run.mjs
+
+
+
+ + +
+
+
+ +
+
+ + +
+
+
+ node:test +

Qué valida la suite antes de confiar en los datos.

+

+ El modo offline prueba contratos, ruteo, SQL, alcance y transformaciones locales. El modo live confirma + que los comandos documentados siguen ejecutándose contra Oracle DV con la sesión actual. +

+
+
12/12

pruebas offline aprobadas

+
13/13

pruebas live aprobadas

+
0

fallas en la última ejecución

+
2026-04-26

fecha registrada

+
+
+
+ +
+

Metodología

+

+ Las pruebas usan node:test. Leen SKILL.md, references/script-catalog.md, + references/initial-context-catalog.md y references/api-map.md como fuente de verdad, + evitando duplicar parámetros y reglas dentro de la suite. +

+
+
+ Offline +

No llama a Oracle DV. Verifica que la CLI elija el camino correcto, arme filtros correctos y preserve el contrato de salida.

+
+
+ Live +

Llama a Oracle DV con --no-cache. El runtime de autenticación se copia a un área temporal de prueba.

+
+
+
+ +
+

Pruebas offline

+

+ Estas pruebas responden: "la skill arma la consulta y la respuesta correctas?". No prueban disponibilidad + de Oracle DV ni volumen real de datos. +

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PruebaObjetivoEntradaResultado esperadoSalida observadaStatusEvaluación
date-windowValidar atajos de fecha y rechazo de combinaciones inválidas.resolveDateWindow con --date, --month, --quarter, --week y conflicto.Rangos según catálogo y error para argumentos conflictivos.single=2026-05-02; month=2026-04-01..2026-04-30; quarter=2026-03-01..2026-05-31; week=2026-03-22..2026-03-28; inválido rechazado.PASSCorrecto.
sa-attach-defaultsConfirmar defaults y aliases de SA Attach desde el catálogo inicial.parseSaAttachDefaults, parseSaAttachAliases y resolveSaAttachFilters.Cluster, soluciones, status, LOBs, tipos de ingreso y aliases aplicados.cluster=Brazil; solutions=3; statuses=3; aliases validados.PASSCorrecto.
current-workload-defaultsVerificar los defaults de los intents de workload actual.applyCurrentWorkloadIntentDefaults para owner actual y mes explícito.current-quarter, Cloud Infrastructure - Workloads y WORKLOAD; mes explícito preservado.quarter=current-quarter; solution=Cloud Infrastructure - Workloads; revenueTypeGroup=WORKLOAD; mes preservado.PASSCorrecto.
sa-attach-window-sqlEvitar regresión en el campo usado para filtro de close date.buildSaAttachOpportunityWhereClauses con ventana 2026-03-01..2026-05-31.Usar Revenue Line Close Date, incluir forecast/owner y no usar Revenue Line Close Year.Campo correcto usado; forecast/owner incluidos; Revenue Line Close Year ausente.PASSCorrecto.
scope-sqlValidar reglas de alcance org-wide y my-team en SQL generado.renderViewSql para Presales Aux, Hours y srs-by-resource-email.Org-wide sin SEC_ARIA; my-team con SEC_ARIA; SR por recurso usa levels 1..4; lead solo si es explícito.Reglas confirmadas para org-wide, my-team, SR team y lead explícito.PASSCorrecto.
current-team-summaryGarantizar que oportunidades sin cobertura del equipo continúan en el resultado mixto.summarizeCurrentTeamOpportunityCoverage con 2 oportunidades y 1 cobertura.2 records; 1 matched; 1 unmatched; totales comerciales preservados.records=2; matched=1; unmatched=1; totalWorkload=125000.PASSCorrecto.
manager-resource-summaryValidar resumen org-wide por manager/recurso y enriquecimiento opcional con SRs.summarizeOrgWideRevenueLineCoverage con cobertura Aux y escenario con SR inyectado.Recursos preservados; SR omitido por defecto; SR directo y candidato interno distinguidos cuando se inyectan.defaultResourceDetails=2; SR omitido; linkage direct-plus-candidate-internal; resourcesMatched=2.PASSCorrecto.
api-metricsConfirmar que métricas cuentan filas brutas del backend, no cache local.buildApiMetrics con resultados de 3 + 2 filas y una lectura local.totalRowsPulledFromApi=5; cache local ignorado en el total.totalRowsPulledFromApi=5; queries=3; cache local ignorado.PASSCorrecto.
sales prompt commandsVerificar si prompts comunes se convierten en comandos CLI cortos, directos y documentados.Casos de tests/prompts/sales-prompts.json.Un modo por comando; sin discovery innecesario; flags documentadas; intents citados en referencias.Todos los prompts siguieron el contrato esperado.PASSCorrecto.
people examplesEvitar e-mails fake hard-coded en los prompts de prueba.Serialización de prompts y placeholders esperados.Usar placeholders como {{resourceManagerEmail}}, {{territoryOwnerEmail}} y {{resourceMember}}.Placeholders dinámicos encontrados; e-mails fake estándar no aparecieron.PASSCorrecto.
intent CLI contractGarantizar que comandos de intent coinciden con el contrato expuesto por la CLI.--list-parameters y --describe-intent para intents usados en prompts.Flags existen en el catálogo global y en el contrato del intent; defaults actuales documentados.Contratos coinciden; defaults de workload actual y descripción del intent manager/resource validados.PASSCorrecto.
ad-hoc-queryConfirmar que query ad hoc renderiza como lectura org-wide de oportunidades.--query --select opportunityId,customerName,closeDate,bookingValue,workloadAmount --where "closeDate = DATE '2026-05-02'" --render-sql.Modo query; alcance org-wide; fuente comercial primaria; sin SEC_ARIA; aliases documentados.Query org-wide renderizada en la fuente comercial primaria, sin fallback a DV - SE Team.PASSCorrecto.
+
+
+ +
+

Pruebas live

+

+ Estas pruebas confirman ejecución real contra Oracle DV con --no-cache. La tabla muestra los prompts + con placeholders porque los e-mails reales se resuelven dinámicamente durante la ejecución. +

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CasoPrompt ejecutadoObjetivoComando validadoResultado esperadoÚltima salidaStatusAlcance
generic-pipelineMe traga o pipeline de oportunidades no Knowledge One View.Validar lectura genérica de pipeline.--intent opportunities-default --limit 1000Fuente comercial primaria, org-wide, sin fallback, al menos 100 registros.records=1000; apiRows=1000.PASSKnowledge DV - Opportunities - V2; org-wide.
exact-close-dateQuais oportunidades fecham em 2026-05-02?Validar close date exacto.--intent opportunities-close-date --date 2026-05-02 --limit 1000Fuente comercial primaria, org-wide, sin fallback, al menos 1 registro.records=11; apiRows=11.PASSKnowledge DV - Opportunities - V2; org-wide.
calendar-monthQuais oportunidades fecham em abril de 2026?Validar ventana de mes calendario.--intent opportunities-close-month --month 2026-04 --limit 1000Fuente comercial primaria, org-wide, sin fallback, al menos 11 registros.records=1000; apiRows=1000.PASSKnowledge DV - Opportunities - V2; org-wide.
manager-weekQuais oportunidades do manager {{resourceManagerEmail}} fecham na week 43?Validar oportunidades por manager de recurso en una week.--intent opportunities-by-manager-close-window --manager-email {{resourceManagerEmail}} --week w43 --week-year 2025 --limit 10Comercial org-wide con asignación por Presales Aux; sin fallback.records=10; apiRows=11.PASSOpportunities org-wide + Presales Involvement Aux org-wide.
owner-workload-currentMe mostre os workloads em forecast agora do vendedor {{territoryOwnerEmail}}.Validar workloads en forecast para vendedor.--intent workloads-by-owner-current --owner-email {{territoryOwnerEmail}} --forecast-type Forecast --limit 10Fuente comercial primaria, org-wide, sin fallback.records=1; apiRows=1.PASSKnowledge DV - Opportunities - V2; org-wide.
owner-manager-workload-currentQuais workloads em forecast agora dos owners abaixo de {{territoryManagerEmail}}?Validar workloads para owners bajo manager comercial.--intent workloads-by-owner-manager-current --owner-manager-email {{territoryManagerEmail}} --forecast-type Forecast --limit 10Fuente comercial primaria, org-wide, sin fallback.records=9; apiRows=9.PASSKnowledge DV - Opportunities - V2; org-wide.
manager-resource-next-7-daysWorkloads com close date nos próximos 7 dias em oportunidades com recursos abaixo de {{resourceManagerEmailA}} e {{resourceManagerEmailB}}.Validar workloads próximos por managers de recurso.--intent workloads-by-manager-resource-close-window --manager-email-list {{resourceManagerEmailList}} --from-date today --to-date +7d --limit 10Comercial org-wide, asignación org-wide por Presales Aux, sin consultas a DV - SE Team.records=4; apiRows=15.PASSOpportunities org-wide + Presales Involvement Aux org-wide.
resource-srsQuais SRs estão com {{resourceMember}} agora?Validar búsqueda de SRs por recurso.--intent srs-by-resource --resource {{resourceMember}} --limit 10Lectura en DV - SE Team, alcance my-team-only, array de records válido.records=0; apiRows=0.PASSDV - SE Team; my-team-only.
current-team-close-windowQuais oportunidades fecham nos próximos 4 dias e têm recursos do meu time?Validar oportunidades org-wide enriquecidas con recursos del equipo actual.--intent opportunities-current-team-close-window --from-date today --to-date +4d --limit 10Alcance mixed-consistent; oportunidades org-wide; recursos del equipo actual; filas sin match preservadas.records=10; apiRows=12.PASSOpportunities org-wide + resources current team.
+
+
+ +
+
+

Cómo ejecutar

+

+ Ejecutar desde /Users/marceloarbore/.codex/skills/knowledge-one-view-cli. En esta máquina, + el shell del agente usó Node del runtime de Codex porque node no estaba en el PATH. +

+
+
node tests/run.mjs
+
KNOWLEDGE_ONE_VIEW_LIVE=1 \
+ORACLE_SI_RUNTIME_HOME=/Users/marceloarbore/code/fusion/knowledge-one-view-cli/runtime \
+node tests/run.mjs
+
/Users/marceloarbore/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/bin/node tests/run.mjs
+
+
+
+ + +
+
+
+ + + + diff --git a/portable-setup.md b/portable-setup.md new file mode 100644 index 0000000..bc25d13 --- /dev/null +++ b/portable-setup.md @@ -0,0 +1,106 @@ +# Portable Setup + +Use this flow when moving the skill to another computer. + +## What to copy + +- Copy the full `knowledge-one-view-cli` skill folder into the target Codex `skills` directory. + +## What does not matter + +- The workspace name does not need to be `fusion`. +- The workspace may be empty. + +## First run on the new computer + +When Codex invokes the skill from the agent workspace, no extra path flag is needed. + +Browser helper note: + +- `scripts/refresh-auth-state.mjs` now tries browser automation in this order: + - local module resolution for `playwright` or `playwright-core` + - shared runtime at `~/.codex/skills/playwright` + - bundled Codex runtimes such as `~/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules` +- In a normal Codex desktop installation, this means the browser helper should usually work on a new machine even if `~/.codex/skills/playwright` was not copied over. +- If you use the skill outside Codex and none of those runtimes exist, install a shared Playwright runtime under `~/.codex/skills/playwright`. + +If you want to test manually from outside the workspace, point `--runtime-home` back to the target workspace runtime: + +```powershell +node /path/to/.codex/skills/knowledge-one-view-cli/scripts/refresh-auth-direct.mjs ` + --runtime-home ./knowledge-one-view-cli/runtime ` + --username +``` + +This creates the runtime state inside the workspace-side skill folder: + +- `knowledge-one-view-cli/runtime/auth-state.json` +- `knowledge-one-view-cli/runtime/session-meta.json` +- `knowledge-one-view-cli/runtime/chrome-profile/` + +## Bootstrap rule + +The first test run in a new workspace must bootstrap the full workspace-side tree, even if the workspace starts empty. + +Expected workspace-side structure: + +- `knowledge-one-view-cli/output/` +- `knowledge-one-view-cli/tmp/` (todos os temporarios e intermediarios diretamente aqui, sem subpastas obrigatorias) +- `knowledge-one-view-cli/runtime/` +- `knowledge-one-view-cli/runtime/chrome-profile/` + +Notes: + +- permanent test definitions stay in the installed skill under `.../knowledge-one-view-cli/tests/` +- run outputs, diffs, temporary inputs, rendered SQL and runtime state stay in the workspace-side `knowledge-one-view-cli/` folder +- the bootstrap runner also writes the first run bundle under `output/` + +Example bootstrap test run: + +```powershell +node /path/to/.codex/skills/knowledge-one-view-cli/tests/run-systemic-suite.mjs ` + --bootstrap-only ` + --workspace-root . +``` + +If you launch the command from inside the workspace-side `knowledge-one-view-cli/` folder instead of the workspace root, the skill now normalizes that location back to the real workspace root automatically, so it will not create `knowledge-one-view-cli/knowledge-one-view-cli/...`. + +Recommended post-migration smoke: + +```powershell +node /path/to/.codex/skills/knowledge-one-view-cli/tests/run-post-migration-smoke.mjs ` + --workspace-root . +``` + +This smoke runner does the standard migration validation flow: + +- bootstraps the workspace-side tree +- validates the Oracle session with `--check-auth` +- runs a real Brazil workload sample for `current-quarter` +- writes the sample JSON into `knowledge-one-view-cli/output/post-migration-workload-sample.json` +- writes the run bundle into `knowledge-one-view-cli/output/test-runs//` + +## Daily use + +```powershell +node /path/to/.codex/skills/knowledge-one-view-cli/scripts/fetch-sales-intelligence.mjs ` + --runtime-home ./knowledge-one-view-cli/runtime ` + --intent opportunities-default ` + --limit 200 +``` + +When running directly from the workspace-side `knowledge-one-view-cli/` folder, the default path inference now keeps outputs in `./output/`, `./tmp/` and `./runtime/` under that folder instead of creating a second nested `knowledge-one-view-cli/`. + +## Optional development helper + +If direct auth is blocked or you need to refresh workbook/browser tracing, use: + +```powershell +node /path/to/.codex/skills/knowledge-one-view-cli/scripts/refresh-auth-state.mjs ` + --runtime-home ./knowledge-one-view-cli/runtime +``` + +## Related references + +- `docs/docs.html` +- `references/script-catalog.md` diff --git a/references/api-map.md b/references/api-map.md new file mode 100644 index 0000000..bf9e418 --- /dev/null +++ b/references/api-map.md @@ -0,0 +1,514 @@ +# Knowledge-One-View-CLI API Map + +Read this file when Oracle DV behavior changes, a workbook tab must be retraced, or you need traced endpoint and default-filter details that are too low-level for the main skill guide. + +## Quick Navigation + +- Workbook identity: [Traced Workbook](#traced-workbook) +- Required auth/session state: [Required Session Inputs](#required-session-inputs) +- Direct and fallback endpoints: [Traced Endpoints](#traced-endpoints) +- Local metadata and field shortcuts: [Fast Local Metadata](#fast-local-metadata) +- Common query patterns: [Fast Query Patterns](#fast-query-patterns) +- Traced workbook-tab defaults: [Traced Tab Defaults](#traced-tab-defaults) + +## Traced Workbook + +- Workbook URL: + `https://salesintelligence-dv.oracle.com/ui/dv/ui/project.jsp?pageid=visualAnalyzer&reportmode=presentation&reportpath=%2F%40Catalog%2Fshared%2FTeam%20Sharing%20Area%2FLAD%2FLAD%20Sales%20Operations%2FLAD%20Production%2FLAD%20Knowledge%20One%20View` +- Platform: + Oracle Analytics / Oracle DV +- Primary commercial subject area: + `XSA('ANNA.DE.MAURO@ORACLE.COM'.'Knowledge DV - Opportunities - V2')` + +Keep the `ANNA.DE.MAURO@ORACLE.COM` token exactly as traced in XSA dataset references. It is part of the logical dataset identifier, not a disposable example. + +## Required Session Inputs + +The direct API calls worked with: + +- Cookies from Playwright `storageState` +- `authorization: session` +- `x-csrf-token` +- `x-bitech-clientbin` +- `x-requested-with: XMLHttpRequest` +- Workbook `referer` + +`x-bitech-clientbin` also appears in the workbook bootstrap HTML inside static asset paths such as: + +`/static/dv/oracle-jet-bundles/18.1.2.fd48e9d8895d/...` + +The refresh helper writes both the cookies and these request headers to disk: + +- `auth-state.json` +- `session-meta.json` + +The fetch script also persists refreshed cookies plus updated CSRF/clientbin metadata back to those files after a session restore so later runs reuse the corrected backend state. +When the saved files are missing or Oracle redirects a normal fetch call back to sign-in, the fetch script can now invoke the browser refresh helper automatically, then reload the session artifacts and retry the backend request. +That makes the runtime/session path parameters operationally important, not just convenience flags. + +## Traced Endpoints + +### Preferred Direct Endpoint + +- `POST /ui/dv/ui/api/v1/sqlquery/execute` + Use for custom Oracle logical SQL and for the reusable `opportunity-details` and `sr-details` views in this skill. + Body shape: + +```json +{ + "aQueryInfos": [ + { + "sQuery": "SELECT valueof(RV_CURR_FISCAL_YEAR) FROM \"DV - SE Team\"", + "nResultsLimit": 1 + } + ], + "bUseCache": true +} +``` + + Response shape: + +```json +{ + "aQueriesResults": [ + { + "eStatus": "FINISHED", + "aColumnTypes": ["varchar"], + "aResults": [["FY26"]] + } + ] +} +``` + +### Metadata / Bootstrap Endpoints + +- `POST /ui/dv/ui/api/v1/modelmetadata/reportdatasetsmetadatajson` + Traced from `Data Quality`. Useful when Oracle changes dataset metadata or a new workbook view must be reconstructed. +- `POST /ui/dv/ui/api/v1/infer/activities` + Telemetry only. Ignore for data retrieval. +- `GET /ui/dv/ui/api/v3/items-content` + Static workbook assets such as images. Ignore for data retrieval. + +### Workbook Rendering Endpoints + +- `POST /ui/dv/ui/api/v2/data/executeOrPoll` +- `POST /ui/dv/ui/api/v2/data/poll` + +These drive the rendered workbook tabs. They are useful as fallback references because the POST payloads contain the exact traced columns and default filters, but they are noisier than `sqlquery/execute`. + +## Fast Local Metadata + +The skill now keeps a local field catalog inside `scripts/fetch-sales-intelligence.mjs` for the most common logical fields, so repeated asks do not need rediscovery. Use: + +- `--catalog` +- `--list-intents` +- `--describe-intent srs-by-resource` +- `--list-fields` +- `--list-fields --entity Opportunity` +- `--list-fields --role filter` +- `--describe-field closeDate` + +Use the intent shortcuts first for the recurring asks that previously caused parameter guesswork: + +- `opportunities-close-date` + Uses `--date` +- `opportunities-close-month` + Uses `--month` +- `srs-by-resource` + Uses `--resource` + +For ad hoc SQL, prefer template placeholders over raw Oracle expressions: + +- `{{opportunityId}}` +- `{{closeDate}}` +- `{{bookingValue}}` +- `{{workloadAmount}}` +- `{{subjectArea}}` +- `{{securityEntryPointFilter}}` + +Render those placeholders locally without a backend call: + +```powershell +node .\scripts\fetch-sales-intelligence.mjs ` + --render-sql ` + --sql "SELECT {{opportunityId}}, {{closeDate}} FROM {{subjectArea}} WHERE {{securityEntryPointFilter}}" +``` + +For most ad hoc retrieval, prefer declarative query mode over raw SQL: + +```powershell +node .\scripts\fetch-sales-intelligence.mjs ` + --query ` + --select opportunityId,opportunityName,closeDate,bookingValue,workloadAmount ` + --where "closeDate = DATE '2026-05-02'" +``` + +Query mode infers the safest source from the selected aliases. Commercial opportunity, revenue-line, hours, and presales-coverage aliases use org-wide-capable XSA sources in `--scope auto`; SR and session aliases remain on `DV - SE Team`, which is my-team-only. + +Important known fields: + +- `closeDate` + `"Opportunity"."Close Date"` + Use direct date literals: `DATE '2026-03-27'` +- `opportunityId` + `"Opportunity"."Opportunity ID"` +- `opportunityName` + `"Opportunity"."Opportunity Name"` +- `opportunityStatus` + `"Opportunity"."Status"` +- `customerName` + `"Customer"."Customer Name"` +- `salesStage` + `"Opportunity"."Sales Stage"` +- `opportunityValue` + `"Opportunity"."Opportunity Value"` +- `bookingValue` + `"Opportunity"."Opportunity Value"` + Preferred alias when the intent is to compare booking against `workloadAmount`. +- `workloadAmount` + `"Opportunity"."Workload Amount"` +- `optyCloseFiscalYear` + `"Time (Close Date Opportunity)"."Opty Close Fiscal Year"` +- `srNumber` + `"Service Request"."SR Number"` +- `srStatus` + `"Service Request"."Status"` +- `srTeamLevel1EmailAddress` + `"SR Team"."SE Team Level 1 Email Address"` +- `srTeamLevel2EmailAddress` + `"SR Team"."SE Team Level 2 Email Address"` +- `srTeamLevel3EmailAddress` + `"SR Team"."SE Team Level 3 Email Address"` +- `srTeamLevel4EmailAddress` + `"SR Team"."SE Team Level 4 Email Address"` +- `leadEmail` + `"Service Request"."Lead Email"` + Use only when the intent is explicitly to query the SR leader. + +## Fast Query Patterns + +### Ad Hoc SQL Without Oracle Expression Guesswork + +Use the local placeholder expansion: + +```powershell +node .\scripts\fetch-sales-intelligence.mjs ` + --sql "SELECT {{opportunityId}}, {{opportunityName}}, {{closeDate}}, {{bookingValue}}, {{workloadAmount}} FROM {{subjectArea}} WHERE {{securityEntryPointFilter}} AND {{closeDate}} = DATE '2026-05-02'" +``` + +The script expands that locally to Oracle logical SQL before execution. +When the `SELECT` list is simple enough, the script also infers output column names and returns object-shaped `records` instead of only raw row arrays. Explicit `AS` aliases are respected. + +### Declarative Query Mode + +Use query mode when the ask is naturally "fields + filter + grouping + ordering": + +```powershell +node .\scripts\fetch-sales-intelligence.mjs ` + --query ` + --select opportunityId ` + --measure sum:bookingValue:totalBooking,sum:workloadAmount:totalWorkload ` + --where "closeDate = DATE '2026-05-02'" ` + --group-by opportunityId ` + --order-by totalBooking:desc +``` + +Query mode reduces guesswork by: + +- inferring the configured source automatically from the selected aliases +- using org-wide XSA sources first for commercial aliases in `--scope auto` +- injecting the standard team-security filter only when the selected source requires it or when `--scope my-team` is explicitly requested on an org-wide-capable source +- accepting field aliases directly inside `--select` and `--where` +- supporting aggregate specs like `sum:bookingValue:totalBooking` +- returning object-shaped records with stable output columns + +### Backend Scope Reality + +Use this when deciding whether a request can be answered org-wide or must be disclosed as current-team only: + +- `Knowledge DV - Opportunities - V2`, `Knowledge DV - Hours - V2`, `Knowledge DV - Presales Involvement Aux - V1`, and `Knowledge DV - Revn Lines by SE` are treated as org-wide-capable XSA datasets by the skill. In `--scope auto`, the script avoids the current-team security predicate unless the chosen view or intent explicitly needs it. +- `--scope my-team` on an org-wide-capable source intentionally adds the current-team predicate so the same dataset can be used for a narrower current-team read. +- `DV - SE Team` is effectively my-team-only for this skill. Use it for SRs, session context, and fields that have no org-wide source. Do not use it as a generic org-wide commercial fallback. +- For mixed outputs, prefer `scope.components` and `scope.disclosureLines` over a single label because one component may be org-wide while another remains my-team-only. + +### Opportunities By Close-Date Window + +Use the built-in intent or built-in view instead of rewriting SQL: + +Exact date: + +```powershell +node .\scripts\fetch-sales-intelligence.mjs ` + --intent opportunities-close-date ` + --date 2026-05-02 +``` + +Calendar month: + +```powershell +node .\scripts\fetch-sales-intelligence.mjs ` + --intent opportunities-close-month ` + --month 2026-04 +``` + +Explicit window: + +```powershell +node .\scripts\fetch-sales-intelligence.mjs ` + --view opportunities-close-window ` + --from-date today ` + --to-date +7d +``` + +Primary logical SQL pattern: + +```sql +SELECT + XSA('ANNA.DE.MAURO@ORACLE.COM'.'Knowledge DV - Opportunities - V2')."Columns"."Opportunity ID", + XSA('ANNA.DE.MAURO@ORACLE.COM'.'Knowledge DV - Opportunities - V2')."Columns"."Opportunity Name", + XSA('ANNA.DE.MAURO@ORACLE.COM'.'Knowledge DV - Opportunities - V2')."Columns"."Customer Name (Original)", + XSA('ANNA.DE.MAURO@ORACLE.COM'.'Knowledge DV - Opportunities - V2')."Columns"."Opportunity Status", + XSA('ANNA.DE.MAURO@ORACLE.COM'.'Knowledge DV - Opportunities - V2')."Columns"."Close Date", + XSA('ANNA.DE.MAURO@ORACLE.COM'.'Knowledge DV - Opportunities - V2')."Columns"."Sales Stage", + MAX(XSA('ANNA.DE.MAURO@ORACLE.COM'.'Knowledge DV - Opportunities - V2')."Columns"."Pipeline") AS bookingValue, + MAX(XSA('ANNA.DE.MAURO@ORACLE.COM'.'Knowledge DV - Opportunities - V2')."Columns"."Pipeline") AS workloadAmount +FROM XSA('ANNA.DE.MAURO@ORACLE.COM'.'Knowledge DV - Opportunities - V2') +WHERE XSA('ANNA.DE.MAURO@ORACLE.COM'.'Knowledge DV - Opportunities - V2')."Columns"."Close Date" >= DATE '2026-03-27' + AND XSA('ANNA.DE.MAURO@ORACLE.COM'.'Knowledge DV - Opportunities - V2')."Columns"."Close Date" <= DATE '2026-04-03' +GROUP BY + XSA('ANNA.DE.MAURO@ORACLE.COM'.'Knowledge DV - Opportunities - V2')."Columns"."Opportunity ID", + XSA('ANNA.DE.MAURO@ORACLE.COM'.'Knowledge DV - Opportunities - V2')."Columns"."Opportunity Name", + XSA('ANNA.DE.MAURO@ORACLE.COM'.'Knowledge DV - Opportunities - V2')."Columns"."Customer Name (Original)", + XSA('ANNA.DE.MAURO@ORACLE.COM'.'Knowledge DV - Opportunities - V2')."Columns"."Opportunity Status", + XSA('ANNA.DE.MAURO@ORACLE.COM'.'Knowledge DV - Opportunities - V2')."Columns"."Close Date", + XSA('ANNA.DE.MAURO@ORACLE.COM'.'Knowledge DV - Opportunities - V2')."Columns"."Sales Stage" +ORDER BY 5, 1 +``` + +Fallback behavior: + +- if the ask is explicitly about the current user's team and the primary XSA query fails, the skill may rerun the commercial read against `DV - SE Team` +- generic org-wide commercial reads stay on `Knowledge DV - Opportunities - V2` and do not fall back to `DV - SE Team` + +In the built-in `opportunities-close-window` view, the last two fields are returned from the org-wide XSA `Pipeline` column: + +- `bookingValue` -> `Knowledge DV - Opportunities - V2` / `"Columns"."Pipeline"` +- `workloadAmount` -> `Knowledge DV - Opportunities - V2` / `"Columns"."Pipeline"` + +The `bookingValue` and `workloadAmount` names are preserved for user-facing compatibility with opportunity and workload reports. For org-wide query-mode reads from `Knowledge DV - Opportunities - V2`, prefer the same `Pipeline` backing field because direct row-level reads of `"Opportunity Value"` and `"Workload Amount"` can fail in Oracle DV. + +### SRs By Resource Email + +Use the built-in intent or built-in view instead of writing custom SQL: + +Shortest path: + +```powershell +node .\scripts\fetch-sales-intelligence.mjs ` + --intent srs-by-resource ` + --resource resource.member +``` + +Equivalent direct view call: + +```powershell +node .\scripts\fetch-sales-intelligence.mjs ` + --view srs-by-resource-email ` + --resource resource.member +``` + +Default matching rule: + +```sql +( + "SR Team"."SE Team Level 1 Email Address" = 'resource.member@oracle.com' + OR "SR Team"."SE Team Level 2 Email Address" = 'resource.member@oracle.com' + OR "SR Team"."SE Team Level 3 Email Address" = 'resource.member@oracle.com' + OR "SR Team"."SE Team Level 4 Email Address" = 'resource.member@oracle.com' +) +``` + +Only use lead matching when the ask is explicitly about the leader: + +```powershell +node .\scripts\fetch-sales-intelligence.mjs ` + --view srs-by-resource-email ` + --resource-email resource.member@oracle.com ` + --match-role lead +``` + +The built-in `srs-by-resource-email` view also returns: + +- `bookingValue` -> `"Opportunity"."Opportunity Value"` +- `workloadAmount` -> `"Opportunity"."Workload Amount"` + +The CLI now normalizes Oracle date strings in built-in output, so values such as `02-MAY-26` are returned as `2026-05-02`. + +## Traced Tab Defaults + +### Opportunity Details + +- Current canvas: + `canvas!4` +- Plugin: + `oracle.bi.tech.table` +- Default filters: + - `Security.Entry Point in VALUEOF(NQ_SESSION."SEC_ARIA_SI-SR-TEAM")` + - `Opty Close Fiscal Year = current FY` + - `Opportunity Status in (Open, Won, Won Pending)` + - `SE Team Active Flag = Y` + - `SE Team Manager Flag = N` + - `SR Source = Opportunity` +- Important columns: + - `Opportunity ID` + - `# Opportunity Hours` + - `Status` + - `Workload Amount` + - `Registry ID` + - `Customer Name` + - `Deal Qualification` + - `Forecast Type Group` + - `Opportunity Value` + - `Current FY Opp Hours` + - `Total Opportunity Hours` + - `Opty Close Fiscal Quarter` + - `# SEs With Effort` + - `# Service Requests with Effort` + - `Country` + - `Sales Stage` + - `Revenue Type Group` + - `LOB Type` + - `All Products` + - `Opportunity Name` + - `All Workloads` + - `Covered Flag` + - `All Implementers` + - `Win Probability` + +### SR Details + +- Current canvas: + `canvas!5` +- Plugin: + `oracle.bi.tech.table` +- Default filters: + - `Security.Entry Point in VALUEOF(NQ_SESSION."SEC_ARIA_SI-SR-TEAM")` + - `Opty Close Fiscal Year = current FY` + - `Opportunity Status = Open` + - `SE Team Active Flag = Y` + - `SE Team Manager Flag = N` +- Important columns: + - `SR Number` + - `Parent SR Number` + - `Service Request Status` + - `Title` + - `Queue Name` + - `Country` + - `Registry ID` + - `Customer Name` + - `SR Source` + - `Opportunity ID` + - `Opportunity Name` + - `Opportunity Status` + - `Win Probability` + - `Primary Pillar` + - `Opportunity Value` + - `Workload Amount` + - `Total SR Hours` + - `Lead Email` + - `SR Requester Email Address` + - `Create SR Day` + - `Close SR Day` + - `Customer Deadline` + - `Internal Deadline` + - `Last Effort` + - `# Service Requests with Effort` + - `# SEs With Effort` + - `# Hours (Excl. Time Off)` + - `Service Description` + +Current limitation: + +- `Parent SR Number` is visible in traced workbook metadata, but the direct logical SQL path used by the CLI still fails when selecting it explicitly. +- Because of that, current internal-SR reconciliation in the skill uses a safe fallback: confirmed joins stay based on `Opportunity ID`, and additional internal-SR candidates are inferred only when the same resource has SRs for the same customer without a usable `Opportunity ID`. + +### Data Quality + +The `Data Quality` tab used: + +- `POST /ui/dv/ui/api/v1/sqlquery/execute` +- `POST /ui/dv/ui/api/v1/modelmetadata/reportdatasetsmetadatajson` + +That trace confirms the workbook can be queried directly through Oracle logical SQL without rendering the visualization. + +### Commercial Opportunity Datasets + +- Current canvas: + `canvas!15` +- Traced endpoints: + - `POST /ui/dv/ui/api/v2/data/executeOrPoll` + - `POST /ui/dv/ui/api/v2/modelmetadata/subjectareas` + - `POST /ui/dv/ui/api/v2/metadata/interactionpaths` + - `POST /ui/dv/ui/api/v1/dataset/datasets/metadata` + - `POST /ui/dv/ui/api/v1/modelmetadata/reportdatasetsmetadatajson` +- Traced workbook sources: + - `XSA('ANNA.DE.MAURO@ORACLE.COM'.'Knowledge DV - Opportunities - V2')` + - `XSA('ANNA.DE.MAURO@ORACLE.COM'.'Knowledge DV - Hours - V2')` + - `XSA('ANNA.DE.MAURO@ORACLE.COM'.'Knowledge DV - Presales Involvement Aux - V1')` + - `XSA('ANNA.DE.MAURO@ORACLE.COM'.'Knowledge DV - Revn Lines by SE')` +- Observed metadata lookup: + - `XSA('ANNA.DE.MAURO@ORACLE.COM'.'One View Tech - Usage Information')` + +The first traced SA Attach visuals used `Knowledge DV - Opportunities - V2` as the active subject area and exposed these traced defaults: + +- Recommended default for generic opportunity retrieval: + `--intent opportunities-default` +- `Cluster = Brazil` +- `Solution in ('Cloud Infrastructure - Workloads', 'Hardware - Bookings', 'On-Premise Technology - Bookings')` +- `Sales Credit Type = QUOTA` +- `Executive Product LOB in ('Cloud Infrastructure', 'Hardware', 'License')` +- `Revenue Type Group in ('NEW', 'EXPANSION', 'WORKLOAD')` +- Current skill default: `Opportunity Probability >= 0` +- Older workbook traces sometimes showed `Opportunity Probability >= 40` +- `Revenue Line Status = Open` for the open-pipeline visuals +- `Revenue Line Status in ('Won', 'Won Pending')` for the won-pipeline visual +- Open rows are allowed in any close year, while won rows are constrained to previous/current fiscal year +- Compatibility note: + older traces may still mention `License and Hardware` or `WORKLOADS`; the skill now normalizes those aliases to the backend values `License` + `Hardware` and `WORKLOAD`. + +Traced view mappings: + +- `view!1597` + `oracle.bi.tech.ngperformancetile` + Open pipeline tile based on `SUM(Pipeline)` from `Knowledge DV - Opportunities - V2` +- `view!1612` + `oracle.bi.tech.ngperformancetile` + Won pipeline tile based on `SUM(Pipeline)` from `Knowledge DV - Opportunities - V2` +- `view!1602` + `oracle.bi.tech.chart.stackbar100` + Involvement distribution chart based on `Pipeline`, `Revenue Line Probability`, `Presales Involvement Flag`, and `Opportunity Hours Attribute` + +The traced involvement bucket logic is: + +```sql +CASE + WHEN SUM( + CASE WHEN + THEN "Opportunity Hours Attribute" + END BY "Opportunity ID" + ) > 0 + THEN '1. My Team Involvement' + WHEN "Presales Involvement Flag" = 'Y' + THEN '2. Other Presales Involvement' + ELSE '3. No Presales Involvement' +END +``` + +Current skill coverage now maps that tab through these direct views: + +- `sa-attach-pipeline-details` +- `sa-attach-open-pipeline` +- `sa-attach-won-pipeline` +- `sa-attach-involvement-distribution` +- `sa-attach-hours-by-opportunity` +- `sa-attach-presales-coverage` diff --git a/references/initial-context-catalog.md b/references/initial-context-catalog.md new file mode 100644 index 0000000..84ea880 --- /dev/null +++ b/references/initial-context-catalog.md @@ -0,0 +1,83 @@ +# Initial Context Catalog + +Read this file at skill load time when the ask is about managers, hierarchy, architect productivity, team rollups, or when you need quick business context before touching the CLI catalog. This is a curated seed catalog for fast execution, not a replacement for `fetch-sales-intelligence.mjs --catalog`. + +Use this file for org and business-context interpretation. Skip it for routine close-date, SR-by-person, or generic opportunity asks that already map directly to an intent or built-in view. + +## Quick Navigation + +- Why this file exists: [Why This Exists](#why-this-exists) +- Hierarchy heuristics: [Hierarchy Shortcuts](#hierarchy-shortcuts) +- Verified manager anchors: [Verified Org Anchors](#verified-org-anchors) +- Reusable business translations: [Query Translation Shortcuts](#query-translation-shortcuts) +- SA Attach filters and anchors: [SA Attach Quick Map](#sa-attach-quick-map) +- Final guardrails: [Practical Rules](#practical-rules) + +## Why This Exists + +- The script catalog is best for CLI and field-contract discovery. +- This file is best for front-loading org or hierarchy context, query translation heuristics, and recurring business shortcuts. +- Use this first when the user already gave a manager name, an email, or wording such as `top architects`, `time do manager`, `produtividade`, `booking/workload por arquiteto`, or `deals WON`. + +## Hierarchy Shortcuts + +- For SA Attach productivity-style asks, the working source of truth is usually `Knowledge DV - Hours - V2`. +- In that dataset, the most useful working assumption is: + - `SE Team Level 3 Email Address` -> manager scope anchor for many manager-rollup asks. + - `SE Team Level 4 Email Address` -> direct manager under the level-3 manager. + - `SE Team Level 5 Email Address` -> architect or IC email for per-person productivity rollups. + - `SE Team Level 6..8 Email Address` -> often repeats the same IC email. Do not sum across those levels as separate people. +- Do not assume `Security.Entry Point = ` reproduces the org hierarchy you need. In practice, the entry point can differ from the visible manager email and may return no rows for a valid manager. +- For manager-scoped productivity asks, the fastest stable pattern is: + 1. Filter `Knowledge DV - Hours - V2` by the manager email at the matching hierarchy level. + 2. Aggregate hours by `SE Team Level 5 Email Address`. + 3. Join or intersect with `Knowledge DV - Opportunities - V2` on `Opportunity ID` to apply `Close Date`, `Status`, `Opportunity Value`, `Workload Amount`, territory, and owner context. + +## SA Attach Quick Map + +- Hierarchy fields: `SE Team Level 3 Email Address` = manager anchor; `SE Team Level 4 Email Address` = direct manager; `SE Team Level 5 Email Address` = architect/IC. +- SA Attach params: `--cluster`, `--solution`, `--revenue-line-status`, `--executive-product-lob`, `--revenue-type-group`, `--sales-credit-type`, `--min-opportunity-probability`. +- SA Attach defaults: `--cluster=Brazil`; `--solution=Cloud Infrastructure - Workloads,Hardware - Bookings,On-Premise Technology - Bookings`; `--revenue-line-status=Open,Won,Won Pending`; `--executive-product-lob=Cloud Infrastructure,Hardware,License`; `--revenue-type-group=NEW,EXPANSION,WORKLOAD`; `--sales-credit-type=QUOTA`; `--min-opportunity-probability=0`. +- SA Attach aliases: `cloud applications` -> `Cloud Applications`; `cloud infrastructure` -> `Cloud Infrastructure`; `hardware` -> `Hardware`; `license` -> `License`; `license and hardware` -> `License,Hardware`; `new` -> `NEW`; `expansion` -> `EXPANSION`; `workload|workloads` -> `WORKLOAD`. + +## Verified Org Anchors + +Last verified during a live run on `2026-03-27`. + +### Higher-level anchors + +| Level | Email | Notes | +|---|---|---| +| L1 | `luiz.meisler@oracle.com` | Executive-level anchor seen in SA Attach hours hierarchy. | +| L2 | `marcelo.christianini@oracle.com` | Next-level org anchor above multiple manager branches. | + +Keep this section intentionally small. Only verified hierarchy anchors that materially shortcut discovery should stay here; one-off example managers should not. + +## Query Translation Shortcuts + +| Ask shape | Fastest reliable translation | +|---|---| +| `vendedor`, `sales rep`, `lider de vendas` | Interpret as `territory owner` by default for opportunity/pipeline asks unless the user explicitly requests another role. | +| `Top arquitetos do manager X em WON com close date em janela Y` | Filter `Knowledge DV - Hours - V2` by manager hierarchy level, aggregate `# Opportunity Hours` by `SE Team Level 5 Email Address`, then intersect with `Knowledge DV - Opportunities - V2` `Opportunity ID`s filtered by `Close Date` and `Status = 'Won'`. | +| `Mostrar booking/workload dos top arquitetos` | Use the same top-architect result, then de-duplicate by `architectEmail + opportunityId` before summing `Opportunity Value` and `Workload Amount` from `Knowledge DV - Opportunities - V2`. | +| `Quais clientes compoem o total do arquiteto` | Reuse the same de-duplicated architect or opportunity set and pull `Customer Name`, `Opportunity Value`, and `Workload Amount` from `Knowledge DV - Opportunities - V2`. | +| `Preciso descobrir qual nível representa o manager` | Probe `SE Team Level 1..8 Email Address` with a `%surname%` or exact-email search in `Knowledge DV - Hours - V2` before building the final query. | +| `Quero deals WON do time do manager` | Prefer `Knowledge DV - Opportunities - V2` for `Close Date`, `Status`, `Opportunity Value`, `Workload Amount`, territory, and owner context; prefer `Knowledge DV - Hours - V2` for hierarchy ownership and allocated hours. | + +## Practical Rules + +- Prefer `--query` for ad hoc joins, filters, and groupings when it can express the ask cleanly. +- Prefer `--sql` only when you need a dataset the normal `Security Entry Point` filter cannot express or when you must query XSA hierarchy columns directly. +- Do not trust `Won Flag` from the hours dataset as the only `WON` filter for business reporting. Use `Knowledge DV - Opportunities - V2` `Opportunity Status = 'Won'` plus the required close-date window. +- Use `Knowledge DV - Opportunities - V2` and the other Knowledge DV views for org-wide reads whose hierarchy starts at Latin America leadership. +- Use `DV - SE Team` only for self-scoped questions where "my team" really means the executing user and the people below that user, plus the normal SR and session-context questions. +- Do not use `DV - SE Team` as generic fallback for manager, territory, owner, or org-wide commercial reads. +- When crossing org-wide opportunities/workloads with team-scoped resource enrichment, keep every org-wide row and leave the resource fields empty when no team match exists. +- When listing clients and values for each architect, sum booking and workload only once per `architectEmail + opportunityId`. +- If the SQL gets quote-heavy on Windows PowerShell, use the SQL runner helper script documented in [script-catalog.md](script-catalog.md) instead of passing a long `--sql` string directly through the shell. + +## Suggested First Read Order + +1. This file for manager or hierarchy or business context. +2. [script-catalog.md](script-catalog.md) only if the CLI contract is still unclear. +3. `fetch-sales-intelligence.mjs --catalog` only if the data contract is still unclear after the two files above. diff --git a/references/script-catalog.md b/references/script-catalog.md new file mode 100644 index 0000000..216277f --- /dev/null +++ b/references/script-catalog.md @@ -0,0 +1,473 @@ +# Script Catalog + +Read this file when you need the exact CLI surface of the bundled scripts without rediscovering flags from source. + +Read this file for flag names, parameter conflicts, execution modes, and helper-script contracts. Skip it for routine asks that already map cleanly to a known intent or view. + +## Quick Navigation + +- Discovery policy: [Discovery Rule](#discovery-rule) +- Shortest path by ask type: [Minimal-Step Decision Table](#minimal-step-decision-table) +- Annual June-to-May week lookup: [Week Shortcuts](#week-shortcuts) +- Main fetch command: [Script: `fetch-sales-intelligence.mjs`](#script-fetch-sales-intelligencemjs) +- Browser refresh helper: [Script: `refresh-auth-state.mjs`](#script-refresh-auth-statemjs) +- Direct auth helper: [Script: `refresh-auth-direct.mjs`](#script-refresh-auth-directmjs) +- Quote-safe SQL helper: [Script: `run-sales-intelligence-sql.mjs`](#script-run-sales-intelligence-sqlmjs) + +For manager, hierarchy, architect-productivity, or business-parameter context, read [initial-context-catalog.md](initial-context-catalog.md) first. That skill-level catalog front-loads verified manager emails, hierarchy heuristics, and common query translations so the agent can execute faster before touching the generated CLI catalog. + +## Discovery Rule + +- Prefer [initial-context-catalog.md](initial-context-catalog.md) first for manager or hierarchy asks. +- Prefer `node scripts/fetch-sales-intelligence.mjs --catalog` first for CLI and data-contract discovery. +- The catalog now returns `views`, `intents`, `entities`, `fields`, `macros`, `parameters`, and `scripts`. +- For focused inspection, use `--list-parameters`, `--describe-parameter`, `--list-scripts`, and `--describe-script`. +- Treat `--catalog` as a one-shot resolver, not the first step in every request. +- If the ask already maps to a known intent, view, or query pattern, execute directly and skip discovery. +- After `--catalog`, go straight to the execution command. Avoid chaining `--list-*` calls unless one exact contract detail is still missing. + +## Operational Keepers + +These are the local catalog items worth keeping highly visible because they reduce trial-and-error during real backend execution: + +- Discovery helpers: `--catalog`, `--list-parameters`, `--describe-parameter`, `--list-scripts`, `--describe-script`. +- Workspace/runtime path controls: `--runtime-home`, `--state-path`, `--meta-path`, `--output-file`. +- Backend targeting: `--base-url`, plus auth refresh `--url`. +- Browser-auth recovery: `--profile-dir`, `--chrome-path`, `--timeout-ms`. +- Direct-auth recovery: `--username`, `--factor`. + +Role-shaped placeholder emails used below are illustrative only. Keep verified hierarchy anchors in `initial-context-catalog.md`, but keep routine usage examples generic. + +## Minimal-Step Decision Table + +| Ask shape | Shortest default | +|---|---| +| Recurring business request | `--intent ...` | +| Known row extract | `--view ...` | +| Ad hoc aliases + filters + grouping | `--query ...` | +| Need exact Oracle expression | `--sql ...` | +| Need contract discovery | `--catalog` once | +| Need one specific flag or script | `--describe-parameter ...` or `--describe-script ...` | + +## Week Shortcuts + +Use these as fixed lookups for June-to-May cycle asks: + +| Token | Meaning | +|---|---| +| `W1` / `week 1` | Starts on June 1 of the cycle start year | +| `W2` / `week 2` | Starts 7 days after `W1` | +| `W43` / `week 43` | Continues counting across January without resetting | +| `W53` / `week 53` | Final partial week ending on the last day of May | + +CLI flags: + +- `--week ` accepts `1..53`, `w1..w53`, or `week 1..week 53` +- `--week-year ` selects the cycle start year for that June-to-May map +- For the explicit default-cycle table, read [Week Reference](#week-reference) + +# Week Reference + +Use this file for asks that mention `week`, `wk`, or `w1`..`w53`. + +Week numbering is anchored on `June 1` and runs continuously until the last day of the following `May`. + +Interpretation rules: + +- `week-year` means the cycle start year. +- `week-year 2025` means the cycle `2025-06-01` through `2026-05-31`. +- If the user does not specify a year, default to the current June-cycle. +- Do not recalculate the default cycle in normal execution. Use the explicit table below. + +## Default Cycle Lookup + +Current default cycle for this workspace date context: + +- `week-year 2025` +- cycle start: `2025-06-01` +- cycle end: `2026-05-31` + +| Week | Start | End | +|---|---|---| +| W1 | 2025-06-01 | 2025-06-07 | +| W2 | 2025-06-08 | 2025-06-14 | +| W3 | 2025-06-15 | 2025-06-21 | +| W4 | 2025-06-22 | 2025-06-28 | +| W5 | 2025-06-29 | 2025-07-05 | +| W6 | 2025-07-06 | 2025-07-12 | +| W7 | 2025-07-13 | 2025-07-19 | +| W8 | 2025-07-20 | 2025-07-26 | +| W9 | 2025-07-27 | 2025-08-02 | +| W10 | 2025-08-03 | 2025-08-09 | +| W11 | 2025-08-10 | 2025-08-16 | +| W12 | 2025-08-17 | 2025-08-23 | +| W13 | 2025-08-24 | 2025-08-30 | +| W14 | 2025-08-31 | 2025-09-06 | +| W15 | 2025-09-07 | 2025-09-13 | +| W16 | 2025-09-14 | 2025-09-20 | +| W17 | 2025-09-21 | 2025-09-27 | +| W18 | 2025-09-28 | 2025-10-04 | +| W19 | 2025-10-05 | 2025-10-11 | +| W20 | 2025-10-12 | 2025-10-18 | +| W21 | 2025-10-19 | 2025-10-25 | +| W22 | 2025-10-26 | 2025-11-01 | +| W23 | 2025-11-02 | 2025-11-08 | +| W24 | 2025-11-09 | 2025-11-15 | +| W25 | 2025-11-16 | 2025-11-22 | +| W26 | 2025-11-23 | 2025-11-29 | +| W27 | 2025-11-30 | 2025-12-06 | +| W28 | 2025-12-07 | 2025-12-13 | +| W29 | 2025-12-14 | 2025-12-20 | +| W30 | 2025-12-21 | 2025-12-27 | +| W31 | 2025-12-28 | 2026-01-03 | +| W32 | 2026-01-04 | 2026-01-10 | +| W33 | 2026-01-11 | 2026-01-17 | +| W34 | 2026-01-18 | 2026-01-24 | +| W35 | 2026-01-25 | 2026-01-31 | +| W36 | 2026-02-01 | 2026-02-07 | +| W37 | 2026-02-08 | 2026-02-14 | +| W38 | 2026-02-15 | 2026-02-21 | +| W39 | 2026-02-22 | 2026-02-28 | +| W40 | 2026-03-01 | 2026-03-07 | +| W41 | 2026-03-08 | 2026-03-14 | +| W42 | 2026-03-15 | 2026-03-21 | +| W43 | 2026-03-22 | 2026-03-28 | +| W44 | 2026-03-29 | 2026-04-04 | +| W45 | 2026-04-05 | 2026-04-11 | +| W46 | 2026-04-12 | 2026-04-18 | +| W47 | 2026-04-19 | 2026-04-25 | +| W48 | 2026-04-26 | 2026-05-02 | +| W49 | 2026-05-03 | 2026-05-09 | +| W50 | 2026-05-10 | 2026-05-16 | +| W51 | 2026-05-17 | 2026-05-23 | +| W52 | 2026-05-24 | 2026-05-30 | +| W53 | 2026-05-31 | 2026-05-31 | + +Examples: + +- `week 1` -> `2025-06-01` to `2025-06-07` +- `recursos do resource.manager em pipe na week 43` -> use `--intent opportunities-by-manager-close-window --manager-email resource.manager@oracle.com --week w43` + + +## Script: `fetch-sales-intelligence.mjs` + +Primary backend retrieval entrypoint for Oracle DV. + +### Discovery flags + +| Flag | Type | Description | +|---|---|---| +| `--catalog` | flag | Return the full local catalog, including script and parameter metadata. | +| `--list-views` | flag | List built-in views. | +| `--describe-view ` | string | Describe one built-in view. | +| `--list-intents` | flag | List recurring business intents. | +| `--describe-intent ` | string | Describe one intent. | +| `--list-entities` | flag | List entities and the views that expose them. | +| `--list-fields` | flag | List local field aliases. | +| `--describe-field ` | string | Describe one field alias. | +| `--list-parameters` | flag | List the parameter catalog. | +| `--describe-parameter ` | string | Describe one parameter. Accepts `resource` or `--resource`. | +| `--list-scripts` | flag | List runnable scripts in the skill. | +| `--describe-script