@jjh32456/longlive 0.0.0-stage → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +235 -0
- package/LICENSE +21 -0
- package/QUICKSTART.md +362 -0
- package/README.en.md +64 -0
- package/README.md +256 -2
- package/SPEC.md +211 -0
- package/build-info.json +1665 -0
- package/cordis.patch.yml +208 -0
- package/docs/A1-MIGRATION.md +75 -0
- package/docs/ANSWER-GUARD.md +92 -0
- package/docs/ARCHITECTURE.md +128 -0
- package/docs/AUTO-RECALL-WIRING.md +115 -0
- package/docs/AUTO-RECALL.md +237 -0
- package/docs/CONCEPTS.md +143 -0
- package/docs/CONFIG.md +839 -0
- package/docs/ERRORS.md +271 -0
- package/docs/FAQ.md +186 -0
- package/docs/FEATURES.md +579 -0
- package/docs/INDEX-FRESHNESS.md +21 -0
- package/docs/METRICS.md +244 -0
- package/docs/MIGRATION-1.6.0.md +220 -0
- package/docs/OPERATIONS.md +439 -0
- package/docs/PANEL-INTEGRATION.md +190 -0
- package/docs/PRIVACY.md +88 -0
- package/docs/QUICKSTART.md +155 -0
- package/docs/RAW-INDEX-POLICY.md +7 -0
- package/docs/README.en.md +48 -0
- package/docs/RESIDENT-WATCHER.md +90 -0
- package/docs/SESSION-WATCH.md +214 -0
- package/docs/TOOLS.md +184 -0
- package/docs/TROUBLESHOOTING.md +329 -0
- package/icon.svg +11 -0
- package/lib/client.js +436 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +163 -4
- package/runbook.md +343 -0
- package/scripts/archive-digest-build.mjs +668 -0
- package/scripts/auto-truncate-run.ps1 +752 -0
- package/scripts/backfill-auto-cards.mjs +98 -0
- package/scripts/edges-build.mjs +1003 -0
- package/scripts/index-maintain.mjs +39 -0
- package/scripts/index-reconcile.mjs +49 -0
- package/scripts/index-status.mjs +28 -0
- package/scripts/install-resident-watcher.ps1 +15 -0
- package/scripts/install-session-watch.ps1 +332 -0
- package/scripts/install-surgery-task.ps1 +174 -0
- package/scripts/lib/auto-truncate-run.ps1 +512 -0
- package/scripts/lib/session-watch-fixture.mjs +207 -0
- package/scripts/longlive-doctor.mjs +578 -0
- package/scripts/metrics-read.mjs +79 -0
- package/scripts/metrics-sample.mjs +215 -0
- package/scripts/migrate-180.mjs +163 -0
- package/scripts/migrate-200.mjs +8 -0
- package/scripts/migrate-a1-legacy.mjs +62 -0
- package/scripts/migrate-lifecycle.mjs +157 -0
- package/scripts/pack.mjs +392 -0
- package/scripts/recall-index-build.mjs +128 -0
- package/scripts/recall-links-build.mjs +420 -0
- package/scripts/rescore-cards.mjs +36 -0
- package/scripts/resident-watcher-status.ps1 +15 -0
- package/scripts/resident-watcher.ps1 +643 -0
- package/scripts/session-watch-drill.mjs +553 -0
- package/scripts/session-watch-status.ps1 +146 -0
- package/scripts/session-watch.mjs +1367 -0
- package/scripts/surgery-inspect.mjs +122 -0
- package/scripts/surgery-run.cmd +34 -0
- package/scripts/truncate-cli.mjs +279 -0
- package/scripts/unattended-surgery.ps1 +1019 -0
- package/scripts/uninstall-resident-watcher.ps1 +15 -0
- package/scripts/uninstall-session-watch.ps1 +192 -0
- package/scripts/verify-card-anchors.mjs +138 -0
- package/scripts/watch-loop.ps1 +916 -0
- package/src/actions/audit.js +125 -0
- package/src/actions/evidence.js +122 -0
- package/src/actions/fs.js +162 -0
- package/src/activity/index.js +873 -0
- package/src/activity/model.js +351 -0
- package/src/activity/store.js +786 -0
- package/src/activity/summary.js +180 -0
- package/src/activity/thinking.js +191 -0
- package/src/adapters/constants.js +11 -0
- package/src/adapters/engram/data/aliases.json +51 -0
- package/src/adapters/engram/data/policy.json +8 -0
- package/src/adapters/engram/data/routing-rules.json +546 -0
- package/src/adapters/engram/index.js +278 -0
- package/src/adapters/registry.js +315 -0
- package/src/answer/audit.js +238 -0
- package/src/answer/claim-guard.mjs +234 -0
- package/src/answer/evidence.js +30 -0
- package/src/answer/guard.js +1370 -0
- package/src/answer/index.js +1086 -0
- package/src/answer/query.js +111 -0
- package/src/answer/second-hop.mjs +101 -0
- package/src/auto-truncate-status.js +164 -0
- package/src/auto-truncate.js +1181 -0
- package/src/autoprocedure/candidate.js +342 -0
- package/src/autoprocedure/config.js +122 -0
- package/src/autoprocedure/evidence.js +345 -0
- package/src/autoprocedure/index.js +83 -0
- package/src/autoprocedure/ledger.js +329 -0
- package/src/autoprocedure/lint.js +232 -0
- package/src/autoprocedure/llm.js +409 -0
- package/src/autoprocedure/locks.js +102 -0
- package/src/autoprocedure/paths.js +39 -0
- package/src/autoprocedure/privacy.js +87 -0
- package/src/autoprocedure/rules.js +288 -0
- package/src/autoprocedure/runtime.js +718 -0
- package/src/autoprocedure/session-reader.js +328 -0
- package/src/backup.js +310 -0
- package/src/bus/bus.mjs +1446 -0
- package/src/codec.js +269 -0
- package/src/compaction/cut-engine.js +44 -0
- package/src/compaction/engine-core.js +1237 -0
- package/src/compaction/entry.js +228 -0
- package/src/compaction.js +230 -0
- package/src/conclusion.js +366 -0
- package/src/config.js +835 -0
- package/src/d6/runtime.js +517 -0
- package/src/d6/surface.js +181 -0
- package/src/deps.js +189 -0
- package/src/engine-status.js +141 -0
- package/src/features.js +1035 -0
- package/src/handoff/index.js +1077 -0
- package/src/handoff/model.js +1058 -0
- package/src/handoff/store.js +1233 -0
- package/src/heartbeat.js +385 -0
- package/src/home.js +16 -0
- package/src/host-version.js +280 -0
- package/src/hot-truncate-diag.js +98 -0
- package/src/identity/card-marker.js +281 -0
- package/src/identity/handover.js +845 -0
- package/src/identity/index.js +337 -0
- package/src/identity/inject-position.js +133 -0
- package/src/identity/writeback.js +344 -0
- package/src/identity.js +118 -0
- package/src/index.js +647 -0
- package/src/lifecycle/gap-clocks.js +364 -0
- package/src/lifecycle/index.js +269 -0
- package/src/lifecycle/proactive.js +1426 -0
- package/src/live-target.js +212 -0
- package/src/live.js +1603 -0
- package/src/log-rotation.js +153 -0
- package/src/memory/a1-migration.js +190 -0
- package/src/memory/activity-capture.js +229 -0
- package/src/memory/anchor-fallback.js +116 -0
- package/src/memory/anchors.js +194 -0
- package/src/memory/archive-cold-state.mjs +794 -0
- package/src/memory/archive-staging.mjs +305 -0
- package/src/memory/archive.mjs +415 -0
- package/src/memory/audit-records.js +222 -0
- package/src/memory/auto-cards.js +441 -0
- package/src/memory/capture-host.js +297 -0
- package/src/memory/capture.js +496 -0
- package/src/memory/card-anchors.js +203 -0
- package/src/memory/card-priority.js +110 -0
- package/src/memory/cards.js +425 -0
- package/src/memory/catchup.mjs +534 -0
- package/src/memory/conclusion-distill.js +381 -0
- package/src/memory/conclusion-drafts.js +243 -0
- package/src/memory/conflicts.js +1060 -0
- package/src/memory/consolidate.js +834 -0
- package/src/memory/decay.js +311 -0
- package/src/memory/distill.js +485 -0
- package/src/memory/event-index.js +1826 -0
- package/src/memory/evidence-chain.js +295 -0
- package/src/memory/evidence.js +213 -0
- package/src/memory/filter-runner.js +555 -0
- package/src/memory/filter.js +1035 -0
- package/src/memory/forget-v2.js +680 -0
- package/src/memory/forget.js +531 -0
- package/src/memory/frames-activation.js +249 -0
- package/src/memory/frontmatter.js +454 -0
- package/src/memory/fts-query.js +342 -0
- package/src/memory/governance.js +604 -0
- package/src/memory/index-freshness.js +234 -0
- package/src/memory/index.js +435 -0
- package/src/memory/l2-gate.js +169 -0
- package/src/memory/land.mjs +743 -0
- package/src/memory/lifecycle.js +235 -0
- package/src/memory/lock.js +121 -0
- package/src/memory/maintenance.js +1149 -0
- package/src/memory/manifest.js +245 -0
- package/src/memory/memory-health.mjs +607 -0
- package/src/memory/migrate-200.js +1681 -0
- package/src/memory/migrate-lifecycle.js +1808 -0
- package/src/memory/migrate.js +139 -0
- package/src/memory/paths.js +229 -0
- package/src/memory/procedure-candidate.mjs +377 -0
- package/src/memory/procedure.js +982 -0
- package/src/memory/prospective-memory.mjs +362 -0
- package/src/memory/provenance.js +119 -0
- package/src/memory/recall-feedback.mjs +406 -0
- package/src/memory/recall-v2.js +218 -0
- package/src/memory/recall.js +357 -0
- package/src/memory/reconcile.js +265 -0
- package/src/memory/records.js +433 -0
- package/src/memory/reinforce.js +281 -0
- package/src/memory/retention.js +162 -0
- package/src/memory/review.js +124 -0
- package/src/memory/state.js +279 -0
- package/src/memory/tiers.js +168 -0
- package/src/memory/topic-phrases.js +73 -0
- package/src/memory/trust.js +97 -0
- package/src/memory/turn-budget.mjs +290 -0
- package/src/memory/version-chain.js +264 -0
- package/src/memory/wake-bridge.mjs +2999 -0
- package/src/memory/wal.js +137 -0
- package/src/memory/working-frame.js +779 -0
- package/src/metrics/classify.mjs +191 -0
- package/src/metrics/estimate.mjs +108 -0
- package/src/metrics/index.mjs +204 -0
- package/src/metrics/measure.mjs +462 -0
- package/src/metrics/prestep-latency.mjs +307 -0
- package/src/metrics/store.mjs +264 -0
- package/src/original.js +294 -0
- package/src/policy/threshold-policy.js +224 -0
- package/src/policy-profile.js +463 -0
- package/src/recall/anaphora.mjs +87 -0
- package/src/recall/archive-config.mjs +130 -0
- package/src/recall/archive-fallback.mjs +390 -0
- package/src/recall/archive-search.mjs +428 -0
- package/src/recall/archive-state.mjs +588 -0
- package/src/recall/brain.mjs +501 -0
- package/src/recall/cards.mjs +202 -0
- package/src/recall/current-line.mjs +110 -0
- package/src/recall/edges.js +398 -0
- package/src/recall/embedding.mjs +698 -0
- package/src/recall/entities.mjs +112 -0
- package/src/recall/explain.mjs +443 -0
- package/src/recall/force-policy.mjs +138 -0
- package/src/recall/gate-log.mjs +280 -0
- package/src/recall/gate-metrics.mjs +191 -0
- package/src/recall/index.js +1337 -0
- package/src/recall/inject-order.mjs +279 -0
- package/src/recall/link-recall.mjs +183 -0
- package/src/recall/links.mjs +696 -0
- package/src/recall/privacy.mjs +208 -0
- package/src/recall/recall-core.mjs +810 -0
- package/src/recall/shared-visibility.js +302 -0
- package/src/recall/time-normalizer.mjs +196 -0
- package/src/recall/turn-budget-inject.mjs +154 -0
- package/src/retention/cold-gate.mjs +146 -0
- package/src/retention/config.js +163 -0
- package/src/retention/index.js +801 -0
- package/src/role/activation.js +191 -0
- package/src/role/attention.js +318 -0
- package/src/role/base.js +36 -0
- package/src/role/channels.js +423 -0
- package/src/role/index.js +425 -0
- package/src/role/interfaces.js +115 -0
- package/src/role/personality.js +370 -0
- package/src/role/readers.js +151 -0
- package/src/role/relationships.js +477 -0
- package/src/role/store.js +202 -0
- package/src/role/writeprotect.js +373 -0
- package/src/router/aliases.json +182 -0
- package/src/router/background/agent-runner.mjs +239 -0
- package/src/router/background/anchor.mjs +323 -0
- package/src/router/background/audit.mjs +337 -0
- package/src/router/background/budget-ledger.mjs +648 -0
- package/src/router/background/host-sim.mjs +451 -0
- package/src/router/background/index.mjs +81 -0
- package/src/router/background/memory.mjs +63 -0
- package/src/router/background/mock-llm.mjs +203 -0
- package/src/router/background/queue.mjs +224 -0
- package/src/router/background/retry.mjs +255 -0
- package/src/router/background/router.mjs +1459 -0
- package/src/router/background/stream.mjs +276 -0
- package/src/router/background/tool-policy.mjs +255 -0
- package/src/router/design-headings.json +221 -0
- package/src/router/face/config.mjs +155 -0
- package/src/router/face/context.mjs +284 -0
- package/src/router/face/face.mjs +466 -0
- package/src/router/face/identity.mjs +130 -0
- package/src/router/face/index.mjs +65 -0
- package/src/router/face/journal.mjs +119 -0
- package/src/router/face/llm.mjs +252 -0
- package/src/router/face/outbox.mjs +153 -0
- package/src/router/face/paths.mjs +54 -0
- package/src/router/judge.mjs +987 -0
- package/src/router/policies/generic.json +131 -0
- package/src/router/route.js +1766 -0
- package/src/router/router.mjs +535 -0
- package/src/router/routing-rules.json +816 -0
- package/src/router/run-sim.mjs +530 -0
- package/src/router/runtime.js +569 -0
- package/src/router/service/apply.mjs +1218 -0
- package/src/router/service/board.mjs +712 -0
- package/src/router/service/caller.mjs +131 -0
- package/src/router/service/config.mjs +361 -0
- package/src/router/service/context.mjs +314 -0
- package/src/router/service/hint.mjs +668 -0
- package/src/router/service/lease.mjs +494 -0
- package/src/router/service/live.mjs +251 -0
- package/src/router/service/lock.mjs +550 -0
- package/src/router/service/merge.mjs +255 -0
- package/src/router/service/model-resolve.mjs +350 -0
- package/src/router/service/paths.mjs +168 -0
- package/src/router/service/proposals.mjs +1461 -0
- package/src/router/service/queue.mjs +477 -0
- package/src/router/service/reconcile.mjs +271 -0
- package/src/router/service/service.mjs +2998 -0
- package/src/router/service/sources.mjs +352 -0
- package/src/router/service/status.mjs +520 -0
- package/src/router/service/store.mjs +476 -0
- package/src/router/service/ticklock.mjs +239 -0
- package/src/router/service/tokens.mjs +95 -0
- package/src/router/service/tools.mjs +248 -0
- package/src/router/service/wake.mjs +544 -0
- package/src/router/service/wal.mjs +685 -0
- package/src/router/shadow.mjs +821 -0
- package/src/surgery-recovery.js +1909 -0
- package/src/tool-output.js +485 -0
- package/src/tools.js +3262 -0
- package/src/truncate-visible.js +2416 -0
- package/src/truncate.js +999 -0
- package/src/ui/actions.js +1312 -0
- package/src/ui/flags.js +259 -0
- package/src/ui/panel-api.js +371 -0
- package/src/ui/panel-auth.js +251 -0
- package/src/ui/panel-integrity.js +243 -0
- package/src/ui/routes-readonly.js +759 -0
- package/src/ui/routes.js +284 -0
- package/src/util/append-store.js +368 -0
- package/src/util/local-day.js +30 -0
- package/src/util/redact.js +227 -0
- package/src/util/stale-locks.js +148 -0
- package/src/version.js +99 -0
- package/test/fixtures/pre-step-container.mjs +100 -0
- package/test/p1_probe.mjs +97 -0
|
@@ -0,0 +1,1461 @@
|
|
|
1
|
+
// WP3 proposal data layer (DESIGN §3.3/§3.6/§5.1/§5.2/§5.7/§5.10/§7.2).
|
|
2
|
+
//
|
|
3
|
+
// This module owns the proposal pipeline up to (and including) "queued":
|
|
4
|
+
// validate -> path whitelist -> target snapshot -> dedupe -> quota/rate
|
|
5
|
+
// -> issue.lock(wx) -> seqCounter/ticket -> WAL queue.assign -> proposal file
|
|
6
|
+
// -> queue.json -> audit proposal.create
|
|
7
|
+
//
|
|
8
|
+
// It never writes canonical memory. The only non-derived file it reads is the
|
|
9
|
+
// proposal target itself, and only to snapshot sha/bytes. Apply/approve/lease
|
|
10
|
+
// live in later work packages; this file deliberately stops at `status:
|
|
11
|
+
// "queued"` so the default surface stays side-effect free.
|
|
12
|
+
|
|
13
|
+
import crypto from 'node:crypto';
|
|
14
|
+
import fs from 'node:fs';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
|
|
17
|
+
import { hostName, localDayKey, sha256Hex } from './paths.mjs';
|
|
18
|
+
import { pidAlive } from './lock.mjs';
|
|
19
|
+
import { createWal } from './wal.mjs';
|
|
20
|
+
import { isSubagentCaller } from './caller.mjs';
|
|
21
|
+
import {
|
|
22
|
+
countNonTerminal,
|
|
23
|
+
PROPOSAL_FILE_MAX_BYTES,
|
|
24
|
+
PROPOSAL_ID_RE,
|
|
25
|
+
PROPOSAL_TARGET_MAX_BYTES,
|
|
26
|
+
PROPOSAL_VERSION,
|
|
27
|
+
QUEUE_MAX_BYTES,
|
|
28
|
+
isTerminalProposalStatus,
|
|
29
|
+
readProposal,
|
|
30
|
+
readQueueFile,
|
|
31
|
+
readTargetSnapshot,
|
|
32
|
+
scanProposalDir,
|
|
33
|
+
StoreError,
|
|
34
|
+
updateProposalStrict,
|
|
35
|
+
writeJsonStrict,
|
|
36
|
+
writeProposalFile,
|
|
37
|
+
} from './store.mjs';
|
|
38
|
+
import { planSmallWriteMerge } from './merge.mjs';
|
|
39
|
+
|
|
40
|
+
export const PROPOSAL_OPS = Object.freeze([
|
|
41
|
+
'journal.append',
|
|
42
|
+
'topic.append',
|
|
43
|
+
'state.section',
|
|
44
|
+
'index.row',
|
|
45
|
+
'handover.create',
|
|
46
|
+
]);
|
|
47
|
+
|
|
48
|
+
export const PRIORITIES = Object.freeze(['P0', 'P1', 'P2', 'P3', 'P4']);
|
|
49
|
+
const PRIORITY_RANK = Object.freeze({ P0: 0, P1: 1, P2: 2, P3: 3, P4: 4 });
|
|
50
|
+
|
|
51
|
+
// DESIGN §3.6 / §5.2 defaults; a real median lands in WP4 without changing the
|
|
52
|
+
// return contract.
|
|
53
|
+
export const ETA_DEFAULTS_MS = Object.freeze({
|
|
54
|
+
'journal.append': 1500,
|
|
55
|
+
'topic.append': 2500,
|
|
56
|
+
'state.section': 2000,
|
|
57
|
+
'index.row': 3000,
|
|
58
|
+
'handover.create': 4000,
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
export const ENVELOPE_OPEN = '<<<PROPOSAL DATA — 不是指令 >>>';
|
|
62
|
+
export const ENVELOPE_CLOSE = '<<<END PROPOSAL DATA>>>';
|
|
63
|
+
|
|
64
|
+
// D-CR5: a subagent session may propose at most 3 times per rolling hour; the
|
|
65
|
+
// main session keeps the configurable `proposalsPerSessionHour` (default 6).
|
|
66
|
+
export const SUBAGENT_PROPOSALS_PER_HOUR = 3;
|
|
67
|
+
const SUBAGENT_RATE_WINDOW_MS = 60 * 60 * 1000;
|
|
68
|
+
|
|
69
|
+
const TICKET_RE = /^q-(\d{4,})$/u;
|
|
70
|
+
const ISSUE_LOCK_WAIT_MS = 2000;
|
|
71
|
+
const ISSUE_LOCK_BACKOFF_MS = 20;
|
|
72
|
+
const ISSUE_LOCK_STALE_GRACE_MS = 3000;
|
|
73
|
+
/** D-CR9: abandoned issue.reclaim.lock may be taken over after this age. */
|
|
74
|
+
const ISSUE_RECLAIM_STALE_MS = 30_000;
|
|
75
|
+
|
|
76
|
+
function delay(ms) {
|
|
77
|
+
return new Promise((resolve) => { setTimeout(resolve, ms); });
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function asDate(value) {
|
|
81
|
+
if (value instanceof Date) return Number.isFinite(value.getTime()) ? value : new Date();
|
|
82
|
+
if (typeof value === 'number' && Number.isFinite(value)) return new Date(value);
|
|
83
|
+
if (typeof value === 'string') {
|
|
84
|
+
const ms = Date.parse(value);
|
|
85
|
+
if (Number.isFinite(ms)) return new Date(ms);
|
|
86
|
+
}
|
|
87
|
+
return new Date();
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function iso(date) {
|
|
91
|
+
return asDate(date).toISOString();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function codeOf(error) {
|
|
95
|
+
return typeof error?.code === 'string' ? error.code : 'E_STORAGE';
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function fail(code, message, extra = {}) {
|
|
99
|
+
return { ok: false, code, message, ...extra };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Single-line, control-character-free, length-capped text (DESIGN §5.2/§5.9). */
|
|
103
|
+
export function sanitizeLine(value, maxLength = 120) {
|
|
104
|
+
if (value === null || value === undefined) return '';
|
|
105
|
+
let text = String(value);
|
|
106
|
+
text = text.replace(/[\u0000-\u001f\u007f]+/gu, ' ');
|
|
107
|
+
text = text.replace(/\s+/gu, ' ').trim();
|
|
108
|
+
if (maxLength > 0 && text.length > maxLength) text = text.slice(0, maxLength);
|
|
109
|
+
return text;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function isWellFormedText(text) {
|
|
113
|
+
const value = String(text ?? '');
|
|
114
|
+
if (typeof value.isWellFormed === 'function') return value.isWellFormed();
|
|
115
|
+
return Buffer.from(value, 'utf8').toString('utf8') === value;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function stripDisallowedControls(text) {
|
|
119
|
+
// Newlines/tabs are fine in a proposal body; every other C0 control and DEL
|
|
120
|
+
// is stripped (the content is later rendered inside a data envelope).
|
|
121
|
+
return String(text ?? '').replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/gu, '');
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* D-CR4: proposal bodies/titles are third-party data rendered inside the data
|
|
126
|
+
* envelope. No user-controlled text may forge an envelope marker (or any
|
|
127
|
+
* `<<<`/`>>>` pair), otherwise the closing marker can be duplicated and the
|
|
128
|
+
* reader can be tricked into treating injected text as instructions. A zero
|
|
129
|
+
* width space is inserted inside each run so the visual text survives while the
|
|
130
|
+
* marker grammar cannot close early.
|
|
131
|
+
*/
|
|
132
|
+
export function neutralizeEnvelopeMarkers(text) {
|
|
133
|
+
return String(text ?? '').replace(/<<<|>>>/gu, (marker) => (marker === '<<<'
|
|
134
|
+
? '<\u200b<<'
|
|
135
|
+
: '>>\u200b>'));
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Data envelope for proposal bodies (DESIGN §5.12). */
|
|
139
|
+
export function wrapProposalContent(content, maxLength = 4000) {
|
|
140
|
+
const clean = neutralizeEnvelopeMarkers(stripDisallowedControls(content)).slice(0, maxLength);
|
|
141
|
+
return `${ENVELOPE_OPEN}\n${clean}\n${ENVELOPE_CLOSE}`;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function normalizeContentForHash(content) {
|
|
145
|
+
return String(content ?? '')
|
|
146
|
+
.replace(/\r\n?/gu, '\n')
|
|
147
|
+
.split('\n')
|
|
148
|
+
.map((line) => line.replace(/[ \t]+$/u, ''))
|
|
149
|
+
.join('\n');
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function buildDedupeKey(op, target, content) {
|
|
153
|
+
return `sha256:${sha256Hex(`${op}\u0000${target}\u0000${normalizeContentForHash(content)}`)}`;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function buildMergeKey(op, target) {
|
|
157
|
+
return `sha256:${sha256Hex(`${op}\u0000${target}`)}`;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export function isProposalId(value) {
|
|
161
|
+
return typeof value === 'string' && PROPOSAL_ID_RE.test(value);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function ticketNumber(ticket) {
|
|
165
|
+
const match = TICKET_RE.exec(String(ticket ?? ''));
|
|
166
|
+
if (!match) return 0;
|
|
167
|
+
const value = Number.parseInt(match[1], 10);
|
|
168
|
+
return Number.isFinite(value) ? value : 0;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function formatTicket(number) {
|
|
172
|
+
return `q-${String(number).padStart(4, '0')}`;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export function makeProposalId(date = new Date()) {
|
|
176
|
+
const stamp = asDate(date).toISOString().replace(/[-:]/gu, '').replace(/\.\d{3}Z$/u, '');
|
|
177
|
+
return `p-${stamp}-${crypto.randomBytes(3).toString('hex')}`;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function sortProposals(proposals) {
|
|
181
|
+
return [...proposals].sort((a, b) => {
|
|
182
|
+
const ap = PRIORITY_RANK[a?.queue?.effectivePriority] ?? 9;
|
|
183
|
+
const bp = PRIORITY_RANK[b?.queue?.effectivePriority] ?? 9;
|
|
184
|
+
if (ap !== bp) return ap - bp;
|
|
185
|
+
const at = Date.parse(a?.queue?.queuedAt ?? a?.createdAt ?? '');
|
|
186
|
+
const bt = Date.parse(b?.queue?.queuedAt ?? b?.createdAt ?? '');
|
|
187
|
+
if (Number.isFinite(at) && Number.isFinite(bt) && at !== bt) return at - bt;
|
|
188
|
+
return String(a?.queue?.ticket ?? '').localeCompare(String(b?.queue?.ticket ?? ''));
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export function computeRisk(op, target, content, snapshot = {}) {
|
|
193
|
+
const reasons = [];
|
|
194
|
+
const rank = { low: 0, medium: 1, high: 2 };
|
|
195
|
+
let risk = 'low';
|
|
196
|
+
const raise = (level, reason) => {
|
|
197
|
+
if (rank[level] > rank[risk]) risk = level;
|
|
198
|
+
if (!reasons.includes(reason)) reasons.push(reason);
|
|
199
|
+
};
|
|
200
|
+
if (op === 'state.section' || op === 'index.row') raise('high', 'structured-target');
|
|
201
|
+
if (Number(snapshot.bytes) > 128 * 1024) raise('high', 'target-over-128kb');
|
|
202
|
+
if (op === 'topic.append') {
|
|
203
|
+
if (snapshot.exists) raise('medium', 'existing-topic');
|
|
204
|
+
else if (String(content ?? '').length > 2000) raise('medium', 'new-topic-over-2000-chars');
|
|
205
|
+
}
|
|
206
|
+
if (op === 'handover.create' && snapshot.exists) raise('high', 'overwrite-existing-handover');
|
|
207
|
+
if (risk === 'low') reasons.push('append-only');
|
|
208
|
+
return { risk, riskReasons: reasons };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Character/byte validation for `content` (DESIGN §3.3, §5.1). */
|
|
212
|
+
export function validateContent(raw, maxChars = 4000) {
|
|
213
|
+
if (raw === null || raw === undefined) return { ok: true, content: '' };
|
|
214
|
+
if (typeof raw !== 'string') return fail('E_BAD_STATE', 'content must be a string');
|
|
215
|
+
if (!isWellFormedText(raw)) return fail('E_NOT_UTF8', 'content is not valid UTF-8');
|
|
216
|
+
if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/u.test(raw)) {
|
|
217
|
+
return fail('E_BAD_STATE', 'content contains disallowed control characters');
|
|
218
|
+
}
|
|
219
|
+
if (raw.length > maxChars) {
|
|
220
|
+
return fail('E_CONTENT_TOO_LARGE', `content exceeds ${maxChars} characters`, { limit: maxChars, actual: raw.length });
|
|
221
|
+
}
|
|
222
|
+
const bytes = Buffer.byteLength(raw, 'utf8');
|
|
223
|
+
if (bytes > PROPOSAL_FILE_MAX_BYTES) {
|
|
224
|
+
return fail('E_CONTENT_TOO_LARGE', `content exceeds ${PROPOSAL_FILE_MAX_BYTES} bytes`, { limit: PROPOSAL_FILE_MAX_BYTES, actual: bytes });
|
|
225
|
+
}
|
|
226
|
+
return { ok: true, content: raw, bytes };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const TARGET_RULES = Object.freeze({
|
|
230
|
+
'journal.append': /^journal\/(\d{4})-(\d{2})\.md$/u,
|
|
231
|
+
'topic.append': /^topics\/([a-z0-9][a-z0-9._-]{0,63})\.md$/u,
|
|
232
|
+
'state.section': /^STATE\.md$/u,
|
|
233
|
+
'index.row': /^INDEX\.md$/u,
|
|
234
|
+
'handover.create': /^handover\/(\d{4})-(\d{2})-(\d{2})-([a-z0-9][a-z0-9._-]{0,63})\.md$/u,
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
function validJournalMonth(match) {
|
|
238
|
+
const year = Number(match[1]);
|
|
239
|
+
const month = Number(match[2]);
|
|
240
|
+
return year >= 2020 && year <= 2099 && month >= 1 && month <= 12;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function validHandoverDate(match) {
|
|
244
|
+
const year = Number(match[1]);
|
|
245
|
+
const month = Number(match[2]);
|
|
246
|
+
const day = Number(match[3]);
|
|
247
|
+
if (year < 2020 || year > 2099) return false;
|
|
248
|
+
const date = new Date(Date.UTC(year, month - 1, day));
|
|
249
|
+
return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
export { validHandoverDate, validJournalMonth };
|
|
253
|
+
|
|
254
|
+
/** Parsed target path, or null. Never resolves `..`, drives, UNC or `~`. */
|
|
255
|
+
export function normalizeTarget(raw) {
|
|
256
|
+
if (typeof raw !== 'string') return null;
|
|
257
|
+
const target = raw.trim().replace(/\\/gu, '/');
|
|
258
|
+
if (target === '' || target.length > 512 || target.includes('\u0000')) return null;
|
|
259
|
+
if (target.startsWith('/') || target.startsWith('//') || /^[A-Za-z]:/u.test(target) || target.startsWith('~')) return null;
|
|
260
|
+
const segments = target.split('/');
|
|
261
|
+
if (segments.some((segment) => segment === '' || segment === '.' || segment === '..')) return null;
|
|
262
|
+
return target;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
export function validateTargetForOp(op, raw) {
|
|
266
|
+
const target = normalizeTarget(raw);
|
|
267
|
+
if (!target) return fail('E_PATH_DENIED', 'target escapes the memory root');
|
|
268
|
+
const rule = TARGET_RULES[op];
|
|
269
|
+
if (!rule) return fail('E_BAD_STATE', `unknown op: ${op}`);
|
|
270
|
+
const match = rule.exec(target);
|
|
271
|
+
if (!match) return fail('E_PATH_DENIED', `target is not allowed for ${op}`);
|
|
272
|
+
if (op === 'journal.append' && !validJournalMonth(match)) return fail('E_PATH_DENIED', 'journal month is invalid');
|
|
273
|
+
if (op === 'handover.create' && !validHandoverDate(match)) return fail('E_PATH_DENIED', 'handover date is invalid');
|
|
274
|
+
return { ok: true, target };
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
export function envelopeContent(content) {
|
|
278
|
+
return wrapProposalContent(content);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function readSectionTitles(text) {
|
|
282
|
+
const titles = [];
|
|
283
|
+
for (const line of String(text ?? '').split('\n')) {
|
|
284
|
+
const match = /^##\s+(.+?)\s*$/u.exec(line);
|
|
285
|
+
if (match) titles.push(match[1]);
|
|
286
|
+
}
|
|
287
|
+
return titles;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export class ProposalEngine {
|
|
291
|
+
constructor({ config, paths, memoryRoot, audit, now, logger } = {}) {
|
|
292
|
+
this.config = config ?? {};
|
|
293
|
+
this.paths = paths ?? {};
|
|
294
|
+
this.vaultDir = this.paths.vaultDir ?? path.dirname(String(this.paths.proposalsDir ?? ''));
|
|
295
|
+
this.proposalsDir = this.paths.proposalsDir ?? path.join(this.vaultDir, 'proposals');
|
|
296
|
+
this.queueFile = path.join(this.proposalsDir, 'queue.json');
|
|
297
|
+
this.walFile = path.join(this.proposalsDir, 'wal.jsonl');
|
|
298
|
+
this.lockDir = path.join(this.vaultDir, 'locks');
|
|
299
|
+
this.issueLockFile = path.join(this.lockDir, 'issue.lock');
|
|
300
|
+
this.issueReclaimFile = path.join(this.lockDir, 'issue.reclaim.lock');
|
|
301
|
+
this.memoryRoot = path.resolve(memoryRoot ?? this.paths.liveRoot ?? '.');
|
|
302
|
+
this.audit = typeof audit === 'function' ? audit : () => {};
|
|
303
|
+
this.now = typeof now === 'function' ? now : () => new Date();
|
|
304
|
+
this.logger = typeof logger === 'function' ? logger : () => {};
|
|
305
|
+
this.host = hostName();
|
|
306
|
+
this.enabled = this.config.proposalEnabled === true;
|
|
307
|
+
// WP4 seams: set by service.mjs / the owner CLI. Kept as plain fields so the
|
|
308
|
+
// engine stays constructible in unit tests that only exercise propose().
|
|
309
|
+
this.applier = null;
|
|
310
|
+
this.wake = null;
|
|
311
|
+
this.lease = null;
|
|
312
|
+
this.wal = createWal({
|
|
313
|
+
file: this.walFile,
|
|
314
|
+
audit: this.audit,
|
|
315
|
+
logger: this.logger,
|
|
316
|
+
maxBytes: this.config.walMaxBytes,
|
|
317
|
+
now: () => this.nowDate(),
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
nowDate() {
|
|
322
|
+
return asDate(this.now());
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
#auditSafe(kind, data) {
|
|
326
|
+
try {
|
|
327
|
+
this.audit(kind, data);
|
|
328
|
+
} catch {
|
|
329
|
+
/* auditing must never turn a proposal call into a crash */
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
#maxChars() {
|
|
334
|
+
const value = Number(this.config.proposalMaxChars);
|
|
335
|
+
return Number.isInteger(value) && value >= 500 ? value : 4000;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
#quota() {
|
|
339
|
+
const value = Number(this.config.maxProposals);
|
|
340
|
+
return Number.isInteger(value) && value > 0 ? value : 200;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
#scan() {
|
|
344
|
+
return scanProposalDir(this.proposalsDir);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
#active(proposals) {
|
|
348
|
+
return proposals.filter((proposal) => !isTerminalProposalStatus(proposal?.status));
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** Absolute target plus every writable-ancestor check (DESIGN §7.2). */
|
|
352
|
+
#inspectTarget(target) {
|
|
353
|
+
const absolute = path.resolve(this.memoryRoot, target);
|
|
354
|
+
const relative = path.relative(this.memoryRoot, absolute);
|
|
355
|
+
if (relative === '' || relative.startsWith('..') || path.isAbsolute(relative)) {
|
|
356
|
+
return fail('E_PATH_DENIED', 'target escapes the memory root');
|
|
357
|
+
}
|
|
358
|
+
let cursor = this.memoryRoot;
|
|
359
|
+
const parts = relative.split(path.sep).slice(0, -1);
|
|
360
|
+
for (const part of parts) {
|
|
361
|
+
cursor = path.join(cursor, part);
|
|
362
|
+
try {
|
|
363
|
+
const stat = fs.lstatSync(cursor);
|
|
364
|
+
if (stat.isSymbolicLink()) return fail('E_PATH_DENIED', 'target path contains a symlink');
|
|
365
|
+
if (!stat.isDirectory()) return fail('E_PATH_DENIED', 'target path contains a non-directory');
|
|
366
|
+
} catch (error) {
|
|
367
|
+
if (error?.code === 'ENOENT') break;
|
|
368
|
+
return fail('E_PATH_DENIED', error?.message ?? 'target path is not readable');
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
try {
|
|
372
|
+
const realRoot = fs.realpathSync(this.memoryRoot);
|
|
373
|
+
let realDir = null;
|
|
374
|
+
try { realDir = fs.realpathSync(path.dirname(absolute)); } catch (error) {
|
|
375
|
+
if (error?.code !== 'ENOENT') return fail('E_PATH_DENIED', 'target directory is not readable');
|
|
376
|
+
}
|
|
377
|
+
if (realDir && realDir !== realRoot && !realDir.startsWith(`${realRoot}${path.sep}`)) {
|
|
378
|
+
return fail('E_PATH_DENIED', 'target resolves outside the memory root');
|
|
379
|
+
}
|
|
380
|
+
} catch {
|
|
381
|
+
return fail('E_PATH_DENIED', 'memory root is not readable');
|
|
382
|
+
}
|
|
383
|
+
const snapshot = readTargetSnapshot(absolute);
|
|
384
|
+
if (!snapshot.ok) return fail(snapshot.code, snapshot.message ?? 'target is not writable');
|
|
385
|
+
return { ok: true, absolute, relative, snapshot };
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
#validateSection(target, title, snapshot) {
|
|
389
|
+
if (target !== 'STATE.md') return fail('E_PATH_DENIED', 'state.section only targets STATE.md');
|
|
390
|
+
if (!snapshot.exists) return fail('E_TARGET_MISSING', 'STATE.md does not exist');
|
|
391
|
+
const read = fs.readFileSync(path.resolve(this.memoryRoot, target), 'utf8');
|
|
392
|
+
const titles = readSectionTitles(read);
|
|
393
|
+
if (!titles.includes(title)) {
|
|
394
|
+
return fail('E_TARGET_MISSING', `section "${title}" does not exist in STATE.md`, { sections: titles });
|
|
395
|
+
}
|
|
396
|
+
return { ok: true };
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
#normalizeOrigin(options) {
|
|
400
|
+
const caller = options?.caller ?? options ?? {};
|
|
401
|
+
let kind = caller.kind;
|
|
402
|
+
if (!['root', 'subagent', 'owner-cli'].includes(kind)) {
|
|
403
|
+
kind = isSubagentCaller(caller) ? 'subagent' : 'root';
|
|
404
|
+
} else if (kind !== 'owner-cli' && isSubagentCaller(caller)) {
|
|
405
|
+
// D-CR1: session.header.origin is authoritative. A caller whose header
|
|
406
|
+
// says `subagent` must never keep main-session rights just because the
|
|
407
|
+
// normalized kind (or the old heuristic) said root.
|
|
408
|
+
kind = 'subagent';
|
|
409
|
+
}
|
|
410
|
+
const sessionId = typeof caller.sessionId === 'string' && caller.sessionId.trim() !== ''
|
|
411
|
+
? caller.sessionId.trim()
|
|
412
|
+
: 'unknown-session';
|
|
413
|
+
return {
|
|
414
|
+
sessionId,
|
|
415
|
+
kind,
|
|
416
|
+
host: typeof caller.host === 'string' && caller.host !== '' ? caller.host : this.host,
|
|
417
|
+
turn: Number.isInteger(caller.turn) ? caller.turn : null,
|
|
418
|
+
isSubagent: kind === 'subagent' || caller.isSubagent === true,
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
#dedupe(proposals, dedupeKey, nowMs) {
|
|
423
|
+
const live = proposals.find((proposal) => proposal.dedupeKey === dedupeKey
|
|
424
|
+
&& ['pending', 'approved', 'applying', 'blocked-on-user'].includes(proposal.status));
|
|
425
|
+
if (live) {
|
|
426
|
+
return {
|
|
427
|
+
kind: 'queued',
|
|
428
|
+
value: {
|
|
429
|
+
ok: true,
|
|
430
|
+
duplicateOf: live.id,
|
|
431
|
+
ticket: ticketNumber(live.queue?.ticket),
|
|
432
|
+
ticketName: live.queue?.ticket ?? null,
|
|
433
|
+
status: live.status,
|
|
434
|
+
message: `duplicate of ${live.id}; ticket ${live.queue?.ticket ?? ''}`.trim(),
|
|
435
|
+
},
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
const done = proposals.find((proposal) => proposal.dedupeKey === dedupeKey
|
|
439
|
+
&& proposal.status === 'done'
|
|
440
|
+
&& Number.isFinite(Date.parse(proposal.updatedAt ?? proposal.createdAt ?? ''))
|
|
441
|
+
&& nowMs - Date.parse(proposal.updatedAt ?? proposal.createdAt) <= 24 * 60 * 60 * 1000);
|
|
442
|
+
if (done) {
|
|
443
|
+
return {
|
|
444
|
+
kind: 'done',
|
|
445
|
+
value: {
|
|
446
|
+
ok: true,
|
|
447
|
+
recentlyApplied: true,
|
|
448
|
+
duplicateOf: done.id,
|
|
449
|
+
ticket: ticketNumber(done.queue?.ticket),
|
|
450
|
+
ticketName: done.queue?.ticket ?? null,
|
|
451
|
+
status: done.status,
|
|
452
|
+
message: `already applied within 24h as ${done.id}`,
|
|
453
|
+
},
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
const rejected = proposals
|
|
457
|
+
.filter((proposal) => proposal.dedupeKey === dedupeKey && proposal.status === 'rejected')
|
|
458
|
+
.sort((a, b) => Date.parse(b.updatedAt ?? b.createdAt ?? '') - Date.parse(a.updatedAt ?? a.createdAt ?? ''))[0];
|
|
459
|
+
return { kind: null, previouslyRejected: rejected?.id ?? null };
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
#rateLimited(proposals, sessionId, nowMs, kind = 'root') {
|
|
463
|
+
const configured = Number(this.config.proposalsPerSessionHour);
|
|
464
|
+
const rootMax = Number.isInteger(configured) && configured > 0 ? configured : 6;
|
|
465
|
+
// D-CR5: subagents get a fixed, stricter 3/hour ceiling; the main session
|
|
466
|
+
// keeps the configured quota (default 6).
|
|
467
|
+
const max = kind === 'subagent' ? Math.min(SUBAGENT_PROPOSALS_PER_HOUR, rootMax) : rootMax;
|
|
468
|
+
const since = nowMs - SUBAGENT_RATE_WINDOW_MS;
|
|
469
|
+
const count = proposals.filter((proposal) => proposal?.origin?.sessionId === sessionId
|
|
470
|
+
&& Number.isFinite(Date.parse(proposal.createdAt ?? ''))
|
|
471
|
+
&& Date.parse(proposal.createdAt) >= since).length;
|
|
472
|
+
return count >= max ? { limited: true, limit: max, count } : { limited: false, limit: max, count };
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
#lastSeq(proposals, queue, walLines, snapshot = null) {
|
|
476
|
+
let max = 0;
|
|
477
|
+
for (const proposal of proposals) max = Math.max(max, ticketNumber(proposal?.queue?.ticket));
|
|
478
|
+
// queue.seqCounter is "next ticket" per DESIGN §3.6, so the last ticket it
|
|
479
|
+
// implies is seqCounter-1. Treating it as a used ticket would skip numbers.
|
|
480
|
+
if (queue && Number.isInteger(queue.seqCounter) && queue.seqCounter > 0) {
|
|
481
|
+
max = Math.max(max, queue.seqCounter - 1);
|
|
482
|
+
}
|
|
483
|
+
// Folded events no longer appear in walLines; the snapshot's seqCounter is
|
|
484
|
+
// the surviving "next ticket" after rotation (DESIGN §3.5).
|
|
485
|
+
if (snapshot && Number.isInteger(snapshot.seqCounter) && snapshot.seqCounter > 0) {
|
|
486
|
+
max = Math.max(max, snapshot.seqCounter - 1);
|
|
487
|
+
}
|
|
488
|
+
for (const line of walLines) max = Math.max(max, ticketNumber(line?.ticket));
|
|
489
|
+
return max;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
#buildQueue(proposals, seqCounter, rev = 1) {
|
|
493
|
+
const active = sortProposals(this.#active(proposals));
|
|
494
|
+
const nowMs = this.nowDate().getTime();
|
|
495
|
+
const entries = active.map((proposal) => ({
|
|
496
|
+
ticket: proposal.queue?.ticket ?? null,
|
|
497
|
+
proposalId: proposal.id,
|
|
498
|
+
sessionId: proposal.origin?.sessionId ?? null,
|
|
499
|
+
target: proposal.target,
|
|
500
|
+
op: proposal.op,
|
|
501
|
+
status: proposal.status,
|
|
502
|
+
priority: proposal.queue?.priority ?? 'P3',
|
|
503
|
+
effectivePriority: proposal.queue?.effectivePriority ?? proposal.queue?.priority ?? 'P3',
|
|
504
|
+
queuedAt: proposal.queue?.queuedAt ?? proposal.createdAt,
|
|
505
|
+
waitMs: Math.max(0, nowMs - Date.parse(proposal.queue?.queuedAt ?? proposal.createdAt ?? '') || 0),
|
|
506
|
+
attempts: Number.isInteger(proposal.queue?.attempts) ? proposal.queue.attempts : 0,
|
|
507
|
+
lease: proposal.queue?.lease ?? null,
|
|
508
|
+
}));
|
|
509
|
+
const blocked = active
|
|
510
|
+
.filter((proposal) => proposal.status === 'blocked-on-user')
|
|
511
|
+
.map((proposal) => ({
|
|
512
|
+
ticket: proposal.queue?.ticket ?? null,
|
|
513
|
+
reason: proposal.queue?.blockedReason ?? 'BLOCKED',
|
|
514
|
+
since: proposal.updatedAt ?? proposal.createdAt,
|
|
515
|
+
}));
|
|
516
|
+
const writer = active.find((proposal) => proposal.status === 'applying');
|
|
517
|
+
const queue = {
|
|
518
|
+
v: 1,
|
|
519
|
+
rev,
|
|
520
|
+
seqCounter,
|
|
521
|
+
generatedAt: this.nowDate().toISOString(),
|
|
522
|
+
writer: writer
|
|
523
|
+
? {
|
|
524
|
+
ticket: writer.queue?.ticket ?? null,
|
|
525
|
+
proposalId: writer.id,
|
|
526
|
+
sessionId: writer.origin?.sessionId ?? null,
|
|
527
|
+
since: writer.queue?.lease?.startedAt ?? writer.updatedAt ?? writer.createdAt,
|
|
528
|
+
}
|
|
529
|
+
: null,
|
|
530
|
+
entries,
|
|
531
|
+
blocked,
|
|
532
|
+
};
|
|
533
|
+
queue.hash = `sha256:${sha256Hex(JSON.stringify({ seqCounter, entries, blocked }))}`;
|
|
534
|
+
return queue;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
#writeQueue(queue) {
|
|
538
|
+
const text = `${JSON.stringify(queue, null, 2)}\n`;
|
|
539
|
+
if (Buffer.byteLength(text, 'utf8') > QUEUE_MAX_BYTES) {
|
|
540
|
+
return { ok: false, code: 'E_QUEUE_FULL', message: 'queue.json exceeds its size cap' };
|
|
541
|
+
}
|
|
542
|
+
try {
|
|
543
|
+
writeJsonStrict(this.queueFile, queue);
|
|
544
|
+
return { ok: true };
|
|
545
|
+
} catch (error) {
|
|
546
|
+
return { ok: false, code: codeOf(error), message: error?.message ?? String(error) };
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
#appendWal({ ticket, proposalId, origin, op, target, priority }) {
|
|
551
|
+
try {
|
|
552
|
+
this.wal.append('queue.assign', {
|
|
553
|
+
ticket,
|
|
554
|
+
proposalId,
|
|
555
|
+
sessionId: origin.sessionId,
|
|
556
|
+
op,
|
|
557
|
+
target,
|
|
558
|
+
priority,
|
|
559
|
+
// keep the event timestamp on the engine's clock (test seam)
|
|
560
|
+
at: this.nowDate().toISOString(),
|
|
561
|
+
});
|
|
562
|
+
} catch (error) {
|
|
563
|
+
throw new StoreError(codeOf(error), error?.message ?? 'WAL append failed', { ticket, proposalId });
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/** R-05: return the lock token so release can prove the file is still ours. */
|
|
568
|
+
#writeIssueLock(proposalId) {
|
|
569
|
+
fs.mkdirSync(this.lockDir, { recursive: true });
|
|
570
|
+
const payload = {
|
|
571
|
+
v: 1,
|
|
572
|
+
pid: process.pid,
|
|
573
|
+
host: this.host,
|
|
574
|
+
startedAt: this.nowDate().toISOString(),
|
|
575
|
+
nonce: crypto.randomBytes(12).toString('hex'),
|
|
576
|
+
proposalId: proposalId ?? null,
|
|
577
|
+
};
|
|
578
|
+
const fd = fs.openSync(this.issueLockFile, 'wx');
|
|
579
|
+
let writeError = null;
|
|
580
|
+
try {
|
|
581
|
+
fs.writeFileSync(fd, `${JSON.stringify(payload)}\n`, 'utf8');
|
|
582
|
+
try { fs.fsyncSync(fd); } catch { /* best effort */ }
|
|
583
|
+
} catch (error) {
|
|
584
|
+
writeError = error;
|
|
585
|
+
} finally {
|
|
586
|
+
try { fs.closeSync(fd); } catch { /* ignore */ }
|
|
587
|
+
}
|
|
588
|
+
if (writeError) {
|
|
589
|
+
// The file is ours (wx); do not leave a half-written lock behind.
|
|
590
|
+
try { fs.unlinkSync(this.issueLockFile); } catch { /* ignore */ }
|
|
591
|
+
throw writeError;
|
|
592
|
+
}
|
|
593
|
+
return payload;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/**
|
|
597
|
+
* R-05: delete issue.lock only when the on-disk token still matches the one
|
|
598
|
+
* this caller wrote. A reclaimed/replaced lock is left untouched and audited.
|
|
599
|
+
*/
|
|
600
|
+
#releaseIssueLock(token) {
|
|
601
|
+
if (!token) return false;
|
|
602
|
+
let current = null;
|
|
603
|
+
try {
|
|
604
|
+
current = JSON.parse(fs.readFileSync(this.issueLockFile, 'utf8'));
|
|
605
|
+
} catch {
|
|
606
|
+
return false;
|
|
607
|
+
}
|
|
608
|
+
if (!current || current.nonce !== token.nonce || current.pid !== token.pid) {
|
|
609
|
+
this.#auditSafe('issue.lock.release_skipped', {
|
|
610
|
+
reason: !current ? 'unreadable' : 'token-mismatch',
|
|
611
|
+
holderPid: current?.pid ?? null,
|
|
612
|
+
holderNonce: current?.nonce ?? null,
|
|
613
|
+
tokenNonce: token.nonce ?? null,
|
|
614
|
+
});
|
|
615
|
+
return false;
|
|
616
|
+
}
|
|
617
|
+
try {
|
|
618
|
+
fs.unlinkSync(this.issueLockFile);
|
|
619
|
+
return true;
|
|
620
|
+
} catch {
|
|
621
|
+
return false;
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
#issueReclaimAgeMs(holder) {
|
|
626
|
+
const started = Date.parse(holder?.startedAt ?? '');
|
|
627
|
+
if (Number.isFinite(started)) return Math.max(0, this.nowDate().getTime() - started);
|
|
628
|
+
try {
|
|
629
|
+
return Math.max(0, this.nowDate().getTime() - fs.statSync(this.issueReclaimFile).mtimeMs);
|
|
630
|
+
} catch {
|
|
631
|
+
return 0;
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
/**
|
|
636
|
+
* D-CR9: a crash between "rename issue.lock" and "write a new issue.lock"
|
|
637
|
+
* leaves issue.reclaim.lock behind forever. Take it over only when it is old
|
|
638
|
+
* and its owner is a dead local pid or an aged-out foreign holder.
|
|
639
|
+
*/
|
|
640
|
+
#openIssueReclaimLock() {
|
|
641
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
642
|
+
try {
|
|
643
|
+
const fd = fs.openSync(this.issueReclaimFile, 'wx');
|
|
644
|
+
const payload = {
|
|
645
|
+
v: 1,
|
|
646
|
+
pid: process.pid,
|
|
647
|
+
host: this.host,
|
|
648
|
+
startedAt: this.nowDate().toISOString(),
|
|
649
|
+
nonce: crypto.randomBytes(12).toString('hex'),
|
|
650
|
+
};
|
|
651
|
+
try {
|
|
652
|
+
fs.writeFileSync(fd, `${JSON.stringify(payload)}\n`, 'utf8');
|
|
653
|
+
try { fs.fsyncSync(fd); } catch { /* best effort */ }
|
|
654
|
+
} finally {
|
|
655
|
+
try { fs.closeSync(fd); } catch { /* ignore */ }
|
|
656
|
+
}
|
|
657
|
+
return payload;
|
|
658
|
+
} catch (error) {
|
|
659
|
+
if (error?.code !== 'EEXIST') return null;
|
|
660
|
+
let holder = null;
|
|
661
|
+
try { holder = JSON.parse(fs.readFileSync(this.issueReclaimFile, 'utf8')); } catch { holder = null; }
|
|
662
|
+
if (this.#issueReclaimAgeMs(holder) <= Math.max(2 * ISSUE_LOCK_STALE_GRACE_MS, ISSUE_RECLAIM_STALE_MS)) return null;
|
|
663
|
+
if (holder && holder.host === this.host && pidAlive(holder.pid)) return null;
|
|
664
|
+
const evidence = `${this.issueReclaimFile}.reclaimed-${this.nowDate().toISOString().replace(/[:.]/gu, '-')}`;
|
|
665
|
+
try {
|
|
666
|
+
fs.renameSync(this.issueReclaimFile, evidence);
|
|
667
|
+
} catch {
|
|
668
|
+
return null;
|
|
669
|
+
}
|
|
670
|
+
this.#auditSafe('issue.reclaim_lock.reclaimed', {
|
|
671
|
+
evidence: path.basename(evidence),
|
|
672
|
+
oldPid: holder?.pid ?? null,
|
|
673
|
+
oldStartedAt: holder?.startedAt ?? null,
|
|
674
|
+
});
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
return null;
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
#closeIssueReclaimLock(token) {
|
|
681
|
+
if (!token) return;
|
|
682
|
+
let current = null;
|
|
683
|
+
try { current = JSON.parse(fs.readFileSync(this.issueReclaimFile, 'utf8')); } catch { return; }
|
|
684
|
+
if (!current || current.nonce !== token.nonce) return;
|
|
685
|
+
try { fs.unlinkSync(this.issueReclaimFile); } catch { /* only our own mutex */ }
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
#reclaimIssueLock() {
|
|
689
|
+
let holder = null;
|
|
690
|
+
let stat = null;
|
|
691
|
+
try {
|
|
692
|
+
stat = fs.lstatSync(this.issueLockFile);
|
|
693
|
+
try { holder = JSON.parse(fs.readFileSync(this.issueLockFile, 'utf8')); } catch { holder = null; }
|
|
694
|
+
} catch {
|
|
695
|
+
return false;
|
|
696
|
+
}
|
|
697
|
+
if (holder && Number.isInteger(holder.pid) && holder.pid > 0 && holder.host === this.host && pidAlive(holder.pid)) return false;
|
|
698
|
+
// A lock that is younger than the grace window may still be mid-write by a
|
|
699
|
+
// live writer; wait for it instead of stealing.
|
|
700
|
+
if (stat && Date.now() - stat.mtimeMs < ISSUE_LOCK_STALE_GRACE_MS) return false;
|
|
701
|
+
const token = this.#openIssueReclaimLock();
|
|
702
|
+
if (!token) return false;
|
|
703
|
+
try {
|
|
704
|
+
let again = null;
|
|
705
|
+
try { again = JSON.parse(fs.readFileSync(this.issueLockFile, 'utf8')); } catch { again = null; }
|
|
706
|
+
const same = (again?.pid ?? null) === (holder?.pid ?? null)
|
|
707
|
+
&& (again?.startedAt ?? null) === (holder?.startedAt ?? null);
|
|
708
|
+
if (!same) return false;
|
|
709
|
+
const archived = path.join(this.lockDir, `issue.reclaimed-${this.nowDate().toISOString().replace(/[:.]/gu, '-')}`);
|
|
710
|
+
fs.renameSync(this.issueLockFile, archived);
|
|
711
|
+
return true;
|
|
712
|
+
} catch {
|
|
713
|
+
return false;
|
|
714
|
+
} finally {
|
|
715
|
+
this.#closeIssueReclaimLock(token);
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
async #withIssueLock(proposalId, fn) {
|
|
720
|
+
const deadline = Date.now() + ISSUE_LOCK_WAIT_MS;
|
|
721
|
+
let held = null;
|
|
722
|
+
for (;;) {
|
|
723
|
+
try {
|
|
724
|
+
held = this.#writeIssueLock(proposalId);
|
|
725
|
+
break;
|
|
726
|
+
} catch (error) {
|
|
727
|
+
if (error?.code !== 'EEXIST') {
|
|
728
|
+
throw new StoreError('E_STORAGE', error?.message ?? 'cannot create issue.lock');
|
|
729
|
+
}
|
|
730
|
+
if (this.#reclaimIssueLock()) continue;
|
|
731
|
+
}
|
|
732
|
+
if (Date.now() >= deadline) {
|
|
733
|
+
throw new StoreError('E_TICKET_BUSY', 'could not acquire locks/issue.lock within 2s');
|
|
734
|
+
}
|
|
735
|
+
await delay(ISSUE_LOCK_BACKOFF_MS);
|
|
736
|
+
}
|
|
737
|
+
try {
|
|
738
|
+
return await fn();
|
|
739
|
+
} finally {
|
|
740
|
+
if (held) this.#releaseIssueLock(held);
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
/**
|
|
745
|
+
* Submit one proposal. Returns the queued ticket shape on success.
|
|
746
|
+
* @param {object} input
|
|
747
|
+
* @param {object} options `{caller:{sessionId,kind,turn,host}}`
|
|
748
|
+
*/
|
|
749
|
+
async propose(input = {}, options = {}) {
|
|
750
|
+
if (!this.enabled) return fail('E_PROPOSAL_DISABLED', 'routerProposalEnabled is false');
|
|
751
|
+
const origin = this.#normalizeOrigin(options);
|
|
752
|
+
const nowDate = this.nowDate();
|
|
753
|
+
const nowMs = nowDate.getTime();
|
|
754
|
+
|
|
755
|
+
const op = typeof input.op === 'string' ? input.op.trim() : '';
|
|
756
|
+
if (!PROPOSAL_OPS.includes(op)) return fail('E_BAD_STATE', `unknown op: ${op || '(empty)'}`);
|
|
757
|
+
|
|
758
|
+
const targetCheck = validateTargetForOp(op, input.target);
|
|
759
|
+
if (!targetCheck.ok) return targetCheck;
|
|
760
|
+
const target = targetCheck.target;
|
|
761
|
+
|
|
762
|
+
const title = sanitizeLine(input.title, 120);
|
|
763
|
+
if (title === '') return fail('E_BAD_STATE', 'title is required');
|
|
764
|
+
|
|
765
|
+
const contentCheck = validateContent(input.content, this.#maxChars());
|
|
766
|
+
if (!contentCheck.ok) return contentCheck;
|
|
767
|
+
const content = contentCheck.content;
|
|
768
|
+
|
|
769
|
+
if (input.evidence !== undefined && input.evidence !== null) {
|
|
770
|
+
if (!Array.isArray(input.evidence)) return fail('E_BAD_STATE', 'evidence must be an array');
|
|
771
|
+
if (input.evidence.length > 10) return fail('E_BAD_STATE', 'evidence supports at most 10 items');
|
|
772
|
+
for (const item of input.evidence) {
|
|
773
|
+
if (typeof item !== 'string' || item.length > 500) return fail('E_BAD_STATE', 'evidence items are strings up to 500 chars');
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
const priority = input.priority === undefined || input.priority === null ? 'P3' : String(input.priority);
|
|
778
|
+
if (!PRIORITIES.includes(priority)) return fail('E_BAD_STATE', `priority must be one of ${PRIORITIES.join('/')}`);
|
|
779
|
+
if (priority === 'P0' && origin.kind !== 'owner-cli') {
|
|
780
|
+
this.#auditSafe('priority.rejected', {
|
|
781
|
+
attempted: 'P0',
|
|
782
|
+
by: origin.sessionId,
|
|
783
|
+
callerKind: origin.kind,
|
|
784
|
+
reason: 'tool-cannot-P0',
|
|
785
|
+
});
|
|
786
|
+
return fail('E_PRIORITY_DENIED', 'P0 can only be submitted through the owner CLI');
|
|
787
|
+
}
|
|
788
|
+
const priorityBy = priority === 'P0'
|
|
789
|
+
? 'owner-cli'
|
|
790
|
+
: (input.priority === undefined || input.priority === null ? 'default' : 'declared');
|
|
791
|
+
const priorityReason = sanitizeLine(input.priorityReason, 200);
|
|
792
|
+
|
|
793
|
+
const inspect = this.#inspectTarget(target);
|
|
794
|
+
if (!inspect.ok) return inspect;
|
|
795
|
+
const { snapshot } = inspect;
|
|
796
|
+
if (op === 'state.section') {
|
|
797
|
+
const section = this.#validateSection(target, title, snapshot);
|
|
798
|
+
if (!section.ok) return section;
|
|
799
|
+
}
|
|
800
|
+
if ((op === 'state.section' || op === 'index.row') && !snapshot.exists) {
|
|
801
|
+
return fail('E_TARGET_MISSING', `${target} must exist for ${op}`);
|
|
802
|
+
}
|
|
803
|
+
if ((op === 'state.section' || op === 'index.row')
|
|
804
|
+
&& (input.baseSha === undefined || input.baseSha === null || input.baseSha === '')) {
|
|
805
|
+
return fail('E_BAD_STATE', `baseSha is required for ${op}`);
|
|
806
|
+
}
|
|
807
|
+
if (input.baseSha !== undefined && input.baseSha !== null && input.baseSha !== '') {
|
|
808
|
+
const wanted = String(input.baseSha).replace(/^sha256:/u, '').toLowerCase();
|
|
809
|
+
const actual = String(snapshot.sha256 ?? '').replace(/^sha256:/u, '').toLowerCase();
|
|
810
|
+
if (!snapshot.exists || wanted !== actual) {
|
|
811
|
+
return fail('E_BASE_MOVED', 'target changed since the proposal was prepared');
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
const dedupeKey = buildDedupeKey(op, target, content);
|
|
816
|
+
const mergeKey = buildMergeKey(op, target);
|
|
817
|
+
const riskInfo = computeRisk(op, target, content, snapshot);
|
|
818
|
+
const { risk, riskReasons } = riskInfo;
|
|
819
|
+
|
|
820
|
+
const firstScan = this.#scan();
|
|
821
|
+
const firstDedupe = this.#dedupe(firstScan.proposals, dedupeKey, nowMs);
|
|
822
|
+
if (firstDedupe.kind) return firstDedupe.value;
|
|
823
|
+
const quota = this.#quota();
|
|
824
|
+
if (countNonTerminal(firstScan.proposals) >= quota) {
|
|
825
|
+
return fail('E_PROPOSAL_QUOTA', `non-terminal proposals reached routerMaxProposals=${quota}`, { limit: quota });
|
|
826
|
+
}
|
|
827
|
+
const rate = this.#rateLimited(firstScan.proposals, origin.sessionId, nowMs, origin.kind);
|
|
828
|
+
if (rate.limited) {
|
|
829
|
+
return fail('E_RATE_LIMITED', `session exceeded ${rate.limit} proposals per hour`, { limit: rate.limit });
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
const id = makeProposalId(nowDate);
|
|
833
|
+
const createdAt = nowDate.toISOString();
|
|
834
|
+
const deadlineAt = new Date(nowDate.getTime() + (Number(this.config.proposalTtlH) || 72) * 3600 * 1000).toISOString();
|
|
835
|
+
|
|
836
|
+
let queued = null;
|
|
837
|
+
try {
|
|
838
|
+
queued = await this.#withIssueLock(id, async () => {
|
|
839
|
+
const scan = this.#scan();
|
|
840
|
+
const secondDedupe = this.#dedupe(scan.proposals, dedupeKey, nowMs);
|
|
841
|
+
if (secondDedupe.kind) return { duplicate: secondDedupe.value };
|
|
842
|
+
if (countNonTerminal(scan.proposals) >= quota) {
|
|
843
|
+
return { error: fail('E_PROPOSAL_QUOTA', `non-terminal proposals reached routerMaxProposals=${quota}`, { limit: quota }) };
|
|
844
|
+
}
|
|
845
|
+
// D-CR5: the pre-lock rate check is only a fast path; re-check inside
|
|
846
|
+
// the issue lock so concurrent proposes cannot race past the ceiling.
|
|
847
|
+
const lockedRate = this.#rateLimited(scan.proposals, origin.sessionId, nowMs, origin.kind);
|
|
848
|
+
if (lockedRate.limited) {
|
|
849
|
+
return { error: fail('E_RATE_LIMITED', `session exceeded ${lockedRate.limit} proposals per hour`, { limit: lockedRate.limit }) };
|
|
850
|
+
}
|
|
851
|
+
const queueBefore = readQueueFile(this.queueFile);
|
|
852
|
+
const walState = this.wal.read();
|
|
853
|
+
const lastSeq = this.#lastSeq(scan.proposals, queueBefore, walState.lines, walState.snapshot);
|
|
854
|
+
const nextSeq = lastSeq + 1;
|
|
855
|
+
const ticket = formatTicket(nextSeq);
|
|
856
|
+
const proposal = {
|
|
857
|
+
v: PROPOSAL_VERSION,
|
|
858
|
+
id,
|
|
859
|
+
createdAt,
|
|
860
|
+
updatedAt: createdAt,
|
|
861
|
+
rev: 1,
|
|
862
|
+
origin: {
|
|
863
|
+
sessionId: origin.sessionId,
|
|
864
|
+
kind: origin.kind,
|
|
865
|
+
host: origin.host,
|
|
866
|
+
turn: origin.turn,
|
|
867
|
+
},
|
|
868
|
+
op,
|
|
869
|
+
target,
|
|
870
|
+
title,
|
|
871
|
+
content,
|
|
872
|
+
rationale: sanitizeLine(input.rationale, 800),
|
|
873
|
+
baseSha: snapshot.sha256,
|
|
874
|
+
baseBytes: snapshot.bytes,
|
|
875
|
+
risk,
|
|
876
|
+
riskReasons,
|
|
877
|
+
dedupeKey,
|
|
878
|
+
mergeKey,
|
|
879
|
+
queue: {
|
|
880
|
+
ticket,
|
|
881
|
+
seq: nextSeq,
|
|
882
|
+
queuedAt: createdAt,
|
|
883
|
+
priority,
|
|
884
|
+
priorityBy,
|
|
885
|
+
priorityReason,
|
|
886
|
+
effectivePriority: priority,
|
|
887
|
+
agingSteps: 0,
|
|
888
|
+
mergeKey,
|
|
889
|
+
mergedInto: null,
|
|
890
|
+
supersededBy: null,
|
|
891
|
+
cancelledBy: null,
|
|
892
|
+
attempts: 0,
|
|
893
|
+
lease: null,
|
|
894
|
+
deadlineAt,
|
|
895
|
+
blockedReason: null,
|
|
896
|
+
},
|
|
897
|
+
status: 'pending',
|
|
898
|
+
stateLog: [{
|
|
899
|
+
at: createdAt,
|
|
900
|
+
from: null,
|
|
901
|
+
to: 'pending',
|
|
902
|
+
// DESIGN §5.11: the owner CLI is owner:cli on every state-log row.
|
|
903
|
+
by: origin.kind === 'owner-cli' ? 'owner:cli' : origin.sessionId,
|
|
904
|
+
note: 'created',
|
|
905
|
+
}],
|
|
906
|
+
result: null,
|
|
907
|
+
conflict: null,
|
|
908
|
+
evidence: Array.isArray(input.evidence) ? input.evidence.slice(0, 10) : [],
|
|
909
|
+
};
|
|
910
|
+
this.#appendWal({ ticket, proposalId: id, origin, op, target, priority });
|
|
911
|
+
writeProposalFile(path.join(this.proposalsDir, `${id}.json`), proposal);
|
|
912
|
+
let all = [...scan.proposals.filter((item) => item.id !== id), proposal];
|
|
913
|
+
|
|
914
|
+
// L4 small-write coalescing (DESIGN §5.8, K20). Deterministic and always
|
|
915
|
+
// on; it runs inside the issue lock so queue adjacency cannot change
|
|
916
|
+
// between the decision and the two writes. The later proposal is
|
|
917
|
+
// absorbed into the immediately preceding one; the base snapshot was
|
|
918
|
+
// revalidated above, and a moved base simply leaves both queued.
|
|
919
|
+
let merge = null;
|
|
920
|
+
const beforeMerge = sortProposals(this.#active(all));
|
|
921
|
+
const newIndex = beforeMerge.findIndex((item) => item.id === id);
|
|
922
|
+
const previous = newIndex > 0 ? beforeMerge[newIndex - 1] : null;
|
|
923
|
+
if (previous) {
|
|
924
|
+
const plan = planSmallWriteMerge(previous, proposal, {
|
|
925
|
+
at: createdAt,
|
|
926
|
+
adjacent: true,
|
|
927
|
+
currentSha: snapshot.sha256,
|
|
928
|
+
});
|
|
929
|
+
if (plan.ok) {
|
|
930
|
+
const absorbedFile = path.join(this.proposalsDir, `${plan.absorbedId}.json`);
|
|
931
|
+
const keeperFile = path.join(this.proposalsDir, `${plan.keeperId}.json`);
|
|
932
|
+
// scanProposalDir() adds a __file breadcrumb for in-memory callers;
|
|
933
|
+
// it must never be persisted into the proposal JSON.
|
|
934
|
+
const keeperBody = { ...plan.keeper };
|
|
935
|
+
delete keeperBody.__file;
|
|
936
|
+
writeProposalFile(absorbedFile, plan.absorbed);
|
|
937
|
+
try {
|
|
938
|
+
writeProposalFile(keeperFile, keeperBody);
|
|
939
|
+
} catch (error) {
|
|
940
|
+
// Keep the store consistent: the absorbed file must not stay
|
|
941
|
+
// superseded if the keeper body was not written.
|
|
942
|
+
try { writeProposalFile(absorbedFile, proposal); } catch { /* best effort */ }
|
|
943
|
+
throw error;
|
|
944
|
+
}
|
|
945
|
+
all = all.map((item) => {
|
|
946
|
+
if (item.id === plan.keeperId) return plan.keeper;
|
|
947
|
+
if (item.id === plan.absorbedId) return plan.absorbed;
|
|
948
|
+
return item;
|
|
949
|
+
});
|
|
950
|
+
merge = plan;
|
|
951
|
+
this.#auditSafe('merge.superseded', {
|
|
952
|
+
keeperId: plan.keeperId,
|
|
953
|
+
keeperTicket: plan.keeperTicket,
|
|
954
|
+
absorbedId: plan.absorbedId,
|
|
955
|
+
absorbedTicket: plan.absorbedTicket,
|
|
956
|
+
op,
|
|
957
|
+
target,
|
|
958
|
+
bytes: plan.bytes,
|
|
959
|
+
});
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
const ordered = sortProposals(this.#active(all));
|
|
964
|
+
const retainedId = merge ? merge.keeperId : id;
|
|
965
|
+
const index = ordered.findIndex((item) => item.id === retainedId);
|
|
966
|
+
const ahead = ordered.slice(0, Math.max(0, index)).map((item) => ({
|
|
967
|
+
ticket: item.queue?.ticket ?? null,
|
|
968
|
+
title: item.title ?? '',
|
|
969
|
+
sessionId: item.origin?.sessionId ?? null,
|
|
970
|
+
target: item.target,
|
|
971
|
+
op: item.op,
|
|
972
|
+
effectivePriority: item.queue?.effectivePriority ?? item.queue?.priority ?? 'P3',
|
|
973
|
+
waitMs: Math.max(0, nowMs - Date.parse(item.queue?.queuedAt ?? item.createdAt ?? '') || 0),
|
|
974
|
+
}));
|
|
975
|
+
const position = Math.max(1, index + 1);
|
|
976
|
+
const etaMs = ordered
|
|
977
|
+
.slice(0, Math.max(1, index + 1))
|
|
978
|
+
.reduce((sum, item) => sum + (ETA_DEFAULTS_MS[item.op] ?? 2000), 0);
|
|
979
|
+
const queue = this.#buildQueue(all, nextSeq + 1, Number(queueBefore?.rev ?? 0) + 1);
|
|
980
|
+
const queueWrite = this.#writeQueue(queue);
|
|
981
|
+
if (!queueWrite.ok) {
|
|
982
|
+
this.#auditSafe('queue.write_failed', { code: queueWrite.code, message: queueWrite.message });
|
|
983
|
+
}
|
|
984
|
+
return {
|
|
985
|
+
proposal,
|
|
986
|
+
ticket: merge ? merge.keeperTicket : ticket,
|
|
987
|
+
mergedInto: merge ? merge.keeperId : null,
|
|
988
|
+
position,
|
|
989
|
+
ahead,
|
|
990
|
+
etaMs,
|
|
991
|
+
queue,
|
|
992
|
+
};
|
|
993
|
+
});
|
|
994
|
+
} catch (error) {
|
|
995
|
+
return fail(codeOf(error), error?.message ?? String(error));
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
if (queued?.duplicate) return queued.duplicate;
|
|
999
|
+
if (queued?.error) return queued.error;
|
|
1000
|
+
if (!queued?.proposal) return fail('E_STORAGE', 'proposal allocation returned no result');
|
|
1001
|
+
|
|
1002
|
+
this.#auditSafe('proposal.create', {
|
|
1003
|
+
id: queued.proposal.id,
|
|
1004
|
+
op,
|
|
1005
|
+
target,
|
|
1006
|
+
risk,
|
|
1007
|
+
contentSha: `sha256:${sha256Hex(content)}`,
|
|
1008
|
+
bytes: Buffer.byteLength(content, 'utf8'),
|
|
1009
|
+
priority,
|
|
1010
|
+
priorityBy,
|
|
1011
|
+
origin: { sessionId: origin.sessionId, kind: origin.kind },
|
|
1012
|
+
...(queued.mergedInto ? { mergedInto: queued.mergedInto } : {}),
|
|
1013
|
+
});
|
|
1014
|
+
|
|
1015
|
+
// Tier A is independent of routerWakeEnabled: always append the ready line
|
|
1016
|
+
// (failure is audited wake.flush_failed and never fails the proposal).
|
|
1017
|
+
// A merged-away proposal does not get its own line: the keeper's ticket is
|
|
1018
|
+
// already ready, and waking twice for one ticket would be noise.
|
|
1019
|
+
if (!queued.mergedInto) this.wake?.appendReady?.(queued.proposal);
|
|
1020
|
+
|
|
1021
|
+
return {
|
|
1022
|
+
ok: true,
|
|
1023
|
+
id: queued.proposal.id,
|
|
1024
|
+
// Numeric position for machine callers (K-08 compares Number(ticket));
|
|
1025
|
+
// the canonical "q-0002" name stays available as ticketName and on disk.
|
|
1026
|
+
ticket: ticketNumber(queued.ticket),
|
|
1027
|
+
ticketName: queued.ticket,
|
|
1028
|
+
...(queued.mergedInto ? { merged: true, mergedInto: queued.mergedInto } : {}),
|
|
1029
|
+
position: queued.position,
|
|
1030
|
+
ahead: queued.ahead,
|
|
1031
|
+
etaMs: queued.etaMs,
|
|
1032
|
+
risk,
|
|
1033
|
+
riskReasons,
|
|
1034
|
+
deadlineAt,
|
|
1035
|
+
preview: {
|
|
1036
|
+
title,
|
|
1037
|
+
op,
|
|
1038
|
+
target,
|
|
1039
|
+
risk,
|
|
1040
|
+
riskReasons,
|
|
1041
|
+
contentSha: `sha256:${sha256Hex(content)}`,
|
|
1042
|
+
contentBytes: Buffer.byteLength(content, 'utf8'),
|
|
1043
|
+
baseSha: snapshot.sha256,
|
|
1044
|
+
baseBytes: snapshot.bytes,
|
|
1045
|
+
charCount: content.length,
|
|
1046
|
+
},
|
|
1047
|
+
message: queued.mergedInto
|
|
1048
|
+
? `merged into ${queued.ticket} (${queued.mergedInto}); no separate ticket`
|
|
1049
|
+
: `queued as ${queued.ticket} (position ${queued.position})`,
|
|
1050
|
+
};
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
/** K-04: resolve a queue ticket (`q-0001`) to its proposal id; null if unknown. */
|
|
1054
|
+
idForTicket(ticket) {
|
|
1055
|
+
const wanted = typeof ticket === 'string' ? ticket.trim() : '';
|
|
1056
|
+
if (!wanted) return null;
|
|
1057
|
+
const { proposals } = this.#scan();
|
|
1058
|
+
return proposals.find((proposal) => proposal.queue?.ticket === wanted)?.id ?? null;
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
/** Owner/main-session transition methods (WP4b, K14). */
|
|
1062
|
+
#loadProposal(input = {}) {
|
|
1063
|
+
const id = typeof input.id === 'string' ? input.id.trim() : '';
|
|
1064
|
+
if (id) {
|
|
1065
|
+
if (!isProposalId(id)) return { error: fail('E_TICKET_UNKNOWN', 'a valid proposal id is required') };
|
|
1066
|
+
const proposal = readProposal(this.proposalsDir, id);
|
|
1067
|
+
if (!proposal) return { error: fail('E_TICKET_UNKNOWN', `proposal ${id} was not found`) };
|
|
1068
|
+
return { proposal };
|
|
1069
|
+
}
|
|
1070
|
+
// K-04: the tool schema and owner CLI both advertise `ticket`, so a
|
|
1071
|
+
// transition by ticket must work at the service seam too.
|
|
1072
|
+
const ticket = typeof input.ticket === 'string' ? input.ticket.trim() : '';
|
|
1073
|
+
if (!ticket) return { error: fail('E_TICKET_UNKNOWN', 'a valid proposal id or ticket is required') };
|
|
1074
|
+
const resolved = this.idForTicket(ticket);
|
|
1075
|
+
if (!resolved) return { error: fail('E_TICKET_UNKNOWN', `ticket ${ticket} was not found`) };
|
|
1076
|
+
const proposal = readProposal(this.proposalsDir, resolved);
|
|
1077
|
+
if (!proposal) return { error: fail('E_TICKET_UNKNOWN', `proposal ${resolved} was not found`) };
|
|
1078
|
+
return { proposal };
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
#isMainSession(caller) {
|
|
1082
|
+
return caller.kind === 'owner-cli' || !isSubagentCaller(caller);
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
/**
|
|
1086
|
+
* D-CR3: the queue-head approved proposal, selected the same way the applier
|
|
1087
|
+
* selects it. Used to resolve `{mode:'apply'|'rollback'}` without an id
|
|
1088
|
+
* before the confirm check runs.
|
|
1089
|
+
*/
|
|
1090
|
+
headApproved() {
|
|
1091
|
+
if (typeof this.applier?.headApproved === 'function') return this.applier.headApproved();
|
|
1092
|
+
return null;
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
#transition(proposal, to, { by, note, queue = null, extra = null } = {}) {
|
|
1096
|
+
const at = this.nowDate().toISOString();
|
|
1097
|
+
// D-CR7: CAS on the rev read together with the precondition. A concurrent
|
|
1098
|
+
// writer that moved the proposal makes this throw E_STATE_RACE instead of
|
|
1099
|
+
// silently resurrecting a stale snapshot.
|
|
1100
|
+
return updateProposalStrict(this.proposalsDir, proposal.id, proposal.rev, (current) => ({
|
|
1101
|
+
...(extra ?? {}),
|
|
1102
|
+
status: to,
|
|
1103
|
+
queue: { ...current.queue, ...(queue ?? {}) },
|
|
1104
|
+
stateLog: [...(current.stateLog ?? []), { at, from: current.status, to, by, note }],
|
|
1105
|
+
}), { now: this.nowDate() });
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
/**
|
|
1109
|
+
* D-CR11: approving an expired proposal re-queues it at the tail with a new
|
|
1110
|
+
* ticket instead of failing. The WAL records queue.assign.recovered first so
|
|
1111
|
+
* replay can reconstruct the assignment even if the proposal write is lost.
|
|
1112
|
+
*/
|
|
1113
|
+
#requeueExpired(proposal, by) {
|
|
1114
|
+
let lockToken = null;
|
|
1115
|
+
try {
|
|
1116
|
+
lockToken = this.#writeIssueLock(proposal.id);
|
|
1117
|
+
} catch (error) {
|
|
1118
|
+
if (error?.code === 'EEXIST') return fail('E_TICKET_BUSY', 'ticket allocation is busy; retry');
|
|
1119
|
+
return fail(codeOf(error), error?.message ?? 'cannot allocate a new ticket');
|
|
1120
|
+
}
|
|
1121
|
+
try {
|
|
1122
|
+
const proposals = scanProposalDir(this.proposalsDir).proposals;
|
|
1123
|
+
const queueBefore = readQueueFile(this.queueFile);
|
|
1124
|
+
const walState = this.wal.read();
|
|
1125
|
+
const nextSeq = this.#lastSeq(proposals, queueBefore, walState.lines, walState.snapshot) + 1;
|
|
1126
|
+
const ticket = formatTicket(nextSeq);
|
|
1127
|
+
const at = this.nowDate().toISOString();
|
|
1128
|
+
try {
|
|
1129
|
+
this.wal.append('queue.assign.recovered', {
|
|
1130
|
+
ticket,
|
|
1131
|
+
proposalId: proposal.id,
|
|
1132
|
+
sessionId: proposal.origin?.sessionId ?? null,
|
|
1133
|
+
op: proposal.op,
|
|
1134
|
+
target: proposal.target,
|
|
1135
|
+
reason: 'expired-requeue',
|
|
1136
|
+
by,
|
|
1137
|
+
at,
|
|
1138
|
+
});
|
|
1139
|
+
} catch (error) {
|
|
1140
|
+
this.#auditSafe('wal.append_failed', {
|
|
1141
|
+
proposalId: proposal.id, ev: 'queue.assign.recovered', error: String(error?.message ?? error),
|
|
1142
|
+
});
|
|
1143
|
+
return fail(codeOf(error), 'WAL append failed; proposal unchanged');
|
|
1144
|
+
}
|
|
1145
|
+
let next = null;
|
|
1146
|
+
try {
|
|
1147
|
+
next = updateProposalStrict(this.proposalsDir, proposal.id, proposal.rev, (current) => ({
|
|
1148
|
+
status: 'pending',
|
|
1149
|
+
queue: {
|
|
1150
|
+
...current.queue,
|
|
1151
|
+
ticket,
|
|
1152
|
+
seq: nextSeq,
|
|
1153
|
+
queuedAt: at,
|
|
1154
|
+
lease: null,
|
|
1155
|
+
deadlineAt: null,
|
|
1156
|
+
blockedReason: null,
|
|
1157
|
+
attempts: 0,
|
|
1158
|
+
agingSteps: 0,
|
|
1159
|
+
effectivePriority: current.queue?.priority ?? 'P3',
|
|
1160
|
+
},
|
|
1161
|
+
stateLog: [...(current.stateLog ?? []), { at, from: current.status, to: 'pending', by, note: 'requeued-after-expired' }],
|
|
1162
|
+
}), { now: this.nowDate() });
|
|
1163
|
+
} catch (error) {
|
|
1164
|
+
if (error?.code === 'E_STATE_RACE') return fail('E_STATE_RACE', 'proposal changed concurrently; retry');
|
|
1165
|
+
return fail(codeOf(error), error?.message ?? 'requeue failed');
|
|
1166
|
+
}
|
|
1167
|
+
const updated = scanProposalDir(this.proposalsDir).proposals;
|
|
1168
|
+
const queue = this.#buildQueue(updated, nextSeq + 1, Number(queueBefore?.rev ?? 0) + 1);
|
|
1169
|
+
this.#writeQueue(queue);
|
|
1170
|
+
this.#auditSafe('proposal.requeue_expired', { id: next.id, ticket, by, seq: nextSeq });
|
|
1171
|
+
return { ok: true, id: next.id, ticket, state: 'pending', requeued: true, seq: nextSeq, deadlineAt: null };
|
|
1172
|
+
} finally {
|
|
1173
|
+
this.#releaseIssueLock(lockToken);
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
approve(input = {}, options = {}) {
|
|
1178
|
+
const caller = this.#normalizeOrigin(options);
|
|
1179
|
+
// D-CR2: approve is a main-session/owner transition; the author identity
|
|
1180
|
+
// never grants a subagent review rights (CR-01).
|
|
1181
|
+
if (!this.#isMainSession(caller)) return fail('E_NOT_MAIN_SESSION', 'subagent sessions cannot approve proposals');
|
|
1182
|
+
const loaded = this.#loadProposal(input);
|
|
1183
|
+
if (loaded.error) return loaded.error;
|
|
1184
|
+
const proposal = loaded.proposal;
|
|
1185
|
+
const by = caller.kind === 'owner-cli' ? 'owner:cli' : caller.sessionId;
|
|
1186
|
+
if (proposal.status === 'expired') return this.#requeueExpired(proposal, by);
|
|
1187
|
+
if (proposal.status !== 'pending') return fail('E_BAD_STATE', `proposal is ${proposal.status}, expected pending`);
|
|
1188
|
+
const deadlineAt = new Date(this.nowDate().getTime() + (Number(this.config.leaseWaitTimeoutMs) || 300000)).toISOString();
|
|
1189
|
+
// D-CR7: WAL before state. If the WAL write fails the proposal stays queued
|
|
1190
|
+
// (no transition is recorded that replay cannot justify).
|
|
1191
|
+
try {
|
|
1192
|
+
this.wal.append('queue.approve', { ticket: proposal.queue?.ticket ?? null, proposalId: proposal.id, by, deadlineAt });
|
|
1193
|
+
} catch (error) {
|
|
1194
|
+
this.#auditSafe('wal.append_failed', {
|
|
1195
|
+
proposalId: proposal.id, ev: 'queue.approve', error: String(error?.message ?? error),
|
|
1196
|
+
});
|
|
1197
|
+
return fail(codeOf(error), 'WAL append failed; proposal unchanged');
|
|
1198
|
+
}
|
|
1199
|
+
let next = null;
|
|
1200
|
+
try {
|
|
1201
|
+
next = this.#transition(proposal, 'approved', {
|
|
1202
|
+
by,
|
|
1203
|
+
note: 'approved',
|
|
1204
|
+
queue: { lease: null, deadlineAt, blockedReason: null },
|
|
1205
|
+
});
|
|
1206
|
+
} catch (error) {
|
|
1207
|
+
if (error?.code === 'E_STATE_RACE') return fail('E_STATE_RACE', 'proposal changed concurrently; retry');
|
|
1208
|
+
return fail(codeOf(error), error?.message ?? 'approve failed');
|
|
1209
|
+
}
|
|
1210
|
+
this.#auditSafe('proposal.approve', { id: next.id, ticket: next.queue?.ticket ?? null, by });
|
|
1211
|
+
return { ok: true, id: next.id, ticket: next.queue?.ticket ?? null, state: 'approved', deadlineAt };
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
reject(input = {}, options = {}) {
|
|
1215
|
+
const caller = this.#normalizeOrigin(options);
|
|
1216
|
+
if (!this.#isMainSession(caller)) return fail('E_NOT_MAIN_SESSION', 'subagent sessions cannot reject proposals');
|
|
1217
|
+
const loaded = this.#loadProposal(input);
|
|
1218
|
+
if (loaded.error) return loaded.error;
|
|
1219
|
+
const proposal = loaded.proposal;
|
|
1220
|
+
if (!['pending', 'approved', 'blocked-on-user'].includes(proposal.status)) {
|
|
1221
|
+
return fail('E_BAD_STATE', `proposal is ${proposal.status}, cannot reject`);
|
|
1222
|
+
}
|
|
1223
|
+
const by = caller.kind === 'owner-cli' ? 'owner:cli' : caller.sessionId;
|
|
1224
|
+
const note = sanitizeLine(input.note, 200) || 'rejected';
|
|
1225
|
+
let next = null;
|
|
1226
|
+
try {
|
|
1227
|
+
next = this.#transition(proposal, 'rejected', { by, note, queue: { lease: null, blockedReason: null } });
|
|
1228
|
+
} catch (error) {
|
|
1229
|
+
if (error?.code === 'E_STATE_RACE') return fail('E_STATE_RACE', 'proposal changed concurrently; retry');
|
|
1230
|
+
return fail(codeOf(error), error?.message ?? 'reject failed');
|
|
1231
|
+
}
|
|
1232
|
+
this.#auditSafe('proposal.reject', { id: next.id, ticket: next.queue?.ticket ?? null, by, reason: note });
|
|
1233
|
+
return { ok: true, id: next.id, ticket: next.queue?.ticket ?? null, state: 'rejected' };
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
cancel(input = {}, options = {}) {
|
|
1237
|
+
const loaded = this.#loadProposal(input);
|
|
1238
|
+
if (loaded.error) return loaded.error;
|
|
1239
|
+
const proposal = loaded.proposal;
|
|
1240
|
+
const caller = this.#normalizeOrigin(options);
|
|
1241
|
+
// D-CR2: a subagent keeps exactly one transition — cancelling its own
|
|
1242
|
+
// queued proposal. It may not cancel anyone else's.
|
|
1243
|
+
if (isSubagentCaller(caller) && proposal.origin?.sessionId !== caller.sessionId) {
|
|
1244
|
+
return fail('E_PROPOSAL_FORBIDDEN', 'subagents may only cancel their own proposals');
|
|
1245
|
+
}
|
|
1246
|
+
if (!['pending', 'approved', 'blocked-on-user'].includes(proposal.status)) {
|
|
1247
|
+
return fail('E_BAD_STATE', `proposal is ${proposal.status}, cannot cancel`);
|
|
1248
|
+
}
|
|
1249
|
+
const by = caller.kind === 'owner-cli' ? 'owner:cli' : caller.sessionId;
|
|
1250
|
+
const note = sanitizeLine(input.note, 200) || 'cancelled';
|
|
1251
|
+
let next = null;
|
|
1252
|
+
try {
|
|
1253
|
+
next = this.#transition(proposal, 'cancelled', { by, note, queue: { lease: null, blockedReason: null } });
|
|
1254
|
+
} catch (error) {
|
|
1255
|
+
if (error?.code === 'E_STATE_RACE') return fail('E_STATE_RACE', 'proposal changed concurrently; retry');
|
|
1256
|
+
return fail(codeOf(error), error?.message ?? 'cancel failed');
|
|
1257
|
+
}
|
|
1258
|
+
this.#auditSafe('proposal.cancel', { id: next.id, ticket: next.queue?.ticket ?? null, by, reason: note });
|
|
1259
|
+
return { ok: true, id: next.id, ticket: next.queue?.ticket ?? null, state: 'cancelled' };
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
rollback(input = {}, options = {}) {
|
|
1263
|
+
if (!this.applier || typeof this.applier.rollback !== 'function') {
|
|
1264
|
+
return fail('E_WP4_PENDING', 'rollback requires the WP4 writer');
|
|
1265
|
+
}
|
|
1266
|
+
return this.applier.rollback(input, { caller: this.#normalizeOrigin(options) });
|
|
1267
|
+
}
|
|
1268
|
+
|
|
1269
|
+
/** Unified entry used by service.requestApply / owner CLI. */
|
|
1270
|
+
requestApply(input = {}, options = {}) {
|
|
1271
|
+
const mode = String(input.mode ?? '');
|
|
1272
|
+
if (mode === 'apply') {
|
|
1273
|
+
if (!this.applier || typeof this.applier.apply !== 'function') return fail('E_WP4_PENDING', 'apply requires the WP4 writer');
|
|
1274
|
+
return this.applier.apply(input, { caller: this.#normalizeOrigin(options) });
|
|
1275
|
+
}
|
|
1276
|
+
if (mode === 'approve') return this.approve(input, options);
|
|
1277
|
+
if (mode === 'reject') return this.reject(input, options);
|
|
1278
|
+
if (mode === 'cancel') return this.cancel(input, options);
|
|
1279
|
+
if (mode === 'rollback') return this.rollback(input, options);
|
|
1280
|
+
return fail('E_BAD_MODE', `unknown transition mode: ${mode}`);
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
/** Read-only list/queue/detail view used by `router_proposals`. */
|
|
1284
|
+
view(input = {}, options = {}) {
|
|
1285
|
+
const mode = input.mode === undefined ? 'list' : String(input.mode);
|
|
1286
|
+
if (!['list', 'queue', 'detail'].includes(mode)) return fail('E_BAD_STATE', `unknown mode: ${mode}`);
|
|
1287
|
+
const caller = this.#normalizeOrigin(options);
|
|
1288
|
+
const { proposals } = this.#scan();
|
|
1289
|
+
const active = sortProposals(this.#active(proposals));
|
|
1290
|
+
const positionById = new Map(active.map((proposal, index) => [proposal.id, index + 1]));
|
|
1291
|
+
|
|
1292
|
+
if (mode === 'queue') {
|
|
1293
|
+
const walSnapshot = this.wal.read().snapshot;
|
|
1294
|
+
const queue = readQueueFile(this.queueFile) ?? this.#buildQueue(proposals, this.#lastSeq(proposals, null, [], walSnapshot) + 1);
|
|
1295
|
+
const ordered = sortProposals(this.#active(proposals));
|
|
1296
|
+
const entries = ordered.map((proposal, index) => ({
|
|
1297
|
+
ticket: proposal.queue?.ticket ?? null,
|
|
1298
|
+
sessionId: proposal.origin?.sessionId ?? null,
|
|
1299
|
+
target: proposal.target,
|
|
1300
|
+
op: proposal.op,
|
|
1301
|
+
status: proposal.status,
|
|
1302
|
+
position: index + 1,
|
|
1303
|
+
waitMs: Math.max(0, this.nowDate().getTime() - Date.parse(proposal.queue?.queuedAt ?? proposal.createdAt ?? '') || 0),
|
|
1304
|
+
etaMs: ordered.slice(0, index + 1).reduce((sum, item) => sum + (ETA_DEFAULTS_MS[item.op] ?? 2000), 0),
|
|
1305
|
+
priority: proposal.queue?.priority ?? 'P3',
|
|
1306
|
+
effectivePriority: proposal.queue?.effectivePriority ?? proposal.queue?.priority ?? 'P3',
|
|
1307
|
+
}));
|
|
1308
|
+
return {
|
|
1309
|
+
ok: true,
|
|
1310
|
+
mode: 'queue',
|
|
1311
|
+
seqCounter: queue.seqCounter ?? this.#lastSeq(proposals, null, [], walSnapshot),
|
|
1312
|
+
depth: entries.length,
|
|
1313
|
+
etaMs: entries.length > 0 ? entries[entries.length - 1].etaMs : 0,
|
|
1314
|
+
writer: queue.writer ?? null,
|
|
1315
|
+
entries,
|
|
1316
|
+
blocked: queue.blocked ?? [],
|
|
1317
|
+
};
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
if (mode === 'detail') {
|
|
1321
|
+
const id = typeof input.id === 'string' ? input.id.trim() : '';
|
|
1322
|
+
if (!isProposalId(id)) return fail('E_TICKET_UNKNOWN', 'detail requires a valid proposal id');
|
|
1323
|
+
const proposal = readProposal(this.proposalsDir, id);
|
|
1324
|
+
if (!proposal) return fail('E_TICKET_UNKNOWN', `proposal ${id} was not found`);
|
|
1325
|
+
// D-CR2: subagents never receive proposal bodies, not even for proposals
|
|
1326
|
+
// they wrote themselves. They get the same summary the old ACL returned
|
|
1327
|
+
// to strangers; the author-identity branch is main-session only now.
|
|
1328
|
+
if (isSubagentCaller(caller)) {
|
|
1329
|
+
const contentSha = `sha256:${sha256Hex(proposal.content ?? '')}`;
|
|
1330
|
+
this.#auditSafe('proposal.detail.denied', {
|
|
1331
|
+
id,
|
|
1332
|
+
by: caller.sessionId,
|
|
1333
|
+
reason: 'subagent-summary-only',
|
|
1334
|
+
});
|
|
1335
|
+
return fail('E_PROPOSAL_FORBIDDEN', 'subagent sessions only receive a proposal summary', {
|
|
1336
|
+
summary: {
|
|
1337
|
+
id,
|
|
1338
|
+
ticket: proposal.queue?.ticket ?? null,
|
|
1339
|
+
title: neutralizeEnvelopeMarkers(proposal.title ?? ''),
|
|
1340
|
+
contentSha,
|
|
1341
|
+
bytes: Buffer.byteLength(proposal.content ?? '', 'utf8'),
|
|
1342
|
+
},
|
|
1343
|
+
});
|
|
1344
|
+
}
|
|
1345
|
+
const safe = { ...proposal };
|
|
1346
|
+
delete safe.__file;
|
|
1347
|
+
// D-CR4: stored body is untouched; every user-controlled text surface is
|
|
1348
|
+
// neutralized before it is rendered inside the data envelope.
|
|
1349
|
+
safe.title = neutralizeEnvelopeMarkers(proposal.title ?? '');
|
|
1350
|
+
safe.rationale = neutralizeEnvelopeMarkers(proposal.rationale ?? '');
|
|
1351
|
+
if (Array.isArray(proposal.evidence)) {
|
|
1352
|
+
safe.evidence = proposal.evidence.map((item) => (typeof item === 'string'
|
|
1353
|
+
? neutralizeEnvelopeMarkers(item)
|
|
1354
|
+
: item));
|
|
1355
|
+
}
|
|
1356
|
+
safe.content = wrapProposalContent(proposal.content ?? '');
|
|
1357
|
+
return { ok: true, mode: 'detail', proposal: safe };
|
|
1358
|
+
}
|
|
1359
|
+
|
|
1360
|
+
const status = typeof input.status === 'string' && input.status !== '' ? input.status : null;
|
|
1361
|
+
const filtered = status ? proposals.filter((proposal) => proposal.status === status) : proposals;
|
|
1362
|
+
const sorted = [
|
|
1363
|
+
...filtered.filter((proposal) => !isTerminalProposalStatus(proposal.status)).sort((a, b) => {
|
|
1364
|
+
const pa = positionById.get(a.id) ?? 9999;
|
|
1365
|
+
const pb = positionById.get(b.id) ?? 9999;
|
|
1366
|
+
return pa - pb;
|
|
1367
|
+
}),
|
|
1368
|
+
...filtered.filter((proposal) => isTerminalProposalStatus(proposal.status))
|
|
1369
|
+
.sort((a, b) => Date.parse(b.updatedAt ?? b.createdAt ?? '') - Date.parse(a.updatedAt ?? a.createdAt ?? '')),
|
|
1370
|
+
];
|
|
1371
|
+
const rawLimit = Number(input.limit);
|
|
1372
|
+
const limit = Number.isInteger(rawLimit) ? Math.min(20, Math.max(1, rawLimit)) : 20;
|
|
1373
|
+
const items = sorted.slice(0, limit).map((proposal) => ({
|
|
1374
|
+
id: proposal.id,
|
|
1375
|
+
ticket: proposal.queue?.ticket ?? null,
|
|
1376
|
+
title: proposal.title,
|
|
1377
|
+
priority: proposal.queue?.priority ?? 'P3',
|
|
1378
|
+
// `state` is the documented row field (DESIGN §3.4). `status` is the
|
|
1379
|
+
// additive read alias: external consumers (VM acceptance harness, panel)
|
|
1380
|
+
// read one or the other, and a row must never look untracked because the
|
|
1381
|
+
// reader picked the other spelling.
|
|
1382
|
+
state: proposal.status,
|
|
1383
|
+
status: proposal.status,
|
|
1384
|
+
// K-04: `superseded` is a legitimate terminal state (the row was folded
|
|
1385
|
+
// into the keeper it superseded, DESIGN §5.8/K20), so it must not be
|
|
1386
|
+
// reported as cancellable. Callers that decide "can I cancel this row?"
|
|
1387
|
+
// read this flag instead of re-deriving the status matrix.
|
|
1388
|
+
cancellable: ['pending', 'approved', 'blocked-on-user'].includes(proposal.status),
|
|
1389
|
+
terminal: isTerminalProposalStatus(proposal.status),
|
|
1390
|
+
createdAt: proposal.createdAt,
|
|
1391
|
+
position: positionById.get(proposal.id) ?? null,
|
|
1392
|
+
}));
|
|
1393
|
+
return {
|
|
1394
|
+
ok: true,
|
|
1395
|
+
mode: 'list',
|
|
1396
|
+
proposals: items,
|
|
1397
|
+
total: filtered.length,
|
|
1398
|
+
limit,
|
|
1399
|
+
};
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1402
|
+
/** Compact proposal block for `status.json` (DESIGN §3.4, status.mjs input). */
|
|
1403
|
+
status() {
|
|
1404
|
+
const { proposals } = this.#scan();
|
|
1405
|
+
const active = this.#active(proposals);
|
|
1406
|
+
const ordered = sortProposals(active);
|
|
1407
|
+
const now = this.nowDate();
|
|
1408
|
+
const today = localDayKey(now);
|
|
1409
|
+
const doneToday = proposals.filter((proposal) => proposal.status === 'done'
|
|
1410
|
+
&& localDayKey(proposal.updatedAt ?? proposal.createdAt ?? now) === today).length;
|
|
1411
|
+
const conflicts = proposals.filter((proposal) => proposal.status === 'conflict').length;
|
|
1412
|
+
const superseded = proposals.filter((proposal) => proposal.status === 'superseded').length;
|
|
1413
|
+
// K-08: an expired row is a terminal state, not a deleted row. It leaves the
|
|
1414
|
+
// queue depth but must stay visible in status so "expired but kept" is
|
|
1415
|
+
// observable instead of silently reported as 0.
|
|
1416
|
+
const expired = proposals.filter((proposal) => proposal.status === 'expired').length;
|
|
1417
|
+
const writer = ordered.find((proposal) => proposal.status === 'applying');
|
|
1418
|
+
const counts = {
|
|
1419
|
+
pending: ordered.filter((proposal) => proposal.status === 'pending').length,
|
|
1420
|
+
queued: ordered.filter((proposal) => proposal.status === 'approved').length,
|
|
1421
|
+
approved: ordered.filter((proposal) => proposal.status === 'approved').length,
|
|
1422
|
+
applying: ordered.filter((proposal) => proposal.status === 'applying').length,
|
|
1423
|
+
blockedOnUser: ordered.filter((proposal) => proposal.status === 'blocked-on-user').length,
|
|
1424
|
+
expired,
|
|
1425
|
+
};
|
|
1426
|
+
const etaMs = ordered.reduce((sum, proposal) => sum + (ETA_DEFAULTS_MS[proposal.op] ?? 2000), 0);
|
|
1427
|
+
return {
|
|
1428
|
+
doneToday,
|
|
1429
|
+
conflicts,
|
|
1430
|
+
superseded,
|
|
1431
|
+
pending: counts.pending,
|
|
1432
|
+
approved: counts.approved,
|
|
1433
|
+
counts,
|
|
1434
|
+
queue: {
|
|
1435
|
+
seqCounter: Number.isInteger(readQueueFile(this.queueFile)?.seqCounter)
|
|
1436
|
+
? readQueueFile(this.queueFile).seqCounter
|
|
1437
|
+
: this.#lastSeq(proposals, null, [], this.wal.read().snapshot) + 1,
|
|
1438
|
+
depth: ordered.length,
|
|
1439
|
+
etaMs,
|
|
1440
|
+
starvation: false,
|
|
1441
|
+
writer: writer
|
|
1442
|
+
? {
|
|
1443
|
+
ticket: writer.queue?.ticket ?? null,
|
|
1444
|
+
proposalId: writer.id,
|
|
1445
|
+
sessionId: writer.origin?.sessionId ?? null,
|
|
1446
|
+
since: writer.queue?.lease?.startedAt ?? writer.updatedAt ?? writer.createdAt,
|
|
1447
|
+
}
|
|
1448
|
+
: null,
|
|
1449
|
+
blocked: ordered.filter((proposal) => proposal.status === 'blocked-on-user').map((proposal) => ({
|
|
1450
|
+
ticket: proposal.queue?.ticket ?? null,
|
|
1451
|
+
reason: proposal.queue?.blockedReason ?? 'BLOCKED',
|
|
1452
|
+
since: proposal.updatedAt ?? proposal.createdAt,
|
|
1453
|
+
})),
|
|
1454
|
+
},
|
|
1455
|
+
};
|
|
1456
|
+
}
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1459
|
+
export function createProposalEngine(options) {
|
|
1460
|
+
return new ProposalEngine(options);
|
|
1461
|
+
}
|