sentinelayer-cli 0.6.2 → 0.8.1
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/README.md +1009 -996
- package/bin/create-sentinelayer.js +5 -5
- package/bin/sentinelayer-cli.js +4 -4
- package/bin/sl.js +5 -5
- package/package.json +64 -63
- package/src/agents/ai-governance/index.js +12 -0
- package/src/agents/ai-governance/tools/base.js +171 -0
- package/src/agents/ai-governance/tools/eval-regression.js +47 -0
- package/src/agents/ai-governance/tools/hitl-audit.js +81 -0
- package/src/agents/ai-governance/tools/index.js +52 -0
- package/src/agents/ai-governance/tools/prompt-drift.js +42 -0
- package/src/agents/ai-governance/tools/provenance-check.js +69 -0
- package/src/agents/backend/index.js +12 -0
- package/src/agents/backend/tools/base.js +189 -0
- package/src/agents/backend/tools/circuit-breaker-check.js +123 -0
- package/src/agents/backend/tools/idempotency-audit.js +105 -0
- package/src/agents/backend/tools/index.js +87 -0
- package/src/agents/backend/tools/retry-audit.js +132 -0
- package/src/agents/backend/tools/timeout-audit.js +144 -0
- package/src/agents/code-quality/index.js +12 -0
- package/src/agents/code-quality/tools/base.js +159 -0
- package/src/agents/code-quality/tools/complexity-measure.js +197 -0
- package/src/agents/code-quality/tools/coupling-analysis.js +81 -0
- package/src/agents/code-quality/tools/cycle-detect.js +49 -0
- package/src/agents/code-quality/tools/dep-graph.js +196 -0
- package/src/agents/code-quality/tools/index.js +89 -0
- package/src/agents/data-layer/index.js +12 -0
- package/src/agents/data-layer/tools/base.js +181 -0
- package/src/agents/data-layer/tools/index-audit.js +165 -0
- package/src/agents/data-layer/tools/index.js +83 -0
- package/src/agents/data-layer/tools/migration-scan.js +135 -0
- package/src/agents/data-layer/tools/query-explain.js +120 -0
- package/src/agents/data-layer/tools/tenancy-scan.js +166 -0
- package/src/agents/documentation/index.js +12 -0
- package/src/agents/documentation/tools/api-diff.js +91 -0
- package/src/agents/documentation/tools/base.js +151 -0
- package/src/agents/documentation/tools/dead-link-check.js +58 -0
- package/src/agents/documentation/tools/docstring-coverage.js +78 -0
- package/src/agents/documentation/tools/index.js +52 -0
- package/src/agents/documentation/tools/readme-freshness.js +61 -0
- package/src/agents/envelope/fix-cycle.js +45 -0
- package/src/agents/envelope/index.js +31 -0
- package/src/agents/envelope/loop.js +150 -0
- package/src/agents/envelope/pulse.js +18 -0
- package/src/agents/envelope/stream.js +40 -0
- package/src/agents/infrastructure/index.js +12 -0
- package/src/agents/infrastructure/tools/base.js +171 -0
- package/src/agents/infrastructure/tools/checkov-run.js +32 -0
- package/src/agents/infrastructure/tools/drift-detect.js +59 -0
- package/src/agents/infrastructure/tools/iam-least-priv-check.js +78 -0
- package/src/agents/infrastructure/tools/index.js +52 -0
- package/src/agents/infrastructure/tools/tflint-run.js +31 -0
- package/src/agents/jules/config/definition.js +160 -160
- package/src/agents/jules/config/system-prompt.js +182 -182
- package/src/agents/jules/error-intake.js +51 -51
- package/src/agents/jules/fix-cycle.js +17 -17
- package/src/agents/jules/loop.js +460 -450
- package/src/agents/jules/pulse.js +10 -10
- package/src/agents/jules/stream.js +187 -186
- package/src/agents/jules/swarm/file-scanner.js +74 -74
- package/src/agents/jules/swarm/index.js +11 -11
- package/src/agents/jules/swarm/orchestrator.js +362 -362
- package/src/agents/jules/swarm/pattern-hunter.js +123 -123
- package/src/agents/jules/swarm/sub-agent.js +315 -309
- package/src/agents/jules/tools/aidenid-email.js +189 -189
- package/src/agents/jules/tools/auth-audit.js +1708 -1691
- package/src/agents/jules/tools/dispatch.js +340 -335
- package/src/agents/jules/tools/file-edit.js +2 -2
- package/src/agents/jules/tools/file-read.js +2 -2
- package/src/agents/jules/tools/frontend-analyze.js +570 -570
- package/src/agents/jules/tools/glob.js +2 -2
- package/src/agents/jules/tools/grep.js +2 -2
- package/src/agents/jules/tools/index.js +29 -29
- package/src/agents/jules/tools/path-guards.js +2 -2
- package/src/agents/jules/tools/runtime-audit.js +507 -507
- package/src/agents/jules/tools/shell.js +2 -2
- package/src/agents/jules/tools/url-policy.js +100 -100
- package/src/agents/mode.js +113 -0
- package/src/agents/observability/index.js +12 -0
- package/src/agents/observability/tools/alert-audit.js +39 -0
- package/src/agents/observability/tools/base.js +181 -0
- package/src/agents/observability/tools/dashboard-gap.js +42 -0
- package/src/agents/observability/tools/index.js +54 -0
- package/src/agents/observability/tools/log-schema-check.js +74 -0
- package/src/agents/observability/tools/span-coverage.js +74 -0
- package/src/agents/persona-visuals.js +102 -61
- package/src/agents/release/index.js +12 -0
- package/src/agents/release/tools/base.js +181 -0
- package/src/agents/release/tools/changelog-diff.js +86 -0
- package/src/agents/release/tools/feature-flag-audit.js +126 -0
- package/src/agents/release/tools/index.js +61 -0
- package/src/agents/release/tools/rollback-verify.js +129 -0
- package/src/agents/release/tools/semver-check.js +109 -0
- package/src/agents/reliability/index.js +12 -0
- package/src/agents/reliability/tools/backpressure-check.js +129 -0
- package/src/agents/reliability/tools/base.js +181 -0
- package/src/agents/reliability/tools/chaos-probe.js +109 -0
- package/src/agents/reliability/tools/graceful-degradation-check.js +114 -0
- package/src/agents/reliability/tools/health-check-audit.js +111 -0
- package/src/agents/reliability/tools/index.js +87 -0
- package/src/agents/run-persona.js +109 -0
- package/src/agents/security/index.js +12 -0
- package/src/agents/security/tools/authz-audit.js +134 -0
- package/src/agents/security/tools/base.js +190 -0
- package/src/agents/security/tools/crypto-review.js +175 -0
- package/src/agents/security/tools/index.js +97 -0
- package/src/agents/security/tools/sast-scan.js +175 -0
- package/src/agents/security/tools/secrets-scan.js +216 -0
- package/src/agents/shared-tools/dispatch-core.js +320 -315
- package/src/agents/shared-tools/file-edit.js +180 -180
- package/src/agents/shared-tools/file-read.js +100 -100
- package/src/agents/shared-tools/glob.js +168 -168
- package/src/agents/shared-tools/grep.js +228 -228
- package/src/agents/shared-tools/index.js +46 -46
- package/src/agents/shared-tools/path-guards.js +161 -161
- package/src/agents/shared-tools/shell.js +383 -383
- package/src/agents/supply-chain/index.js +12 -0
- package/src/agents/supply-chain/tools/attestation-check.js +42 -0
- package/src/agents/supply-chain/tools/base.js +151 -0
- package/src/agents/supply-chain/tools/index.js +52 -0
- package/src/agents/supply-chain/tools/lockfile-integrity.js +73 -0
- package/src/agents/supply-chain/tools/package-verify.js +56 -0
- package/src/agents/supply-chain/tools/sbom-diff.js +34 -0
- package/src/agents/testing/index.js +12 -0
- package/src/agents/testing/tools/base.js +202 -0
- package/src/agents/testing/tools/coverage-gap.js +144 -0
- package/src/agents/testing/tools/flake-detect.js +125 -0
- package/src/agents/testing/tools/index.js +85 -0
- package/src/agents/testing/tools/mutation-test.js +143 -0
- package/src/agents/testing/tools/snapshot-diff.js +103 -0
- package/src/ai/aidenid.js +1021 -1009
- package/src/ai/client.js +553 -553
- package/src/ai/domain-target-store.js +268 -268
- package/src/ai/identity-store.js +270 -270
- package/src/ai/proxy.js +137 -137
- package/src/ai/site-store.js +145 -145
- package/src/audit/agents/architecture.js +180 -180
- package/src/audit/agents/compliance.js +179 -179
- package/src/audit/agents/documentation.js +165 -165
- package/src/audit/agents/performance.js +145 -145
- package/src/audit/agents/security.js +215 -215
- package/src/audit/agents/testing.js +172 -172
- package/src/audit/orchestrator.js +557 -557
- package/src/audit/package.js +204 -204
- package/src/audit/registry.js +284 -284
- package/src/audit/replay.js +103 -103
- package/src/auth/gate.js +428 -371
- package/src/auth/http.js +681 -611
- package/src/auth/service.js +1106 -1106
- package/src/auth/session-store.js +813 -813
- package/src/cli.js +257 -252
- package/src/commands/ai/identity-lifecycle.js +1338 -1338
- package/src/commands/ai/provision-governance.js +1272 -1272
- package/src/commands/ai/shared.js +147 -147
- package/src/commands/ai.js +11 -11
- package/src/commands/apply.js +12 -12
- package/src/commands/audit.js +1171 -1166
- package/src/commands/auth.js +419 -419
- package/src/commands/chat.js +184 -191
- package/src/commands/config.js +184 -184
- package/src/commands/cost.js +311 -311
- package/src/commands/daemon/core.js +850 -850
- package/src/commands/daemon/extended.js +1048 -1048
- package/src/commands/daemon/shared.js +213 -213
- package/src/commands/daemon.js +11 -11
- package/src/commands/guide.js +174 -174
- package/src/commands/ingest.js +58 -58
- package/src/commands/init.js +55 -55
- package/src/commands/legacy-args.js +20 -10
- package/src/commands/mcp.js +461 -461
- package/src/commands/omargate.js +63 -29
- package/src/commands/persona.js +65 -20
- package/src/commands/plugin.js +260 -260
- package/src/commands/policy.js +132 -132
- package/src/commands/prompt.js +238 -238
- package/src/commands/review.js +704 -704
- package/src/commands/scan.js +865 -872
- package/src/commands/session.js +1238 -0
- package/src/commands/spec.js +771 -716
- package/src/commands/swarm.js +651 -651
- package/src/commands/telemetry.js +202 -202
- package/src/commands/watch.js +511 -511
- package/src/config/agent-dictionary.js +182 -182
- package/src/config/io.js +56 -56
- package/src/config/paths.js +18 -18
- package/src/config/schema.js +55 -55
- package/src/config/service.js +184 -184
- package/src/coord/events-log.js +141 -0
- package/src/coord/handshake.js +719 -0
- package/src/coord/index.js +35 -0
- package/src/coord/paths.js +84 -0
- package/src/coord/priority.js +62 -0
- package/src/coord/tarjan.js +157 -0
- package/src/cost/budget.js +235 -235
- package/src/cost/history.js +188 -188
- package/src/cost/tokenizer.js +160 -0
- package/src/cost/tracker.js +232 -171
- package/src/daemon/artifact-lineage.js +896 -534
- package/src/daemon/assignment-ledger.js +1083 -770
- package/src/daemon/ast-drift.js +496 -0
- package/src/daemon/ast-parser-layer.js +258 -258
- package/src/daemon/budget-governor.js +633 -633
- package/src/daemon/callgraph-overlay.js +646 -646
- package/src/daemon/error-worker.js +1209 -626
- package/src/daemon/fix-cycle.js +384 -377
- package/src/daemon/hybrid-mapper.js +929 -929
- package/src/daemon/ingest-refresh.js +79 -11
- package/src/daemon/jira-lifecycle.js +767 -632
- package/src/daemon/operator-control.js +657 -657
- package/src/daemon/pulse.js +327 -327
- package/src/daemon/reliability-lane.js +471 -471
- package/src/daemon/scope-engine.js +1068 -0
- package/src/daemon/watchdog.js +971 -971
- package/src/events/schema.js +190 -0
- package/src/guide/generator.js +316 -316
- package/src/ingest/engine.js +933 -918
- package/src/ingest/ownership.js +380 -0
- package/src/interactive/index.js +97 -97
- package/src/legacy-cli.js +3228 -2994
- package/src/mcp/registry.js +695 -695
- package/src/memory/blackboard.js +301 -301
- package/src/memory/retrieval.js +581 -581
- package/src/orchestrator/kai-chen.js +126 -0
- package/src/plugin/manifest.js +553 -553
- package/src/policy/packs.js +144 -144
- package/src/prompt/generator.js +136 -118
- package/src/review/ai-review.js +672 -679
- package/src/review/compliance-pack.js +389 -0
- package/src/review/investor-dd-config.js +54 -0
- package/src/review/investor-dd-file-loop.js +303 -0
- package/src/review/investor-dd-file-router.js +406 -0
- package/src/review/investor-dd-html-report.js +233 -0
- package/src/review/investor-dd-notification.js +120 -0
- package/src/review/investor-dd-orchestrator.js +405 -0
- package/src/review/investor-dd-persona-runner.js +275 -0
- package/src/review/live-validator.js +253 -0
- package/src/review/local-review.js +1351 -1305
- package/src/review/omargate-interactive.js +68 -68
- package/src/review/omargate-orchestrator.js +492 -300
- package/src/review/persona-prompts.js +484 -296
- package/src/review/reconciliation-rules.js +329 -0
- package/src/review/replay.js +235 -235
- package/src/review/report.js +664 -664
- package/src/review/reproducibility-chain.js +136 -0
- package/src/review/scan-modes.js +147 -42
- package/src/review/spec-binding.js +487 -487
- package/src/scaffold/generator.js +67 -67
- package/src/scaffold/templates.js +150 -150
- package/src/scan/generator.js +418 -418
- package/src/scan/gh-secrets.js +107 -107
- package/src/session/agent-registry.js +359 -0
- package/src/session/analytics.js +479 -0
- package/src/session/daemon.js +1396 -0
- package/src/session/file-locks.js +666 -0
- package/src/session/paths.js +37 -0
- package/src/session/recap.js +567 -0
- package/src/session/redact.js +82 -0
- package/src/session/runtime-bridge.js +762 -0
- package/src/session/scoring.js +406 -0
- package/src/session/setup-guides.js +304 -0
- package/src/session/store.js +704 -0
- package/src/session/stream.js +333 -0
- package/src/session/sync.js +753 -0
- package/src/session/tasks.js +1054 -0
- package/src/session/templates.js +188 -0
- package/src/spec/generator.js +619 -519
- package/src/spec/regenerate.js +237 -237
- package/src/spec/templates.js +91 -91
- package/src/swarm/dashboard.js +247 -247
- package/src/swarm/factory.js +363 -363
- package/src/swarm/pentest.js +934 -934
- package/src/swarm/registry.js +419 -419
- package/src/swarm/report.js +158 -158
- package/src/swarm/runtime.js +569 -576
- package/src/swarm/scenario-dsl.js +272 -272
- package/src/telemetry/ledger.js +302 -302
- package/src/telemetry/session-tracker.js +234 -234
- package/src/telemetry/sync.js +203 -203
- package/src/ui/command-hints.js +13 -13
- package/src/ui/markdown.js +220 -220
|
@@ -0,0 +1,704 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import fsp from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import process from "node:process";
|
|
5
|
+
|
|
6
|
+
import { buildArtifactLineageIndex, verifyArtifactChain } from "../daemon/artifact-lineage.js";
|
|
7
|
+
import { collectCodebaseIngest } from "../ingest/engine.js";
|
|
8
|
+
import { computeSessionAnalytics } from "./analytics.js";
|
|
9
|
+
import { resolveSessionPaths, resolveSessionsRoot } from "./paths.js";
|
|
10
|
+
import { appendToStream } from "./stream.js";
|
|
11
|
+
|
|
12
|
+
const SESSION_SCHEMA_VERSION = "1.0.0";
|
|
13
|
+
const DEFAULT_TTL_SECONDS = 24 * 60 * 60;
|
|
14
|
+
const RENEWAL_SECONDS = 24 * 60 * 60;
|
|
15
|
+
const MAX_SESSION_LIFETIME_SECONDS = 72 * 60 * 60;
|
|
16
|
+
const SESSION_STATUS_ACTIVE = "active";
|
|
17
|
+
const SESSION_STATUS_EXPIRED = "expired";
|
|
18
|
+
const SESSION_STATUS_ARCHIVED = "archived";
|
|
19
|
+
|
|
20
|
+
function normalizeString(value) {
|
|
21
|
+
return String(value || "").trim();
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function normalizePositiveInteger(value, fallbackValue) {
|
|
25
|
+
if (value === undefined || value === null || normalizeString(value) === "") {
|
|
26
|
+
return fallbackValue;
|
|
27
|
+
}
|
|
28
|
+
const normalized = Number(value);
|
|
29
|
+
if (!Number.isFinite(normalized) || normalized <= 0) {
|
|
30
|
+
throw new Error("Value must be a positive integer.");
|
|
31
|
+
}
|
|
32
|
+
return Math.floor(normalized);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function normalizeNonNegativeInteger(value, fallbackValue = 0) {
|
|
36
|
+
if (value === undefined || value === null || normalizeString(value) === "") {
|
|
37
|
+
return fallbackValue;
|
|
38
|
+
}
|
|
39
|
+
const normalized = Number(value);
|
|
40
|
+
if (!Number.isFinite(normalized) || normalized < 0) {
|
|
41
|
+
return fallbackValue;
|
|
42
|
+
}
|
|
43
|
+
return Math.floor(normalized);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function normalizeIsoTimestamp(value, fallbackIso = new Date().toISOString()) {
|
|
47
|
+
const normalized = normalizeString(value);
|
|
48
|
+
if (!normalized) {
|
|
49
|
+
return fallbackIso;
|
|
50
|
+
}
|
|
51
|
+
const epoch = Date.parse(normalized);
|
|
52
|
+
if (!Number.isFinite(epoch)) {
|
|
53
|
+
return fallbackIso;
|
|
54
|
+
}
|
|
55
|
+
return new Date(epoch).toISOString();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function toIsoAfterSeconds(nowIso, seconds) {
|
|
59
|
+
const nowEpoch = Date.parse(normalizeIsoTimestamp(nowIso));
|
|
60
|
+
return new Date(nowEpoch + seconds * 1000).toISOString();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function buildElapsedTimer(fromIso, nowIso = new Date().toISOString()) {
|
|
64
|
+
const fromEpoch = Date.parse(normalizeIsoTimestamp(fromIso, nowIso));
|
|
65
|
+
const nowEpoch = Date.parse(normalizeIsoTimestamp(nowIso, new Date().toISOString()));
|
|
66
|
+
if (!Number.isFinite(fromEpoch) || !Number.isFinite(nowEpoch) || nowEpoch <= fromEpoch) {
|
|
67
|
+
return "0m";
|
|
68
|
+
}
|
|
69
|
+
const totalSeconds = Math.floor((nowEpoch - fromEpoch) / 1000);
|
|
70
|
+
const totalMinutes = Math.floor(totalSeconds / 60);
|
|
71
|
+
const hours = Math.floor(totalMinutes / 60);
|
|
72
|
+
const minutes = totalMinutes % 60;
|
|
73
|
+
if (hours <= 0) {
|
|
74
|
+
return `${Math.max(0, minutes)}m`;
|
|
75
|
+
}
|
|
76
|
+
return `${hours}h ${minutes}m`;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function readJsonFile(filePath, { allowMissing = true } = {}) {
|
|
80
|
+
try {
|
|
81
|
+
const raw = await fsp.readFile(filePath, "utf-8");
|
|
82
|
+
return JSON.parse(raw);
|
|
83
|
+
} catch (error) {
|
|
84
|
+
if (
|
|
85
|
+
allowMissing &&
|
|
86
|
+
error &&
|
|
87
|
+
typeof error === "object" &&
|
|
88
|
+
error.code === "ENOENT"
|
|
89
|
+
) {
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
throw error;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async function writeJsonFile(filePath, payload) {
|
|
97
|
+
await fsp.mkdir(path.dirname(filePath), { recursive: true });
|
|
98
|
+
const tmpPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
|
|
99
|
+
await fsp.writeFile(tmpPath, `${JSON.stringify(payload, null, 2)}\n`, "utf-8");
|
|
100
|
+
await fsp.rename(tmpPath, filePath);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function normalizeCodebaseContext(ingest = {}) {
|
|
104
|
+
return {
|
|
105
|
+
summary:
|
|
106
|
+
ingest && typeof ingest.summary === "object" && ingest.summary
|
|
107
|
+
? {
|
|
108
|
+
filesScanned: Number(ingest.summary.filesScanned || 0),
|
|
109
|
+
directoriesScanned: Number(ingest.summary.directoriesScanned || 0),
|
|
110
|
+
totalLoc: Number(ingest.summary.totalLoc || 0),
|
|
111
|
+
totalBytes: Number(ingest.summary.totalBytes || 0),
|
|
112
|
+
}
|
|
113
|
+
: {
|
|
114
|
+
filesScanned: 0,
|
|
115
|
+
directoriesScanned: 0,
|
|
116
|
+
totalLoc: 0,
|
|
117
|
+
totalBytes: 0,
|
|
118
|
+
},
|
|
119
|
+
frameworks: Array.isArray(ingest.frameworks) ? [...ingest.frameworks] : [],
|
|
120
|
+
entryPoints: Array.isArray(ingest.entryPoints) ? [...ingest.entryPoints] : [],
|
|
121
|
+
riskSurfaces: Array.isArray(ingest.riskSurfaces) ? [...ingest.riskSurfaces] : [],
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function normalizeStringList(values = []) {
|
|
126
|
+
if (!Array.isArray(values)) {
|
|
127
|
+
return [];
|
|
128
|
+
}
|
|
129
|
+
return Array.from(
|
|
130
|
+
new Set(
|
|
131
|
+
values
|
|
132
|
+
.map((value) => normalizeString(value))
|
|
133
|
+
.filter(Boolean)
|
|
134
|
+
)
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function toPosixPath(value = "") {
|
|
139
|
+
return String(value || "").replace(/\\/g, "/");
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function toRelativePosix(baseDir, absolutePath) {
|
|
143
|
+
if (!absolutePath) {
|
|
144
|
+
return "";
|
|
145
|
+
}
|
|
146
|
+
return toPosixPath(path.relative(baseDir, absolutePath));
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function normalizeDateKeyFromCloseoutPath(closeoutPath = "", fallbackIso = new Date().toISOString()) {
|
|
150
|
+
const normalized = toPosixPath(closeoutPath);
|
|
151
|
+
const match = /\/observability\/(\d{4}-\d{2}-\d{2})\//.exec(`/${normalized}`);
|
|
152
|
+
if (match) {
|
|
153
|
+
return match[1];
|
|
154
|
+
}
|
|
155
|
+
return normalizeIsoTimestamp(fallbackIso).slice(0, 10);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function normalizeSharedResources(raw = {}, { nowIso = new Date().toISOString() } = {}) {
|
|
159
|
+
const source = raw && typeof raw === "object" ? raw : {};
|
|
160
|
+
return {
|
|
161
|
+
provisionedIdentityIds: normalizeStringList(source.provisionedIdentityIds),
|
|
162
|
+
provisioningTags: normalizeStringList(source.provisioningTags),
|
|
163
|
+
provisionCount: normalizeNonNegativeInteger(source.provisionCount, 0),
|
|
164
|
+
lastProvisionedAt: source.lastProvisionedAt
|
|
165
|
+
? normalizeIsoTimestamp(source.lastProvisionedAt, nowIso)
|
|
166
|
+
: null,
|
|
167
|
+
updatedAt: normalizeIsoTimestamp(source.updatedAt, nowIso),
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function normalizeTemplateAgent(raw = {}) {
|
|
172
|
+
const source = raw && typeof raw === "object" ? raw : {};
|
|
173
|
+
return {
|
|
174
|
+
role: normalizeString(source.role) || "agent",
|
|
175
|
+
instructions: normalizeString(source.instructions) || "Follow session guidance.",
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function normalizeSessionTemplate(raw = null) {
|
|
180
|
+
if (!raw || typeof raw !== "object") {
|
|
181
|
+
return null;
|
|
182
|
+
}
|
|
183
|
+
const source = raw;
|
|
184
|
+
const id = normalizeString(source.id || source.name);
|
|
185
|
+
if (!id) {
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
const suggestedAgents = Array.isArray(source.suggestedAgents)
|
|
189
|
+
? source.suggestedAgents.map((agent) => normalizeTemplateAgent(agent))
|
|
190
|
+
: [];
|
|
191
|
+
const ttlHours = normalizePositiveInteger(source.ttlHours, 1);
|
|
192
|
+
const normalizedAutoProvision =
|
|
193
|
+
source.autoProvisionEmails === undefined || source.autoProvisionEmails === null
|
|
194
|
+
? null
|
|
195
|
+
: normalizePositiveInteger(source.autoProvisionEmails, 1);
|
|
196
|
+
|
|
197
|
+
return {
|
|
198
|
+
id,
|
|
199
|
+
version: normalizeString(source.version) || "1.0.0",
|
|
200
|
+
registryVersion: normalizeString(source.registryVersion) || "1.0.0",
|
|
201
|
+
description: normalizeString(source.description),
|
|
202
|
+
daemonModel: normalizeString(source.daemonModel),
|
|
203
|
+
ttlHours,
|
|
204
|
+
autoProvisionEmails: normalizedAutoProvision,
|
|
205
|
+
suggestedAgents,
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
async function collectSessionCodebaseContext(targetPath) {
|
|
210
|
+
const cachedIngestPath = path.join(targetPath, ".sentinelayer", "CODEBASE_INGEST.json");
|
|
211
|
+
const cachedIngest = await readJsonFile(cachedIngestPath, { allowMissing: true });
|
|
212
|
+
if (cachedIngest && typeof cachedIngest === "object") {
|
|
213
|
+
return normalizeCodebaseContext(cachedIngest);
|
|
214
|
+
}
|
|
215
|
+
const ingest = await collectCodebaseIngest({ rootPath: targetPath });
|
|
216
|
+
return normalizeCodebaseContext(ingest);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async function buildArchiveSidecars(
|
|
220
|
+
sessionId,
|
|
221
|
+
{
|
|
222
|
+
targetPath,
|
|
223
|
+
outputDir = "",
|
|
224
|
+
env,
|
|
225
|
+
homeDir,
|
|
226
|
+
nowIso = new Date().toISOString(),
|
|
227
|
+
} = {}
|
|
228
|
+
) {
|
|
229
|
+
const normalizedSessionId = normalizeString(sessionId);
|
|
230
|
+
const normalizedTargetPath = path.resolve(String(targetPath || "."));
|
|
231
|
+
const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
|
|
232
|
+
|
|
233
|
+
const analytics = await computeSessionAnalytics(normalizedSessionId, {
|
|
234
|
+
targetPath: normalizedTargetPath,
|
|
235
|
+
outputDir,
|
|
236
|
+
env,
|
|
237
|
+
homeDir,
|
|
238
|
+
nowIso: normalizedNow,
|
|
239
|
+
});
|
|
240
|
+
const lineage = await buildArtifactLineageIndex({
|
|
241
|
+
targetPath: normalizedTargetPath,
|
|
242
|
+
outputDir,
|
|
243
|
+
env,
|
|
244
|
+
homeDir,
|
|
245
|
+
nowIso: normalizedNow,
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
const sessionWorkItems = Array.isArray(lineage.workItems)
|
|
249
|
+
? lineage.workItems.filter(
|
|
250
|
+
(item) => normalizeString(item?.links?.sessionId) === normalizedSessionId
|
|
251
|
+
)
|
|
252
|
+
: [];
|
|
253
|
+
const verification = [];
|
|
254
|
+
|
|
255
|
+
for (const workItem of sessionWorkItems) {
|
|
256
|
+
const workItemId = normalizeString(workItem.workItemId);
|
|
257
|
+
if (!workItemId) {
|
|
258
|
+
continue;
|
|
259
|
+
}
|
|
260
|
+
const closeoutPath = normalizeString(workItem?.artifacts?.closeoutPath);
|
|
261
|
+
const dateKey = normalizeDateKeyFromCloseoutPath(closeoutPath, normalizedNow);
|
|
262
|
+
const chain = await verifyArtifactChain({
|
|
263
|
+
workItemId,
|
|
264
|
+
date: dateKey,
|
|
265
|
+
targetPath: normalizedTargetPath,
|
|
266
|
+
outputDir,
|
|
267
|
+
env,
|
|
268
|
+
homeDir,
|
|
269
|
+
});
|
|
270
|
+
verification.push({
|
|
271
|
+
workItemId,
|
|
272
|
+
date: chain.date,
|
|
273
|
+
closeoutPath: closeoutPath || null,
|
|
274
|
+
closeoutAnchorSha256: normalizeString(workItem?.artifacts?.closeoutAnchorSha256) || null,
|
|
275
|
+
valid: chain.valid,
|
|
276
|
+
mismatchCount: Array.isArray(chain.mismatches) ? chain.mismatches.length : 0,
|
|
277
|
+
mismatches: Array.isArray(chain.mismatches) ? chain.mismatches : [],
|
|
278
|
+
});
|
|
279
|
+
if (!chain.valid) {
|
|
280
|
+
throw new Error(
|
|
281
|
+
`Artifact chain verification failed for work item '${workItemId}' (${dateKey}).`
|
|
282
|
+
);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const analyticsSidecar = {
|
|
287
|
+
schemaVersion: "1.0.0",
|
|
288
|
+
generatedAt: normalizedNow,
|
|
289
|
+
sessionId: normalizedSessionId,
|
|
290
|
+
metrics: analytics,
|
|
291
|
+
};
|
|
292
|
+
const artifactChainSidecar = {
|
|
293
|
+
schemaVersion: "1.0.0",
|
|
294
|
+
generatedAt: normalizedNow,
|
|
295
|
+
sessionId: normalizedSessionId,
|
|
296
|
+
lineageRunId: normalizeString(lineage.lineageRunId) || null,
|
|
297
|
+
lineageIndexPath: toRelativePosix(
|
|
298
|
+
normalizedTargetPath,
|
|
299
|
+
normalizeString(lineage.indexPath)
|
|
300
|
+
) || null,
|
|
301
|
+
summary: {
|
|
302
|
+
totalWorkItemsIndexed: Number(lineage?.summary?.totalWorkItemsIndexed || 0),
|
|
303
|
+
sessionWorkItems: sessionWorkItems.length,
|
|
304
|
+
verifiedWorkItems: verification.filter((item) => item.valid).length,
|
|
305
|
+
},
|
|
306
|
+
workItems: verification,
|
|
307
|
+
};
|
|
308
|
+
|
|
309
|
+
return {
|
|
310
|
+
analyticsSidecar,
|
|
311
|
+
artifactChainSidecar,
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function normalizeSessionStatus(value) {
|
|
316
|
+
const normalized = normalizeString(value).toLowerCase();
|
|
317
|
+
if (normalized === SESSION_STATUS_EXPIRED) return SESSION_STATUS_EXPIRED;
|
|
318
|
+
if (normalized === SESSION_STATUS_ARCHIVED) return SESSION_STATUS_ARCHIVED;
|
|
319
|
+
return SESSION_STATUS_ACTIVE;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function normalizeMetadata(raw = {}, { sessionId, targetPath, nowIso } = {}) {
|
|
323
|
+
const createdAt = normalizeIsoTimestamp(raw.createdAt, nowIso);
|
|
324
|
+
const ttlSeconds = normalizePositiveInteger(raw.ttlSeconds, DEFAULT_TTL_SECONDS);
|
|
325
|
+
const expiresAt = normalizeIsoTimestamp(raw.expiresAt, toIsoAfterSeconds(createdAt, ttlSeconds));
|
|
326
|
+
return {
|
|
327
|
+
schemaVersion: SESSION_SCHEMA_VERSION,
|
|
328
|
+
sessionId: normalizeString(raw.sessionId) || sessionId,
|
|
329
|
+
targetPath: path.resolve(normalizeString(raw.targetPath) || targetPath),
|
|
330
|
+
createdAt,
|
|
331
|
+
updatedAt: normalizeIsoTimestamp(raw.updatedAt, nowIso),
|
|
332
|
+
expiresAt,
|
|
333
|
+
ttlSeconds,
|
|
334
|
+
renewalCount: Math.max(0, Number(raw.renewalCount || 0)),
|
|
335
|
+
maxLifetimeSeconds: normalizePositiveInteger(raw.maxLifetimeSeconds, MAX_SESSION_LIFETIME_SECONDS),
|
|
336
|
+
status: normalizeSessionStatus(raw.status),
|
|
337
|
+
lastInteractionAt: normalizeIsoTimestamp(raw.lastInteractionAt, createdAt),
|
|
338
|
+
expiredAt: raw.expiredAt ? normalizeIsoTimestamp(raw.expiredAt, nowIso) : null,
|
|
339
|
+
archivedAt: raw.archivedAt ? normalizeIsoTimestamp(raw.archivedAt, nowIso) : null,
|
|
340
|
+
s3Path: normalizeString(raw.s3Path) || null,
|
|
341
|
+
archiveStatus: normalizeString(raw.archiveStatus) || "pending",
|
|
342
|
+
codebaseContext: normalizeCodebaseContext(raw.codebaseContext || {}),
|
|
343
|
+
sharedResources: normalizeSharedResources(raw.sharedResources || {}, { nowIso }),
|
|
344
|
+
template: normalizeSessionTemplate(raw.template || null),
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
function isExpired(metadata, nowIso = new Date().toISOString()) {
|
|
349
|
+
if (!metadata || normalizeSessionStatus(metadata.status) === SESSION_STATUS_EXPIRED) {
|
|
350
|
+
return true;
|
|
351
|
+
}
|
|
352
|
+
const expiryEpoch = Date.parse(normalizeIsoTimestamp(metadata.expiresAt, nowIso));
|
|
353
|
+
const nowEpoch = Date.parse(normalizeIsoTimestamp(nowIso, new Date().toISOString()));
|
|
354
|
+
if (!Number.isFinite(expiryEpoch) || !Number.isFinite(nowEpoch)) {
|
|
355
|
+
return false;
|
|
356
|
+
}
|
|
357
|
+
return nowEpoch >= expiryEpoch;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function buildSessionPayload(metadata, paths, nowIso = new Date().toISOString()) {
|
|
361
|
+
return {
|
|
362
|
+
sessionId: metadata.sessionId,
|
|
363
|
+
sessionDir: paths.sessionDir,
|
|
364
|
+
metadataPath: paths.metadataPath,
|
|
365
|
+
streamPath: paths.streamPath,
|
|
366
|
+
createdAt: metadata.createdAt,
|
|
367
|
+
expiresAt: metadata.expiresAt,
|
|
368
|
+
elapsedTimer: buildElapsedTimer(metadata.createdAt, nowIso),
|
|
369
|
+
renewalCount: metadata.renewalCount,
|
|
370
|
+
status: metadata.status,
|
|
371
|
+
archivedAt: metadata.archivedAt,
|
|
372
|
+
s3Path: metadata.s3Path,
|
|
373
|
+
codebaseContext: metadata.codebaseContext,
|
|
374
|
+
sharedResources: metadata.sharedResources,
|
|
375
|
+
template: metadata.template,
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
async function loadMetadata(sessionId, { targetPath = process.cwd() } = {}) {
|
|
380
|
+
const resolvedTargetPath = path.resolve(String(targetPath || "."));
|
|
381
|
+
const paths = resolveSessionPaths(sessionId, { targetPath: resolvedTargetPath });
|
|
382
|
+
const nowIso = new Date().toISOString();
|
|
383
|
+
const raw = await readJsonFile(paths.metadataPath, { allowMissing: true });
|
|
384
|
+
if (!raw || typeof raw !== "object") {
|
|
385
|
+
return null;
|
|
386
|
+
}
|
|
387
|
+
const metadata = normalizeMetadata(raw, {
|
|
388
|
+
sessionId: paths.sessionId,
|
|
389
|
+
targetPath: resolvedTargetPath,
|
|
390
|
+
nowIso,
|
|
391
|
+
});
|
|
392
|
+
return { metadata, paths, targetPath: resolvedTargetPath };
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
async function saveMetadata(metadata, paths) {
|
|
396
|
+
const normalized = normalizeMetadata(metadata, {
|
|
397
|
+
sessionId: paths.sessionId,
|
|
398
|
+
targetPath: metadata.targetPath,
|
|
399
|
+
nowIso: new Date().toISOString(),
|
|
400
|
+
});
|
|
401
|
+
await writeJsonFile(paths.metadataPath, normalized);
|
|
402
|
+
return normalized;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
export async function createSession({
|
|
406
|
+
targetPath = process.cwd(),
|
|
407
|
+
ttlSeconds = DEFAULT_TTL_SECONDS,
|
|
408
|
+
template = null,
|
|
409
|
+
} = {}) {
|
|
410
|
+
const resolvedTargetPath = path.resolve(String(targetPath || "."));
|
|
411
|
+
const normalizedTtlSeconds = normalizePositiveInteger(ttlSeconds, DEFAULT_TTL_SECONDS);
|
|
412
|
+
const sessionId = randomUUID();
|
|
413
|
+
const nowIso = new Date().toISOString();
|
|
414
|
+
const paths = resolveSessionPaths(sessionId, { targetPath: resolvedTargetPath });
|
|
415
|
+
const codebaseContext = await collectSessionCodebaseContext(resolvedTargetPath);
|
|
416
|
+
|
|
417
|
+
const metadata = normalizeMetadata(
|
|
418
|
+
{
|
|
419
|
+
schemaVersion: SESSION_SCHEMA_VERSION,
|
|
420
|
+
sessionId,
|
|
421
|
+
targetPath: resolvedTargetPath,
|
|
422
|
+
createdAt: nowIso,
|
|
423
|
+
updatedAt: nowIso,
|
|
424
|
+
expiresAt: toIsoAfterSeconds(nowIso, normalizedTtlSeconds),
|
|
425
|
+
ttlSeconds: normalizedTtlSeconds,
|
|
426
|
+
renewalCount: 0,
|
|
427
|
+
maxLifetimeSeconds: MAX_SESSION_LIFETIME_SECONDS,
|
|
428
|
+
status: SESSION_STATUS_ACTIVE,
|
|
429
|
+
lastInteractionAt: nowIso,
|
|
430
|
+
expiredAt: null,
|
|
431
|
+
archivedAt: null,
|
|
432
|
+
s3Path: null,
|
|
433
|
+
archiveStatus: "pending",
|
|
434
|
+
codebaseContext,
|
|
435
|
+
sharedResources: normalizeSharedResources({}, { nowIso }),
|
|
436
|
+
template: normalizeSessionTemplate(template),
|
|
437
|
+
},
|
|
438
|
+
{
|
|
439
|
+
sessionId,
|
|
440
|
+
targetPath: resolvedTargetPath,
|
|
441
|
+
nowIso,
|
|
442
|
+
}
|
|
443
|
+
);
|
|
444
|
+
|
|
445
|
+
await fsp.mkdir(paths.agentsDir, { recursive: true });
|
|
446
|
+
await saveMetadata(metadata, paths);
|
|
447
|
+
await fsp.writeFile(paths.streamPath, "", { encoding: "utf-8", flag: "a" });
|
|
448
|
+
|
|
449
|
+
return buildSessionPayload(metadata, paths, nowIso);
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
export async function getSession(sessionId, { targetPath = process.cwd() } = {}) {
|
|
453
|
+
const loaded = await loadMetadata(sessionId, { targetPath });
|
|
454
|
+
if (!loaded) {
|
|
455
|
+
return null;
|
|
456
|
+
}
|
|
457
|
+
return buildSessionPayload(loaded.metadata, loaded.paths);
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
export async function listActiveSessions({ targetPath = process.cwd() } = {}) {
|
|
461
|
+
const resolvedTargetPath = path.resolve(String(targetPath || "."));
|
|
462
|
+
const sessionsRoot = resolveSessionsRoot({ targetPath: resolvedTargetPath });
|
|
463
|
+
let entries = [];
|
|
464
|
+
try {
|
|
465
|
+
entries = await fsp.readdir(sessionsRoot, { withFileTypes: true });
|
|
466
|
+
} catch (error) {
|
|
467
|
+
if (error && typeof error === "object" && error.code === "ENOENT") {
|
|
468
|
+
return [];
|
|
469
|
+
}
|
|
470
|
+
throw error;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
const sessions = [];
|
|
474
|
+
for (const entry of entries) {
|
|
475
|
+
if (!entry.isDirectory()) continue;
|
|
476
|
+
const loaded = await loadMetadata(entry.name, { targetPath: resolvedTargetPath });
|
|
477
|
+
if (!loaded) continue;
|
|
478
|
+
if (isExpired(loaded.metadata)) continue;
|
|
479
|
+
if (loaded.metadata.status === SESSION_STATUS_ARCHIVED) continue;
|
|
480
|
+
sessions.push(buildSessionPayload(loaded.metadata, loaded.paths));
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
sessions.sort((left, right) => left.createdAt.localeCompare(right.createdAt));
|
|
484
|
+
return sessions;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
export async function renewSession(sessionId, { targetPath = process.cwd() } = {}) {
|
|
488
|
+
const loaded = await loadMetadata(sessionId, { targetPath });
|
|
489
|
+
if (!loaded) {
|
|
490
|
+
throw new Error(`Session '${sessionId}' was not found.`);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
const nowIso = new Date().toISOString();
|
|
494
|
+
const createdEpoch = Date.parse(normalizeIsoTimestamp(loaded.metadata.createdAt, nowIso));
|
|
495
|
+
const expiresEpoch = Date.parse(normalizeIsoTimestamp(loaded.metadata.expiresAt, nowIso));
|
|
496
|
+
if (!Number.isFinite(createdEpoch) || !Number.isFinite(expiresEpoch)) {
|
|
497
|
+
throw new Error(`Session '${sessionId}' has invalid timestamps.`);
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
const maxExpiryEpoch = createdEpoch + loaded.metadata.maxLifetimeSeconds * 1000;
|
|
501
|
+
const nextExpiryEpoch = Math.min(expiresEpoch + RENEWAL_SECONDS * 1000, maxExpiryEpoch);
|
|
502
|
+
if (nextExpiryEpoch <= expiresEpoch) {
|
|
503
|
+
return buildSessionPayload(loaded.metadata, loaded.paths, nowIso);
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
loaded.metadata.expiresAt = new Date(nextExpiryEpoch).toISOString();
|
|
507
|
+
loaded.metadata.renewalCount = Math.max(0, Number(loaded.metadata.renewalCount || 0)) + 1;
|
|
508
|
+
loaded.metadata.updatedAt = nowIso;
|
|
509
|
+
loaded.metadata.lastInteractionAt = nowIso;
|
|
510
|
+
loaded.metadata.status = SESSION_STATUS_ACTIVE;
|
|
511
|
+
loaded.metadata.expiredAt = null;
|
|
512
|
+
|
|
513
|
+
const saved = await saveMetadata(loaded.metadata, loaded.paths);
|
|
514
|
+
|
|
515
|
+
try {
|
|
516
|
+
await appendToStream(
|
|
517
|
+
loaded.paths.sessionId,
|
|
518
|
+
{
|
|
519
|
+
event: "daemon_alert",
|
|
520
|
+
agentId: "senti",
|
|
521
|
+
payload: {
|
|
522
|
+
alert: "session_renewed",
|
|
523
|
+
expiresAt: saved.expiresAt,
|
|
524
|
+
renewalCount: saved.renewalCount,
|
|
525
|
+
},
|
|
526
|
+
ts: nowIso,
|
|
527
|
+
},
|
|
528
|
+
{ targetPath: loaded.targetPath }
|
|
529
|
+
);
|
|
530
|
+
} catch {
|
|
531
|
+
// Renewal should not fail if stream event persistence is unavailable.
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
return buildSessionPayload(saved, loaded.paths, nowIso);
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
export async function expireSession(sessionId, { targetPath = process.cwd() } = {}) {
|
|
538
|
+
const loaded = await loadMetadata(sessionId, { targetPath });
|
|
539
|
+
if (!loaded) {
|
|
540
|
+
throw new Error(`Session '${sessionId}' was not found.`);
|
|
541
|
+
}
|
|
542
|
+
const nowIso = new Date().toISOString();
|
|
543
|
+
loaded.metadata.status = SESSION_STATUS_EXPIRED;
|
|
544
|
+
loaded.metadata.expiredAt = nowIso;
|
|
545
|
+
loaded.metadata.updatedAt = nowIso;
|
|
546
|
+
const saved = await saveMetadata(loaded.metadata, loaded.paths);
|
|
547
|
+
return buildSessionPayload(saved, loaded.paths, nowIso);
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
export async function archiveSession(
|
|
551
|
+
sessionId,
|
|
552
|
+
{
|
|
553
|
+
s3Bucket,
|
|
554
|
+
s3Prefix = "",
|
|
555
|
+
targetPath = process.cwd(),
|
|
556
|
+
outputDir = "",
|
|
557
|
+
env,
|
|
558
|
+
homeDir,
|
|
559
|
+
} = {}
|
|
560
|
+
) {
|
|
561
|
+
const loaded = await loadMetadata(sessionId, { targetPath });
|
|
562
|
+
if (!loaded) {
|
|
563
|
+
throw new Error(`Session '${sessionId}' was not found.`);
|
|
564
|
+
}
|
|
565
|
+
const normalizedBucket = normalizeString(s3Bucket);
|
|
566
|
+
if (!normalizedBucket) {
|
|
567
|
+
throw new Error("archiveSession requires s3Bucket.");
|
|
568
|
+
}
|
|
569
|
+
const normalizedPrefix = normalizeString(s3Prefix).replace(/^\/+|\/+$/g, "");
|
|
570
|
+
const prefixSegment = normalizedPrefix ? `${normalizedPrefix}/` : "";
|
|
571
|
+
const s3Path = `s3://${normalizedBucket}/${prefixSegment}sessions/${loaded.paths.sessionId}/`;
|
|
572
|
+
const nowIso = new Date().toISOString();
|
|
573
|
+
const sidecars = await buildArchiveSidecars(loaded.paths.sessionId, {
|
|
574
|
+
targetPath: loaded.targetPath,
|
|
575
|
+
outputDir,
|
|
576
|
+
env,
|
|
577
|
+
homeDir,
|
|
578
|
+
nowIso,
|
|
579
|
+
});
|
|
580
|
+
|
|
581
|
+
loaded.metadata.status = SESSION_STATUS_ARCHIVED;
|
|
582
|
+
loaded.metadata.archivedAt = nowIso;
|
|
583
|
+
loaded.metadata.updatedAt = nowIso;
|
|
584
|
+
loaded.metadata.archiveStatus = "archived";
|
|
585
|
+
loaded.metadata.s3Path = s3Path;
|
|
586
|
+
const saved = await saveMetadata(loaded.metadata, loaded.paths);
|
|
587
|
+
|
|
588
|
+
await Promise.all([
|
|
589
|
+
writeJsonFile(path.join(loaded.paths.sessionDir, "analytics.json"), sidecars.analyticsSidecar),
|
|
590
|
+
writeJsonFile(
|
|
591
|
+
path.join(loaded.paths.sessionDir, "artifact-chain.json"),
|
|
592
|
+
sidecars.artifactChainSidecar
|
|
593
|
+
),
|
|
594
|
+
]);
|
|
595
|
+
await writeJsonFile(path.join(loaded.paths.sessionDir, "archive-manifest.json"), {
|
|
596
|
+
sessionId: loaded.paths.sessionId,
|
|
597
|
+
archivedAt: nowIso,
|
|
598
|
+
s3Path,
|
|
599
|
+
files: [
|
|
600
|
+
"metadata.json",
|
|
601
|
+
"stream.ndjson",
|
|
602
|
+
"stream.1.ndjson",
|
|
603
|
+
"agents/",
|
|
604
|
+
"analytics.json",
|
|
605
|
+
"artifact-chain.json",
|
|
606
|
+
],
|
|
607
|
+
});
|
|
608
|
+
|
|
609
|
+
return buildSessionPayload(saved, loaded.paths, nowIso);
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
// Emit analytics.json + artifact-chain.json for a live session without archiving.
|
|
613
|
+
// Callers should invoke this on a timer (spec §PR 10 line 1451: "S3 archive
|
|
614
|
+
// carries analytics.json sidecar" + line 1452-1453: closeout.json observability
|
|
615
|
+
// invariant — mid-flight observability requires the sidecar on disk too).
|
|
616
|
+
// Safe to call frequently; the payload is idempotent per (sessionId, nowIso).
|
|
617
|
+
export async function persistSessionSidecarsSnapshot(
|
|
618
|
+
sessionId,
|
|
619
|
+
{
|
|
620
|
+
targetPath = process.cwd(),
|
|
621
|
+
outputDir = "",
|
|
622
|
+
env = process.env,
|
|
623
|
+
homeDir,
|
|
624
|
+
nowIso = new Date().toISOString(),
|
|
625
|
+
} = {}
|
|
626
|
+
) {
|
|
627
|
+
const loaded = await loadMetadata(sessionId, { targetPath });
|
|
628
|
+
if (!loaded) {
|
|
629
|
+
throw new Error(`Session '${sessionId}' was not found.`);
|
|
630
|
+
}
|
|
631
|
+
const sidecars = await buildArchiveSidecars(loaded.paths.sessionId, {
|
|
632
|
+
targetPath: loaded.targetPath,
|
|
633
|
+
outputDir,
|
|
634
|
+
env,
|
|
635
|
+
homeDir,
|
|
636
|
+
nowIso,
|
|
637
|
+
});
|
|
638
|
+
await Promise.all([
|
|
639
|
+
writeJsonFile(path.join(loaded.paths.sessionDir, "analytics.json"), sidecars.analyticsSidecar),
|
|
640
|
+
writeJsonFile(
|
|
641
|
+
path.join(loaded.paths.sessionDir, "artifact-chain.json"),
|
|
642
|
+
sidecars.artifactChainSidecar
|
|
643
|
+
),
|
|
644
|
+
]);
|
|
645
|
+
return {
|
|
646
|
+
sessionId: loaded.paths.sessionId,
|
|
647
|
+
analyticsSidecar: sidecars.analyticsSidecar,
|
|
648
|
+
artifactChainSidecar: sidecars.artifactChainSidecar,
|
|
649
|
+
};
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
export async function recordSessionProvisionedIdentities(
|
|
653
|
+
sessionId,
|
|
654
|
+
{ targetPath = process.cwd(), identityIds = [], tags = [] } = {}
|
|
655
|
+
) {
|
|
656
|
+
const loaded = await loadMetadata(sessionId, { targetPath });
|
|
657
|
+
if (!loaded) {
|
|
658
|
+
throw new Error(`Session '${sessionId}' was not found.`);
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
const nowIso = new Date().toISOString();
|
|
662
|
+
const normalizedIdentityIds = normalizeStringList(identityIds);
|
|
663
|
+
if (normalizedIdentityIds.length === 0) {
|
|
664
|
+
return buildSessionPayload(loaded.metadata, loaded.paths, nowIso);
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
const existingSharedResources = normalizeSharedResources(loaded.metadata.sharedResources || {}, {
|
|
668
|
+
nowIso,
|
|
669
|
+
});
|
|
670
|
+
const mergedIdentityIds = normalizeStringList([
|
|
671
|
+
...existingSharedResources.provisionedIdentityIds,
|
|
672
|
+
...normalizedIdentityIds,
|
|
673
|
+
]);
|
|
674
|
+
const mergedTags = normalizeStringList([
|
|
675
|
+
...existingSharedResources.provisioningTags,
|
|
676
|
+
...normalizeStringList(tags),
|
|
677
|
+
]);
|
|
678
|
+
|
|
679
|
+
loaded.metadata.sharedResources = normalizeSharedResources(
|
|
680
|
+
{
|
|
681
|
+
...existingSharedResources,
|
|
682
|
+
provisionedIdentityIds: mergedIdentityIds,
|
|
683
|
+
provisioningTags: mergedTags,
|
|
684
|
+
provisionCount:
|
|
685
|
+
normalizeNonNegativeInteger(existingSharedResources.provisionCount, 0) +
|
|
686
|
+
normalizedIdentityIds.length,
|
|
687
|
+
lastProvisionedAt: nowIso,
|
|
688
|
+
updatedAt: nowIso,
|
|
689
|
+
},
|
|
690
|
+
{ nowIso }
|
|
691
|
+
);
|
|
692
|
+
loaded.metadata.updatedAt = nowIso;
|
|
693
|
+
loaded.metadata.lastInteractionAt = nowIso;
|
|
694
|
+
loaded.metadata.status = SESSION_STATUS_ACTIVE;
|
|
695
|
+
|
|
696
|
+
const saved = await saveMetadata(loaded.metadata, loaded.paths);
|
|
697
|
+
return buildSessionPayload(saved, loaded.paths, nowIso);
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
export {
|
|
701
|
+
DEFAULT_TTL_SECONDS,
|
|
702
|
+
MAX_SESSION_LIFETIME_SECONDS,
|
|
703
|
+
RENEWAL_SECONDS,
|
|
704
|
+
};
|