blun-king-cli 9.1.642 → 9.1.644
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/LIESMICH.txt +18 -0
- package/README.md +20 -6
- package/bin/blun.js +3 -3
- package/bin/king.js +3 -3
- package/bin/launcher-mode.js +125 -126
- package/bin/launcher-runtime.js +603 -616
- package/bin/plugin-bootstrap.js +339 -405
- package/bin/rename-private-staging.cjs +2 -2
- package/bin/retired-bundled-plugins.cjs +84 -0
- package/bin/startup-security-host.cjs +105 -0
- package/bin/startup-security.cjs +9 -105
- package/bin/startup-warning-policy.cjs +22 -0
- package/bin/update-lease-installer.cjs +125 -0
- package/bin/update-lease-sockets.cjs +228 -0
- package/bin/update-lease.js +22 -327
- package/bin/verify-bundled-agent-sources.cjs +2 -4
- package/blun.mjs +78 -193
- package/bundled-agent-sources.json +1 -552
- package/package.json +4 -6
- package/tool-liveness642/index.cjs +7 -0
- package/tool-liveness642/queue-delivery.cjs +109 -0
- package/tool-liveness642/receipt.json +40 -0
- package/tool-liveness642/shell-yield.cjs +43 -0
- package/tool-liveness642/task-wait.cjs +45 -0
- package/versionierung/BELEG.json +43 -0
- package/versionierung/LIESMICH.md +5 -0
- package/versionierung/urspruenglicher-overlay-beleg.json +39 -0
- package/worker-host.mjs +48 -128
- package/agent-spine-plugin/.claude-plugin/marketplace.json +0 -20
- package/agent-spine-plugin/.claude-plugin/plugin.json +0 -14
- package/agent-spine-plugin/.codex-plugin/plugin.json +0 -47
- package/agent-spine-plugin/.mcp.json +0 -8
- package/agent-spine-plugin/CHANGELOG.md +0 -1614
- package/agent-spine-plugin/LICENSE +0 -186
- package/agent-spine-plugin/README.md +0 -432
- package/agent-spine-plugin/assets/agentspine-banner.svg +0 -32
- package/agent-spine-plugin/bin/agentspine-mcp.js +0 -4
- package/agent-spine-plugin/bin/agentspine.js +0 -7
- package/agent-spine-plugin/blun.plugin.json +0 -68
- package/agent-spine-plugin/docs/acceptance.md +0 -61
- package/agent-spine-plugin/docs/artifact-evaluation.md +0 -93
- package/agent-spine-plugin/docs/host-integration.md +0 -193
- package/agent-spine-plugin/docs/preflight-recall.md +0 -71
- package/agent-spine-plugin/docs/preservation-contract.md +0 -53
- package/agent-spine-plugin/docs/quality-gates.md +0 -50
- package/agent-spine-plugin/docs/session-timeline.md +0 -112
- package/agent-spine-plugin/docs/source-roots.md +0 -113
- package/agent-spine-plugin/docs/world-model.md +0 -119
- package/agent-spine-plugin/hooks/codex.json +0 -47
- package/agent-spine-plugin/hooks/hooks.json +0 -106
- package/agent-spine-plugin/hooks/version.json +0 -5
- package/agent-spine-plugin/package.json +0 -77
- package/agent-spine-plugin/scripts/check-codex-install.js +0 -226
- package/agent-spine-plugin/scripts/check-hosts.js +0 -208
- package/agent-spine-plugin/scripts/check-install-hook.js +0 -227
- package/agent-spine-plugin/scripts/check-install-selfstarter.js +0 -154
- package/agent-spine-plugin/scripts/check-install.js +0 -478
- package/agent-spine-plugin/scripts/check-line-budget.js +0 -58
- package/agent-spine-plugin/scripts/check-syntax.js +0 -29
- package/agent-spine-plugin/scripts/github-actions.js +0 -11
- package/agent-spine-plugin/scripts/hermetic-process.js +0 -191
- package/agent-spine-plugin/scripts/release-check.js +0 -150
- package/agent-spine-plugin/scripts/run-acceptance.js +0 -19
- package/agent-spine-plugin/scripts/run-checks.js +0 -50
- package/agent-spine-plugin/scripts/run-tests-hermetic.js +0 -112
- package/agent-spine-plugin/skills/agent-spine/SKILL.md +0 -99
- package/agent-spine-plugin/spine-example/1-identity.md +0 -12
- package/agent-spine-plugin/spine-example/2-voice.md +0 -6
- package/agent-spine-plugin/spine-example/3-conduct.md +0 -8
- package/agent-spine-plugin/spine-example/4-history.md +0 -4
- package/agent-spine-plugin/src/cli-agent.js +0 -315
- package/agent-spine-plugin/src/cli-attention.js +0 -95
- package/agent-spine-plugin/src/cli-autonomy.js +0 -36
- package/agent-spine-plugin/src/cli-common.js +0 -71
- package/agent-spine-plugin/src/cli-continuity.js +0 -116
- package/agent-spine-plugin/src/cli-core.js +0 -128
- package/agent-spine-plugin/src/cli-diagnostics.js +0 -291
- package/agent-spine-plugin/src/cli-host.js +0 -21
- package/agent-spine-plugin/src/cli-learning.js +0 -320
- package/agent-spine-plugin/src/cli-premortem.js +0 -16
- package/agent-spine-plugin/src/cli-sharing.js +0 -230
- package/agent-spine-plugin/src/cli.js +0 -181
- package/agent-spine-plugin/src/codex-reader-launcher.js +0 -182
- package/agent-spine-plugin/src/hook.js +0 -500
- package/agent-spine-plugin/src/index.js +0 -108
- package/agent-spine-plugin/src/lib/acceptance.js +0 -435
- package/agent-spine-plugin/src/lib/action-lesson-recall.js +0 -118
- package/agent-spine-plugin/src/lib/attention-context.js +0 -167
- package/agent-spine-plugin/src/lib/attention-events.js +0 -113
- package/agent-spine-plugin/src/lib/attention-privacy.js +0 -72
- package/agent-spine-plugin/src/lib/attention-schema.js +0 -164
- package/agent-spine-plugin/src/lib/attention-storage.js +0 -93
- package/agent-spine-plugin/src/lib/attention.js +0 -164
- package/agent-spine-plugin/src/lib/audit-premortem.js +0 -223
- package/agent-spine-plugin/src/lib/audit.js +0 -401
- package/agent-spine-plugin/src/lib/authentication.js +0 -515
- package/agent-spine-plugin/src/lib/autonomy-policy.js +0 -110
- package/agent-spine-plugin/src/lib/autonomy-store.js +0 -202
- package/agent-spine-plugin/src/lib/autonomy.js +0 -8
- package/agent-spine-plugin/src/lib/briefing.js +0 -493
- package/agent-spine-plugin/src/lib/catalog-document-read.js +0 -51
- package/agent-spine-plugin/src/lib/catalog.js +0 -167
- package/agent-spine-plugin/src/lib/channel-continuity.js +0 -19
- package/agent-spine-plugin/src/lib/channel-runtime.js +0 -665
- package/agent-spine-plugin/src/lib/codex-installation.js +0 -231
- package/agent-spine-plugin/src/lib/codex-skill-installation.js +0 -211
- package/agent-spine-plugin/src/lib/context.js +0 -156
- package/agent-spine-plugin/src/lib/continuity.js +0 -338
- package/agent-spine-plugin/src/lib/coordination.js +0 -577
- package/agent-spine-plugin/src/lib/delivery-agent-usage.js +0 -231
- package/agent-spine-plugin/src/lib/delivery-assignment.js +0 -220
- package/agent-spine-plugin/src/lib/delivery-command-actions.js +0 -462
- package/agent-spine-plugin/src/lib/delivery-knowledge.js +0 -78
- package/agent-spine-plugin/src/lib/delivery-premortem-binding.js +0 -107
- package/agent-spine-plugin/src/lib/delivery-premortem-closure.js +0 -171
- package/agent-spine-plugin/src/lib/delivery-premortem-codec.js +0 -45
- package/agent-spine-plugin/src/lib/delivery-premortem-correction.js +0 -101
- package/agent-spine-plugin/src/lib/delivery-premortem-file.js +0 -21
- package/agent-spine-plugin/src/lib/delivery-premortem-index.js +0 -493
- package/agent-spine-plugin/src/lib/delivery-premortem-inspection.js +0 -37
- package/agent-spine-plugin/src/lib/delivery-premortem-recovery.js +0 -120
- package/agent-spine-plugin/src/lib/delivery-premortem-rejection.js +0 -65
- package/agent-spine-plugin/src/lib/delivery-premortem-results.js +0 -28
- package/agent-spine-plugin/src/lib/delivery-premortem-session-guard.js +0 -46
- package/agent-spine-plugin/src/lib/delivery-premortem-write-ledger.js +0 -285
- package/agent-spine-plugin/src/lib/delivery-premortem.js +0 -499
- package/agent-spine-plugin/src/lib/delivery-shell-heredoc.js +0 -115
- package/agent-spine-plugin/src/lib/delivery-shell-substitutions.js +0 -111
- package/agent-spine-plugin/src/lib/delivery-shell-wrapper.js +0 -64
- package/agent-spine-plugin/src/lib/delivery-target.js +0 -73
- package/agent-spine-plugin/src/lib/delivery-verification.js +0 -445
- package/agent-spine-plugin/src/lib/documents.js +0 -239
- package/agent-spine-plugin/src/lib/feed-transport.js +0 -499
- package/agent-spine-plugin/src/lib/filesystem-retry.js +0 -34
- package/agent-spine-plugin/src/lib/gateway-common.js +0 -68
- package/agent-spine-plugin/src/lib/gateway-control.js +0 -370
- package/agent-spine-plugin/src/lib/gateway-delivery.js +0 -103
- package/agent-spine-plugin/src/lib/gateway-execution.js +0 -350
- package/agent-spine-plugin/src/lib/gateway-group-response.js +0 -128
- package/agent-spine-plugin/src/lib/gateway-host-fencing.js +0 -92
- package/agent-spine-plugin/src/lib/gateway-host-lifecycle.js +0 -193
- package/agent-spine-plugin/src/lib/gateway-inspection.js +0 -85
- package/agent-spine-plugin/src/lib/gateway-knowledge.js +0 -129
- package/agent-spine-plugin/src/lib/gateway-policy-provenance.js +0 -197
- package/agent-spine-plugin/src/lib/gateway-premortem-disposition.js +0 -82
- package/agent-spine-plugin/src/lib/gateway-premortem.js +0 -363
- package/agent-spine-plugin/src/lib/gateway-prepared-host.js +0 -28
- package/agent-spine-plugin/src/lib/gateway-runs.js +0 -345
- package/agent-spine-plugin/src/lib/gateway-runtime-identity.js +0 -31
- package/agent-spine-plugin/src/lib/gateway-runtime-records.js +0 -21
- package/agent-spine-plugin/src/lib/gateway-runtime.js +0 -18
- package/agent-spine-plugin/src/lib/gateway-state-transaction.js +0 -356
- package/agent-spine-plugin/src/lib/gateway-state.js +0 -344
- package/agent-spine-plugin/src/lib/graph.js +0 -337
- package/agent-spine-plugin/src/lib/hook-artifact-guards.js +0 -356
- package/agent-spine-plugin/src/lib/hook-audit.js +0 -43
- package/agent-spine-plugin/src/lib/hook-briefing-use.js +0 -78
- package/agent-spine-plugin/src/lib/hook-context.js +0 -441
- package/agent-spine-plugin/src/lib/hook-final-message.js +0 -26
- package/agent-spine-plugin/src/lib/hook-input.js +0 -27
- package/agent-spine-plugin/src/lib/hook-output.js +0 -284
- package/agent-spine-plugin/src/lib/hook-premortem.js +0 -257
- package/agent-spine-plugin/src/lib/hook-process-advisory.js +0 -36
- package/agent-spine-plugin/src/lib/hook-protection.js +0 -95
- package/agent-spine-plugin/src/lib/hook-stop-verification.js +0 -84
- package/agent-spine-plugin/src/lib/hook-timeline.js +0 -102
- package/agent-spine-plugin/src/lib/host-instruction-budget.js +0 -11
- package/agent-spine-plugin/src/lib/https-transport.js +0 -392
- package/agent-spine-plugin/src/lib/identifier-analysis.js +0 -446
- package/agent-spine-plugin/src/lib/indexed-memory-offline.js +0 -40
- package/agent-spine-plugin/src/lib/indexed-memory.js +0 -298
- package/agent-spine-plugin/src/lib/knowledge-evidence.js +0 -431
- package/agent-spine-plugin/src/lib/learning-applications.js +0 -441
- package/agent-spine-plugin/src/lib/learning-artifact-evaluator.js +0 -114
- package/agent-spine-plugin/src/lib/learning-candidates.js +0 -274
- package/agent-spine-plugin/src/lib/learning-context.js +0 -137
- package/agent-spine-plugin/src/lib/learning-delivery-contracts.js +0 -310
- package/agent-spine-plugin/src/lib/learning-evaluation-contracts.js +0 -350
- package/agent-spine-plugin/src/lib/learning-evaluation-registration.js +0 -372
- package/agent-spine-plugin/src/lib/learning-evaluation-revocation.js +0 -292
- package/agent-spine-plugin/src/lib/learning-evidence-contracts.js +0 -321
- package/agent-spine-plugin/src/lib/learning-findings.js +0 -458
- package/agent-spine-plugin/src/lib/learning-measurement-contracts.js +0 -285
- package/agent-spine-plugin/src/lib/learning-measurements.js +0 -265
- package/agent-spine-plugin/src/lib/learning-outcome-contracts.js +0 -165
- package/agent-spine-plugin/src/lib/learning-outcomes.js +0 -343
- package/agent-spine-plugin/src/lib/learning-reconciliation.js +0 -290
- package/agent-spine-plugin/src/lib/learning-retry-contracts.js +0 -188
- package/agent-spine-plugin/src/lib/learning-schema.js +0 -229
- package/agent-spine-plugin/src/lib/learning-scope-targets.js +0 -424
- package/agent-spine-plugin/src/lib/learning-state-upgrade.js +0 -477
- package/agent-spine-plugin/src/lib/learning-status-configuration.js +0 -476
- package/agent-spine-plugin/src/lib/learning-storage.js +0 -203
- package/agent-spine-plugin/src/lib/learning-trial-recovery.js +0 -218
- package/agent-spine-plugin/src/lib/learning-validation-contracts.js +0 -375
- package/agent-spine-plugin/src/lib/learning-validation-renewal.js +0 -298
- package/agent-spine-plugin/src/lib/learning-validation-runtime.js +0 -234
- package/agent-spine-plugin/src/lib/learning.js +0 -36
- package/agent-spine-plugin/src/lib/lesson-recall-session.js +0 -172
- package/agent-spine-plugin/src/lib/mcp-autonomy-tools.js +0 -37
- package/agent-spine-plugin/src/lib/mcp-delivery-completion.js +0 -124
- package/agent-spine-plugin/src/lib/mcp-delivery-tools.js +0 -45
- package/agent-spine-plugin/src/lib/mcp-premortem.js +0 -68
- package/agent-spine-plugin/src/lib/mcp-runtime.js +0 -355
- package/agent-spine-plugin/src/lib/mcp-source-context.js +0 -61
- package/agent-spine-plugin/src/lib/mcp-timeline-tools.js +0 -240
- package/agent-spine-plugin/src/lib/mcp-world-tools.js +0 -52
- package/agent-spine-plugin/src/lib/object-transport.js +0 -206
- package/agent-spine-plugin/src/lib/owned-file-lock.js +0 -182
- package/agent-spine-plugin/src/lib/paths.js +0 -109
- package/agent-spine-plugin/src/lib/peer-transport.js +0 -283
- package/agent-spine-plugin/src/lib/persona-runtime.js +0 -581
- package/agent-spine-plugin/src/lib/pre-answer-timeline-recall.js +0 -104
- package/agent-spine-plugin/src/lib/preflight-delivery-id.js +0 -27
- package/agent-spine-plugin/src/lib/preflight.js +0 -688
- package/agent-spine-plugin/src/lib/project-portfolio.js +0 -176
- package/agent-spine-plugin/src/lib/runtime.js +0 -13
- package/agent-spine-plugin/src/lib/selfstarter-core.js +0 -382
- package/agent-spine-plugin/src/lib/selfstarter-jobs.js +0 -149
- package/agent-spine-plugin/src/lib/selfstarter-lease.js +0 -204
- package/agent-spine-plugin/src/lib/selfstarter-policy.js +0 -90
- package/agent-spine-plugin/src/lib/selfstarter-workspace.js +0 -111
- package/agent-spine-plugin/src/lib/selfstarter.js +0 -11
- package/agent-spine-plugin/src/lib/session-timeline-auth.js +0 -316
- package/agent-spine-plugin/src/lib/session-timeline-codex.js +0 -69
- package/agent-spine-plugin/src/lib/session-timeline-contract.js +0 -56
- package/agent-spine-plugin/src/lib/session-timeline-enrollment-source.js +0 -38
- package/agent-spine-plugin/src/lib/session-timeline-enrollment-storage.js +0 -128
- package/agent-spine-plugin/src/lib/session-timeline-enrollment-transport.js +0 -15
- package/agent-spine-plugin/src/lib/session-timeline-enrollment.js +0 -478
- package/agent-spine-plugin/src/lib/session-timeline-event-extract.js +0 -186
- package/agent-spine-plugin/src/lib/session-timeline-host-origin.js +0 -73
- package/agent-spine-plugin/src/lib/session-timeline-host-receipt.js +0 -117
- package/agent-spine-plugin/src/lib/session-timeline-invocation.js +0 -201
- package/agent-spine-plugin/src/lib/session-timeline-king.js +0 -93
- package/agent-spine-plugin/src/lib/session-timeline-prior.js +0 -57
- package/agent-spine-plugin/src/lib/session-timeline-provider.js +0 -36
- package/agent-spine-plugin/src/lib/session-timeline-query.js +0 -56
- package/agent-spine-plugin/src/lib/session-timeline-results.js +0 -56
- package/agent-spine-plugin/src/lib/session-timeline-root.js +0 -11
- package/agent-spine-plugin/src/lib/session-timeline-search.js +0 -82
- package/agent-spine-plugin/src/lib/session-timeline-sid-acl.js +0 -213
- package/agent-spine-plugin/src/lib/session-timeline-source-open.js +0 -30
- package/agent-spine-plugin/src/lib/session-timeline-source.js +0 -80
- package/agent-spine-plugin/src/lib/session-timeline-state.js +0 -45
- package/agent-spine-plugin/src/lib/session-timeline-transport.js +0 -42
- package/agent-spine-plugin/src/lib/session-timeline-windows-acl.js +0 -145
- package/agent-spine-plugin/src/lib/session-timeline.js +0 -462
- package/agent-spine-plugin/src/lib/sharing.js +0 -969
- package/agent-spine-plugin/src/lib/source-roots.js +0 -475
- package/agent-spine-plugin/src/lib/source-tree-scan.js +0 -178
- package/agent-spine-plugin/src/lib/sqlite-transport.js +0 -501
- package/agent-spine-plugin/src/lib/task-knowledge-context.js +0 -99
- package/agent-spine-plugin/src/lib/telegram-adapter.js +0 -119
- package/agent-spine-plugin/src/lib/timeline-continuation-update.js +0 -100
- package/agent-spine-plugin/src/lib/timeline-tool-guard.js +0 -225
- package/agent-spine-plugin/src/lib/timeline-user-feedback.js +0 -216
- package/agent-spine-plugin/src/lib/timeline-world-capture.js +0 -233
- package/agent-spine-plugin/src/lib/voice-runtime.js +0 -39
- package/agent-spine-plugin/src/lib/world-knowledge.js +0 -306
- package/agent-spine-plugin/src/lib/world-model.js +0 -333
- package/agent-spine-plugin/src/mcp.js +0 -456
- package/agent-spine-plugin/src/version.js +0 -1
- package/agent-spine-plugin/src/worker.js +0 -257
- package/bin/agentspine-king-goal-inbox.mjs +0 -127
- package/bin/agentspine-king-goal-intake.mjs +0 -106
- package/bin/agentspine-king-host-runner.mjs +0 -109
- package/bin/agentspine-king-snapshot-policy.cjs +0 -80
- package/bin/agentspine-king-status-policy.mjs +0 -226
- package/bin/agentspine-king-worker-host.mjs +0 -160
- package/bin/managed-plugin-selection.cjs +0 -141
- package/bin/verify-agent-behavior.cjs +0 -122
- package/bin/verify-agent-components.cjs +0 -104
|
@@ -1,306 +0,0 @@
|
|
|
1
|
-
import { taskKnowledgeContext } from "./task-knowledge-context.js";
|
|
2
|
-
import { validateUserFeedback } from "./timeline-user-feedback.js";
|
|
3
|
-
|
|
4
|
-
const KNOWLEDGE_KINDS = new Set([
|
|
5
|
-
"fact", "user-preference", "decision", "task-state", "error-lesson"
|
|
6
|
-
]);
|
|
7
|
-
|
|
8
|
-
const SESSION_REF = /^session-ref:[a-f0-9]{32}$/;
|
|
9
|
-
const MESSAGE_REF = /^[a-z][a-z0-9-]{0,31}:[A-Za-z0-9][A-Za-z0-9._/-]{0,190}$/;
|
|
10
|
-
const SECRET_RE = /-----BEGIN [A-Z ]*PRIVATE KEY-----|\b(?:sk[-_](?:proj[-_])?|gh[opusu]_)[A-Za-z0-9_-]{20,}\b|\b(?:xox[bapcrs]-|github_pat_|glpat-|npm_)[A-Za-z0-9_-]{12,}\b|\bAKIA[0-9A-Z]{16}\b|\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/i;
|
|
11
|
-
const TASK_CONTINUATION_SCHEMA = "agentspine.task-continuation/v1";
|
|
12
|
-
export const TIMELINE_OUTCOME_CONTRACT_SCHEMA = "agentspine.timeline-continuation-outcome-contract/v1";
|
|
13
|
-
const TASK_STATUSES = new Set(["active", "blocked", "paused", "completed"]);
|
|
14
|
-
const STEP_RESULTS = new Set(["passed", "failed", "blocked"]);
|
|
15
|
-
const STABLE_ID = /^[a-z][a-z0-9-]{0,31}:[A-Za-z0-9][A-Za-z0-9._/-]{0,190}$/;
|
|
16
|
-
const DIGEST = /^[a-f0-9]{64}$/;
|
|
17
|
-
|
|
18
|
-
function containsSecret(value) {
|
|
19
|
-
const pending = [value];
|
|
20
|
-
while (pending.length) {
|
|
21
|
-
const item = pending.pop();
|
|
22
|
-
if (typeof item === "string" && SECRET_RE.test(item)) return true;
|
|
23
|
-
if (Array.isArray(item)) pending.push(...item);
|
|
24
|
-
else if (item && typeof item === "object") pending.push(...Object.values(item));
|
|
25
|
-
}
|
|
26
|
-
return false;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
function pairedSourceRefs(sessionRef, messageRef) {
|
|
30
|
-
if ((sessionRef === null) !== (messageRef === null)) {
|
|
31
|
-
throw new Error("sessionRef and messageRef must be provided together");
|
|
32
|
-
}
|
|
33
|
-
if (sessionRef !== null && (!SESSION_REF.test(sessionRef) || !MESSAGE_REF.test(messageRef))) {
|
|
34
|
-
throw new Error("sessionRef and messageRef must be stable provenance references");
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
function exactKeys(value, expected, field) {
|
|
39
|
-
if (!value || typeof value !== "object" || Array.isArray(value)
|
|
40
|
-
|| Object.keys(value).sort().join("\0") !== [...expected].sort().join("\0")) {
|
|
41
|
-
throw new Error(`${field} has an invalid structure`);
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
function boundedText(value, field, maximum) {
|
|
46
|
-
if (typeof value !== "string" || !value.trim() || value.length > maximum) {
|
|
47
|
-
throw new Error(`${field} must be a bounded non-empty string`);
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
function validateContinuation(input, value) {
|
|
52
|
-
if (value?.schema !== TASK_CONTINUATION_SCHEMA) return;
|
|
53
|
-
exactKeys(value, ["schema", "taskId", "status", "objective", "lastVerifiedStep", "openQuestions", "nextStep"], "task continuation");
|
|
54
|
-
if (input.knowledgeKind !== "task-state" || input.predicate !== "task.continuation"
|
|
55
|
-
|| value.taskId !== input.subjectId || !STABLE_ID.test(value.taskId || "")) {
|
|
56
|
-
throw new Error("task continuation must be a task-state bound to its task subject and predicate");
|
|
57
|
-
}
|
|
58
|
-
if (input.sessionRef === undefined || input.messageRef === undefined) {
|
|
59
|
-
throw new Error("task continuation requires stable session and message source references");
|
|
60
|
-
}
|
|
61
|
-
if (!TASK_STATUSES.has(value.status)) throw new Error("task continuation status is invalid");
|
|
62
|
-
boundedText(value.objective, "task continuation objective", 500);
|
|
63
|
-
if (!Array.isArray(value.openQuestions) || value.openQuestions.length > 8) {
|
|
64
|
-
throw new Error("task continuation openQuestions must be a bounded array");
|
|
65
|
-
}
|
|
66
|
-
for (const question of value.openQuestions) {
|
|
67
|
-
exactKeys(question, ["id", "question"], "task continuation question");
|
|
68
|
-
if (!STABLE_ID.test(question.id || "")) throw new Error("task continuation question id is invalid");
|
|
69
|
-
boundedText(question.question, "task continuation question", 300);
|
|
70
|
-
}
|
|
71
|
-
if (new Set(value.openQuestions.map((item) => item.id)).size !== value.openQuestions.length) {
|
|
72
|
-
throw new Error("task continuation question ids must be unique");
|
|
73
|
-
}
|
|
74
|
-
if (value.nextStep !== null) {
|
|
75
|
-
exactKeys(value.nextStep, ["id", "summary"], "task continuation nextStep");
|
|
76
|
-
if (!STABLE_ID.test(value.nextStep.id || "")) throw new Error("task continuation next step id is invalid");
|
|
77
|
-
boundedText(value.nextStep.summary, "task continuation next step", 500);
|
|
78
|
-
}
|
|
79
|
-
if (value.lastVerifiedStep !== null) {
|
|
80
|
-
exactKeys(value.lastVerifiedStep,
|
|
81
|
-
["id", "summary", "result", "evidenceId", "evidenceDigest", "observedAt", "sessionRef", "messageRef"],
|
|
82
|
-
"task continuation lastVerifiedStep");
|
|
83
|
-
if (!STABLE_ID.test(value.lastVerifiedStep.id || "") || !STEP_RESULTS.has(value.lastVerifiedStep.result)
|
|
84
|
-
|| !STABLE_ID.test(value.lastVerifiedStep.evidenceId || "")
|
|
85
|
-
|| !DIGEST.test(value.lastVerifiedStep.evidenceDigest || "")) {
|
|
86
|
-
throw new Error("task continuation verified step evidence is invalid");
|
|
87
|
-
}
|
|
88
|
-
boundedText(value.lastVerifiedStep.summary, "task continuation verified step", 500);
|
|
89
|
-
if (new Date(value.lastVerifiedStep.observedAt).toISOString() !== value.lastVerifiedStep.observedAt
|
|
90
|
-
|| new Date(value.lastVerifiedStep.observedAt).getTime() > new Date(input.observedAt).getTime()) {
|
|
91
|
-
throw new Error("task continuation verified step timestamp is invalid");
|
|
92
|
-
}
|
|
93
|
-
pairedSourceRefs(value.lastVerifiedStep.sessionRef, value.lastVerifiedStep.messageRef);
|
|
94
|
-
}
|
|
95
|
-
if (value.status === "completed" && (value.nextStep !== null || value.openQuestions.length)) {
|
|
96
|
-
throw new Error("completed task continuation cannot retain a next step or open questions");
|
|
97
|
-
}
|
|
98
|
-
if (value.status === "completed" && value.lastVerifiedStep?.result !== "passed") {
|
|
99
|
-
throw new Error("completed task continuation requires a passed verified step");
|
|
100
|
-
}
|
|
101
|
-
if (value.status === "completed" && input.evidenceKind !== "objective-measurement") {
|
|
102
|
-
throw new Error("completed task continuation requires objective measurement evidence");
|
|
103
|
-
}
|
|
104
|
-
if (value.status === "completed") {
|
|
105
|
-
const step = value.lastVerifiedStep;
|
|
106
|
-
if (input.evidenceId !== step.evidenceId || input.evidenceDigest !== step.evidenceDigest
|
|
107
|
-
|| input.observedAt !== step.observedAt || (input.sessionRef ?? null) !== step.sessionRef
|
|
108
|
-
|| (input.messageRef ?? null) !== step.messageRef) {
|
|
109
|
-
throw new Error("completed task continuation evidence must match its passed verified step");
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
if (value.status !== "completed" && value.nextStep === null) {
|
|
113
|
-
throw new Error("resumable task continuation requires a next step");
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
function validateTimelineOutcomeContract(input, value) {
|
|
118
|
-
if (value?.schema !== TIMELINE_OUTCOME_CONTRACT_SCHEMA) return;
|
|
119
|
-
exactKeys(value, ["schema", "taskId", "step", "measurement", "onSuccess"],
|
|
120
|
-
"timeline outcome contract");
|
|
121
|
-
if (input.knowledgeKind !== "task-state" || input.predicate !== "task.timeline-outcome-contract"
|
|
122
|
-
|| value.taskId !== input.subjectId || !STABLE_ID.test(value.taskId || "")
|
|
123
|
-
|| input.privacy !== "private" || input.groupId !== null || !input.portalRef || !input.threadRef
|
|
124
|
-
|| !["explicit-user-feedback", "objective-measurement"].includes(input.evidenceKind)) {
|
|
125
|
-
throw new Error("timeline outcome contract must be a private source-bound task contract");
|
|
126
|
-
}
|
|
127
|
-
exactKeys(value.step, ["id", "summary"], "timeline outcome contract step");
|
|
128
|
-
if (!STABLE_ID.test(value.step.id || "")) throw new Error("timeline outcome contract step id is invalid");
|
|
129
|
-
boundedText(value.step.summary, "timeline outcome contract step", 500);
|
|
130
|
-
exactKeys(value.measurement, ["testLabel", "total", "successCount"],
|
|
131
|
-
"timeline outcome contract measurement");
|
|
132
|
-
const label = value.measurement.testLabel;
|
|
133
|
-
const total = value.measurement.total;
|
|
134
|
-
const successCount = value.measurement.successCount;
|
|
135
|
-
if (!/^(?:suite-(?:0|[1-9]\d{0,3})|acceptance|audit|npm-check|ci|test)$/.test(label || "")
|
|
136
|
-
|| !(total === null || Number.isSafeInteger(total) && total > 0)
|
|
137
|
-
|| !(successCount === null || Number.isSafeInteger(successCount) && successCount >= 0)
|
|
138
|
-
|| (total === null) !== (successCount === null)
|
|
139
|
-
|| (total !== null && successCount > total)) {
|
|
140
|
-
throw new Error("timeline outcome contract measurement is invalid");
|
|
141
|
-
}
|
|
142
|
-
exactKeys(value.onSuccess, ["status", "nextStep"], "timeline outcome contract success state");
|
|
143
|
-
if (!["active", "paused", "completed"].includes(value.onSuccess.status)) {
|
|
144
|
-
throw new Error("timeline outcome contract success status is invalid");
|
|
145
|
-
}
|
|
146
|
-
if (value.onSuccess.status === "completed") {
|
|
147
|
-
if (value.onSuccess.nextStep !== null) {
|
|
148
|
-
throw new Error("completed timeline outcome contract cannot define a next step");
|
|
149
|
-
}
|
|
150
|
-
} else {
|
|
151
|
-
exactKeys(value.onSuccess.nextStep, ["id", "summary"], "timeline outcome contract next step");
|
|
152
|
-
if (!STABLE_ID.test(value.onSuccess.nextStep.id || "")) {
|
|
153
|
-
throw new Error("timeline outcome contract next step id is invalid");
|
|
154
|
-
}
|
|
155
|
-
boundedText(value.onSuccess.nextStep.summary, "timeline outcome contract next step", 500);
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
export function normalizeKnowledgeFields(input, evidenceKind, value) {
|
|
160
|
-
validateUserFeedback(input, value);
|
|
161
|
-
const kind = input.knowledgeKind ?? null;
|
|
162
|
-
if (kind === null) {
|
|
163
|
-
if (input.sessionRef !== undefined || input.messageRef !== undefined) {
|
|
164
|
-
throw new Error("session references require knowledgeKind");
|
|
165
|
-
}
|
|
166
|
-
return { knowledgeKind: null, sessionRef: null, messageRef: null };
|
|
167
|
-
}
|
|
168
|
-
if (!KNOWLEDGE_KINDS.has(kind)) throw new Error("unsupported knowledgeKind");
|
|
169
|
-
if (containsSecret(value) || containsSecret(input.reason || "")) {
|
|
170
|
-
throw new Error("secret-shaped content cannot enter structured knowledge");
|
|
171
|
-
}
|
|
172
|
-
validateContinuation(input, value);
|
|
173
|
-
validateTimelineOutcomeContract(input, value);
|
|
174
|
-
if (kind === "user-preference" && !["explicit-user-feedback", "model-suggestion"].includes(evidenceKind)) {
|
|
175
|
-
throw new Error("user preferences require explicit feedback or remain a model suggestion");
|
|
176
|
-
}
|
|
177
|
-
if (kind === "decision" && !["explicit-user-feedback", "model-suggestion"].includes(evidenceKind)) {
|
|
178
|
-
throw new Error("decisions require explicit feedback or remain a model suggestion");
|
|
179
|
-
}
|
|
180
|
-
if (kind === "decision" && (typeof input.reason !== "string" || !input.reason.trim())) {
|
|
181
|
-
throw new Error("decisions require a bounded rationale");
|
|
182
|
-
}
|
|
183
|
-
const sessionRef = input.sessionRef ?? null;
|
|
184
|
-
const messageRef = input.messageRef ?? null;
|
|
185
|
-
pairedSourceRefs(sessionRef, messageRef);
|
|
186
|
-
return { knowledgeKind: kind, sessionRef, messageRef };
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
export function validKnowledgeFields(assertion) {
|
|
190
|
-
try { validateUserFeedback(assertion, assertion.value); } catch { return false; }
|
|
191
|
-
const kind = assertion.knowledgeKind ?? null;
|
|
192
|
-
if (kind === null) return assertion.sessionRef === undefined && assertion.messageRef === undefined;
|
|
193
|
-
if (!KNOWLEDGE_KINDS.has(kind)) return false;
|
|
194
|
-
if (containsSecret(assertion.value) || containsSecret(assertion.reason || "")) return false;
|
|
195
|
-
if (kind === "user-preference" && !["explicit-user-feedback", "model-suggestion"].includes(assertion.evidenceKind)) return false;
|
|
196
|
-
if (kind === "decision" && !["explicit-user-feedback", "model-suggestion"].includes(assertion.evidenceKind)) return false;
|
|
197
|
-
if (kind === "decision" && !assertion.reason) return false;
|
|
198
|
-
try {
|
|
199
|
-
validateContinuation(assertion, assertion.value);
|
|
200
|
-
validateTimelineOutcomeContract(assertion, assertion.value);
|
|
201
|
-
pairedSourceRefs(assertion.sessionRef ?? null, assertion.messageRef ?? null);
|
|
202
|
-
return true;
|
|
203
|
-
} catch {
|
|
204
|
-
return false;
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
function continuationView(entries, taskId, maxItems) {
|
|
209
|
-
const eligible = entries.filter((item) => item.kind === "task-state" && item.status === "confirmed"
|
|
210
|
-
&& item.predicate === "task.continuation" && item.value?.schema === TASK_CONTINUATION_SCHEMA
|
|
211
|
-
&& (!taskId || item.subjectId === taskId));
|
|
212
|
-
const selected = new Map();
|
|
213
|
-
for (const item of eligible) {
|
|
214
|
-
if (!selected.has(item.subjectId)) selected.set(item.subjectId, item);
|
|
215
|
-
}
|
|
216
|
-
const capsules = [...selected.values()].map((item) => ({
|
|
217
|
-
schema: TASK_CONTINUATION_SCHEMA,
|
|
218
|
-
assertionId: item.id,
|
|
219
|
-
...structuredClone(item.value),
|
|
220
|
-
source: structuredClone(item.source),
|
|
221
|
-
observedAt: item.observedAt,
|
|
222
|
-
scope: structuredClone(item.scope),
|
|
223
|
-
authority: "context-only"
|
|
224
|
-
}));
|
|
225
|
-
const limited = capsules.slice(0, Math.min(maxItems, 8));
|
|
226
|
-
return {
|
|
227
|
-
schema: "agentspine.task-continuation-context/v1",
|
|
228
|
-
tasks: limited.filter((item) => item.status !== "completed"),
|
|
229
|
-
terminal: limited.filter((item) => item.status === "completed"),
|
|
230
|
-
omitted: capsules.length - limited.length,
|
|
231
|
-
authority: "context-only",
|
|
232
|
-
note: "Continuation is descriptive context only and never grants permission, tools, delegation, or execution."
|
|
233
|
-
};
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
function publicEntry(assertion, status, statusReason) {
|
|
237
|
-
return {
|
|
238
|
-
id: assertion.id,
|
|
239
|
-
kind: assertion.knowledgeKind,
|
|
240
|
-
subjectId: assertion.subjectId,
|
|
241
|
-
predicate: assertion.predicate,
|
|
242
|
-
value: structuredClone(assertion.value),
|
|
243
|
-
status,
|
|
244
|
-
statusReason,
|
|
245
|
-
source: {
|
|
246
|
-
kind: assertion.evidenceKind,
|
|
247
|
-
id: assertion.evidenceId,
|
|
248
|
-
digest: assertion.evidenceDigest,
|
|
249
|
-
sessionRef: assertion.sessionRef ?? null,
|
|
250
|
-
messageRef: assertion.messageRef ?? null
|
|
251
|
-
},
|
|
252
|
-
observedAt: assertion.observedAt,
|
|
253
|
-
expiresAt: assertion.expiresAt,
|
|
254
|
-
recordedAt: assertion.recordedAt,
|
|
255
|
-
rationale: assertion.reason || null,
|
|
256
|
-
scope: {
|
|
257
|
-
projectId: assertion.projectId,
|
|
258
|
-
groupId: assertion.groupId,
|
|
259
|
-
privacy: assertion.privacy,
|
|
260
|
-
...(assertion.portalRef ? { portalRef: assertion.portalRef, threadRef: assertion.threadRef } : {})
|
|
261
|
-
},
|
|
262
|
-
authority: "context-only"
|
|
263
|
-
};
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
function statusFor(assertion, { staleIds, supersededIds, conflictIds }) {
|
|
267
|
-
if (staleIds.has(assertion.id)) return ["superseded", "expired"];
|
|
268
|
-
if (supersededIds.has(assertion.id)) return ["superseded", "replaced"];
|
|
269
|
-
if (assertion.status === "proposed") return ["assumption", assertion.evidenceKind];
|
|
270
|
-
if (conflictIds.has(assertion.id)) return ["contradictory", "active-conflict"];
|
|
271
|
-
return ["confirmed", "established-evidence"];
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
export function structuredKnowledgeView({
|
|
275
|
-
candidates, stale, active, supersededIds, conflictAssertions,
|
|
276
|
-
includeHistory = false, continuationTaskId = null, maxItems = 100
|
|
277
|
-
}) {
|
|
278
|
-
const staleIds = new Set(stale.map((item) => item.id));
|
|
279
|
-
const activeIds = new Set(active.map((item) => item.id));
|
|
280
|
-
const conflictIds = new Set(conflictAssertions.flatMap((items) => items.map((item) => item.id)));
|
|
281
|
-
const entries = candidates.filter((item) => item.knowledgeKind).map((assertion) => {
|
|
282
|
-
const [status, reason] = statusFor(assertion, { staleIds, supersededIds, conflictIds });
|
|
283
|
-
return publicEntry(assertion, status, reason);
|
|
284
|
-
}).sort((left, right) => right.observedAt.localeCompare(left.observedAt) || left.id.localeCompare(right.id));
|
|
285
|
-
const current = entries.filter((item) => activeIds.has(item.id));
|
|
286
|
-
const historical = entries.filter((item) => !activeIds.has(item.id));
|
|
287
|
-
const history = includeHistory ? historical : [];
|
|
288
|
-
const counts = Object.fromEntries(["confirmed", "assumption", "superseded", "contradictory"]
|
|
289
|
-
.map((status) => [status, entries.filter((item) => item.status === status).length]));
|
|
290
|
-
const continuation = continuationView(current, continuationTaskId, maxItems);
|
|
291
|
-
return {
|
|
292
|
-
schema: "agentspine.structured-knowledge/v1",
|
|
293
|
-
current: current.slice(0, maxItems),
|
|
294
|
-
history: history.slice(0, maxItems),
|
|
295
|
-
continuation,
|
|
296
|
-
taskContext: taskKnowledgeContext(current, {
|
|
297
|
-
taskId: continuationTaskId, continuation, maxItems
|
|
298
|
-
}),
|
|
299
|
-
counts,
|
|
300
|
-
omitted: {
|
|
301
|
-
current: Math.max(0, current.length - maxItems),
|
|
302
|
-
history: includeHistory ? Math.max(0, historical.length - maxItems) : historical.length
|
|
303
|
-
},
|
|
304
|
-
authority: "context-only"
|
|
305
|
-
};
|
|
306
|
-
}
|
|
@@ -1,333 +0,0 @@
|
|
|
1
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
-
import { readFile, stat, writeFile } from "node:fs/promises";
|
|
3
|
-
import { join } from "node:path";
|
|
4
|
-
import { replaceFileWithRetry } from "./filesystem-retry.js";
|
|
5
|
-
import { withOwnedFileLock } from "./owned-file-lock.js";
|
|
6
|
-
import { canonicalPath, projectStateDir } from "./paths.js";
|
|
7
|
-
|
|
8
|
-
const SCHEMA = "agentspine.world-model/v1";
|
|
9
|
-
const ASSERTION_SCHEMA = "agentspine.world-assertion/v1";
|
|
10
|
-
const MAX_STATE_BYTES = 5 * 1024 * 1024;
|
|
11
|
-
const MAX_VALUE_BYTES = 8192;
|
|
12
|
-
const EVIDENCE_KINDS = new Set([
|
|
13
|
-
"objective-measurement", "explicit-user-feedback", "model-suggestion", "uninterpreted-user-message"
|
|
14
|
-
]);
|
|
15
|
-
const PRIVACY = new Set(["private", "shared", "group"]);
|
|
16
|
-
const STABLE_ID = /^[a-z][a-z0-9-]{0,31}:[A-Za-z0-9][A-Za-z0-9._/-]{0,190}$/;
|
|
17
|
-
const PREDICATE = /^[a-z][a-z0-9.-]{0,127}$/;
|
|
18
|
-
const DIGEST = /^[a-f0-9]{64}$/;
|
|
19
|
-
const PORTAL_REF = /^portal-ref:[a-f0-9]{32}$/;
|
|
20
|
-
const THREAD_REF = /^thread-ref:[a-f0-9]{32}$/;
|
|
21
|
-
const FORBIDDEN = /(^|[-_.])(permissions?|rights?|authori[sz]ation|credentials?|secrets?|tokens?|api[-_]?keys?|delegation|tool[-_]?access|production[-_]?access|payments?|spending)([-_.]|$)/i;
|
|
22
|
-
|
|
23
|
-
function sha256(value) {
|
|
24
|
-
return createHash("sha256").update(value).digest("hex");
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
function canonicalValue(value, path = "value") {
|
|
28
|
-
if (value === null || ["string", "boolean"].includes(typeof value)) return value;
|
|
29
|
-
if (typeof value === "number") {
|
|
30
|
-
if (!Number.isFinite(value)) throw new Error(`${path} numbers must be finite`);
|
|
31
|
-
return value;
|
|
32
|
-
}
|
|
33
|
-
if (Array.isArray(value)) return value.map((item, index) => canonicalValue(item, `${path}[${index}]`));
|
|
34
|
-
if (!value || typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype) {
|
|
35
|
-
throw new Error(`${path} must be JSON data`);
|
|
36
|
-
}
|
|
37
|
-
const result = {};
|
|
38
|
-
for (const key of Object.keys(value).sort()) {
|
|
39
|
-
if (FORBIDDEN.test(key)) throw new Error(`${path}.${key} is authority data and cannot enter the world model`);
|
|
40
|
-
result[key] = canonicalValue(value[key], `${path}.${key}`);
|
|
41
|
-
}
|
|
42
|
-
return result;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
function exactTime(value, field, fallback = null) {
|
|
46
|
-
if ((value === null || value === undefined) && fallback !== null) return fallback;
|
|
47
|
-
if (typeof value !== "string" || !value) throw new Error(`${field} is required`);
|
|
48
|
-
const date = new Date(value);
|
|
49
|
-
if (!Number.isFinite(date.getTime()) || date.toISOString() !== value) {
|
|
50
|
-
throw new Error(`${field} must be an exact ISO timestamp`);
|
|
51
|
-
}
|
|
52
|
-
return value;
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
function stableId(value, field) {
|
|
56
|
-
if (typeof value !== "string" || !STABLE_ID.test(value)) throw new Error(`${field} must be a stable namespaced id`);
|
|
57
|
-
return value;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
function optionalStableId(value, field) {
|
|
61
|
-
return value === null || value === undefined ? null : stableId(value, field);
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
function routeBinding(input) {
|
|
65
|
-
const portalRef = input.portalRef ?? null;
|
|
66
|
-
const threadRef = input.threadRef ?? null;
|
|
67
|
-
if (Boolean(portalRef) !== Boolean(threadRef)) {
|
|
68
|
-
throw new Error("portalRef and threadRef must be provided together");
|
|
69
|
-
}
|
|
70
|
-
if (portalRef !== null && (!PORTAL_REF.test(portalRef) || !THREAD_REF.test(threadRef))) {
|
|
71
|
-
throw new Error("portalRef and threadRef must be opaque gateway references");
|
|
72
|
-
}
|
|
73
|
-
return portalRef ? { portalRef, threadRef } : {};
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
function sameRoute(left, right) {
|
|
77
|
-
return (left.portalRef ?? null) === (right.portalRef ?? null)
|
|
78
|
-
&& (left.threadRef ?? null) === (right.threadRef ?? null);
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
function emptyModel(root) {
|
|
82
|
-
return { schema: SCHEMA, root, revision: 0, assertions: [], events: [], authority: "context-only" };
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
function validateStoredAssertion(assertion, validKnowledgeFields) {
|
|
86
|
-
if (!assertion || assertion.schema !== ASSERTION_SCHEMA || assertion.authority !== "context-only") return false;
|
|
87
|
-
if (!STABLE_ID.test(assertion.id || "") || !STABLE_ID.test(assertion.subjectId || "")) return false;
|
|
88
|
-
if (!PREDICATE.test(assertion.predicate || "") || FORBIDDEN.test(assertion.predicate)
|
|
89
|
-
|| !EVIDENCE_KINDS.has(assertion.evidenceKind)) return false;
|
|
90
|
-
if (!PRIVACY.has(assertion.privacy) || !DIGEST.test(assertion.evidenceDigest || "")) return false;
|
|
91
|
-
if ((assertion.privacy === "group") !== Boolean(assertion.groupId)
|
|
92
|
-
|| (assertion.groupId && !STABLE_ID.test(assertion.groupId))
|
|
93
|
-
|| (assertion.projectId && !STABLE_ID.test(assertion.projectId))
|
|
94
|
-
|| Boolean(assertion.portalRef) !== Boolean(assertion.threadRef)
|
|
95
|
-
|| (assertion.portalRef && (!PORTAL_REF.test(assertion.portalRef) || !THREAD_REF.test(assertion.threadRef)))
|
|
96
|
-
|| !STABLE_ID.test(assertion.evidenceId || "") || !Array.isArray(assertion.supersedes)
|
|
97
|
-
|| assertion.supersedes.some((item) => !STABLE_ID.test(item))) return false;
|
|
98
|
-
if (!validKnowledgeFields(assertion)) return false;
|
|
99
|
-
try {
|
|
100
|
-
if (exactTime(assertion.observedAt, "observedAt") !== assertion.observedAt) return false;
|
|
101
|
-
if (assertion.expiresAt) exactTime(assertion.expiresAt, "expiresAt");
|
|
102
|
-
const value = canonicalValue(assertion.value);
|
|
103
|
-
if (sha256(JSON.stringify(value)) !== assertion.valueDigest) return false;
|
|
104
|
-
} catch {
|
|
105
|
-
return false;
|
|
106
|
-
}
|
|
107
|
-
return assertion.status === (["model-suggestion", "uninterpreted-user-message"].includes(assertion.evidenceKind)
|
|
108
|
-
? "proposed" : "established");
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
function normalizeModel(value, root, validKnowledgeFields) {
|
|
112
|
-
if (!value || value.schema !== SCHEMA || value.root !== root || value.authority !== "context-only"
|
|
113
|
-
|| !Number.isInteger(value.revision) || value.revision < 0 || !Array.isArray(value.assertions)
|
|
114
|
-
|| !Array.isArray(value.events) || value.assertions.some((item) => !validateStoredAssertion(item, validKnowledgeFields))
|
|
115
|
-
|| value.events.some((item) => !item || item.authority !== "context-only")) {
|
|
116
|
-
throw new Error("world model state is invalid");
|
|
117
|
-
}
|
|
118
|
-
return value;
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
async function stateNames(root) {
|
|
122
|
-
const canonicalRoot = await canonicalPath(root);
|
|
123
|
-
const directory = await projectStateDir(canonicalRoot);
|
|
124
|
-
const path = join(directory, "world-model.json");
|
|
125
|
-
return { root: canonicalRoot, path, lockPath: `${path}.lock` };
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
async function readModel(names) {
|
|
129
|
-
try {
|
|
130
|
-
const metadata = await stat(names.path);
|
|
131
|
-
if (metadata.size > MAX_STATE_BYTES) throw new Error("world model exceeds the 5 MiB read limit");
|
|
132
|
-
const { validKnowledgeFields } = await import("./world-knowledge.js");
|
|
133
|
-
return normalizeModel(JSON.parse(await readFile(names.path, "utf8")), names.root, validKnowledgeFields);
|
|
134
|
-
} catch (error) {
|
|
135
|
-
if (error.code === "ENOENT") return emptyModel(names.root);
|
|
136
|
-
if (error instanceof SyntaxError) throw new Error("world model state is not valid JSON");
|
|
137
|
-
throw error;
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
async function writeModel(model, names, assertOwned) {
|
|
142
|
-
const content = `${JSON.stringify(model, null, 2)}\n`;
|
|
143
|
-
if (Buffer.byteLength(content) > MAX_STATE_BYTES) throw new Error("world model exceeds 5 MiB");
|
|
144
|
-
const temporary = `${names.path}.${process.pid}.${randomUUID()}.tmp`;
|
|
145
|
-
await writeFile(temporary, content, { mode: 0o600 });
|
|
146
|
-
await replaceFileWithRetry(temporary, names.path, { beforeAttempt: assertOwned });
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
function assertionInput(input, now, normalizeKnowledgeFields) {
|
|
150
|
-
const id = stableId(input.id, "id");
|
|
151
|
-
const subjectId = stableId(input.subjectId, "subjectId");
|
|
152
|
-
if (typeof input.predicate !== "string" || !PREDICATE.test(input.predicate)) {
|
|
153
|
-
throw new Error("predicate must be a lowercase dotted key");
|
|
154
|
-
}
|
|
155
|
-
if (FORBIDDEN.test(input.predicate)) throw new Error("authority predicates cannot enter the world model");
|
|
156
|
-
if (!EVIDENCE_KINDS.has(input.evidenceKind)) throw new Error("unsupported evidenceKind");
|
|
157
|
-
const evidenceId = stableId(input.evidenceId, "evidenceId");
|
|
158
|
-
if (!DIGEST.test(input.evidenceDigest || "")) throw new Error("evidenceDigest must be a lowercase SHA-256 digest");
|
|
159
|
-
const observedAt = exactTime(input.observedAt, "observedAt");
|
|
160
|
-
const nowTime = new Date(now).getTime();
|
|
161
|
-
if (new Date(observedAt).getTime() > nowTime) throw new Error("observedAt cannot be in the future");
|
|
162
|
-
const expiresAt = input.expiresAt === null || input.expiresAt === undefined
|
|
163
|
-
? null : exactTime(input.expiresAt, "expiresAt");
|
|
164
|
-
if (expiresAt && new Date(expiresAt).getTime() <= new Date(observedAt).getTime()) {
|
|
165
|
-
throw new Error("expiresAt must be after observedAt");
|
|
166
|
-
}
|
|
167
|
-
const privacy = input.privacy || "private";
|
|
168
|
-
if (!PRIVACY.has(privacy)) throw new Error("unsupported privacy");
|
|
169
|
-
const groupId = optionalStableId(input.groupId, "groupId");
|
|
170
|
-
if ((privacy === "group") !== Boolean(groupId)) throw new Error("group privacy requires exactly one groupId");
|
|
171
|
-
const value = canonicalValue(input.value);
|
|
172
|
-
if (Buffer.byteLength(JSON.stringify(value)) > MAX_VALUE_BYTES) throw new Error("value exceeds 8 KiB");
|
|
173
|
-
const supersedes = [...new Set((input.supersedes || []).map((item) => stableId(item, "supersedes")))].sort();
|
|
174
|
-
const knowledge = normalizeKnowledgeFields(input, input.evidenceKind, value);
|
|
175
|
-
return {
|
|
176
|
-
schema: ASSERTION_SCHEMA, id, subjectId, predicate: input.predicate, value,
|
|
177
|
-
valueDigest: sha256(JSON.stringify(value)), evidenceKind: input.evidenceKind,
|
|
178
|
-
evidenceId, evidenceDigest: input.evidenceDigest, observedAt, expiresAt,
|
|
179
|
-
projectId: optionalStableId(input.projectId, "projectId"), groupId, privacy,
|
|
180
|
-
supersedes, reason: typeof input.reason === "string" ? input.reason.trim().slice(0, 500) : "",
|
|
181
|
-
status: ["model-suggestion", "uninterpreted-user-message"].includes(input.evidenceKind) ? "proposed" : "established",
|
|
182
|
-
recordedAt: new Date(now).toISOString(), authority: "context-only",
|
|
183
|
-
...routeBinding(input),
|
|
184
|
-
...(knowledge.knowledgeKind ? knowledge : {})
|
|
185
|
-
};
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
function assertionDigest(assertion) {
|
|
189
|
-
const { recordedAt: _recordedAt, ...material } = assertion;
|
|
190
|
-
return sha256(JSON.stringify(material));
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
export async function recordWorldAssertion(input = {}) {
|
|
194
|
-
const now = input.now || new Date();
|
|
195
|
-
const { normalizeKnowledgeFields } = await import("./world-knowledge.js");
|
|
196
|
-
const candidate = assertionInput(input, now, normalizeKnowledgeFields);
|
|
197
|
-
const names = await stateNames(input.root || process.cwd());
|
|
198
|
-
return withOwnedFileLock(names.lockPath, async ({ assertOwned }) => {
|
|
199
|
-
const model = await readModel(names);
|
|
200
|
-
const existing = model.assertions.find((item) => item.id === candidate.id);
|
|
201
|
-
if (existing) {
|
|
202
|
-
if (assertionDigest(existing) !== assertionDigest(candidate)) throw new Error(`world assertion id is already used: ${candidate.id}`);
|
|
203
|
-
return { status: "duplicate", assertion: structuredClone(existing), revision: model.revision, authority: "context-only" };
|
|
204
|
-
}
|
|
205
|
-
if (input.requireActiveSupersedes === true) {
|
|
206
|
-
if (!candidate.supersedes.length) throw new Error("active supersession requires at least one assertion");
|
|
207
|
-
const cutoff = new Date(now).getTime();
|
|
208
|
-
const live = model.assertions.filter((item) => item.status === "established"
|
|
209
|
-
&& item.subjectId === candidate.subjectId && item.predicate === candidate.predicate
|
|
210
|
-
&& item.projectId === candidate.projectId && item.groupId === candidate.groupId
|
|
211
|
-
&& item.privacy === candidate.privacy && sameRoute(item, candidate)
|
|
212
|
-
&& (!item.expiresAt || new Date(item.expiresAt).getTime() > cutoff));
|
|
213
|
-
const replaced = new Set(live.flatMap((item) => item.supersedes));
|
|
214
|
-
const activeIds = live.filter((item) => !replaced.has(item.id)).map((item) => item.id).sort();
|
|
215
|
-
if (activeIds.join("\0") !== candidate.supersedes.join("\0")) {
|
|
216
|
-
throw new Error("active supersession compare-and-swap failed");
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
for (const id of candidate.supersedes) {
|
|
220
|
-
const previous = model.assertions.find((item) => item.id === id);
|
|
221
|
-
if (!previous) throw new Error(`superseded assertion does not exist: ${id}`);
|
|
222
|
-
if (previous.subjectId !== candidate.subjectId || previous.predicate !== candidate.predicate) {
|
|
223
|
-
throw new Error("supersession must keep the same subject and predicate");
|
|
224
|
-
}
|
|
225
|
-
if (!sameRoute(previous, candidate)) {
|
|
226
|
-
throw new Error("supersession must keep the same portal and thread scope");
|
|
227
|
-
}
|
|
228
|
-
if (candidate.status !== "established") throw new Error("model suggestions cannot supersede established context");
|
|
229
|
-
}
|
|
230
|
-
model.revision += 1;
|
|
231
|
-
model.assertions.push(candidate);
|
|
232
|
-
model.events.push({ kind: candidate.supersedes.length ? "resolved" : "recorded", assertionId: candidate.id,
|
|
233
|
-
supersedes: candidate.supersedes, at: candidate.recordedAt, authority: "context-only" });
|
|
234
|
-
await writeModel(model, names, assertOwned);
|
|
235
|
-
return { status: "recorded", assertion: structuredClone(candidate), revision: model.revision, authority: "context-only" };
|
|
236
|
-
});
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
function visible(assertion, { includePrivate, groupId, projectId, portalRef, threadRef, continuationTaskId }) {
|
|
240
|
-
if (assertion.privacy === "private" && (!includePrivate || groupId)) return false;
|
|
241
|
-
if (assertion.privacy === "group" && assertion.groupId !== groupId) return false;
|
|
242
|
-
if (assertion.projectId !== null && assertion.projectId !== projectId) return false;
|
|
243
|
-
const currentRoute = Boolean(portalRef && threadRef);
|
|
244
|
-
const assertionRoute = Boolean(assertion.portalRef && assertion.threadRef);
|
|
245
|
-
if (assertionRoute) return currentRoute && sameRoute(assertion, { portalRef, threadRef });
|
|
246
|
-
// A portal-bound task must not silently inherit an older unbound checkpoint
|
|
247
|
-
// or task-local correction. General user/project knowledge remains portable.
|
|
248
|
-
if (currentRoute && continuationTaskId && assertion.knowledgeKind
|
|
249
|
-
&& assertion.subjectId === continuationTaskId) return false;
|
|
250
|
-
return true;
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
function publicAssertion(assertion) {
|
|
254
|
-
return structuredClone(assertion);
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
export async function worldContext({
|
|
258
|
-
root = process.cwd(), subjectId = null, projectId = null, groupId = null,
|
|
259
|
-
includePrivate = false, includeKnowledgeHistory = false, continuationTaskId = null,
|
|
260
|
-
portalRef = null, threadRef = null, maxItems = 100, now = new Date()
|
|
261
|
-
} = {}) {
|
|
262
|
-
if (groupId !== null && includePrivate) throw new Error("private world context cannot be assembled for a group audience");
|
|
263
|
-
if (!Number.isInteger(maxItems) || maxItems < 1 || maxItems > 500) throw new Error("maxItems must be between 1 and 500");
|
|
264
|
-
subjectId = optionalStableId(subjectId, "subjectId");
|
|
265
|
-
projectId = optionalStableId(projectId, "projectId");
|
|
266
|
-
groupId = optionalStableId(groupId, "groupId");
|
|
267
|
-
continuationTaskId = optionalStableId(continuationTaskId, "continuationTaskId");
|
|
268
|
-
({ portalRef = null, threadRef = null } = routeBinding({ portalRef, threadRef }));
|
|
269
|
-
const names = await stateNames(root);
|
|
270
|
-
const model = await readModel(names);
|
|
271
|
-
const { structuredKnowledgeView } = await import("./world-knowledge.js");
|
|
272
|
-
const cutoff = new Date(now).getTime();
|
|
273
|
-
if (!Number.isFinite(cutoff)) throw new Error("now is invalid");
|
|
274
|
-
const candidates = model.assertions.filter((item) => visible(item, {
|
|
275
|
-
includePrivate, groupId, projectId, portalRef, threadRef, continuationTaskId
|
|
276
|
-
})
|
|
277
|
-
&& (!subjectId || item.subjectId === subjectId));
|
|
278
|
-
const stale = candidates.filter((item) => item.expiresAt && new Date(item.expiresAt).getTime() <= cutoff);
|
|
279
|
-
const current = candidates.filter((item) => !item.expiresAt || new Date(item.expiresAt).getTime() > cutoff);
|
|
280
|
-
const superseded = new Set(current.flatMap((item) => item.status === "established" ? item.supersedes : []));
|
|
281
|
-
const active = current.filter((item) => !superseded.has(item.id));
|
|
282
|
-
const proposals = active.filter((item) => item.status === "proposed");
|
|
283
|
-
const established = active.filter((item) => item.status === "established");
|
|
284
|
-
const buckets = new Map();
|
|
285
|
-
for (const item of established) {
|
|
286
|
-
const key = `${item.subjectId}\0${item.predicate}`;
|
|
287
|
-
if (!buckets.has(key)) buckets.set(key, []);
|
|
288
|
-
buckets.get(key).push(item);
|
|
289
|
-
}
|
|
290
|
-
const facts = [];
|
|
291
|
-
const conflicts = [];
|
|
292
|
-
const conflictAssertions = [];
|
|
293
|
-
for (const assertions of buckets.values()) {
|
|
294
|
-
const values = new Set(assertions.map((item) => item.valueDigest));
|
|
295
|
-
if (values.size > 1) {
|
|
296
|
-
conflictAssertions.push(assertions);
|
|
297
|
-
conflicts.push({ subjectId: assertions[0].subjectId, predicate: assertions[0].predicate,
|
|
298
|
-
assertions: assertions.map(publicAssertion), authority: "context-only" });
|
|
299
|
-
continue;
|
|
300
|
-
}
|
|
301
|
-
const newest = [...assertions].sort((a, b) => b.observedAt.localeCompare(a.observedAt))[0];
|
|
302
|
-
facts.push({ subjectId: newest.subjectId, predicate: newest.predicate, value: structuredClone(newest.value),
|
|
303
|
-
assertionIds: assertions.map((item) => item.id).sort(), evidenceKinds: [...new Set(assertions.map((item) => item.evidenceKind))].sort(),
|
|
304
|
-
latestObservedAt: newest.observedAt, expiresAt: newest.expiresAt, privacy: newest.privacy,
|
|
305
|
-
groupId: newest.groupId, projectId: newest.projectId,
|
|
306
|
-
...(newest.portalRef ? { portalRef: newest.portalRef, threadRef: newest.threadRef } : {}),
|
|
307
|
-
authority: "context-only" });
|
|
308
|
-
}
|
|
309
|
-
const order = (left, right) => left.subjectId.localeCompare(right.subjectId) || left.predicate.localeCompare(right.predicate);
|
|
310
|
-
facts.sort(order); conflicts.sort(order); proposals.sort(order); stale.sort(order);
|
|
311
|
-
const knowledge = structuredKnowledgeView({
|
|
312
|
-
candidates, stale, active, supersededIds: superseded, conflictAssertions,
|
|
313
|
-
includeHistory: Boolean(includeKnowledgeHistory), continuationTaskId, maxItems
|
|
314
|
-
});
|
|
315
|
-
return {
|
|
316
|
-
schema: "agentspine.world-context/v1", root: names.root, revision: model.revision,
|
|
317
|
-
scope: { projectId, groupId, includePrivate,
|
|
318
|
-
...(portalRef ? { portalRef, threadRef } : {}) },
|
|
319
|
-
facts: facts.slice(0, maxItems), conflicts: conflicts.slice(0, maxItems),
|
|
320
|
-
proposals: proposals.slice(0, maxItems).map(publicAssertion), stale: stale.slice(0, maxItems).map(publicAssertion),
|
|
321
|
-
knowledge,
|
|
322
|
-
omitted: { facts: Math.max(0, facts.length - maxItems), conflicts: Math.max(0, conflicts.length - maxItems),
|
|
323
|
-
proposals: Math.max(0, proposals.length - maxItems), stale: Math.max(0, stale.length - maxItems) },
|
|
324
|
-
uncertainty: { requiresResolution: conflicts.length > 0, conflicts: conflicts.length,
|
|
325
|
-
proposals: proposals.length, stale: stale.length },
|
|
326
|
-
authority: "context-only",
|
|
327
|
-
note: "Only unexpired, non-conflicting measured or explicitly user-confirmed assertions are facts. Model suggestions and uninterpreted user messages remain proposals and grant no authority."
|
|
328
|
-
};
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
export async function worldModelStatePath(root = process.cwd()) {
|
|
332
|
-
return (await stateNames(root)).path;
|
|
333
|
-
}
|