@aragon-agent/cli 0.6.55 → 0.6.57
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 +2935 -2864
- package/README.md +160 -45
- package/dist/agent/controller.d.ts +47 -0
- package/dist/agent/controller.js +153 -2
- package/dist/agent/governance-wiring.js +8 -1
- package/dist/agent/system-prompt.d.ts +26 -0
- package/dist/agent/system-prompt.js +11 -0
- package/dist/app/App.js +101 -3
- package/dist/cli.js +29 -1
- package/dist/commands/builtins.js +4 -0
- package/dist/commands/catalog.js +1 -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 +2 -1
- package/dist/config/env.js +12 -1
- package/dist/config/load.d.ts +10 -0
- package/dist/config/load.js +13 -2
- package/dist/config/store.js +11 -1
- 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 +104 -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 +206 -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 +243 -0
- package/dist/gene/curator/tools-write.d.ts +26 -0
- package/dist/gene/curator/tools-write.js +434 -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 +24 -0
- package/dist/gene/curator/validate/evidence-tokens.js +217 -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 +41 -0
- package/dist/gene/curator/validate/knowledge.js +255 -0
- package/dist/gene/curator/validate/live-check.d.ts +14 -0
- package/dist/gene/curator/validate/live-check.js +150 -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 +165 -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 +116 -0
- package/dist/gene/learn/learn-call.js +165 -0
- package/dist/gene/learn/learn-prompt.d.ts +58 -0
- package/dist/gene/learn/learn-prompt.js +254 -0
- package/dist/gene/learn/learner.d.ts +187 -0
- package/dist/gene/learn/learner.js +448 -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 +207 -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 +84 -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/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/team/runtime.d.ts +5 -0
- package/dist/team/runtime.js +23 -0
- package/dist/team/subagent.d.ts +34 -0
- package/dist/team/subagent.js +39 -2
- package/dist/tools/index.d.ts +36 -2
- package/dist/tools/index.js +48 -7
- package/package.json +3 -3
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `ProjectLearningPolicy`: the per-project "do not learn here" switch (gene-bank spec I3-5).
|
|
3
|
+
*
|
|
4
|
+
* ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
|
|
5
|
+
*
|
|
6
|
+
* THE PROMISE. A project that is switched off sends ZERO session content to the fast model and
|
|
7
|
+
* writes nothing about the session to disk. The switch only ever makes the system more
|
|
8
|
+
* conservative: it closes the LEARN path and leaves USE (search, read, context) and manual
|
|
9
|
+
* management alone.
|
|
10
|
+
*
|
|
11
|
+
* TWO SOURCES, THE STRICTER WINS:
|
|
12
|
+
* 1. user-private `<genes>/policy.json`, keyed by the project key (the same key the project
|
|
13
|
+
* scope uses - never a second keying scheme);
|
|
14
|
+
* 2. repository-shared `<projectRoot>/.aragon/gene.json` `{ "learn": false }`. It can only
|
|
15
|
+
* TIGHTEN: `true`, any other value and any unknown field have no effect, so a cloned
|
|
16
|
+
* repository can never pre-load a permissive state.
|
|
17
|
+
*
|
|
18
|
+
* FAIL DIRECTIONS (the part that is easiest to write backwards):
|
|
19
|
+
* - `policy.json` ABSENT is the normal case and means "nobody is excluded".
|
|
20
|
+
* - `policy.json` PRESENT but unreadable (bad JSON, schema > 1, > 64 KB, a directory, a
|
|
21
|
+
* symlink, a permission error that survives the Windows retry) means "every project is
|
|
22
|
+
* excluded": reading a broken restriction as "no restriction" would fail OPEN on a privacy
|
|
23
|
+
* switch. Use and manual management are unaffected.
|
|
24
|
+
* - the repository marker ABSENT (ENOENT / ENOTDIR) means no marker; PRESENT but unreadable
|
|
25
|
+
* (> 4 KB, symlink, directory, bad JSON) means "excluded".
|
|
26
|
+
*
|
|
27
|
+
* WRITES ARE SERIALISED. TUI, CLI and the desktop settings page are three processes that all
|
|
28
|
+
* read-modify-write the same file; a lost update would silently re-enable learning for an
|
|
29
|
+
* excluded project. The whole cycle runs inside `<genes>/policy.lock` with a re-read inside the
|
|
30
|
+
* lock; a lock that cannot be taken is a `GENE_UNAVAILABLE`, never an unlocked write.
|
|
31
|
+
*
|
|
32
|
+
* THE CACHE IS FOR DISPLAY. `refresh` is the authority (a stat or two per learning trigger);
|
|
33
|
+
* `lastVerdict` is a synchronous read of what `refresh` last decided, so `learner.view()` stays
|
|
34
|
+
* a pure function. A stale cache can only affect what is SHOWN, never the zero-call guarantee,
|
|
35
|
+
* which is enforced by awaiting `refresh` immediately before a transport call can be made.
|
|
36
|
+
*/
|
|
37
|
+
import { promises as nodeFs } from 'node:fs';
|
|
38
|
+
import { dirname } from 'node:path';
|
|
39
|
+
import { isValidScopeKey } from '@aragon-agent/tui/model/gene/ids';
|
|
40
|
+
import { GeneStoreError } from './gene-errors.js';
|
|
41
|
+
import { acquireLock, defaultIsPidAlive, ensureDir, readLock, removeLock, retryOnWindowsContention, writeJsonStrict, } from './fs.js';
|
|
42
|
+
import { policyFile, policyLockFile, projectMarkerFile } from './paths.js';
|
|
43
|
+
export const POLICY_SCHEMA = 1;
|
|
44
|
+
const POLICY_MAX_BYTES = 64 * 1024;
|
|
45
|
+
const MARKER_MAX_BYTES = 4 * 1024;
|
|
46
|
+
const LOCK_STALE_MS = 15_000;
|
|
47
|
+
const LOCK_TIMEOUT_MS = 4_000;
|
|
48
|
+
const LOCK_POLL_MS = 40;
|
|
49
|
+
const LABEL_MAX = 80;
|
|
50
|
+
export const LEARN_ALLOWED = { learn: true, source: 'none', user: false, repo: false };
|
|
51
|
+
function errorCode(error) {
|
|
52
|
+
const code = error?.code;
|
|
53
|
+
return typeof code === 'string' ? code : undefined;
|
|
54
|
+
}
|
|
55
|
+
/** `lstat` first: a symlink is never followed (it could point anywhere, including a huge file). */
|
|
56
|
+
async function lstatOrNull(path) {
|
|
57
|
+
try {
|
|
58
|
+
return await retryOnWindowsContention(() => nodeFs.lstat(path));
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
const code = errorCode(error);
|
|
62
|
+
if (code === 'ENOENT' || code === 'ENOTDIR')
|
|
63
|
+
return null;
|
|
64
|
+
return 'error';
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
async function readBounded(path, maxBytes) {
|
|
68
|
+
const stat = await lstatOrNull(path);
|
|
69
|
+
if (stat === null)
|
|
70
|
+
return 'absent';
|
|
71
|
+
if (stat === 'error' || !stat.isFile() || stat.size > maxBytes)
|
|
72
|
+
return 'unreadable';
|
|
73
|
+
try {
|
|
74
|
+
return await retryOnWindowsContention(() => nodeFs.readFile(path, 'utf8'));
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
// The file vanished between the stat and the read: that is "absent", not "broken".
|
|
78
|
+
const code = errorCode(error);
|
|
79
|
+
return code === 'ENOENT' ? 'absent' : 'unreadable';
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
function isRecord(value) {
|
|
83
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
84
|
+
}
|
|
85
|
+
function parseUserPolicy(text) {
|
|
86
|
+
let raw;
|
|
87
|
+
try {
|
|
88
|
+
raw = JSON.parse(text);
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
return { state: 'unreadable' };
|
|
92
|
+
}
|
|
93
|
+
if (!isRecord(raw))
|
|
94
|
+
return { state: 'unreadable' };
|
|
95
|
+
if (typeof raw.schema !== 'number' || !Number.isFinite(raw.schema) || raw.schema > POLICY_SCHEMA) {
|
|
96
|
+
return { state: 'unreadable' };
|
|
97
|
+
}
|
|
98
|
+
const projects = {};
|
|
99
|
+
if (isRecord(raw.projects)) {
|
|
100
|
+
for (const [key, entry] of Object.entries(raw.projects)) {
|
|
101
|
+
if (!isValidScopeKey('project', key) || !isRecord(entry) || entry.learn !== false)
|
|
102
|
+
continue;
|
|
103
|
+
projects[key] = {
|
|
104
|
+
learn: false,
|
|
105
|
+
label: typeof entry.label === 'string' ? entry.label.slice(0, LABEL_MAX) : '',
|
|
106
|
+
setAt: typeof entry.setAt === 'number' && Number.isFinite(entry.setAt) ? entry.setAt : 0,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return { state: 'ok', projects };
|
|
111
|
+
}
|
|
112
|
+
function parseMarker(text) {
|
|
113
|
+
let raw;
|
|
114
|
+
try {
|
|
115
|
+
raw = JSON.parse(text);
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
return 'unreadable';
|
|
119
|
+
}
|
|
120
|
+
if (!isRecord(raw))
|
|
121
|
+
return 'unreadable';
|
|
122
|
+
// Only an explicit `false` tightens. Anything else (true, "false", missing) is inert.
|
|
123
|
+
return raw.learn === false ? 'tight' : 'loose';
|
|
124
|
+
}
|
|
125
|
+
export class ProjectLearningPolicy {
|
|
126
|
+
ctx;
|
|
127
|
+
now;
|
|
128
|
+
pid;
|
|
129
|
+
isPidAlive;
|
|
130
|
+
lockTimeoutMs;
|
|
131
|
+
lockPollMs;
|
|
132
|
+
sleep;
|
|
133
|
+
userCache = null;
|
|
134
|
+
markerCache = new Map();
|
|
135
|
+
verdicts = new Map();
|
|
136
|
+
/** In-process FIFO: two writes in ONE process must not both "own" the lock file. */
|
|
137
|
+
writeChain = Promise.resolve();
|
|
138
|
+
constructor(options = {}) {
|
|
139
|
+
this.ctx = options.ctx ?? {};
|
|
140
|
+
this.now = options.now ?? Date.now;
|
|
141
|
+
this.pid = options.pid ?? process.pid;
|
|
142
|
+
this.isPidAlive = options.isPidAlive ?? defaultIsPidAlive;
|
|
143
|
+
this.lockTimeoutMs = options.lockTimeoutMs ?? LOCK_TIMEOUT_MS;
|
|
144
|
+
this.lockPollMs = options.lockPollMs ?? LOCK_POLL_MS;
|
|
145
|
+
this.sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* The authority. Re-reads a file only when its size or mtime moved. `projectKey === null`
|
|
149
|
+
* (no project known) is never excluded by project; the global switch still applies elsewhere.
|
|
150
|
+
*/
|
|
151
|
+
async refresh(projectKey, projectRoot) {
|
|
152
|
+
if (projectKey === null || !isValidScopeKey('project', projectKey))
|
|
153
|
+
return LEARN_ALLOWED;
|
|
154
|
+
const user = await this.readUser();
|
|
155
|
+
const marker = projectRoot === null ? 'absent' : await this.readMarker(projectRoot);
|
|
156
|
+
const verdict = combine(projectKey, user, marker);
|
|
157
|
+
this.verdicts.set(projectKey, verdict);
|
|
158
|
+
return verdict;
|
|
159
|
+
}
|
|
160
|
+
/** Synchronous read of the last `refresh`; undefined = never asked (callers show nothing). */
|
|
161
|
+
lastVerdict(projectKey) {
|
|
162
|
+
return projectKey === null ? undefined : this.verdicts.get(projectKey);
|
|
163
|
+
}
|
|
164
|
+
/** The user-private entries, for listings and the diagnostic bundle. */
|
|
165
|
+
async userEntries() {
|
|
166
|
+
const read = await this.readUser();
|
|
167
|
+
return { state: read.state, projects: read.state === 'ok' ? read.projects : {} };
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Switch learning on (`learn: true` DELETES the entry; no explicit "allowed" state exists) or
|
|
171
|
+
* off for one project. Serialised across processes; throws `GeneStoreError` on a busy lock or
|
|
172
|
+
* an unwritable file. A policy file that is present but unreadable is NOT silently replaced:
|
|
173
|
+
* the caller must repair or remove it first (replacing it would erase exclusions it held).
|
|
174
|
+
*/
|
|
175
|
+
setProject(projectKey, label, learn) {
|
|
176
|
+
if (!isValidScopeKey('project', projectKey)) {
|
|
177
|
+
return Promise.reject(new GeneStoreError('GENE_INVALID_ID', 'That is not a valid project key.', 'project_key'));
|
|
178
|
+
}
|
|
179
|
+
const run = this.writeChain.then(() => this.writeLocked(projectKey, label, learn));
|
|
180
|
+
this.writeChain = run.catch(() => undefined);
|
|
181
|
+
return run;
|
|
182
|
+
}
|
|
183
|
+
// ---- reading -------------------------------------------------------------------------
|
|
184
|
+
async readUser() {
|
|
185
|
+
const path = policyFile(this.ctx);
|
|
186
|
+
const stat = await lstatOrNull(path);
|
|
187
|
+
if (stat === null) {
|
|
188
|
+
this.userCache = null;
|
|
189
|
+
return { state: 'absent' };
|
|
190
|
+
}
|
|
191
|
+
if (stat === 'error')
|
|
192
|
+
return { state: 'unreadable' };
|
|
193
|
+
const stamp = `${stat.size}:${stat.mtimeMs}:${stat.isFile()}`;
|
|
194
|
+
if (this.userCache !== null && this.userCache.stamp === stamp)
|
|
195
|
+
return this.userCache.value;
|
|
196
|
+
const text = await readBounded(path, POLICY_MAX_BYTES);
|
|
197
|
+
const value = text === 'absent' ? { state: 'absent' } : text === 'unreadable' ? { state: 'unreadable' } : parseUserPolicy(text);
|
|
198
|
+
// An unreadable result is not cached on a transient-looking stamp: try again next time.
|
|
199
|
+
if (value.state === 'ok')
|
|
200
|
+
this.userCache = { stamp, value };
|
|
201
|
+
else
|
|
202
|
+
this.userCache = null;
|
|
203
|
+
return value;
|
|
204
|
+
}
|
|
205
|
+
async readMarker(projectRoot) {
|
|
206
|
+
const path = projectMarkerFile(projectRoot);
|
|
207
|
+
const stat = await lstatOrNull(path);
|
|
208
|
+
if (stat === null) {
|
|
209
|
+
this.markerCache.delete(path);
|
|
210
|
+
return 'absent';
|
|
211
|
+
}
|
|
212
|
+
if (stat === 'error')
|
|
213
|
+
return 'unreadable';
|
|
214
|
+
const stamp = `${stat.size}:${stat.mtimeMs}:${stat.isFile()}`;
|
|
215
|
+
const cached = this.markerCache.get(path);
|
|
216
|
+
if (cached !== undefined && cached.stamp === stamp)
|
|
217
|
+
return cached.value;
|
|
218
|
+
const text = await readBounded(path, MARKER_MAX_BYTES);
|
|
219
|
+
const value = text === 'absent' ? 'absent' : text === 'unreadable' ? 'unreadable' : parseMarker(text);
|
|
220
|
+
if (value === 'unreadable')
|
|
221
|
+
this.markerCache.delete(path);
|
|
222
|
+
else
|
|
223
|
+
this.markerCache.set(path, { stamp, value });
|
|
224
|
+
return value;
|
|
225
|
+
}
|
|
226
|
+
// ---- writing -------------------------------------------------------------------------
|
|
227
|
+
async writeLocked(projectKey, label, learn) {
|
|
228
|
+
const lockPath = policyLockFile(this.ctx);
|
|
229
|
+
await this.acquire(lockPath);
|
|
230
|
+
try {
|
|
231
|
+
// Re-read INSIDE the lock: the copy read before waiting for it may already be stale.
|
|
232
|
+
this.userCache = null;
|
|
233
|
+
const current = await this.readUser();
|
|
234
|
+
if (current.state === 'unreadable') {
|
|
235
|
+
throw new GeneStoreError('GENE_UNAVAILABLE', 'The project policy file is unreadable; repair or remove it first.', 'policy_unreadable');
|
|
236
|
+
}
|
|
237
|
+
const projects = current.state === 'ok' ? { ...current.projects } : {};
|
|
238
|
+
if (learn)
|
|
239
|
+
delete projects[projectKey];
|
|
240
|
+
else
|
|
241
|
+
projects[projectKey] = { learn: false, label: label.slice(0, LABEL_MAX), setAt: this.now() };
|
|
242
|
+
await ensureDir(dirname(policyFile(this.ctx)));
|
|
243
|
+
await writeJsonStrict(policyFile(this.ctx), { schema: POLICY_SCHEMA, projects });
|
|
244
|
+
this.userCache = null;
|
|
245
|
+
}
|
|
246
|
+
finally {
|
|
247
|
+
await removeLock(lockPath, this.lockDeps()).catch(() => undefined);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
lockDeps() {
|
|
251
|
+
return { now: this.now, pid: this.pid, isPidAlive: () => true, staleMs: Number.POSITIVE_INFINITY };
|
|
252
|
+
}
|
|
253
|
+
async acquire(lockPath) {
|
|
254
|
+
await ensureDir(dirname(lockPath));
|
|
255
|
+
const deadline = this.now() + this.lockTimeoutMs;
|
|
256
|
+
for (;;) {
|
|
257
|
+
const info = await readLock(lockPath);
|
|
258
|
+
if (info !== null && this.isStale(info))
|
|
259
|
+
await this.breakStale(lockPath);
|
|
260
|
+
const result = await acquireLock(lockPath, this.lockDeps());
|
|
261
|
+
if (result.ok)
|
|
262
|
+
return;
|
|
263
|
+
if (this.now() >= deadline) {
|
|
264
|
+
throw new GeneStoreError('GENE_UNAVAILABLE', 'The project policy is busy; try again.', 'policy_lock_busy');
|
|
265
|
+
}
|
|
266
|
+
await this.sleep(this.lockPollMs);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
/** Heartbeat expired AND holder gone; the lock is short-lived, so a long silence is a crash. */
|
|
270
|
+
isStale(info) {
|
|
271
|
+
if (info.pid === this.pid)
|
|
272
|
+
return false;
|
|
273
|
+
return this.now() - info.heartbeatAt >= LOCK_STALE_MS && !this.isPidAlive(info.pid);
|
|
274
|
+
}
|
|
275
|
+
async breakStale(lockPath) {
|
|
276
|
+
const aside = `${lockPath}.stale.${this.pid}.${this.now()}`;
|
|
277
|
+
try {
|
|
278
|
+
await retryOnWindowsContention(() => nodeFs.rename(lockPath, aside));
|
|
279
|
+
}
|
|
280
|
+
catch {
|
|
281
|
+
return; // someone else won the takeover, or it is already gone
|
|
282
|
+
}
|
|
283
|
+
await nodeFs.unlink(aside).catch(() => undefined);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
/** Fold the two layers into one verdict. Precedence of the displayed source: unreadable > repo > user. */
|
|
287
|
+
function combine(projectKey, user, marker) {
|
|
288
|
+
const userUnreadable = user.state === 'unreadable';
|
|
289
|
+
const userExcluded = user.state === 'ok' && user.projects[projectKey] !== undefined;
|
|
290
|
+
const repoUnreadable = marker === 'unreadable';
|
|
291
|
+
const repoExcluded = marker === 'tight';
|
|
292
|
+
if (userUnreadable || repoUnreadable) {
|
|
293
|
+
return { learn: false, source: 'unreadable', user: userExcluded, repo: repoExcluded };
|
|
294
|
+
}
|
|
295
|
+
if (repoExcluded)
|
|
296
|
+
return { learn: false, source: 'repo', user: userExcluded, repo: true };
|
|
297
|
+
if (userExcluded)
|
|
298
|
+
return { learn: false, source: 'user', user: true, repo: false };
|
|
299
|
+
return LEARN_ALLOWED;
|
|
300
|
+
}
|
|
301
|
+
/** Fixed, English, text-free copy for a verdict (status line and chip). */
|
|
302
|
+
export function verdictSummary(verdict) {
|
|
303
|
+
switch (verdict.source) {
|
|
304
|
+
case 'none':
|
|
305
|
+
return 'learning on';
|
|
306
|
+
case 'user':
|
|
307
|
+
return 'learning off (your setting)';
|
|
308
|
+
case 'repo':
|
|
309
|
+
return 'learning off (.aragon/gene.json)';
|
|
310
|
+
case 'unreadable':
|
|
311
|
+
return 'learning off (policy file unreadable)';
|
|
312
|
+
}
|
|
313
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { GeneResult } from '@aragon-agent/tui/model/gene/types';
|
|
2
|
+
import type { ManagerCore } from './manager-context.js';
|
|
3
|
+
import type { PolicySource, ProjectLearningPolicy } from './policy.js';
|
|
4
|
+
export interface ProjectLearningState {
|
|
5
|
+
projectKey: string;
|
|
6
|
+
label: string;
|
|
7
|
+
learn: boolean;
|
|
8
|
+
source: PolicySource;
|
|
9
|
+
/** The user-private layer excludes the project (changeable here). */
|
|
10
|
+
user: boolean;
|
|
11
|
+
/** The repository marker excludes the project (only editing the file changes this). */
|
|
12
|
+
repo: boolean;
|
|
13
|
+
}
|
|
14
|
+
export interface ProjectLearningChange extends ProjectLearningState {
|
|
15
|
+
/** Queued proposals of this project that were settled (text stripped) by switching off. */
|
|
16
|
+
dropped: number;
|
|
17
|
+
}
|
|
18
|
+
/** The current project's state, or null when the session has no project. */
|
|
19
|
+
export declare function readProjectLearning(core: ManagerCore, policy: ProjectLearningPolicy): Promise<GeneResult<ProjectLearningState | null>>;
|
|
20
|
+
/**
|
|
21
|
+
* Switch the current project's learning on or off for this user. Off also settles, text
|
|
22
|
+
* stripped, what the project already queued; on only removes the user entry (a repository
|
|
23
|
+
* marker keeps excluding and the result says so through `repo`).
|
|
24
|
+
*/
|
|
25
|
+
export declare function changeProjectLearning(core: ManagerCore, policy: ProjectLearningPolicy, learn: boolean): Promise<GeneResult<ProjectLearningChange>>;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The manager-level face of the per-project learning switch (gene-bank spec I3-5).
|
|
3
|
+
*
|
|
4
|
+
* ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
|
|
5
|
+
*
|
|
6
|
+
* One definition of "the current project's learning state" for the slash command, the
|
|
7
|
+
* `aragon gene learn --project` subcommand, the desktop IPC and the diagnostic bundle. It works
|
|
8
|
+
* on files (the policy and the repository marker), so it is correct from a process that has no
|
|
9
|
+
* live session: the switch is a fact about the project, not about the process asking.
|
|
10
|
+
*/
|
|
11
|
+
import { sourceCarriesProjectContent } from './curator/switches.js';
|
|
12
|
+
import { geneFail, geneOk } from './gene-errors.js';
|
|
13
|
+
/** The current project's state, or null when the session has no project. */
|
|
14
|
+
export async function readProjectLearning(core, policy) {
|
|
15
|
+
const project = core.project();
|
|
16
|
+
if (project === null)
|
|
17
|
+
return geneOk(null);
|
|
18
|
+
const verdict = await policy.refresh(project.key, project.root);
|
|
19
|
+
return geneOk({
|
|
20
|
+
projectKey: project.key,
|
|
21
|
+
label: project.label,
|
|
22
|
+
learn: verdict.learn,
|
|
23
|
+
source: verdict.source,
|
|
24
|
+
user: verdict.user,
|
|
25
|
+
repo: verdict.repo,
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Switch the current project's learning on or off for this user. Off also settles, text
|
|
30
|
+
* stripped, what the project already queued; on only removes the user entry (a repository
|
|
31
|
+
* marker keeps excluding and the result says so through `repo`).
|
|
32
|
+
*/
|
|
33
|
+
export async function changeProjectLearning(core, policy, learn) {
|
|
34
|
+
const project = core.project();
|
|
35
|
+
if (project === null) {
|
|
36
|
+
return geneFail('GENE_UNAVAILABLE', 'There is no project in this session.', 'no_project');
|
|
37
|
+
}
|
|
38
|
+
await policy.setProject(project.key, project.label, learn);
|
|
39
|
+
const verdict = await policy.refresh(project.key, project.root);
|
|
40
|
+
let dropped = 0;
|
|
41
|
+
if (!verdict.learn) {
|
|
42
|
+
const ids = await core.lib.queue.dropExcludedWhere((p) => p.origin.projectKey === project.key && sourceCarriesProjectContent(p.origin.source));
|
|
43
|
+
dropped = ids.length;
|
|
44
|
+
}
|
|
45
|
+
return geneOk({
|
|
46
|
+
projectKey: project.key,
|
|
47
|
+
label: project.label,
|
|
48
|
+
learn: verdict.learn,
|
|
49
|
+
source: verdict.source,
|
|
50
|
+
user: verdict.user,
|
|
51
|
+
repo: verdict.repo,
|
|
52
|
+
dropped,
|
|
53
|
+
});
|
|
54
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Dependency propagation (gene-bank spec 7.1 step 10, 10.9; RV-6; I-22).
|
|
3
|
+
*
|
|
4
|
+
* ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
|
|
5
|
+
*
|
|
6
|
+
* WHEN A GENE STOPS BEING WHAT ITS DEPENDENTS WERE WRITTEN AGAINST - it is archived, deleted,
|
|
7
|
+
* revoked, marked broken, or a tool's `interfaceVersion` moves - everything that `requires` it
|
|
8
|
+
* must be re-checked. The commit that caused it has ALREADY released its scope lock when this
|
|
9
|
+
* runs (step 10 is outside the lock), and each dependent is marked by its own `setHealth` commit
|
|
10
|
+
* that takes ONLY that dependent's scope lock. So a propagation never holds two locks, never
|
|
11
|
+
* nests inside the lock of the commit that triggered it, and a crash halfway only leaves some
|
|
12
|
+
* dependents unmarked - the session-start reconciliation marks the rest.
|
|
13
|
+
*
|
|
14
|
+
* FAN-OUT IS BOUNDED (`dependentFanoutMax`, 50). Past it the remaining dependents are not marked
|
|
15
|
+
* one by one; the notice carries `truncated: true` and the queue folds them into a single
|
|
16
|
+
* `maintenance` proposal instead of flooding the curator with 5000 rechecks.
|
|
17
|
+
*
|
|
18
|
+
* NEVER THROWS, NEVER BLOCKS THE CALLER'S RESULT. The commit already succeeded; failing to mark a
|
|
19
|
+
* dependent is logged by absence (the dependent stays `ok` until the next reconciliation) and the
|
|
20
|
+
* hook is best-effort for the same reason.
|
|
21
|
+
*
|
|
22
|
+
* THE DEFAULT RESOLVER reads the index rows of every scope on disk. That is more than a single
|
|
23
|
+
* process may show a user (11.1) - and that is correct here: marking a project's SKILL
|
|
24
|
+
* `recheck` because a user-scope tool changed is maintenance, not disclosure.
|
|
25
|
+
*/
|
|
26
|
+
import type { GeneHealth, GeneResult } from '@aragon-agent/tui/model/gene/types';
|
|
27
|
+
import type { DependentRef, DependentsResolver, InvalidateHook, InvalidationNotice } from './commit-types.js';
|
|
28
|
+
import type { GeneStore } from './store.js';
|
|
29
|
+
import type { ScopeRowsView } from './store-rows.js';
|
|
30
|
+
export declare class StoreDependentsResolver implements DependentsResolver {
|
|
31
|
+
private readonly store;
|
|
32
|
+
private readonly rows;
|
|
33
|
+
constructor(store: GeneStore, rows: ScopeRowsView);
|
|
34
|
+
dependentsOf(id: string, options: {
|
|
35
|
+
cap: number;
|
|
36
|
+
}): Promise<{
|
|
37
|
+
refs: DependentRef[];
|
|
38
|
+
truncated: boolean;
|
|
39
|
+
}>;
|
|
40
|
+
}
|
|
41
|
+
export interface PropagationEnv {
|
|
42
|
+
resolver: DependentsResolver;
|
|
43
|
+
/** One metadata commit in the DEPENDENT's own scope. */
|
|
44
|
+
markHealth: (ref: DependentRef, health: GeneHealth, reason: string) => Promise<GeneResult<unknown>>;
|
|
45
|
+
onInvalidate?: InvalidateHook;
|
|
46
|
+
}
|
|
47
|
+
/** Mark every direct dependent `recheck` and tell the queue. Resolves when done; never rejects. */
|
|
48
|
+
export declare function propagateInvalidation(env: PropagationEnv, cause: InvalidationNotice['cause']): Promise<InvalidationNotice | null>;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { GENE_LIMITS } from '@aragon-agent/tui/model/gene/limits';
|
|
2
|
+
export class StoreDependentsResolver {
|
|
3
|
+
store;
|
|
4
|
+
rows;
|
|
5
|
+
constructor(store, rows) {
|
|
6
|
+
this.store = store;
|
|
7
|
+
this.rows = rows;
|
|
8
|
+
}
|
|
9
|
+
async dependentsOf(id, options) {
|
|
10
|
+
const refs = [];
|
|
11
|
+
for (const scope of await this.store.listScopes()) {
|
|
12
|
+
for (const row of await this.rows.rows(scope)) {
|
|
13
|
+
if (row.id !== id && row.deps.some((dep) => dep.id === id && dep.kind === 'requires')) {
|
|
14
|
+
refs.push({ id: row.id, scope: row.scope, status: row.status });
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
refs.sort((a, b) => a.id.localeCompare(b.id));
|
|
19
|
+
return { refs: refs.slice(0, options.cap), truncated: refs.length > options.cap };
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
const MARKABLE = new Set(['published', 'candidate']);
|
|
23
|
+
/** Mark every direct dependent `recheck` and tell the queue. Resolves when done; never rejects. */
|
|
24
|
+
export async function propagateInvalidation(env, cause) {
|
|
25
|
+
try {
|
|
26
|
+
const cap = GENE_LIMITS.dependentFanoutMax;
|
|
27
|
+
const found = await env.resolver.dependentsOf(cause.id, { cap });
|
|
28
|
+
const reason = `dependency:${cause.id}@${cause.version}`;
|
|
29
|
+
const marked = [];
|
|
30
|
+
for (const ref of found.refs) {
|
|
31
|
+
if (!MARKABLE.has(ref.status))
|
|
32
|
+
continue;
|
|
33
|
+
const result = await env.markHealth(ref, 'recheck', reason);
|
|
34
|
+
if (result.ok)
|
|
35
|
+
marked.push(ref);
|
|
36
|
+
}
|
|
37
|
+
const notice = { cause, dependents: marked, truncated: found.truncated };
|
|
38
|
+
if (marked.length > 0 || found.truncated)
|
|
39
|
+
await env.onInvalidate?.(notice);
|
|
40
|
+
return notice;
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export interface QueueLockOptions {
|
|
2
|
+
/** `<root>/queue/locks` */
|
|
3
|
+
dir: string;
|
|
4
|
+
pid: number;
|
|
5
|
+
/** Attempts to take the lock before giving up (each failed attempt waits `waitMs`). */
|
|
6
|
+
attempts?: number;
|
|
7
|
+
waitMs?: number;
|
|
8
|
+
/** Injectable pause between attempts; defaults to a real timer. */
|
|
9
|
+
sleep?: (ms: number) => Promise<void>;
|
|
10
|
+
}
|
|
11
|
+
export type LockOutcome<T> = {
|
|
12
|
+
held: true;
|
|
13
|
+
value: T;
|
|
14
|
+
} | {
|
|
15
|
+
held: false;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Run `body` while holding the lock for queue item `name`. Returns `{ held: false }` when the
|
|
19
|
+
* lock could not be taken within the attempts; the caller decides whether that means "skip
|
|
20
|
+
* this item" (a claim) or "try again later" (a settle).
|
|
21
|
+
*/
|
|
22
|
+
export declare function withQueueLock<T>(options: QueueLockOptions, name: string, body: () => Promise<T>): Promise<LockOutcome<T>>;
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-item locks for the proposal queue (gene-bank spec 10.5.5, I-21).
|
|
3
|
+
*
|
|
4
|
+
* ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
|
|
5
|
+
*
|
|
6
|
+
* WHY `rename` IS NOT ENOUGH. The spec's claim is "an atomic rename; a failed rename means
|
|
7
|
+
* someone else got it". On POSIX that is true: `rename(2)` resolves the SOURCE PATH, so the
|
|
8
|
+
* second of two racing renames finds nothing and gets ENOENT. On Windows it is NOT. libuv's
|
|
9
|
+
* `fs.rename` opens the source and then renames the OPEN FILE OBJECT, so a second rename that
|
|
10
|
+
* opened the file before the first one moved it follows the object to its new home and moves
|
|
11
|
+
* it AGAIN - both calls succeed, and the item ends up claimed twice (measured: four workers on
|
|
12
|
+
* one directory claimed the same file). The same race exists between any two renames of one
|
|
13
|
+
* file: a claim and a merge, a claim and a supersede, a settle and a stale recovery.
|
|
14
|
+
*
|
|
15
|
+
* EXCLUSIVE CREATE IS ATOMIC EVERYWHERE (`CREATE_NEW` / `O_EXCL`), so it carries the mutual
|
|
16
|
+
* exclusion instead: a transition on item `X` first creates `queue/locks/X.lock`; whoever
|
|
17
|
+
* fails to create it does not touch `X`. The lock is held for a handful of filesystem calls
|
|
18
|
+
* (milliseconds) and released in `finally`.
|
|
19
|
+
*
|
|
20
|
+
* A CRASH LEAVES A LOCK. One older than `GENE_LIMITS.lockStaleMs` is reaped by the next
|
|
21
|
+
* contender. That comparison uses the OS clock (`Date.now()`), not the queue's injected one,
|
|
22
|
+
* because the OS stamped the file's mtime: mixing the two clocks would reap a live lock
|
|
23
|
+
* whenever a test (or a skewed clock) put them apart. Two contenders reaping the SAME stale
|
|
24
|
+
* lock at once can both end up holding it; that needs a crash plus a simultaneous reap, and the
|
|
25
|
+
* curator is idempotent by `proposalId` (10.5.5), so the worst case is a duplicate look at one
|
|
26
|
+
* item, not a duplicate publish.
|
|
27
|
+
*/
|
|
28
|
+
import { promises as nodeFs } from 'node:fs';
|
|
29
|
+
import { join } from 'node:path';
|
|
30
|
+
import { GENE_LIMITS } from '@aragon-agent/tui/model/gene/limits';
|
|
31
|
+
import { ensureDir, retryOnWindowsContention, statOrNull } from './fs.js';
|
|
32
|
+
function realSleep(ms) {
|
|
33
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
34
|
+
}
|
|
35
|
+
function codeOf(error) {
|
|
36
|
+
const code = error?.code;
|
|
37
|
+
return typeof code === 'string' ? code : undefined;
|
|
38
|
+
}
|
|
39
|
+
/** Create the lock file exclusively. False = somebody holds it (or it is being deleted). */
|
|
40
|
+
async function tryCreate(path, pid) {
|
|
41
|
+
try {
|
|
42
|
+
const handle = await retryOnWindowsContention(() => nodeFs.open(path, 'wx', 0o600));
|
|
43
|
+
try {
|
|
44
|
+
await handle.write(JSON.stringify({ pid, at: Date.now() }));
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
await handle.close();
|
|
48
|
+
}
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
const code = codeOf(error);
|
|
53
|
+
// EPERM / EBUSY / EACCES: on Windows a lock that was just unlinked is delete-pending.
|
|
54
|
+
if (code === 'EEXIST' || code === 'EPERM' || code === 'EBUSY' || code === 'EACCES')
|
|
55
|
+
return false;
|
|
56
|
+
throw error;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
async function reapIfStale(path) {
|
|
60
|
+
const stamp = await statOrNull(path);
|
|
61
|
+
if (stamp === null)
|
|
62
|
+
return true; // it vanished: the next create may succeed
|
|
63
|
+
if (Date.now() - stamp.mtimeMs <= GENE_LIMITS.lockStaleMs)
|
|
64
|
+
return false;
|
|
65
|
+
await retryOnWindowsContention(() => nodeFs.unlink(path)).catch(() => undefined);
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
async function acquire(path, pid) {
|
|
69
|
+
if (await tryCreate(path, pid))
|
|
70
|
+
return true;
|
|
71
|
+
return (await reapIfStale(path)) ? tryCreate(path, pid) : false;
|
|
72
|
+
}
|
|
73
|
+
async function release(path) {
|
|
74
|
+
await retryOnWindowsContention(() => nodeFs.unlink(path)).catch(() => undefined);
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Run `body` while holding the lock for queue item `name`. Returns `{ held: false }` when the
|
|
78
|
+
* lock could not be taken within the attempts; the caller decides whether that means "skip
|
|
79
|
+
* this item" (a claim) or "try again later" (a settle).
|
|
80
|
+
*/
|
|
81
|
+
export async function withQueueLock(options, name, body) {
|
|
82
|
+
const path = join(options.dir, `${name}.lock`);
|
|
83
|
+
const attempts = Math.max(1, options.attempts ?? 1);
|
|
84
|
+
const sleep = options.sleep ?? realSleep;
|
|
85
|
+
await ensureDir(options.dir);
|
|
86
|
+
for (let attempt = 1; attempt <= attempts; attempt += 1) {
|
|
87
|
+
if (await acquire(path, options.pid)) {
|
|
88
|
+
try {
|
|
89
|
+
return { held: true, value: await body() };
|
|
90
|
+
}
|
|
91
|
+
finally {
|
|
92
|
+
await release(path);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
if (attempt < attempts)
|
|
96
|
+
await sleep(options.waitMs ?? 15);
|
|
97
|
+
}
|
|
98
|
+
return { held: false };
|
|
99
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a queue file IS: its name, its stored shape, how two proposals merge and how an item is
|
|
3
|
+
* kept under the size limit (gene-bank spec 10.5.1, 10.5.3).
|
|
4
|
+
*
|
|
5
|
+
* ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
|
|
6
|
+
*
|
|
7
|
+
* PURE. Nothing here touches the filesystem; `queue.ts` owns every read, write and rename. The
|
|
8
|
+
* split exists so the rules that decide WHAT a valid item is and how duplicates fold together can
|
|
9
|
+
* be tested without a directory, and so `queue.ts` stays readable.
|
|
10
|
+
*/
|
|
11
|
+
import type { GeneProposal, GeneQueueItem, ProposalPriority } from '@aragon-agent/tui/model/gene/types';
|
|
12
|
+
/** Why an item left the queue without being an error. `detail` carries stable tokens only. */
|
|
13
|
+
export type QueueResult = 'done' | 'published' | 'merged' | 'archived' | 'revoked' | 'no_change' | 'rejected' | 'needs_human' | 'superseded' | 'target_gone' | 'forgotten' | 'discarded' | 'evicted' | 'project_excluded';
|
|
14
|
+
export interface QueueOutcome {
|
|
15
|
+
result: QueueResult;
|
|
16
|
+
/** A stable token such as `learning_off` or `human_edit`; never gene text (I-19). */
|
|
17
|
+
detail?: string;
|
|
18
|
+
at: number;
|
|
19
|
+
}
|
|
20
|
+
/** A queue file as stored: the frozen `GeneQueueItem` plus the settled outcome, if any. */
|
|
21
|
+
export interface GeneQueueRecord extends GeneQueueItem {
|
|
22
|
+
outcome?: QueueOutcome;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The privacy-safe husk of a proposal (I3-5, RV-42): every field that can carry session or
|
|
26
|
+
* project text is emptied; the identity fields stay so the done/ trace still says WHICH
|
|
27
|
+
* proposal was dropped and from which project. Nothing here is a model-written sentence.
|
|
28
|
+
*/
|
|
29
|
+
export declare function redactProposal(proposal: GeneProposal): GeneProposal;
|
|
30
|
+
export interface ParsedQueueName {
|
|
31
|
+
name: string;
|
|
32
|
+
priority: ProposalPriority;
|
|
33
|
+
createdAt: number;
|
|
34
|
+
dedupe8: string;
|
|
35
|
+
proposalId: string;
|
|
36
|
+
}
|
|
37
|
+
/** Split a queue file name; null when it is not one of ours (such files are ignored). */
|
|
38
|
+
export declare function parseQueueName(name: string): ParsedQueueName | null;
|
|
39
|
+
/** Only names we mint count as queue items; anything else in these directories is not ours. */
|
|
40
|
+
export declare function isQueueName(name: string): boolean;
|
|
41
|
+
/** Tolerant: a hand-edited or torn file is `null`, never an exception. */
|
|
42
|
+
export declare function coerceQueueRecord(raw: unknown): GeneQueueRecord | null;
|
|
43
|
+
/**
|
|
44
|
+
* Fold `incoming` into `existing` (10.5.3): evidence by text hash up to the cap, the higher
|
|
45
|
+
* priority (smaller number), the newer draft, `merged` counting every folded request. The
|
|
46
|
+
* existing id and `createdAt` survive on purpose: the item has been waiting, and aging must
|
|
47
|
+
* keep counting from the first request, not restart on every duplicate.
|
|
48
|
+
*/
|
|
49
|
+
export declare function mergeProposals(existing: GeneProposal, incoming: GeneProposal): GeneProposal;
|
|
50
|
+
/**
|
|
51
|
+
* Shrink a record until its JSON fits `queueItemMaxKB`: clip evidence texts, drop evidence from
|
|
52
|
+
* the tail, finally drop the draft. Returns null when even that is not enough.
|
|
53
|
+
*/
|
|
54
|
+
export declare function fitRecordToLimit(record: GeneQueueRecord): {
|
|
55
|
+
record: GeneQueueRecord;
|
|
56
|
+
text: string;
|
|
57
|
+
} | null;
|