@aragon-agent/cli 0.6.54 → 0.6.56
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/CHANGELOG.md +2912 -2838
- package/README.md +4226 -4042
- package/dist/agent/controller.d.ts +119 -0
- package/dist/agent/controller.js +365 -2
- package/dist/agent/governance-wiring.js +8 -1
- package/dist/agent/redteam-prompt.d.ts +47 -0
- package/dist/agent/redteam-prompt.js +161 -0
- package/dist/agent/redteam-wiring.d.ts +159 -0
- package/dist/agent/redteam-wiring.js +349 -0
- package/dist/agent/system-prompt.d.ts +39 -0
- package/dist/agent/system-prompt.js +18 -0
- package/dist/app/App.d.ts +10 -1
- package/dist/app/App.js +233 -24
- package/dist/app/use-redteam-mode.d.ts +56 -0
- package/dist/app/use-redteam-mode.js +121 -0
- package/dist/cli.js +82 -4
- package/dist/commands/builtins.js +43 -1
- package/dist/commands/catalog.js +5 -0
- package/dist/commands/index-build.js +2 -1
- package/dist/commands/redteam-command.d.ts +22 -0
- package/dist/commands/redteam-command.js +141 -0
- package/dist/commands/registry.d.ts +8 -0
- package/dist/config/app-paths.d.ts +10 -0
- package/dist/config/app-paths.js +12 -0
- package/dist/config/cli-commands.d.ts +29 -0
- package/dist/config/cli-commands.js +76 -1
- package/dist/config/env.d.ts +3 -1
- package/dist/config/env.js +23 -1
- package/dist/config/load.d.ts +22 -0
- package/dist/config/load.js +22 -2
- package/dist/config/redteam-launch.d.ts +77 -0
- package/dist/config/redteam-launch.js +58 -0
- package/dist/config/store.js +21 -1
- package/dist/config/ui-state.d.ts +44 -0
- package/dist/config/ui-state.js +38 -0
- package/dist/exec/bridge/server.d.ts +7 -0
- package/dist/exec/bridge/server.js +6 -2
- package/dist/exec/cli-commands.js +4 -0
- package/dist/exec/index.js +2 -0
- package/dist/exec/options.d.ts +11 -0
- package/dist/exec/options.js +21 -1
- package/dist/gene/block.d.ts +33 -0
- package/dist/gene/block.js +51 -0
- package/dist/gene/capacity.d.ts +74 -0
- package/dist/gene/capacity.js +169 -0
- package/dist/gene/catalog-reconcile.d.ts +13 -0
- package/dist/gene/catalog-reconcile.js +105 -0
- package/dist/gene/catalog-stats.d.ts +27 -0
- package/dist/gene/catalog-stats.js +89 -0
- package/dist/gene/catalog-sync.d.ts +82 -0
- package/dist/gene/catalog-sync.js +324 -0
- package/dist/gene/catalog.d.ts +160 -0
- package/dist/gene/catalog.js +433 -0
- package/dist/gene/cli-commands.d.ts +50 -0
- package/dist/gene/cli-commands.js +500 -0
- package/dist/gene/command-report.d.ts +40 -0
- package/dist/gene/command-report.js +246 -0
- package/dist/gene/command.d.ts +29 -0
- package/dist/gene/command.js +561 -0
- package/dist/gene/commit-apply-types.d.ts +13 -0
- package/dist/gene/commit-apply-types.js +1 -0
- package/dist/gene/commit-compound.d.ts +34 -0
- package/dist/gene/commit-compound.js +212 -0
- package/dist/gene/commit-counts.d.ts +41 -0
- package/dist/gene/commit-counts.js +70 -0
- package/dist/gene/commit-exec.d.ts +42 -0
- package/dist/gene/commit-exec.js +134 -0
- package/dist/gene/commit-head.d.ts +52 -0
- package/dist/gene/commit-head.js +97 -0
- package/dist/gene/commit-plan.d.ts +95 -0
- package/dist/gene/commit-plan.js +68 -0
- package/dist/gene/commit-prepare.d.ts +63 -0
- package/dist/gene/commit-prepare.js +159 -0
- package/dist/gene/commit-types.d.ts +234 -0
- package/dist/gene/commit-types.js +3 -0
- package/dist/gene/curator/agent.d.ts +137 -0
- package/dist/gene/curator/agent.js +203 -0
- package/dist/gene/curator/budget.d.ts +69 -0
- package/dist/gene/curator/budget.js +131 -0
- package/dist/gene/curator/conflicts.d.ts +54 -0
- package/dist/gene/curator/conflicts.js +143 -0
- package/dist/gene/curator/curator.d.ts +170 -0
- package/dist/gene/curator/curator.js +617 -0
- package/dist/gene/curator/deps.d.ts +34 -0
- package/dist/gene/curator/deps.js +48 -0
- package/dist/gene/curator/deterministic.d.ts +62 -0
- package/dist/gene/curator/deterministic.js +287 -0
- package/dist/gene/curator/executors.d.ts +36 -0
- package/dist/gene/curator/executors.js +379 -0
- package/dist/gene/curator/lanes.d.ts +52 -0
- package/dist/gene/curator/lanes.js +99 -0
- package/dist/gene/curator/lease.d.ts +76 -0
- package/dist/gene/curator/lease.js +171 -0
- package/dist/gene/curator/library.d.ts +36 -0
- package/dist/gene/curator/library.js +169 -0
- package/dist/gene/curator/lifecycle.d.ts +52 -0
- package/dist/gene/curator/lifecycle.js +109 -0
- package/dist/gene/curator/maintenance.d.ts +71 -0
- package/dist/gene/curator/maintenance.js +213 -0
- package/dist/gene/curator/probation.d.ts +51 -0
- package/dist/gene/curator/probation.js +71 -0
- package/dist/gene/curator/probe.d.ts +131 -0
- package/dist/gene/curator/probe.js +534 -0
- package/dist/gene/curator/prompt.d.ts +18 -0
- package/dist/gene/curator/prompt.js +128 -0
- package/dist/gene/curator/publish.d.ts +64 -0
- package/dist/gene/curator/publish.js +113 -0
- package/dist/gene/curator/recheck.d.ts +55 -0
- package/dist/gene/curator/recheck.js +103 -0
- package/dist/gene/curator/run-events.d.ts +63 -0
- package/dist/gene/curator/run-events.js +55 -0
- package/dist/gene/curator/similarity.d.ts +13 -0
- package/dist/gene/curator/similarity.js +46 -0
- package/dist/gene/curator/switches.d.ts +78 -0
- package/dist/gene/curator/switches.js +146 -0
- package/dist/gene/curator/task-context.d.ts +93 -0
- package/dist/gene/curator/task-context.js +63 -0
- package/dist/gene/curator/task-runner.d.ts +56 -0
- package/dist/gene/curator/task-runner.js +257 -0
- package/dist/gene/curator/tool-support.d.ts +112 -0
- package/dist/gene/curator/tool-support.js +197 -0
- package/dist/gene/curator/toolkit.d.ts +49 -0
- package/dist/gene/curator/toolkit.js +104 -0
- package/dist/gene/curator/tools-read.d.ts +4 -0
- package/dist/gene/curator/tools-read.js +177 -0
- package/dist/gene/curator/tools-release.d.ts +73 -0
- package/dist/gene/curator/tools-release.js +287 -0
- package/dist/gene/curator/tools-verify.d.ts +47 -0
- package/dist/gene/curator/tools-verify.js +202 -0
- package/dist/gene/curator/tools-write.d.ts +26 -0
- package/dist/gene/curator/tools-write.js +394 -0
- package/dist/gene/curator/tools.d.ts +23 -0
- package/dist/gene/curator/tools.js +21 -0
- package/dist/gene/curator/validate/common.d.ts +87 -0
- package/dist/gene/curator/validate/common.js +132 -0
- package/dist/gene/curator/validate/evidence-tokens.d.ts +36 -0
- package/dist/gene/curator/validate/evidence-tokens.js +139 -0
- package/dist/gene/curator/validate/index.d.ts +23 -0
- package/dist/gene/curator/validate/index.js +62 -0
- package/dist/gene/curator/validate/knowledge.d.ts +25 -0
- package/dist/gene/curator/validate/knowledge.js +216 -0
- package/dist/gene/curator/validate/live-check.d.ts +14 -0
- package/dist/gene/curator/validate/live-check.js +144 -0
- package/dist/gene/curator/validate/ports.d.ts +67 -0
- package/dist/gene/curator/validate/ports.js +1 -0
- package/dist/gene/curator/validate/prompts.d.ts +41 -0
- package/dist/gene/curator/validate/prompts.js +161 -0
- package/dist/gene/curator/validate/skill.d.ts +15 -0
- package/dist/gene/curator/validate/skill.js +251 -0
- package/dist/gene/curator/validate/tool.d.ts +6 -0
- package/dist/gene/curator/validate/tool.js +217 -0
- package/dist/gene/curator/validate/types.d.ts +90 -0
- package/dist/gene/curator/validate/types.js +1 -0
- package/dist/gene/curator/validator-ports.d.ts +38 -0
- package/dist/gene/curator/validator-ports.js +29 -0
- package/dist/gene/diag.d.ts +209 -0
- package/dist/gene/diag.js +549 -0
- package/dist/gene/env.d.ts +10 -0
- package/dist/gene/env.js +214 -0
- package/dist/gene/eval-recorder.d.ts +84 -0
- package/dist/gene/eval-recorder.js +222 -0
- package/dist/gene/explain-transport.d.ts +3 -0
- package/dist/gene/explain-transport.js +39 -0
- package/dist/gene/explain.d.ts +96 -0
- package/dist/gene/explain.js +293 -0
- package/dist/gene/fs.d.ts +39 -0
- package/dist/gene/fs.js +139 -0
- package/dist/gene/fsck.d.ts +68 -0
- package/dist/gene/fsck.js +134 -0
- package/dist/gene/gc-library-sweeps.d.ts +9 -0
- package/dist/gene/gc-library-sweeps.js +220 -0
- package/dist/gene/gc-rejected-set.d.ts +15 -0
- package/dist/gene/gc-rejected-set.js +63 -0
- package/dist/gene/gc-safe.d.ts +12 -0
- package/dist/gene/gc-safe.js +74 -0
- package/dist/gene/gc-scope-sweeps.d.ts +18 -0
- package/dist/gene/gc-scope-sweeps.js +297 -0
- package/dist/gene/gc-types.d.ts +55 -0
- package/dist/gene/gc-types.js +26 -0
- package/dist/gene/gc.d.ts +42 -0
- package/dist/gene/gc.js +129 -0
- package/dist/gene/gene-errors.d.ts +23 -0
- package/dist/gene/gene-errors.js +29 -0
- package/dist/gene/hints.d.ts +91 -0
- package/dist/gene/hints.js +394 -0
- package/dist/gene/hub.d.ts +149 -0
- package/dist/gene/hub.js +371 -0
- package/dist/gene/import-plan.d.ts +80 -0
- package/dist/gene/import-plan.js +294 -0
- package/dist/gene/import-proposal.d.ts +23 -0
- package/dist/gene/import-proposal.js +101 -0
- package/dist/gene/import-skill-port.d.ts +6 -0
- package/dist/gene/import-skill-port.js +53 -0
- package/dist/gene/import-sources.d.ts +48 -0
- package/dist/gene/import-sources.js +140 -0
- package/dist/gene/index-writer.d.ts +36 -0
- package/dist/gene/index-writer.js +101 -0
- package/dist/gene/learn/learn-call.d.ts +63 -0
- package/dist/gene/learn/learn-call.js +157 -0
- package/dist/gene/learn/learn-prompt.d.ts +51 -0
- package/dist/gene/learn/learn-prompt.js +245 -0
- package/dist/gene/learn/learner.d.ts +181 -0
- package/dist/gene/learn/learner.js +426 -0
- package/dist/gene/learn/ledger.d.ts +220 -0
- package/dist/gene/learn/ledger.js +394 -0
- package/dist/gene/learn/proposal-build.d.ts +83 -0
- package/dist/gene/learn/proposal-build.js +211 -0
- package/dist/gene/learn/proposal-guard.d.ts +43 -0
- package/dist/gene/learn/proposal-guard.js +37 -0
- package/dist/gene/learn/signals-port.d.ts +47 -0
- package/dist/gene/learn/signals-port.js +86 -0
- package/dist/gene/maintenance-paths.d.ts +7 -0
- package/dist/gene/maintenance-paths.js +20 -0
- package/dist/gene/maintenance-probation.d.ts +33 -0
- package/dist/gene/maintenance-probation.js +127 -0
- package/dist/gene/maintenance-proposals.d.ts +24 -0
- package/dist/gene/maintenance-proposals.js +68 -0
- package/dist/gene/maintenance-runner.d.ts +92 -0
- package/dist/gene/maintenance-runner.js +262 -0
- package/dist/gene/maintenance-tasks.d.ts +37 -0
- package/dist/gene/maintenance-tasks.js +95 -0
- package/dist/gene/manager-actions.d.ts +12 -0
- package/dist/gene/manager-actions.js +279 -0
- package/dist/gene/manager-approve.d.ts +29 -0
- package/dist/gene/manager-approve.js +84 -0
- package/dist/gene/manager-context.d.ts +90 -0
- package/dist/gene/manager-context.js +201 -0
- package/dist/gene/manager-detail.d.ts +17 -0
- package/dist/gene/manager-detail.js +313 -0
- package/dist/gene/manager-gc.d.ts +13 -0
- package/dist/gene/manager-gc.js +81 -0
- package/dist/gene/manager-library.d.ts +39 -0
- package/dist/gene/manager-library.js +90 -0
- package/dist/gene/manager-list.d.ts +27 -0
- package/dist/gene/manager-list.js +170 -0
- package/dist/gene/manager-queue.d.ts +16 -0
- package/dist/gene/manager-queue.js +124 -0
- package/dist/gene/manager-stats.d.ts +28 -0
- package/dist/gene/manager-stats.js +53 -0
- package/dist/gene/manager-view.d.ts +27 -0
- package/dist/gene/manager-view.js +124 -0
- package/dist/gene/manager.d.ts +56 -0
- package/dist/gene/manager.js +179 -0
- package/dist/gene/orphan-scopes.d.ts +37 -0
- package/dist/gene/orphan-scopes.js +150 -0
- package/dist/gene/paths.d.ts +73 -0
- package/dist/gene/paths.js +239 -0
- package/dist/gene/plan-content.d.ts +73 -0
- package/dist/gene/plan-content.js +522 -0
- package/dist/gene/plan-lifecycle.d.ts +29 -0
- package/dist/gene/plan-lifecycle.js +310 -0
- package/dist/gene/policy.d.ts +71 -0
- package/dist/gene/policy.js +313 -0
- package/dist/gene/project-learning.d.ts +25 -0
- package/dist/gene/project-learning.js +54 -0
- package/dist/gene/propagation.d.ts +48 -0
- package/dist/gene/propagation.js +45 -0
- package/dist/gene/queue-lock.d.ts +22 -0
- package/dist/gene/queue-lock.js +99 -0
- package/dist/gene/queue-record.d.ts +57 -0
- package/dist/gene/queue-record.js +145 -0
- package/dist/gene/queue.d.ts +235 -0
- package/dist/gene/queue.js +764 -0
- package/dist/gene/read.d.ts +61 -0
- package/dist/gene/read.js +252 -0
- package/dist/gene/runlog.d.ts +101 -0
- package/dist/gene/runlog.js +404 -0
- package/dist/gene/schema-lite.d.ts +24 -0
- package/dist/gene/schema-lite.js +159 -0
- package/dist/gene/scope-guard.d.ts +23 -0
- package/dist/gene/scope-guard.js +9 -0
- package/dist/gene/scope-lock.d.ts +48 -0
- package/dist/gene/scope-lock.js +222 -0
- package/dist/gene/scope-verify.d.ts +63 -0
- package/dist/gene/scope-verify.js +123 -0
- package/dist/gene/secrets.d.ts +43 -0
- package/dist/gene/secrets.js +161 -0
- package/dist/gene/service-context.d.ts +43 -0
- package/dist/gene/service-context.js +79 -0
- package/dist/gene/service-prepare.d.ts +25 -0
- package/dist/gene/service-prepare.js +219 -0
- package/dist/gene/service-types.d.ts +196 -0
- package/dist/gene/service-types.js +1 -0
- package/dist/gene/service-view.d.ts +41 -0
- package/dist/gene/service-view.js +69 -0
- package/dist/gene/service.d.ts +114 -0
- package/dist/gene/service.js +761 -0
- package/dist/gene/session-start.d.ts +36 -0
- package/dist/gene/session-start.js +212 -0
- package/dist/gene/store-port.d.ts +88 -0
- package/dist/gene/store-port.js +10 -0
- package/dist/gene/store-rows.d.ts +36 -0
- package/dist/gene/store-rows.js +72 -0
- package/dist/gene/store.d.ts +125 -0
- package/dist/gene/store.js +622 -0
- package/dist/gene/tombstones.d.ts +47 -0
- package/dist/gene/tombstones.js +61 -0
- package/dist/gene/tool-runner.d.ts +47 -0
- package/dist/gene/tool-runner.js +154 -0
- package/dist/gene/tool-screen.d.ts +41 -0
- package/dist/gene/tool-screen.js +227 -0
- package/dist/gene/tools.d.ts +112 -0
- package/dist/gene/tools.js +539 -0
- package/dist/gene/transfer.d.ts +85 -0
- package/dist/gene/transfer.js +433 -0
- package/dist/gene/ui-hints.d.ts +15 -0
- package/dist/gene/ui-hints.js +67 -0
- package/dist/gene/usage-fold-cursor.d.ts +24 -0
- package/dist/gene/usage-fold-cursor.js +115 -0
- package/dist/gene/usage-fold.d.ts +49 -0
- package/dist/gene/usage-fold.js +397 -0
- package/dist/gene/usage.d.ts +67 -0
- package/dist/gene/usage.js +231 -0
- package/dist/gene/version-service.d.ts +118 -0
- package/dist/gene/version-service.js +453 -0
- package/dist/gene/wiring-events.d.ts +43 -0
- package/dist/gene/wiring-events.js +113 -0
- package/dist/gene/wiring-models.d.ts +46 -0
- package/dist/gene/wiring-models.js +81 -0
- package/dist/gene/wiring.d.ts +200 -0
- package/dist/gene/wiring.js +764 -0
- package/dist/governance/prompts/orchestrator-block.js +3 -2
- package/dist/host/controller-factory.d.ts +8 -0
- package/dist/host/controller-factory.js +7 -0
- package/dist/host/gene.d.ts +26 -0
- package/dist/host/gene.js +24 -0
- package/dist/host/index.d.ts +1 -0
- package/dist/host/index.js +1 -0
- package/dist/session/checkpoint.d.ts +15 -0
- package/dist/session/checkpoint.js +18 -0
- package/dist/session/persist.d.ts +21 -0
- package/dist/session/persist.js +10 -0
- package/dist/session/startup-session.d.ts +11 -2
- package/dist/session/startup-session.js +12 -2
- package/dist/session/validate-session.js +31 -0
- package/dist/team/runtime.d.ts +16 -0
- package/dist/team/runtime.js +29 -0
- package/dist/team/subagent.d.ts +55 -0
- package/dist/team/subagent.js +46 -2
- package/dist/tools/index.d.ts +60 -2
- package/dist/tools/index.js +68 -10
- package/package.json +3 -3
- package/skills/project-indexer/SKILL.md +275 -147
- package/skills/project-indexer/templates/artifact-hygiene-template.md +14 -0
- package/skills/project-indexer/templates/config-template.md +12 -0
- package/skills/project-indexer/templates/index-template.md +4 -0
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The processing record: `runs/<yyyy-mm-dd>.jsonl`, append-only (gene-bank spec 6.7, 12.8,
|
|
3
|
+
* I-19, I-23).
|
|
4
|
+
*
|
|
5
|
+
* ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
|
|
6
|
+
*
|
|
7
|
+
* THIS FILE IS THE PROCESSES' SHARED MEMORY. The learner (in the session that is running),
|
|
8
|
+
* the curator (in whichever process holds the lease) and the version service all append here,
|
|
9
|
+
* and the activity hub of EVERY open UI tails it. That is how a desktop window shows what a
|
|
10
|
+
* terminal's curator is doing without any IPC between them (I-23).
|
|
11
|
+
*
|
|
12
|
+
* I-19: A RECORD NEVER CARRIES GENE TEXT. The entry type has no field for a body, an evidence
|
|
13
|
+
* quote or a summary; the only free text is `detail`, which is flattened to one line, run
|
|
14
|
+
* through `redactSecrets` and clipped to 240 code points BEFORE it is written. Everything else
|
|
15
|
+
* is an id, a number or an enum, and each is validated rather than trusted - a caller bug must
|
|
16
|
+
* not be able to smuggle text through `geneId`.
|
|
17
|
+
*
|
|
18
|
+
* WRITES NEVER THROW. A full disk or a locked file must not fail the user turn that happened to
|
|
19
|
+
* trigger a log line; `append` returns null and the caller carries on (I-24).
|
|
20
|
+
*
|
|
21
|
+
* READS ARE TOLERANT. `seq` is monotonic only within one process (two processes appending to the
|
|
22
|
+
* same day interleave), and a torn or hand-edited line is skipped, so nothing here assumes a
|
|
23
|
+
* clean file.
|
|
24
|
+
*/
|
|
25
|
+
import { promises as nodeFs } from 'node:fs';
|
|
26
|
+
import { GENE_TYPES } from '@aragon-agent/tui/model/gene/types';
|
|
27
|
+
import { isValidGeneId, isValidProposalId, isValidScope } from '@aragon-agent/tui/model/gene/ids';
|
|
28
|
+
import { GENE_LIMITS } from '@aragon-agent/tui/model/gene/limits';
|
|
29
|
+
import { dayStamp, geneRoot, runsDir, runsFile } from './paths.js';
|
|
30
|
+
import { appendJsonl, listDir, readJsonlFrom, removeInside, statOrNull } from './fs.js';
|
|
31
|
+
import { redactSecrets } from './secrets.js';
|
|
32
|
+
export const RUN_DETAIL_MAX = 240;
|
|
33
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
34
|
+
const READ_BATCH_LINES = 200;
|
|
35
|
+
const READ_CHUNK_BYTES = 64 * 1024;
|
|
36
|
+
const RUN_FILE_RE = /^(\d{4}-\d{2}-\d{2})\.jsonl$/;
|
|
37
|
+
const TOKEN_COMPONENTS = ['curator', 'validation', 'reviewer', 'retrieval'];
|
|
38
|
+
// ---------------------------------------------------------------------------
|
|
39
|
+
// Pure helpers
|
|
40
|
+
// ---------------------------------------------------------------------------
|
|
41
|
+
function clipPoints(text, max) {
|
|
42
|
+
const points = Array.from(text);
|
|
43
|
+
return points.length <= max ? text : points.slice(0, max).join('').trimEnd();
|
|
44
|
+
}
|
|
45
|
+
/** Flatten, scrub, clip - in that order, so a secret cut by the clip cannot survive half-visible. */
|
|
46
|
+
export function sanitizeDetail(detail, knownSecrets = []) {
|
|
47
|
+
if (typeof detail !== 'string')
|
|
48
|
+
return undefined;
|
|
49
|
+
const flat = detail.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim();
|
|
50
|
+
if (flat.length === 0)
|
|
51
|
+
return undefined;
|
|
52
|
+
return clipPoints(redactSecrets(flat, knownSecrets).text, RUN_DETAIL_MAX);
|
|
53
|
+
}
|
|
54
|
+
function nonNegativeInt(value) {
|
|
55
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.trunc(value) : undefined;
|
|
56
|
+
}
|
|
57
|
+
function sanitizeTokens(tokens) {
|
|
58
|
+
if (!tokens || !TOKEN_COMPONENTS.includes(tokens.component))
|
|
59
|
+
return undefined;
|
|
60
|
+
const input = nonNegativeInt(tokens.in);
|
|
61
|
+
const output = nonNegativeInt(tokens.out);
|
|
62
|
+
if (input === undefined || output === undefined)
|
|
63
|
+
return undefined;
|
|
64
|
+
return { in: input, out: output, component: tokens.component };
|
|
65
|
+
}
|
|
66
|
+
/** The identifiers, version and tokens of an entry - each checked, none trusted (I-19). */
|
|
67
|
+
function validatedFields(entry) {
|
|
68
|
+
const tokens = sanitizeTokens(entry.tokens);
|
|
69
|
+
const version = nonNegativeInt(entry.version);
|
|
70
|
+
return {
|
|
71
|
+
...(isValidProposalId(entry.proposalId) ? { proposalId: entry.proposalId } : {}),
|
|
72
|
+
...(isValidGeneId(entry.geneId) ? { geneId: entry.geneId } : {}),
|
|
73
|
+
...(version !== undefined && version > 0 ? { version } : {}),
|
|
74
|
+
...(isValidScope(entry.scope) ? { scope: entry.scope } : {}),
|
|
75
|
+
...(entry.type && GENE_TYPES.includes(entry.type) ? { type: entry.type } : {}),
|
|
76
|
+
...(tokens ? { tokens } : {}),
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
/** A parsed line is a record only if it has the two fields every reader depends on. */
|
|
80
|
+
function isRunRecord(value) {
|
|
81
|
+
if (typeof value !== 'object' || value === null)
|
|
82
|
+
return false;
|
|
83
|
+
const r = value;
|
|
84
|
+
return typeof r.ev === 'string' && typeof r.t === 'number' && Number.isFinite(r.t);
|
|
85
|
+
}
|
|
86
|
+
function encodeCursor(cursor) {
|
|
87
|
+
return Buffer.from(JSON.stringify(cursor), 'utf8').toString('base64url');
|
|
88
|
+
}
|
|
89
|
+
function decodeCursor(raw) {
|
|
90
|
+
if (!raw)
|
|
91
|
+
return null;
|
|
92
|
+
try {
|
|
93
|
+
const parsed = JSON.parse(Buffer.from(raw, 'base64url').toString('utf8'));
|
|
94
|
+
const c = parsed;
|
|
95
|
+
const dayOk = typeof c?.d === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(c.d);
|
|
96
|
+
const ok = dayOk && Number.isInteger(c.o) && c.o >= 0;
|
|
97
|
+
return ok ? { d: c.d, o: c.o } : null;
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Up to `maxLines` lines ending at byte `endOffset`, newest first, each with its start offset.
|
|
105
|
+
* Works on BYTES (never decodes a chunk boundary), so a multi-byte character straddling two
|
|
106
|
+
* chunks is not corrupted.
|
|
107
|
+
*/
|
|
108
|
+
async function readLinesBackward(path, endOffset, maxLines) {
|
|
109
|
+
let handle;
|
|
110
|
+
try {
|
|
111
|
+
handle = await nodeFs.open(path, 'r');
|
|
112
|
+
const { size } = await handle.stat();
|
|
113
|
+
const end = Math.min(endOffset, size);
|
|
114
|
+
const lines = [];
|
|
115
|
+
let acc = Buffer.alloc(0);
|
|
116
|
+
let accStart = end;
|
|
117
|
+
for (;;) {
|
|
118
|
+
acc = extractLines({ acc, accStart, lines, maxLines });
|
|
119
|
+
if (lines.length >= maxLines || accStart === 0)
|
|
120
|
+
break;
|
|
121
|
+
const start = Math.max(0, accStart - READ_CHUNK_BYTES);
|
|
122
|
+
const chunk = Buffer.alloc(accStart - start);
|
|
123
|
+
await handle.read(chunk, 0, chunk.length, start);
|
|
124
|
+
acc = Buffer.concat([chunk, acc]);
|
|
125
|
+
accStart = start;
|
|
126
|
+
}
|
|
127
|
+
if (accStart === 0 && lines.length < maxLines)
|
|
128
|
+
pushFirstLine(acc, lines);
|
|
129
|
+
return lines;
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
return [];
|
|
133
|
+
}
|
|
134
|
+
finally {
|
|
135
|
+
await handle?.close().catch(() => undefined);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
/** Pull complete lines off the END of `acc`; returns what is left (the partial head). */
|
|
139
|
+
function extractLines(args) {
|
|
140
|
+
let acc = args.acc;
|
|
141
|
+
while (args.lines.length < args.maxLines) {
|
|
142
|
+
let hi = acc.length;
|
|
143
|
+
if (hi > 0 && acc[hi - 1] === 0x0a)
|
|
144
|
+
hi -= 1;
|
|
145
|
+
const nl = hi > 0 ? acc.lastIndexOf(0x0a, hi - 1) : -1;
|
|
146
|
+
if (nl < 0)
|
|
147
|
+
break;
|
|
148
|
+
args.lines.push({ text: acc.subarray(nl + 1, hi).toString('utf8'), start: args.accStart + nl + 1 });
|
|
149
|
+
acc = acc.subarray(0, nl + 1);
|
|
150
|
+
}
|
|
151
|
+
return acc;
|
|
152
|
+
}
|
|
153
|
+
/** The first line of the file has no newline before it, so `extractLines` cannot find it. */
|
|
154
|
+
function pushFirstLine(acc, lines) {
|
|
155
|
+
let hi = acc.length;
|
|
156
|
+
if (hi > 0 && acc[hi - 1] === 0x0a)
|
|
157
|
+
hi -= 1;
|
|
158
|
+
if (hi > 0)
|
|
159
|
+
lines.push({ text: acc.subarray(0, hi).toString('utf8'), start: 0 });
|
|
160
|
+
}
|
|
161
|
+
export class GeneRunLog {
|
|
162
|
+
deps;
|
|
163
|
+
ctx;
|
|
164
|
+
seqByDay = new Map();
|
|
165
|
+
meter = new Map();
|
|
166
|
+
/** Appends are serialised so file order equals `seq` order within this process. */
|
|
167
|
+
chain = Promise.resolve();
|
|
168
|
+
constructor(deps) {
|
|
169
|
+
this.deps = deps;
|
|
170
|
+
this.ctx = deps.ctx ?? {};
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* The shape the version service's run-log port expects (`record`, result ignored). It is the
|
|
174
|
+
* same write as `append`, so a commit's record gets the same validation and the same `seq`.
|
|
175
|
+
*/
|
|
176
|
+
async record(entry) {
|
|
177
|
+
await this.append(entry);
|
|
178
|
+
}
|
|
179
|
+
/** Append one record. Returns the record as written, or null if it could not be written. */
|
|
180
|
+
append(entry) {
|
|
181
|
+
const run = this.chain.then(() => this.appendNow(entry));
|
|
182
|
+
this.chain = run.catch(() => undefined);
|
|
183
|
+
return run;
|
|
184
|
+
}
|
|
185
|
+
async appendNow(entry) {
|
|
186
|
+
try {
|
|
187
|
+
const t = this.deps.now();
|
|
188
|
+
const path = runsFile(dayStamp(t), this.ctx);
|
|
189
|
+
if (path === null)
|
|
190
|
+
return null;
|
|
191
|
+
const seq = await this.nextSeq(dayStamp(t), path);
|
|
192
|
+
const record = this.buildRecord(entry, t, seq);
|
|
193
|
+
await appendJsonl(path, record);
|
|
194
|
+
return record;
|
|
195
|
+
}
|
|
196
|
+
catch (error) {
|
|
197
|
+
this.deps.onError?.(error);
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
buildRecord(entry, t, seq) {
|
|
202
|
+
const detail = sanitizeDetail(entry.detail, this.deps.knownSecrets?.() ?? []);
|
|
203
|
+
return {
|
|
204
|
+
t,
|
|
205
|
+
seq,
|
|
206
|
+
by: {
|
|
207
|
+
pid: this.deps.pid,
|
|
208
|
+
kind: this.deps.kind,
|
|
209
|
+
...(this.deps.sessionId ? { sessionId: this.deps.sessionId } : {}),
|
|
210
|
+
...(entry.lease === true ? { lease: true } : {}),
|
|
211
|
+
},
|
|
212
|
+
ev: entry.ev,
|
|
213
|
+
...validatedFields(entry),
|
|
214
|
+
...(detail !== undefined ? { detail } : {}),
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
/** Continue from the file's last `seq` the first time a day is seen, then count in memory. */
|
|
218
|
+
async nextSeq(day, path) {
|
|
219
|
+
let last = this.seqByDay.get(day);
|
|
220
|
+
if (last === undefined) {
|
|
221
|
+
const tail = await readLinesBackward(path, Number.MAX_SAFE_INTEGER, 3);
|
|
222
|
+
last = 0;
|
|
223
|
+
for (const line of tail) {
|
|
224
|
+
try {
|
|
225
|
+
const seq = JSON.parse(line.text).seq;
|
|
226
|
+
if (typeof seq === 'number' && Number.isFinite(seq))
|
|
227
|
+
last = Math.max(last, seq);
|
|
228
|
+
}
|
|
229
|
+
catch {
|
|
230
|
+
// A torn last line has no seq; the next complete one does.
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
const next = last + 1;
|
|
235
|
+
this.seqByDay.set(day, next);
|
|
236
|
+
return next;
|
|
237
|
+
}
|
|
238
|
+
/** `yyyy-mm-dd` of the file new records go to right now. */
|
|
239
|
+
today() {
|
|
240
|
+
return dayStamp(this.deps.now());
|
|
241
|
+
}
|
|
242
|
+
/** Size in bytes of one day's file, or 0. */
|
|
243
|
+
async sizeOf(day) {
|
|
244
|
+
const path = runsFile(day, this.ctx);
|
|
245
|
+
return path === null ? 0 : ((await statOrNull(path))?.size ?? 0);
|
|
246
|
+
}
|
|
247
|
+
// ---- reading -----------------------------------------------------------
|
|
248
|
+
/**
|
|
249
|
+
* Newest-first pagination across day files with an opaque cursor. `events` filters while
|
|
250
|
+
* scanning, so a filtered page still fills up instead of coming back short.
|
|
251
|
+
*/
|
|
252
|
+
async read(options) {
|
|
253
|
+
const limit = Math.min(500, Math.max(1, Math.trunc(options.limit) || 1));
|
|
254
|
+
const wanted = options.events && options.events.length > 0 ? new Set(options.events) : null;
|
|
255
|
+
const from = decodeCursor(options.cursor);
|
|
256
|
+
const days = (await this.listDays()).filter((d) => from === null || d <= from.d);
|
|
257
|
+
const found = await this.collect({ days, from, limit, wanted });
|
|
258
|
+
const full = found.records.length >= limit;
|
|
259
|
+
const more = found.lastStart !== null && full && (await this.hasEarlier(days, found.lastStart));
|
|
260
|
+
return { records: found.records, ...(more && found.lastStart ? { next: encodeCursor(found.lastStart) } : {}) };
|
|
261
|
+
}
|
|
262
|
+
/** Walk the day files newest first until `limit` records matched. */
|
|
263
|
+
async collect(args) {
|
|
264
|
+
const records = [];
|
|
265
|
+
let lastStart = null;
|
|
266
|
+
for (const day of args.days) {
|
|
267
|
+
const path = runsFile(day, this.ctx);
|
|
268
|
+
if (path === null)
|
|
269
|
+
continue;
|
|
270
|
+
const size = (await statOrNull(path))?.size ?? 0;
|
|
271
|
+
const end = args.from !== null && day === args.from.d ? Math.min(args.from.o, size) : size;
|
|
272
|
+
const scan = await scanDay({ path, day, end, want: args.limit - records.length, wanted: args.wanted });
|
|
273
|
+
records.push(...scan.records);
|
|
274
|
+
lastStart = scan.lastStart ?? lastStart;
|
|
275
|
+
if (records.length >= args.limit)
|
|
276
|
+
break;
|
|
277
|
+
}
|
|
278
|
+
return { records, lastStart };
|
|
279
|
+
}
|
|
280
|
+
async hasEarlier(days, at) {
|
|
281
|
+
if (at.o > 0)
|
|
282
|
+
return true;
|
|
283
|
+
for (const day of days.filter((d) => d < at.d)) {
|
|
284
|
+
if ((await this.sizeOf(day)) > 0)
|
|
285
|
+
return true;
|
|
286
|
+
}
|
|
287
|
+
return false;
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Complete records after byte `offset` of one day's file - the hub's incremental read. A
|
|
291
|
+
* truncated file resets to 0 (`reset: true`) rather than returning a negative increment.
|
|
292
|
+
*/
|
|
293
|
+
async tailFrom(day, offset) {
|
|
294
|
+
const path = runsFile(day, this.ctx);
|
|
295
|
+
if (path === null)
|
|
296
|
+
return { records: [], nextOffset: 0, reset: false };
|
|
297
|
+
const read = await readJsonlFrom(path, Math.max(0, offset));
|
|
298
|
+
if (read.corrupt === -1)
|
|
299
|
+
return { records: [], nextOffset: 0, reset: true };
|
|
300
|
+
return { records: read.rows.filter(isRunRecord), nextOffset: read.nextOffset, reset: false };
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* Records from the tail of one day's file, for a subscriber that needs the CURRENT state and
|
|
304
|
+
* not just what happens next. Returns the offset to continue from.
|
|
305
|
+
*/
|
|
306
|
+
async tailInit(day, maxBytes) {
|
|
307
|
+
const path = runsFile(day, this.ctx);
|
|
308
|
+
const size = path === null ? 0 : ((await statOrNull(path))?.size ?? 0);
|
|
309
|
+
const start = Math.max(0, size - maxBytes);
|
|
310
|
+
// A window that starts mid-line makes its first fragment unparseable; `tailFrom` skips it.
|
|
311
|
+
return this.tailFrom(day, start);
|
|
312
|
+
}
|
|
313
|
+
// ---- budget and retention ---------------------------------------------
|
|
314
|
+
/**
|
|
315
|
+
* Tokens spent by learning, curation, validation and retrieval since `sinceMs`, summed from
|
|
316
|
+
* every process's records (the daily budget is shared, 10.6). Incremental: each day file is
|
|
317
|
+
* parsed once and then only its new tail.
|
|
318
|
+
*/
|
|
319
|
+
async tokensSince(sinceMs) {
|
|
320
|
+
const now = this.deps.now();
|
|
321
|
+
// A window longer than three days is not a budget window; clamp so a bad argument cannot
|
|
322
|
+
// make this walk the whole retention period.
|
|
323
|
+
const since = Math.max(sinceMs, now - 3 * DAY_MS);
|
|
324
|
+
const last = dayStamp(now);
|
|
325
|
+
let total = 0;
|
|
326
|
+
for (let t = since, day = dayStamp(t); day <= last; t += DAY_MS, day = dayStamp(t)) {
|
|
327
|
+
total += await this.sumDay(day, since);
|
|
328
|
+
}
|
|
329
|
+
return total;
|
|
330
|
+
}
|
|
331
|
+
async sumDay(day, sinceMs) {
|
|
332
|
+
const state = this.meter.get(day) ?? { offset: 0, items: [] };
|
|
333
|
+
let tail = await this.tailFrom(day, state.offset);
|
|
334
|
+
if (tail.reset) {
|
|
335
|
+
state.items = [];
|
|
336
|
+
tail = await this.tailFrom(day, 0);
|
|
337
|
+
}
|
|
338
|
+
for (const record of tail.records) {
|
|
339
|
+
const spent = (record.tokens?.in ?? 0) + (record.tokens?.out ?? 0);
|
|
340
|
+
if (spent > 0)
|
|
341
|
+
state.items.push({ t: record.t, tokens: spent });
|
|
342
|
+
}
|
|
343
|
+
state.offset = tail.nextOffset;
|
|
344
|
+
this.meter.set(day, state);
|
|
345
|
+
return state.items.filter((i) => i.t >= sinceMs).reduce((sum, i) => sum + i.tokens, 0);
|
|
346
|
+
}
|
|
347
|
+
/** Delete day files older than `runsKeepDays` (14). Returns how many went. */
|
|
348
|
+
async prune() {
|
|
349
|
+
const cutoff = dayStamp(this.deps.now() - GENE_LIMITS.runsKeepDays * DAY_MS);
|
|
350
|
+
let removed = 0;
|
|
351
|
+
for (const day of await this.listDays()) {
|
|
352
|
+
const path = day < cutoff ? runsFile(day, this.ctx) : null;
|
|
353
|
+
if (path === null)
|
|
354
|
+
continue;
|
|
355
|
+
if (await removeInside(geneRoot(this.ctx), path)) {
|
|
356
|
+
removed += 1;
|
|
357
|
+
this.meter.delete(day);
|
|
358
|
+
this.seqByDay.delete(day);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
return removed;
|
|
362
|
+
}
|
|
363
|
+
async listDays() {
|
|
364
|
+
const names = await listDir(runsDir(this.ctx));
|
|
365
|
+
return names
|
|
366
|
+
.map((n) => RUN_FILE_RE.exec(n)?.[1])
|
|
367
|
+
.filter((d) => d !== undefined)
|
|
368
|
+
.sort()
|
|
369
|
+
.reverse();
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
/** Read one day file backwards in batches, keeping matches until `want` are found. */
|
|
373
|
+
async function scanDay(args) {
|
|
374
|
+
const records = [];
|
|
375
|
+
let lastStart = null;
|
|
376
|
+
let end = args.end;
|
|
377
|
+
while (end > 0 && records.length < args.want) {
|
|
378
|
+
const batch = await readLinesBackward(args.path, end, READ_BATCH_LINES);
|
|
379
|
+
if (batch.length === 0)
|
|
380
|
+
break;
|
|
381
|
+
for (const line of batch) {
|
|
382
|
+
const record = parseLine(line.text);
|
|
383
|
+
if (record === null || (args.wanted !== null && !args.wanted.has(record.ev)))
|
|
384
|
+
continue;
|
|
385
|
+
records.push(record);
|
|
386
|
+
lastStart = { d: args.day, o: line.start };
|
|
387
|
+
if (records.length >= args.want)
|
|
388
|
+
break;
|
|
389
|
+
}
|
|
390
|
+
end = batch[batch.length - 1].start;
|
|
391
|
+
}
|
|
392
|
+
return { records, lastStart };
|
|
393
|
+
}
|
|
394
|
+
function parseLine(text) {
|
|
395
|
+
if (text.trim().length === 0)
|
|
396
|
+
return null;
|
|
397
|
+
try {
|
|
398
|
+
const parsed = JSON.parse(text);
|
|
399
|
+
return isRunRecord(parsed) ? parsed : null;
|
|
400
|
+
}
|
|
401
|
+
catch {
|
|
402
|
+
return null;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A small JSON-Schema subset validator for tool genes (gene-bank spec 6.3.2, 9.1, 10.7.2 T1/T6).
|
|
3
|
+
*
|
|
4
|
+
* ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`. PURE.
|
|
5
|
+
*
|
|
6
|
+
* WHY NOT AJV: Ajv is an OPTIONAL dependency of this package (the tool parameter validator
|
|
7
|
+
* falls back without it), and a tool gene's argument check must not depend on whether an
|
|
8
|
+
* optional package happens to be installed. The subset below is exactly what a tool gene's
|
|
9
|
+
* `inputSchema` / `outputSchema` need and what a model can write reliably: `type`, `enum`,
|
|
10
|
+
* `pattern`, `minLength` / `maxLength`, `minimum` / `maximum`, `required`, `properties`,
|
|
11
|
+
* `additionalProperties: false` and `items`. Anything else in a schema is IGNORED for
|
|
12
|
+
* validation but REJECTED by `checkSchemaShape` when it would change the meaning (`$ref`,
|
|
13
|
+
* `oneOf`, ...): a schema this validator cannot honour must not be accepted as if it could.
|
|
14
|
+
*/
|
|
15
|
+
export interface SchemaIssue {
|
|
16
|
+
path: string;
|
|
17
|
+
message: string;
|
|
18
|
+
}
|
|
19
|
+
/** A pattern that cannot be compiled, or is long enough to be a ReDoS vector, is not honoured. */
|
|
20
|
+
export declare function safeRegExp(pattern: string): RegExp | null;
|
|
21
|
+
/** Validate `value` against `schema`. An empty list means valid. */
|
|
22
|
+
export declare function validateAgainstSchema(schema: unknown, value: unknown): SchemaIssue[];
|
|
23
|
+
/** Is this a schema the validator can honour (T1)? */
|
|
24
|
+
export declare function checkSchemaShape(schema: unknown, maxBytes?: number): SchemaIssue[];
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A small JSON-Schema subset validator for tool genes (gene-bank spec 6.3.2, 9.1, 10.7.2 T1/T6).
|
|
3
|
+
*
|
|
4
|
+
* ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`. PURE.
|
|
5
|
+
*
|
|
6
|
+
* WHY NOT AJV: Ajv is an OPTIONAL dependency of this package (the tool parameter validator
|
|
7
|
+
* falls back without it), and a tool gene's argument check must not depend on whether an
|
|
8
|
+
* optional package happens to be installed. The subset below is exactly what a tool gene's
|
|
9
|
+
* `inputSchema` / `outputSchema` need and what a model can write reliably: `type`, `enum`,
|
|
10
|
+
* `pattern`, `minLength` / `maxLength`, `minimum` / `maximum`, `required`, `properties`,
|
|
11
|
+
* `additionalProperties: false` and `items`. Anything else in a schema is IGNORED for
|
|
12
|
+
* validation but REJECTED by `checkSchemaShape` when it would change the meaning (`$ref`,
|
|
13
|
+
* `oneOf`, ...): a schema this validator cannot honour must not be accepted as if it could.
|
|
14
|
+
*/
|
|
15
|
+
const SCALAR_TYPES = new Set(['string', 'number', 'integer', 'boolean', 'null']);
|
|
16
|
+
const ALL_TYPES = new Set([...SCALAR_TYPES, 'object', 'array']);
|
|
17
|
+
const UNSUPPORTED_KEYWORDS = ['$ref', 'oneOf', 'anyOf', 'allOf', 'not', 'if', 'then', 'else', 'patternProperties', 'dependencies'];
|
|
18
|
+
const MAX_DEPTH = 6;
|
|
19
|
+
const MAX_PATTERN_LENGTH = 200;
|
|
20
|
+
function isObject(v) {
|
|
21
|
+
return !!v && typeof v === 'object' && !Array.isArray(v);
|
|
22
|
+
}
|
|
23
|
+
function typeOf(value) {
|
|
24
|
+
if (value === null)
|
|
25
|
+
return 'null';
|
|
26
|
+
if (Array.isArray(value))
|
|
27
|
+
return 'array';
|
|
28
|
+
if (typeof value === 'number')
|
|
29
|
+
return Number.isInteger(value) ? 'integer' : 'number';
|
|
30
|
+
return typeof value;
|
|
31
|
+
}
|
|
32
|
+
function typeMatches(want, value) {
|
|
33
|
+
const got = typeOf(value);
|
|
34
|
+
return want === got || (want === 'number' && got === 'integer');
|
|
35
|
+
}
|
|
36
|
+
/** A pattern that cannot be compiled, or is long enough to be a ReDoS vector, is not honoured. */
|
|
37
|
+
export function safeRegExp(pattern) {
|
|
38
|
+
if (pattern.length > MAX_PATTERN_LENGTH)
|
|
39
|
+
return null;
|
|
40
|
+
if (/(\([^)]*[+*][^)]*\))[+*]/.test(pattern))
|
|
41
|
+
return null; // nested quantifier: (a+)+
|
|
42
|
+
try {
|
|
43
|
+
return new RegExp(pattern);
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
function checkScalar(schema, value, path, issues) {
|
|
50
|
+
if (Array.isArray(schema.enum) && !schema.enum.some((e) => e === value)) {
|
|
51
|
+
issues.push({ path, message: 'not one of the allowed values' });
|
|
52
|
+
}
|
|
53
|
+
if (typeof value === 'string') {
|
|
54
|
+
if (typeof schema.maxLength === 'number' && value.length > schema.maxLength) {
|
|
55
|
+
issues.push({ path, message: `longer than ${schema.maxLength}` });
|
|
56
|
+
}
|
|
57
|
+
if (typeof schema.minLength === 'number' && value.length < schema.minLength) {
|
|
58
|
+
issues.push({ path, message: `shorter than ${schema.minLength}` });
|
|
59
|
+
}
|
|
60
|
+
if (typeof schema.pattern === 'string') {
|
|
61
|
+
const re = safeRegExp(schema.pattern);
|
|
62
|
+
if (re && !re.test(value))
|
|
63
|
+
issues.push({ path, message: 'does not match the required pattern' });
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
if (typeof value === 'number') {
|
|
67
|
+
if (typeof schema.minimum === 'number' && value < schema.minimum)
|
|
68
|
+
issues.push({ path, message: `below ${schema.minimum}` });
|
|
69
|
+
if (typeof schema.maximum === 'number' && value > schema.maximum)
|
|
70
|
+
issues.push({ path, message: `above ${schema.maximum}` });
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
function checkObject(schema, value, path, issues, depth) {
|
|
74
|
+
const props = isObject(schema.properties) ? schema.properties : {};
|
|
75
|
+
const required = Array.isArray(schema.required) ? schema.required.filter((r) => typeof r === 'string') : [];
|
|
76
|
+
for (const key of required) {
|
|
77
|
+
if (!(key in value))
|
|
78
|
+
issues.push({ path: `${path}.${key}`, message: 'is required' });
|
|
79
|
+
}
|
|
80
|
+
for (const [key, sub] of Object.entries(value)) {
|
|
81
|
+
const child = props[key];
|
|
82
|
+
if (child === undefined) {
|
|
83
|
+
if (schema.additionalProperties === false)
|
|
84
|
+
issues.push({ path: `${path}.${key}`, message: 'is not allowed' });
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
if (isObject(child))
|
|
88
|
+
validateInto(child, sub, `${path}.${key}`, issues, depth + 1);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
function validateInto(schema, value, path, issues, depth) {
|
|
92
|
+
if (depth > MAX_DEPTH)
|
|
93
|
+
return;
|
|
94
|
+
const want = typeof schema.type === 'string' ? schema.type : undefined;
|
|
95
|
+
if (want && !typeMatches(want, value)) {
|
|
96
|
+
issues.push({ path, message: `expected ${want}, got ${typeOf(value)}` });
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
checkScalar(schema, value, path, issues);
|
|
100
|
+
if (isObject(value) && (want === 'object' || want === undefined))
|
|
101
|
+
checkObject(schema, value, path, issues, depth);
|
|
102
|
+
if (Array.isArray(value) && isObject(schema.items)) {
|
|
103
|
+
value.slice(0, 200).forEach((item, i) => validateInto(schema.items, item, `${path}[${i}]`, issues, depth + 1));
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/** Validate `value` against `schema`. An empty list means valid. */
|
|
107
|
+
export function validateAgainstSchema(schema, value) {
|
|
108
|
+
const issues = [];
|
|
109
|
+
if (!isObject(schema))
|
|
110
|
+
return [{ path: '$', message: 'schema is not an object' }];
|
|
111
|
+
validateInto(schema, value, '$', issues, 0);
|
|
112
|
+
return issues;
|
|
113
|
+
}
|
|
114
|
+
function shapeInto(schema, path, issues, depth, root) {
|
|
115
|
+
if (!isObject(schema)) {
|
|
116
|
+
issues.push({ path, message: 'schema node is not an object' });
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
if (depth > MAX_DEPTH) {
|
|
120
|
+
issues.push({ path, message: 'schema is nested too deeply' });
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
for (const k of UNSUPPORTED_KEYWORDS)
|
|
124
|
+
if (k in schema)
|
|
125
|
+
issues.push({ path, message: `keyword ${k} is not supported` });
|
|
126
|
+
const t = schema.type;
|
|
127
|
+
if (typeof t !== 'string' || !ALL_TYPES.has(t))
|
|
128
|
+
issues.push({ path, message: 'type must be one of the supported types' });
|
|
129
|
+
if (typeof schema.pattern === 'string' && safeRegExp(schema.pattern) === null) {
|
|
130
|
+
issues.push({ path, message: 'pattern is invalid or too risky' });
|
|
131
|
+
}
|
|
132
|
+
if (t === 'object') {
|
|
133
|
+
if (schema.additionalProperties !== false)
|
|
134
|
+
issues.push({ path, message: 'additionalProperties must be false' });
|
|
135
|
+
const props = isObject(schema.properties) ? schema.properties : {};
|
|
136
|
+
for (const [k, sub] of Object.entries(props))
|
|
137
|
+
shapeInto(sub, `${path}.${k}`, issues, depth + 1, false);
|
|
138
|
+
}
|
|
139
|
+
else if (root) {
|
|
140
|
+
issues.push({ path, message: 'the root schema must be an object' });
|
|
141
|
+
}
|
|
142
|
+
if (t === 'array' && schema.items !== undefined)
|
|
143
|
+
shapeInto(schema.items, `${path}[]`, issues, depth + 1, false);
|
|
144
|
+
}
|
|
145
|
+
/** Is this a schema the validator can honour (T1)? */
|
|
146
|
+
export function checkSchemaShape(schema, maxBytes = 4096) {
|
|
147
|
+
const issues = [];
|
|
148
|
+
let size = 0;
|
|
149
|
+
try {
|
|
150
|
+
size = Buffer.byteLength(JSON.stringify(schema) ?? '', 'utf8');
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
return [{ path: '$', message: 'schema is not serialisable' }];
|
|
154
|
+
}
|
|
155
|
+
if (size > maxBytes)
|
|
156
|
+
issues.push({ path: '$', message: `schema is larger than ${maxBytes} bytes` });
|
|
157
|
+
shapeInto(schema, '$', issues, 0, true);
|
|
158
|
+
return issues;
|
|
159
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scope-key hygiene the frozen id validators do not provide (gene-bank spec 6.8 rule 1).
|
|
3
|
+
*
|
|
4
|
+
* ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
|
|
5
|
+
*
|
|
6
|
+
* `isValidScopeKey` (model/gene/ids.ts) bounds the ALPHABET of a project, task or team key, which
|
|
7
|
+
* is enough to keep `..`, separators and drive letters out of a path. It does not reject the Win32
|
|
8
|
+
* reserved device names (`con`, `nul`, `aux`, `prn`, `com1`..`com9`, `lpt1`..`lpt9`, with or
|
|
9
|
+
* without an extension): every one of them matches the key regexes. A directory with such a name
|
|
10
|
+
* cannot be created on Windows, so the best case is a confusing `GENE_UNAVAILABLE` and the worst a
|
|
11
|
+
* read that lands on a device. Gene ids never have the problem (the `gk_` / `gt_` / `gs_` prefix
|
|
12
|
+
* rules them out); scope keys do, and they come from an IPC argument or a session id.
|
|
13
|
+
*
|
|
14
|
+
* THE GUARD LIVES HERE, IN THE ENGINE, because the validators are shared with the pure model and
|
|
15
|
+
* the desktop app and are not this module's to change. It is applied wherever the engine turns a
|
|
16
|
+
* scope into a directory it will WRITE (the store) or accept from a caller (the service), and when
|
|
17
|
+
* it lists the scopes on disk.
|
|
18
|
+
*/
|
|
19
|
+
import type { GeneScope } from '@aragon-agent/tui/model/gene/types';
|
|
20
|
+
/** Is `key` a Win32 reserved device name (any case, any extension)? */
|
|
21
|
+
export declare function isReservedDeviceName(key: string): boolean;
|
|
22
|
+
/** A scope whose key is safe to use as a directory name on every platform. */
|
|
23
|
+
export declare function scopeKeyIsSafe(scope: GeneScope): boolean;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
const RESERVED = /^(?:con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\..*)?$/i;
|
|
2
|
+
/** Is `key` a Win32 reserved device name (any case, any extension)? */
|
|
3
|
+
export function isReservedDeviceName(key) {
|
|
4
|
+
return RESERVED.test(key);
|
|
5
|
+
}
|
|
6
|
+
/** A scope whose key is safe to use as a directory name on every platform. */
|
|
7
|
+
export function scopeKeyIsSafe(scope) {
|
|
8
|
+
return scope.key === undefined || !isReservedDeviceName(scope.key);
|
|
9
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { GeneScope } from '@aragon-agent/tui/model/gene/types';
|
|
2
|
+
import * as P from './paths.js';
|
|
3
|
+
export interface ScopeLockObserver {
|
|
4
|
+
acquired?: (scopeId: string) => void;
|
|
5
|
+
released?: (scopeId: string) => void;
|
|
6
|
+
}
|
|
7
|
+
export interface ScopeLockOptions {
|
|
8
|
+
pid?: number;
|
|
9
|
+
now?: () => number;
|
|
10
|
+
isPidAlive?: (pid: number) => boolean;
|
|
11
|
+
sleep?: (ms: number) => Promise<void>;
|
|
12
|
+
/** Whole acquisition budget (mutex + file lock). Default `GENE_LIMITS.lockTimeoutMs`. */
|
|
13
|
+
timeoutMs?: number;
|
|
14
|
+
/** A heartbeat older than this counts as expired. Default `GENE_LIMITS.lockStaleMs`. */
|
|
15
|
+
staleMs?: number;
|
|
16
|
+
heartbeatMs?: number;
|
|
17
|
+
pollMs?: number;
|
|
18
|
+
observer?: ScopeLockObserver;
|
|
19
|
+
}
|
|
20
|
+
export declare class ScopeLockManager {
|
|
21
|
+
private readonly pathContext;
|
|
22
|
+
private readonly pid;
|
|
23
|
+
private readonly now;
|
|
24
|
+
private readonly isPidAlive;
|
|
25
|
+
private readonly sleep;
|
|
26
|
+
private readonly timeoutMs;
|
|
27
|
+
private readonly staleMs;
|
|
28
|
+
private readonly heartbeatMs;
|
|
29
|
+
private readonly pollMs;
|
|
30
|
+
private readonly observer;
|
|
31
|
+
private readonly context;
|
|
32
|
+
private held;
|
|
33
|
+
constructor(pathContext: P.GenePathContext, options?: ScopeLockOptions);
|
|
34
|
+
/** How many scope locks this manager holds right now (0 or 1 by construction). */
|
|
35
|
+
get heldCount(): number;
|
|
36
|
+
/** Run `body` while holding the write lock of `scope`. Throws `GeneStoreError` on timeout. */
|
|
37
|
+
withLock<T>(scope: GeneScope, body: () => Promise<T>): Promise<T>;
|
|
38
|
+
private takeMutex;
|
|
39
|
+
private timeout;
|
|
40
|
+
private runHeld;
|
|
41
|
+
private heartbeat;
|
|
42
|
+
/** Deps for the governance primitive: it may create the file and report contention only. */
|
|
43
|
+
private lockDeps;
|
|
44
|
+
private acquireFile;
|
|
45
|
+
/** Heartbeat expired AND holder dead (7.1). A lock with our own pid is never "stale" here. */
|
|
46
|
+
private isStale;
|
|
47
|
+
private takeOverStale;
|
|
48
|
+
}
|