@orkastery/cli 0.4.3 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/adapters/README.md +11 -0
- package/adapters/claude-code/.claude-plugin/plugin.json +3 -1
- package/adapters/claude-code/agents/ork-check.md +1 -1
- package/adapters/claude-code/agents/ork-go.md +2 -2
- package/adapters/claude-code/agents/ork-goal.md +1 -1
- package/adapters/claude-code/agents/ork-master.md +1 -1
- package/adapters/claude-code/agents/ork-plan.md +1 -1
- package/adapters/claude-code/agents/ork-ship.md +1 -1
- package/adapters/claude-code/commands/master.md +11 -8
- package/adapters/claude-code/commands/ork.md +8 -0
- package/adapters/claude-code/commands/ship.md +2 -2
- package/adapters/codex/skills/ork/SKILL.md +12 -1
- package/adapters/hermes/README.md +3 -0
- package/adapters/hermes/bin/ork-abrir-thread.sh +17 -2
- package/adapters/hermes/bin/ork-brain.sh +3 -0
- package/adapters/hermes/bin/ork-maestro.sh +4 -1
- package/adapters/hermes/bin/ork-network-roadmap.sh +11 -0
- package/adapters/hermes/bin/ork-roadmap-status.sh +9 -0
- package/adapters/hermes/hermes.plugin.json +2 -0
- package/adapters/hermes/hitl-ingress/__init__.py +36 -3
- package/adapters/hermes/skills/orkastery-devmaster/SKILL.md +19 -20
- package/adapters/openclaw/README.md +34 -2
- package/adapters/openclaw/dist/hitl-ingress.js +37 -3
- package/adapters/openclaw/dist/index.js +92 -20
- package/adapters/openclaw/openclaw.plugin.json +10 -1
- package/adapters/openclaw/package.json +2 -2
- package/adapters/openclaw/src/hitl-ingress.ts +32 -3
- package/adapters/openclaw/src/index.ts +108 -20
- package/assets/docs/padroes/documentacao-de-produto.md +2 -2
- package/assets/docs/padroes/roadmap-de-produto.md +1 -1
- package/assets/docs/produto/_modelo-feature.md +2 -0
- package/assets/orkmind_bridge.py +214 -1
- package/dist/adapters/claude-bg.js +6 -3
- package/dist/board.js +74 -0
- package/dist/branch-de-estado.js +5 -4
- package/dist/busca-semantica.js +161 -0
- package/dist/ci.js +141 -10
- package/dist/company-brain-cli.js +27 -2
- package/dist/company-brain-context.js +132 -0
- package/dist/company-brain-dossie.js +376 -0
- package/dist/company-brain-mcp.js +4 -1
- package/dist/conducao.js +71 -18
- package/dist/decisao-autonoma.js +42 -0
- package/dist/docs.js +64 -22
- package/dist/doctor.js +33 -0
- package/dist/entrega-pr.js +109 -5
- package/dist/experiencia-instalacao.js +256 -0
- package/dist/experiencia.js +72 -0
- package/dist/fabrica-estado.js +43 -10
- package/dist/fechamento.js +105 -0
- package/dist/forja.js +435 -0
- package/dist/gates.js +9 -1
- package/dist/hitl-classificacao.js +11 -1
- package/dist/hitl-contract.js +50 -7
- package/dist/hitl-curto.js +158 -0
- package/dist/hitl-gates.js +67 -1
- package/dist/hitl-lote.js +30 -15
- package/dist/hitl-presentation.js +10 -7
- package/dist/hitl-resumo.js +33 -12
- package/dist/hitl-texto-livre.js +150 -0
- package/dist/hosts.js +86 -1
- package/dist/index.js +602 -38
- package/dist/indice-vetorial.js +317 -0
- package/dist/init.js +13 -0
- package/dist/integracoes-locais.js +1 -1
- package/dist/intelligence-benchmark-contract.js +570 -0
- package/dist/intelligence-graph-cli.js +430 -0
- package/dist/intelligence-graph-contract.js +577 -0
- package/dist/intelligence-graph-extract-md.js +469 -0
- package/dist/intelligence-graph-extract-ts.js +810 -0
- package/dist/intelligence-graph-extract.js +369 -0
- package/dist/intelligence-graph-index.js +512 -0
- package/dist/intelligence-graph-parsers.js +327 -0
- package/dist/intelligence-graph-query.js +344 -0
- package/dist/intelligence-graph-repo.js +187 -0
- package/dist/leases.js +84 -0
- package/dist/ledger.js +14 -0
- package/dist/maestro-cli.js +10 -1
- package/dist/maestro-contract.js +5 -1
- package/dist/maestro-discovery.js +16 -2
- package/dist/maestro-snapshot.js +6 -2
- package/dist/manifest.js +142 -5
- package/dist/master-batch.js +3 -2
- package/dist/master-digest.js +2 -2
- package/dist/master-nota.js +203 -0
- package/dist/master.js +4 -0
- package/dist/mcp-experiencia.js +164 -0
- package/dist/mcp-git.js +4 -0
- package/dist/mcp-install.js +3 -1
- package/dist/mcp-maestro.js +3 -2
- package/dist/mcp-server.js +84 -5
- package/dist/memoria.js +147 -1
- package/dist/network-roadmap.js +907 -0
- package/dist/ocupacao.js +38 -2
- package/dist/onboarding.js +113 -7
- package/dist/orkmind.js +165 -9
- package/dist/phase.js +166 -13
- package/dist/policies.js +2 -0
- package/dist/projeto-alvo.js +551 -0
- package/dist/prompts.js +1 -1
- package/dist/pulse-consentimento.js +4 -2
- package/dist/pulse-delivery.js +5 -0
- package/dist/pulse-resposta.js +674 -49
- package/dist/pulse.js +21 -0
- package/dist/retry.js +51 -8
- package/dist/roadmap-reservas.js +262 -20
- package/dist/roadmap-status.js +213 -0
- package/dist/thread-close.js +3 -0
- package/dist/verify.js +4 -3
- package/eval/casos/orchestration-experience-pt-br.json +48 -0
- package/eval/casos/orchestration-experience.json +48 -0
- package/package.json +1 -1
- package/schemas/code-artifact-graph.v1.schema.json +581 -0
- package/schemas/graph-benchmark.v1.schema.json +2240 -0
- package/schemas/maestro-snapshot.schema.json +23 -0
- package/skills/README.md +7 -5
- package/skills/core/onboarding/SKILL.md +7 -0
- package/skills/core/orchestration-experience/SKILL.md +113 -0
- package/skills/core/orchestration-experience-pt-br/SKILL.md +112 -0
- package/skills/core/orkastery-bootstrap/SKILL.md +2 -2
- package/skills/phases/go-implementation/SKILL.md +2 -0
|
@@ -0,0 +1,512 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.versoesDoParser = exports.EXCLUSOES_DA_ARVORE = exports.MODULOS_DO_EXTRATOR = exports.PRAZO_DE_SOBRA_MS = exports.NOME_DE_INDICE = exports.INDICE_SCHEMA = void 0;
|
|
37
|
+
exports.impressaoDoExtrator = impressaoDoExtrator;
|
|
38
|
+
exports.perfilDoIndice = perfilDoIndice;
|
|
39
|
+
exports.chaveDoIndice = chaveDoIndice;
|
|
40
|
+
exports.concessaoLocal = concessaoLocal;
|
|
41
|
+
exports.pastaDoGrafo = pastaDoGrafo;
|
|
42
|
+
exports.lerIndice = lerIndice;
|
|
43
|
+
exports.construirIndice = construirIndice;
|
|
44
|
+
exports.indiceDoHead = indiceDoHead;
|
|
45
|
+
exports.estadoDosIndices = estadoDosIndices;
|
|
46
|
+
exports.limparIndices = limparIndices;
|
|
47
|
+
/**
|
|
48
|
+
* RM-031 KG3 (D2 a D4, D6): indice persistente e local do grafo de codigo.
|
|
49
|
+
*
|
|
50
|
+
* O indice e derivado do grafo do KG2 e chaveado pela revisao da arvore limpa: mora no estado
|
|
51
|
+
* canonico do projeto, fora do git, uma pasta por chave:
|
|
52
|
+
*
|
|
53
|
+
* <raiz canonica>/.orkastery/grafo/idx-<sha256>/{indice.json, grafo.json, relatorio.json}
|
|
54
|
+
*
|
|
55
|
+
* Pastas 0700 e arquivos 0600, do dono do processo, sem link simbolico nem segundo link fisico. A
|
|
56
|
+
* chave deriva da revisao, do repositorio, do tenant, da ACL, das versoes dos analisadores, do fecho
|
|
57
|
+
* de pacotes deles e da impressao do codigo compilado do extrator e do indice: mesma chave, mesmo
|
|
58
|
+
* conteudo, byte a byte, sem horario. Arquivo rastreado que a leitura nao alcanca (sparse checkout,
|
|
59
|
+
* `skip-worktree`) recusa a construcao: o grafo precisa ser o da revisao inteira.
|
|
60
|
+
* A construcao valida o grafo, confere cada fonte e cada evidencia contra os bytes lidos e so entao
|
|
61
|
+
* publica, por pasta temporaria e `rename`; a leitura confere tamanho e digest dos bytes.
|
|
62
|
+
*
|
|
63
|
+
* O indice nao e autoridade de fato: e projecao descartavel do repositorio. Nada nele concede acesso.
|
|
64
|
+
*/
|
|
65
|
+
const node_crypto_1 = require("node:crypto");
|
|
66
|
+
const fs = __importStar(require("node:fs"));
|
|
67
|
+
const path = __importStar(require("node:path"));
|
|
68
|
+
const intelligence_graph_contract_1 = require("./intelligence-graph-contract");
|
|
69
|
+
const intelligence_graph_extract_1 = require("./intelligence-graph-extract");
|
|
70
|
+
const intelligence_graph_parsers_1 = require("./intelligence-graph-parsers");
|
|
71
|
+
const intelligence_graph_repo_1 = require("./intelligence-graph-repo");
|
|
72
|
+
exports.INDICE_SCHEMA = 'ork.code-graph-index/v0';
|
|
73
|
+
exports.NOME_DE_INDICE = /^idx-[a-f0-9]{64}$/;
|
|
74
|
+
const ARQUIVOS = { manifesto: 'indice.json', grafo: 'grafo.json', relatorio: 'relatorio.json' };
|
|
75
|
+
/** Temporario e lixo de construcao interrompida so saem no `limpar` depois deste prazo. */
|
|
76
|
+
exports.PRAZO_DE_SOBRA_MS = 60 * 60 * 1000;
|
|
77
|
+
/** D3: os modulos compilados da extracao e do indice. Codigo corrigido sem troca de versao muda a chave. */
|
|
78
|
+
exports.MODULOS_DO_EXTRATOR = [
|
|
79
|
+
'intelligence-graph-contract', 'intelligence-graph-extract', 'intelligence-graph-extract-ts', 'intelligence-graph-extract-md',
|
|
80
|
+
'intelligence-graph-repo', 'intelligence-graph-parsers', 'intelligence-graph-index', 'yaml',
|
|
81
|
+
];
|
|
82
|
+
/**
|
|
83
|
+
* CHECK rodada 1 (B1): exclusoes do KG2 que dependem da arvore, nao da revisao. Com o status limpo,
|
|
84
|
+
* elas vem de sparse checkout ou `skip-worktree`, e o grafo seria outro na mesma revisao.
|
|
85
|
+
*/
|
|
86
|
+
exports.EXCLUSOES_DA_ARVORE = new Set(['ausente-na-arvore', 'nao-e-arquivo', 'fora-do-repositorio']);
|
|
87
|
+
function falha(codigo, detalhe) {
|
|
88
|
+
throw new Error(detalhe ? `${codigo}: ${detalhe}` : codigo);
|
|
89
|
+
}
|
|
90
|
+
const sha256 = (b) => (0, node_crypto_1.createHash)('sha256').update(b).digest('hex');
|
|
91
|
+
const uid = () => (typeof process.getuid === 'function' ? process.getuid() : null);
|
|
92
|
+
/** As versoes do `Parser` carregado, no formato que `versoesDosAnalisadores` le sem carregar. */
|
|
93
|
+
const versoesDoParser = (p) => ({ typescript: p.ts.version, javascript: p.javascript.versao, markdown: p.markdown.versao, unicode: p.unicode });
|
|
94
|
+
exports.versoesDoParser = versoesDoParser;
|
|
95
|
+
/** D3: SHA-256 dos bytes compilados dos modulos da extracao, na ordem fixa; `dir` so muda em teste. */
|
|
96
|
+
function impressaoDoExtrator(dir = __dirname) {
|
|
97
|
+
const h = (0, node_crypto_1.createHash)('sha256');
|
|
98
|
+
for (const m of exports.MODULOS_DO_EXTRATOR) {
|
|
99
|
+
const bytes = fs.readFileSync(path.join(dir, `${m}.js`));
|
|
100
|
+
h.update(`${m}\u0000${bytes.length}\u0000`).update(bytes);
|
|
101
|
+
}
|
|
102
|
+
return h.digest('hex');
|
|
103
|
+
}
|
|
104
|
+
function perfilDoIndice(raiz, analisadores = (0, intelligence_graph_parsers_1.versoesDosAnalisadores)(), leitura = {}) {
|
|
105
|
+
const id = (0, intelligence_graph_repo_1.identidadeDaLeitura)(raiz, leitura);
|
|
106
|
+
return {
|
|
107
|
+
...id, acl_refs: [...new Set(id.acl_refs)].sort(intelligence_graph_contract_1.compararUtf8), analisadores, pacotes: (0, intelligence_graph_parsers_1.pacotesDosAnalisadores)(), codigo: impressaoDoExtrator(),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
/** A leitura do contexto: o repositorio do manifesto do CLI, se veio, sob as opcoes pedidas. */
|
|
111
|
+
const leituraDo = (ctx, leitura = {}) => (ctx.repositorio && leitura.repository_id === undefined ? { ...leitura, repository_id: ctx.repositorio } : leitura);
|
|
112
|
+
/** D3: a chave particiona por revisao, repositorio, tenant, ACL, analisadores e codigo do extrator. */
|
|
113
|
+
function chaveDoIndice(revision, perfil) {
|
|
114
|
+
return `idx-${(0, intelligence_graph_contract_1.sha256DoCanonico)({ schema: exports.INDICE_SCHEMA, revision, ...perfil })}`;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* D6: a avaliacao local. Quem roda o CLI e le a raiz do repositorio recebe a leitura dele, no
|
|
118
|
+
* tenant local; nada mais. Sem leitura, a recusa e explicita, sem cair para outro escopo.
|
|
119
|
+
*/
|
|
120
|
+
function concessaoLocal(raiz, perfil) {
|
|
121
|
+
try {
|
|
122
|
+
fs.accessSync(raiz, fs.constants.R_OK | fs.constants.X_OK);
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
falha('grafo.acesso.negado', 'quem roda o CLI nao le a raiz do repositorio');
|
|
126
|
+
}
|
|
127
|
+
return { tenant_id: intelligence_graph_repo_1.TENANT_PADRAO, acl_refs: [`repo:${perfil.repository_id}:leitura`] };
|
|
128
|
+
}
|
|
129
|
+
/** Pasta do estado: real, do dono e 0700; `criar` ajusta a que o proprio processo cria. */
|
|
130
|
+
function pastaPrivada(p, criar) {
|
|
131
|
+
if (criar) {
|
|
132
|
+
try {
|
|
133
|
+
fs.mkdirSync(p, { mode: 0o700 });
|
|
134
|
+
}
|
|
135
|
+
catch (e) {
|
|
136
|
+
if (e.code !== 'EEXIST')
|
|
137
|
+
throw e;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
const st = fs.lstatSync(p, { throwIfNoEntry: false });
|
|
141
|
+
if (!st)
|
|
142
|
+
falha('grafo.indice.ausente');
|
|
143
|
+
if (st.isSymbolicLink() || !st.isDirectory())
|
|
144
|
+
falha('grafo.indice.permissao-invalida', `${path.basename(p)} nao e pasta real`);
|
|
145
|
+
const dono = uid();
|
|
146
|
+
if (dono !== null && st.uid !== dono)
|
|
147
|
+
falha('grafo.indice.permissao-invalida', `${path.basename(p)} de outro dono`);
|
|
148
|
+
if ((st.mode & 0o777) !== 0o700) {
|
|
149
|
+
if (!criar)
|
|
150
|
+
falha('grafo.indice.permissao-invalida', `${path.basename(p)} com modo ${(st.mode & 0o777).toString(8)}`);
|
|
151
|
+
fs.chmodSync(p, 0o700);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
/** `<estado>/.orkastery/grafo`, real e privada. So a construcao cria. */
|
|
155
|
+
function pastaDoGrafo(ctx, criar) {
|
|
156
|
+
const estado = path.join(ctx.estado, '.orkastery');
|
|
157
|
+
if (criar)
|
|
158
|
+
fs.mkdirSync(estado, { recursive: true });
|
|
159
|
+
const st = fs.lstatSync(estado, { throwIfNoEntry: false });
|
|
160
|
+
if (!st)
|
|
161
|
+
falha('grafo.indice.ausente');
|
|
162
|
+
if (st.isSymbolicLink() || !st.isDirectory())
|
|
163
|
+
falha('grafo.indice.permissao-invalida', '.orkastery nao e pasta real');
|
|
164
|
+
const dir = path.join(estado, 'grafo');
|
|
165
|
+
pastaPrivada(dir, criar);
|
|
166
|
+
return dir;
|
|
167
|
+
}
|
|
168
|
+
/** Le arquivo do indice pelo descritor aberto sem seguir link: regular, do dono, 0600 e com um link so. */
|
|
169
|
+
function lerPrivado(arquivo) {
|
|
170
|
+
let fd;
|
|
171
|
+
try {
|
|
172
|
+
fd = fs.openSync(arquivo, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
|
|
173
|
+
}
|
|
174
|
+
catch (e) {
|
|
175
|
+
const codigo = e.code;
|
|
176
|
+
if (codigo === 'ENOENT')
|
|
177
|
+
falha('grafo.indice.corrompido', `${path.basename(arquivo)} ausente`);
|
|
178
|
+
falha('grafo.indice.permissao-invalida', `${path.basename(arquivo)} (${codigo ?? 'erro'})`);
|
|
179
|
+
}
|
|
180
|
+
try {
|
|
181
|
+
const st = fs.fstatSync(fd);
|
|
182
|
+
const dono = uid();
|
|
183
|
+
if (!st.isFile() || st.nlink !== 1 || (dono !== null && st.uid !== dono) || (st.mode & 0o777) !== 0o600) {
|
|
184
|
+
falha('grafo.indice.permissao-invalida', path.basename(arquivo));
|
|
185
|
+
}
|
|
186
|
+
return fs.readFileSync(fd);
|
|
187
|
+
}
|
|
188
|
+
finally {
|
|
189
|
+
fs.closeSync(fd);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
function gravarPrivado(arquivo, texto) {
|
|
193
|
+
const fd = fs.openSync(arquivo, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
|
|
194
|
+
try {
|
|
195
|
+
fs.fchmodSync(fd, 0o600);
|
|
196
|
+
fs.writeFileSync(fd, texto, 'utf8');
|
|
197
|
+
fs.fsyncSync(fd);
|
|
198
|
+
}
|
|
199
|
+
finally {
|
|
200
|
+
fs.closeSync(fd);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
function sincronizarPasta(dir) {
|
|
204
|
+
const fd = fs.openSync(dir, 'r');
|
|
205
|
+
try {
|
|
206
|
+
fs.fsyncSync(fd);
|
|
207
|
+
}
|
|
208
|
+
finally {
|
|
209
|
+
fs.closeSync(fd);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
const HEX64 = /^[a-f0-9]{64}$/;
|
|
213
|
+
function manifestoValido(m, chave) {
|
|
214
|
+
const o = m;
|
|
215
|
+
const inteiro = (n) => Number.isSafeInteger(n) && n >= 0;
|
|
216
|
+
if (!o || typeof o !== 'object' || o.schema !== exports.INDICE_SCHEMA || o.chave !== chave || o.graph_schema !== intelligence_graph_contract_1.GRAFO_SCHEMA
|
|
217
|
+
|| typeof o.revision !== 'string' || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(o.revision)
|
|
218
|
+
|| !HEX64.test(o.graph_digest) || !HEX64.test(o.report_digest) || !inteiro(o.graph_bytes) || !inteiro(o.report_bytes)
|
|
219
|
+
|| typeof o.snapshot_id !== 'string' || typeof o.repository_id !== 'string' || typeof o.tenant_id !== 'string'
|
|
220
|
+
|| !Array.isArray(o.acl_refs) || !o.analisadores || !Array.isArray(o.pacotes) || typeof o.codigo !== 'string') {
|
|
221
|
+
falha('grafo.indice.corrompido', 'indice.json');
|
|
222
|
+
}
|
|
223
|
+
return o;
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Le o indice da chave e confere a integridade: permissao de pasta e arquivo, manifesto, tamanho e
|
|
227
|
+
* digest dos bytes do grafo e do relatorio, e o envelope do grafo contra o manifesto. Nao roda
|
|
228
|
+
* `validarGrafo` (D4): a construcao ja validou, e o digest prova que os bytes sao aqueles.
|
|
229
|
+
*/
|
|
230
|
+
function lerIndice(ctx, chave, opcoes = {}) {
|
|
231
|
+
if (!exports.NOME_DE_INDICE.test(chave))
|
|
232
|
+
falha('grafo.indice.chave-invalida');
|
|
233
|
+
const dir = path.join(pastaDoGrafo(ctx, false), chave);
|
|
234
|
+
pastaPrivada(dir, false);
|
|
235
|
+
let manifesto;
|
|
236
|
+
try {
|
|
237
|
+
manifesto = manifestoValido(JSON.parse(lerPrivado(path.join(dir, ARQUIVOS.manifesto)).toString('utf8')), chave);
|
|
238
|
+
}
|
|
239
|
+
catch (e) {
|
|
240
|
+
if (e instanceof SyntaxError)
|
|
241
|
+
falha('grafo.indice.corrompido', 'indice.json');
|
|
242
|
+
throw e;
|
|
243
|
+
}
|
|
244
|
+
const conferido = (nome, bytes, digest) => {
|
|
245
|
+
const b = lerPrivado(path.join(dir, nome));
|
|
246
|
+
if (b.length !== bytes || sha256(b) !== digest)
|
|
247
|
+
falha('grafo.indice.corrompido', `${nome} nao bate com o digest`);
|
|
248
|
+
return b;
|
|
249
|
+
};
|
|
250
|
+
const bytesDoGrafo = conferido(ARQUIVOS.grafo, manifesto.graph_bytes, manifesto.graph_digest);
|
|
251
|
+
const bytesDoRelatorio = conferido(ARQUIVOS.relatorio, manifesto.report_bytes, manifesto.report_digest);
|
|
252
|
+
let grafo = null;
|
|
253
|
+
if (opcoes.grafo !== false) {
|
|
254
|
+
grafo = JSON.parse(bytesDoGrafo.toString('utf8'));
|
|
255
|
+
const s = grafo.snapshot;
|
|
256
|
+
if (grafo.schema !== intelligence_graph_contract_1.GRAFO_SCHEMA || grafo.tenant_id !== manifesto.tenant_id || grafo.repository_id !== manifesto.repository_id
|
|
257
|
+
|| !s || s.snapshot_id !== manifesto.snapshot_id || s.revision !== manifesto.revision) {
|
|
258
|
+
falha('grafo.indice.corrompido', 'grafo.json fora do manifesto');
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
const relatorio = opcoes.relatorio ? JSON.parse(bytesDoRelatorio.toString('utf8')) : null;
|
|
262
|
+
return { dir, manifesto, grafo, relatorio };
|
|
263
|
+
}
|
|
264
|
+
/** Embaralhamento reproduzivel (LCG): a permutacao da verificacao nao depende de acaso. */
|
|
265
|
+
function embaralhar(itens, semente) {
|
|
266
|
+
const r = [...itens];
|
|
267
|
+
let s = semente >>> 0;
|
|
268
|
+
for (let i = r.length - 1; i > 0; i--) {
|
|
269
|
+
s = (Math.imul(s, 1664525) + 1013904223) >>> 0;
|
|
270
|
+
const j = s % (i + 1);
|
|
271
|
+
[r[i], r[j]] = [r[j], r[i]];
|
|
272
|
+
}
|
|
273
|
+
return r;
|
|
274
|
+
}
|
|
275
|
+
function mesmoConteudo(dir, conteudos) {
|
|
276
|
+
try {
|
|
277
|
+
return Object.entries(conteudos).every(([nome, texto]) => lerPrivado(path.join(dir, nome)).equals(Buffer.from(texto, 'utf8')))
|
|
278
|
+
&& fs.readdirSync(dir).length === Object.keys(conteudos).length;
|
|
279
|
+
}
|
|
280
|
+
catch {
|
|
281
|
+
return false;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
function removerPasta(grafoDir, nome) {
|
|
285
|
+
const alvo = path.join(grafoDir, nome);
|
|
286
|
+
const st = fs.lstatSync(alvo, { throwIfNoEntry: false });
|
|
287
|
+
if (!st)
|
|
288
|
+
return;
|
|
289
|
+
if (st.isSymbolicLink() || !st.isDirectory()) {
|
|
290
|
+
fs.unlinkSync(alvo);
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
// Renomeia antes de apagar: quem le nunca ve a pasta da chave pela metade.
|
|
294
|
+
const lixo = nome.startsWith('.lixo-') ? alvo : path.join(grafoDir, `.lixo-${(0, node_crypto_1.randomUUID)()}`);
|
|
295
|
+
if (lixo !== alvo)
|
|
296
|
+
fs.renameSync(alvo, lixo);
|
|
297
|
+
fs.rmSync(lixo, { recursive: true, force: true });
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Constroi o indice do HEAD limpo, ou confirma o que ja existe. `--forcar` extrai de novo e so
|
|
301
|
+
* troca os arquivos se o conteudo mudou; `--verificar` extrai de novo, prova o determinismo com a
|
|
302
|
+
* ordem de leitura trocada e reprova se o guardado integro difere; indice que nao passa na leitura
|
|
303
|
+
* e substituido.
|
|
304
|
+
*/
|
|
305
|
+
function construirIndice(ctx, opcoes = {}) {
|
|
306
|
+
const inicio = process.hrtime.bigint();
|
|
307
|
+
const ms = () => Number((process.hrtime.bigint() - inicio) / 1000000n);
|
|
308
|
+
const arvore = (0, intelligence_graph_repo_1.revisaoDaArvore)(ctx.raiz);
|
|
309
|
+
if (arvore.motivo !== null || arvore.head === null)
|
|
310
|
+
falha('grafo.indice.arvore-nao-limpa', arvore.motivo ?? 'sem-commit');
|
|
311
|
+
const parser = opcoes.parser ?? (0, intelligence_graph_parsers_1.carregarAnalisadores)();
|
|
312
|
+
const leitura = leituraDo(ctx, opcoes.leitura);
|
|
313
|
+
const perfil = perfilDoIndice(arvore.raiz, (0, exports.versoesDoParser)(parser), leitura);
|
|
314
|
+
const chave = chaveDoIndice(arvore.head, perfil);
|
|
315
|
+
const grafoDir = pastaDoGrafo(ctx, true);
|
|
316
|
+
const final = path.join(grafoDir, chave);
|
|
317
|
+
let motivo = null;
|
|
318
|
+
const existia = !!fs.lstatSync(final, { throwIfNoEntry: false });
|
|
319
|
+
if (existia) {
|
|
320
|
+
try {
|
|
321
|
+
const atual = lerIndice(ctx, chave, { grafo: false });
|
|
322
|
+
// `--verificar` nunca confia no guardado: extrai de novo e compara, como o `--forcar`.
|
|
323
|
+
if (!opcoes.forcar && !opcoes.verificar)
|
|
324
|
+
return { estado: 'existente', motivo: null, chave, dir: final, manifesto: atual.manifesto, determinismo: null, ms: ms() };
|
|
325
|
+
}
|
|
326
|
+
catch (e) {
|
|
327
|
+
motivo = e.message;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
const entrada = (0, intelligence_graph_repo_1.lerRepositorio)(arvore.raiz, leitura);
|
|
331
|
+
if (entrada.revision !== arvore.head)
|
|
332
|
+
falha('grafo.indice.arvore-nao-limpa', entrada.revision_unavailable_reason ?? 'revisao-mudou');
|
|
333
|
+
const fora = (entrada.excluidas ?? []).filter((e) => exports.EXCLUSOES_DA_ARVORE.has(e.motivo)).sort((a, b) => (0, intelligence_graph_contract_1.compararUtf8)(a.path, b.path));
|
|
334
|
+
if (fora.length) {
|
|
335
|
+
falha('grafo.indice.arvore-nao-limpa', `rastreado fora da leitura (${fora[0].motivo}: ${fora[0].path}${fora.length > 1 ? ` e mais ${fora.length - 1}` : ''})`);
|
|
336
|
+
}
|
|
337
|
+
const r = (0, intelligence_graph_extract_1.extrairGrafo)(entrada, parser);
|
|
338
|
+
const bytesDe = new Map(entrada.fontes.map((f) => [f.path, f.bytes]));
|
|
339
|
+
const fornecidas = new Map(r.grafo.snapshot.source_manifest.map((m) => {
|
|
340
|
+
const b = bytesDe.get(m.path);
|
|
341
|
+
return [m.path, { tipo: (0, intelligence_graph_extract_1.decodificarUtf8)(b) === null ? 'binario' : 'texto', bytes: b }];
|
|
342
|
+
}));
|
|
343
|
+
const conferencia = (0, intelligence_graph_contract_1.conferirFontes)(r.grafo, fornecidas);
|
|
344
|
+
if (conferencia.estado !== 'verificada' || conferencia.evidenciasIndisponiveis > 0)
|
|
345
|
+
falha('grafo.indice.fontes-nao-conferidas');
|
|
346
|
+
let determinismo = null;
|
|
347
|
+
if (opcoes.verificar) {
|
|
348
|
+
const relatorio = (0, intelligence_graph_contract_1.sha256DoCanonico)(r.relatorio);
|
|
349
|
+
determinismo = [['ordem invertida', [...entrada.fontes].reverse()], ['ordem embaralhada', embaralhar(entrada.fontes, 2026)]]
|
|
350
|
+
.map(([ordem, fontes]) => {
|
|
351
|
+
const outra = (0, intelligence_graph_extract_1.extrairGrafo)({ ...entrada, fontes }, parser);
|
|
352
|
+
const doOutro = (0, intelligence_graph_contract_1.sha256DoCanonico)(outra.relatorio);
|
|
353
|
+
return { ordem, digest: outra.digest, relatorio: doOutro, igual: outra.digest === r.digest && doOutro === relatorio };
|
|
354
|
+
});
|
|
355
|
+
const diferente = determinismo.find((d) => !d.igual);
|
|
356
|
+
if (diferente)
|
|
357
|
+
falha('grafo.indice.nao-deterministico', diferente.ordem);
|
|
358
|
+
}
|
|
359
|
+
const textoDoGrafo = (0, intelligence_graph_contract_1.canonico)(r.grafo), textoDoRelatorio = (0, intelligence_graph_contract_1.canonico)(r.relatorio);
|
|
360
|
+
if (sha256(textoDoGrafo) !== r.digest)
|
|
361
|
+
falha('grafo.indice.digest-divergente');
|
|
362
|
+
const manifesto = {
|
|
363
|
+
schema: exports.INDICE_SCHEMA, chave, revision: arvore.head, ...perfil, graph_schema: intelligence_graph_contract_1.GRAFO_SCHEMA, snapshot_id: r.grafo.snapshot.snapshot_id,
|
|
364
|
+
graph_digest: r.digest, graph_bytes: Buffer.byteLength(textoDoGrafo, 'utf8'),
|
|
365
|
+
report_digest: sha256(textoDoRelatorio), report_bytes: Buffer.byteLength(textoDoRelatorio, 'utf8'),
|
|
366
|
+
contagens: r.relatorio.contagens,
|
|
367
|
+
conferencia: { fontes: conferencia.fontesVerificadas.length, evidencias: conferencia.evidenciasVerificadas },
|
|
368
|
+
};
|
|
369
|
+
const conteudos = {
|
|
370
|
+
[ARQUIVOS.manifesto]: (0, intelligence_graph_contract_1.canonico)(manifesto), [ARQUIVOS.grafo]: textoDoGrafo, [ARQUIVOS.relatorio]: textoDoRelatorio,
|
|
371
|
+
};
|
|
372
|
+
const tmp = path.join(grafoDir, `.tmp-${(0, node_crypto_1.randomUUID)()}`);
|
|
373
|
+
pastaPrivada(tmp, true);
|
|
374
|
+
try {
|
|
375
|
+
for (const [nome, texto] of Object.entries(conteudos))
|
|
376
|
+
gravarPrivado(path.join(tmp, nome), texto);
|
|
377
|
+
sincronizarPasta(tmp);
|
|
378
|
+
opcoes.antesDePublicar?.();
|
|
379
|
+
const resultado = (estado) => ({ estado, motivo, chave, dir: final, manifesto, determinismo, ms: ms() });
|
|
380
|
+
if (!existia && fs.lstatSync(final, { throwIfNoEntry: false })) {
|
|
381
|
+
// Corrida: outra construcao publicou a mesma chave durante esta. Vale a dela, se estiver integra.
|
|
382
|
+
lerIndice(ctx, chave, { grafo: false });
|
|
383
|
+
return resultado('existente');
|
|
384
|
+
}
|
|
385
|
+
if (existia && fs.lstatSync(final, { throwIfNoEntry: false })) {
|
|
386
|
+
if (motivo === null && mesmoConteudo(final, conteudos))
|
|
387
|
+
return resultado('reconstruido-identico');
|
|
388
|
+
// Mesma chave e conteudo integro diferente: a extracao nao se repetiu. A verificacao reprova; o forcar troca.
|
|
389
|
+
if (motivo === null && opcoes.verificar)
|
|
390
|
+
falha('grafo.indice.nao-deterministico', 'o indice guardado difere da extracao nova');
|
|
391
|
+
if (motivo === null)
|
|
392
|
+
motivo = 'conteudo diferente na mesma chave';
|
|
393
|
+
removerPasta(grafoDir, chave);
|
|
394
|
+
fs.renameSync(tmp, final);
|
|
395
|
+
sincronizarPasta(grafoDir);
|
|
396
|
+
return resultado('substituido');
|
|
397
|
+
}
|
|
398
|
+
try {
|
|
399
|
+
fs.renameSync(tmp, final);
|
|
400
|
+
}
|
|
401
|
+
catch (e) {
|
|
402
|
+
const codigo = e.code;
|
|
403
|
+
if (codigo !== 'ENOTEMPTY' && codigo !== 'EEXIST')
|
|
404
|
+
throw e;
|
|
405
|
+
lerIndice(ctx, chave, { grafo: false });
|
|
406
|
+
return resultado('existente');
|
|
407
|
+
}
|
|
408
|
+
sincronizarPasta(grafoDir);
|
|
409
|
+
return resultado('criado');
|
|
410
|
+
}
|
|
411
|
+
finally {
|
|
412
|
+
if (fs.lstatSync(tmp, { throwIfNoEntry: false }))
|
|
413
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
/** O indice do HEAD com o extrator desta instalacao, e a arvore como esta agora. */
|
|
417
|
+
function indiceDoHead(ctx, opcoes = {}) {
|
|
418
|
+
const arvore = (0, intelligence_graph_repo_1.revisaoDaArvore)(ctx.raiz);
|
|
419
|
+
if (arvore.head === null)
|
|
420
|
+
falha('grafo.indice.arvore-nao-limpa', 'sem-commit');
|
|
421
|
+
const perfil = perfilDoIndice(arvore.raiz, undefined, leituraDo(ctx));
|
|
422
|
+
const chave = chaveDoIndice(arvore.head, perfil);
|
|
423
|
+
try {
|
|
424
|
+
return { arvore, perfil, chave, indice: lerIndice(ctx, chave, opcoes) };
|
|
425
|
+
}
|
|
426
|
+
catch (e) {
|
|
427
|
+
if (e.message === 'grafo.indice.ausente')
|
|
428
|
+
falha('grafo.indice.ausente', `sem indice do HEAD ${arvore.head.slice(0, 12)}; rode ork grafo indexar`);
|
|
429
|
+
throw e;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
function bytesDaPasta(dir) {
|
|
433
|
+
let total = 0;
|
|
434
|
+
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
435
|
+
const p = path.join(dir, e.name);
|
|
436
|
+
const st = fs.lstatSync(p);
|
|
437
|
+
total += st.isDirectory() ? bytesDaPasta(p) : st.size;
|
|
438
|
+
}
|
|
439
|
+
return total;
|
|
440
|
+
}
|
|
441
|
+
/** Os indices guardados, com a integridade de cada um, e as sobras de construcao interrompida. */
|
|
442
|
+
function estadoDosIndices(ctx) {
|
|
443
|
+
let dir;
|
|
444
|
+
try {
|
|
445
|
+
dir = pastaDoGrafo(ctx, false);
|
|
446
|
+
}
|
|
447
|
+
catch (e) {
|
|
448
|
+
if (e.message === 'grafo.indice.ausente')
|
|
449
|
+
return { dir: null, indices: [], sobras: [], bytes: 0 };
|
|
450
|
+
throw e;
|
|
451
|
+
}
|
|
452
|
+
const indices = [], sobras = [];
|
|
453
|
+
let bytes = 0;
|
|
454
|
+
for (const nome of fs.readdirSync(dir).sort(intelligence_graph_contract_1.compararUtf8)) {
|
|
455
|
+
// Uma construcao concorrente pode renomear o `.tmp-` entre a listagem e o `lstat`: some da lista.
|
|
456
|
+
const p = path.join(dir, nome), st = fs.lstatSync(p, { throwIfNoEntry: false });
|
|
457
|
+
if (!st)
|
|
458
|
+
continue;
|
|
459
|
+
let tamanho;
|
|
460
|
+
try {
|
|
461
|
+
tamanho = st.isDirectory() && !st.isSymbolicLink() ? bytesDaPasta(p) : st.size;
|
|
462
|
+
}
|
|
463
|
+
catch (e) {
|
|
464
|
+
if (e.code === 'ENOENT')
|
|
465
|
+
continue;
|
|
466
|
+
throw e;
|
|
467
|
+
}
|
|
468
|
+
bytes += tamanho;
|
|
469
|
+
if (!exports.NOME_DE_INDICE.test(nome)) {
|
|
470
|
+
sobras.push(nome);
|
|
471
|
+
continue;
|
|
472
|
+
}
|
|
473
|
+
try {
|
|
474
|
+
const { manifesto } = lerIndice(ctx, nome, { grafo: false });
|
|
475
|
+
indices.push({ chave: nome, bytes: tamanho, revision: manifesto.revision, repository_id: manifesto.repository_id, snapshot_id: manifesto.snapshot_id, problema: null });
|
|
476
|
+
}
|
|
477
|
+
catch (e) {
|
|
478
|
+
indices.push({ chave: nome, bytes: tamanho, revision: null, repository_id: null, snapshot_id: null, problema: e.message });
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
return { dir, indices, sobras, bytes };
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* Apaga os indices fora de `manter` e cuja revisao nao esta em `manterRevisoes` (ou todos, com
|
|
485
|
+
* `tudo`), e as sobras `.tmp-` e `.lixo-` com mais de uma hora. Nome que nao e do indice nunca e
|
|
486
|
+
* apagado.
|
|
487
|
+
*/
|
|
488
|
+
function limparIndices(ctx, opcoes = {}) {
|
|
489
|
+
const estado = estadoDosIndices(ctx);
|
|
490
|
+
if (!estado.dir)
|
|
491
|
+
return { removidos: [], bytes: 0 };
|
|
492
|
+
const dir = estado.dir, agora = opcoes.agora ?? Date.now(), manter = new Set(opcoes.manter ?? []);
|
|
493
|
+
const revisoes = new Set(opcoes.manterRevisoes ?? []);
|
|
494
|
+
const removidos = [];
|
|
495
|
+
for (const i of estado.indices) {
|
|
496
|
+
if (!opcoes.tudo && (manter.has(i.chave) || (i.revision !== null && revisoes.has(i.revision))))
|
|
497
|
+
continue;
|
|
498
|
+
removerPasta(dir, i.chave);
|
|
499
|
+
removidos.push({ nome: i.chave, bytes: i.bytes });
|
|
500
|
+
}
|
|
501
|
+
for (const nome of estado.sobras) {
|
|
502
|
+
if (!/^\.(tmp|lixo)-[0-9a-f-]{36}$/.test(nome))
|
|
503
|
+
continue;
|
|
504
|
+
const p = path.join(dir, nome), st = fs.lstatSync(p, { throwIfNoEntry: false });
|
|
505
|
+
if (!st || agora - st.mtimeMs < exports.PRAZO_DE_SOBRA_MS)
|
|
506
|
+
continue;
|
|
507
|
+
const tamanho = st.isDirectory() && !st.isSymbolicLink() ? bytesDaPasta(p) : st.size;
|
|
508
|
+
removerPasta(dir, nome);
|
|
509
|
+
removidos.push({ nome, bytes: tamanho });
|
|
510
|
+
}
|
|
511
|
+
return { removidos, bytes: removidos.reduce((n, r) => n + r.bytes, 0) };
|
|
512
|
+
}
|