@aibyzero/cm-workflow 0.16.5 → 0.16.7
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/.codex-plugin/plugin.json +1 -1
- package/AGENTS.md +14 -0
- package/CHANGELOG.md +19 -1
- package/README.md +17 -4
- package/THIRD_PARTY_NOTICES.md +9 -0
- package/VERSION +1 -1
- package/docs/architecture.md +43 -0
- package/docs/execution-optimizations.md +33 -0
- package/docs/external-models.md +114 -0
- package/docs/fixes/.reviews/20260929-bootstrap-unchanged-review-r1.md +7 -0
- package/docs/fixes/.reviews/20260930-develop-package-limit-recovery-r4.md +9 -0
- package/docs/fixes/20260929-bootstrap-rule-refresh-conflict.md +22 -0
- package/docs/fixes/20260929-bootstrap-unchanged-review.md +26 -0
- package/docs/fixes/20260930-develop-package-limit-recovery.md +65 -0
- package/docs/human-correction.md +31 -0
- package/docs/installation.md +28 -7
- package/docs/js-workflow-control.md +96 -6
- package/docs/live-evidence-drivers.md +62 -0
- package/docs/next-steps.md +15 -10
- package/docs/untested-branches.md +27 -4
- package/docs/user-guide.md +23 -8
- package/install-codex.sh +28 -11
- package/package.json +1 -1
- package/runtime/js/cm-ai/claude-review-adapter.mjs +7 -4
- package/runtime/js/cm-ai/claude-tool-preview.mjs +4 -4
- package/runtime/js/cm-ai/cm-ai-admission.mjs +34 -10
- package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +9 -5
- package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +111 -34
- package/runtime/js/cm-ai/cm-ai-qa-log.mjs +93 -31
- package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +13 -57
- package/runtime/js/cm-ai/codex-config.mjs +3 -2
- package/runtime/js/cm-ai/codex-review-adapter.mjs +34 -15
- package/runtime/js/cm-ai/committed-rule-basis.mjs +76 -0
- package/runtime/js/cm-ai/developer-adapter.mjs +8 -5
- package/runtime/js/cm-ai/drive-bootstrap.mjs +22 -12
- package/runtime/js/cm-ai/drive-core.mjs +9 -3
- package/runtime/js/cm-ai/durable-runner-state.mjs +146 -14
- package/runtime/js/cm-ai/effect-contract.mjs +1 -1
- package/runtime/js/cm-ai/execution-policy.mjs +58 -0
- package/runtime/js/cm-ai/external-group-models.mjs +53 -0
- package/runtime/js/cm-ai/external-model-launch.mjs +23 -0
- package/runtime/js/cm-ai/external-models.mjs +52 -0
- package/runtime/js/cm-ai/external-run-guard.mjs +96 -0
- package/runtime/js/cm-ai/host-bootstrap.mjs +70 -20
- package/runtime/js/cm-ai/host-check.mjs +30 -4
- package/runtime/js/cm-ai/host-conversation-execution.mjs +59 -17
- package/runtime/js/cm-ai/host-documentation.mjs +2 -2
- package/runtime/js/cm-ai/host-progress.mjs +80 -0
- package/runtime/js/cm-ai/host-project-execution.mjs +16 -11
- package/runtime/js/cm-ai/host-qa-executor.mjs +54 -8
- package/runtime/js/cm-ai/host-qa-fix-owner.mjs +22 -5
- package/runtime/js/cm-ai/host-session.mjs +1 -1
- package/runtime/js/cm-ai/host-workflow-capabilities.mjs +3 -1
- package/runtime/js/cm-ai/knowledge-closeout.mjs +56 -0
- package/runtime/js/cm-ai/legacy-model-run-preview.mjs +24 -0
- package/runtime/js/cm-ai/legacy-model-settings.mjs +59 -0
- package/runtime/js/cm-ai/live-evidence.mjs +96 -0
- package/runtime/js/cm-ai/log-rows.mjs +36 -0
- package/runtime/js/cm-ai/model-configuration-file.mjs +63 -0
- package/runtime/js/cm-ai/model_configuration_write.py +214 -0
- package/runtime/js/cm-ai/native-usage-log.mjs +26 -0
- package/runtime/js/cm-ai/operator-guidance.mjs +89 -0
- package/runtime/js/cm-ai/owned-process-cleanup.mjs +22 -0
- package/runtime/js/cm-ai/provider-review-observation.mjs +15 -0
- package/runtime/js/cm-ai/provider-usage.mjs +39 -0
- package/runtime/js/cm-ai/review-package.mjs +11 -0
- package/runtime/js/cm-ai/review-presentation.mjs +45 -0
- package/runtime/js/cm-ai/review-reconciliation.mjs +20 -0
- package/runtime/js/cm-ai/status-projection.mjs +93 -0
- package/runtime/js/cm-ai/task-runner.mjs +176 -25
- package/runtime/js/cm-ai/tool-preview.mjs +8 -4
- package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
- package/runtime/js/cm-ai/worker-claude.mjs +63 -19
- package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -9
- package/runtime/js/cm-ai/worker-codex.mjs +45 -19
- package/runtime/js/cm-fix/cause-evidence.mjs +5 -3
- package/runtime/js/cm-fix/cause-invocation.mjs +6 -3
- package/runtime/js/cm-fix/cause-package.mjs +10 -1
- package/runtime/js/cm-fix/execution.mjs +183 -40
- package/runtime/js/cm-fix/final-review.mjs +18 -10
- package/runtime/js/cm-fix/finish.mjs +2 -19
- package/runtime/js/cm-fix/host-review.mjs +25 -6
- package/runtime/js/cm-fix/host.mjs +4 -1
- package/runtime/js/cm-fix/layout.mjs +1 -1
- package/runtime/js/cm-fix/log-events.mjs +29 -0
- package/runtime/js/cm-fix/metrics.mjs +3 -2
- package/runtime/js/cm-fix/progress.mjs +4 -0
- package/runtime/js/cm-fix/review-reconciliation.mjs +64 -0
- package/runtime/js/cm-prd/analysis.mjs +5 -2
- package/runtime/js/cm-prd/response-recovery.mjs +23 -0
- package/runtime/js/cm-prd/review-host.mjs +2 -1
- package/runtime/js/cm-prd/review-publication.mjs +23 -13
- package/runtime/js/cm-prd/review-time.mjs +29 -0
- package/runtime/js/cm-prd/session.mjs +53 -6
- package/runtime/js/cm-security/finalize.mjs +32 -0
- package/runtime/js/cm-test/recovery.mjs +4 -4
- package/runtime/review.md +5 -0
- package/runtime/task-gates.md +6 -0
- package/runtime/workflow-config.md +10 -1
- package/scripts/cm-ai-admission.mjs +14 -3
- package/scripts/cm-ai-batch-drive.mjs +52 -23
- package/scripts/cm-ai-batch-drive.test.mjs +47 -2
- package/scripts/cm-ai-batch-host.mjs +44 -16
- package/scripts/cm-ai-batch-run.mjs +77 -29
- package/scripts/cm-ai-bootstrap-flow.test.mjs +3 -2
- package/scripts/cm-ai-bootstrap-merge.test.mjs +118 -1
- package/scripts/cm-ai-bootstrap.test.mjs +80 -87
- package/scripts/cm-ai-conversation-entry-ops.test.mjs +15 -0
- package/scripts/cm-ai-develop-driver-gaps.test.mjs +102 -0
- package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +2 -2
- package/scripts/cm-ai-drive.mjs +73 -28
- package/scripts/cm-ai-drive.test.mjs +119 -1
- package/scripts/cm-ai-feature-selection.test.mjs +178 -0
- package/scripts/cm-ai-host.mjs +79 -27
- package/scripts/cm-ai-host.test.mjs +88 -0
- package/scripts/cm-ai-operator-guidance.test.mjs +94 -0
- package/scripts/cm-ai-progress.test.mjs +521 -0
- package/scripts/cm-ai-protected-scope.test.mjs +194 -0
- package/scripts/cm-ai-qa-config-revision.test.mjs +21 -0
- package/scripts/cm-ai-review-failure.test.mjs +71 -11
- package/scripts/cm-ai-run.mjs +94 -19
- package/scripts/cm-ai-run.test.mjs +2 -1
- package/scripts/cm-bootstrap-review-recovery.test.mjs +70 -0
- package/scripts/cm-check-drive.test.mjs +1 -0
- package/scripts/cm-check-runtime.sh +11 -0
- package/scripts/cm-claude-install-layout.test.mjs +26 -0
- package/scripts/cm-claude-probe.test.mjs +1 -1
- package/scripts/cm-codex-plugin-metadata.py +83 -0
- package/scripts/cm-codex-plugin-metadata.test.mjs +55 -0
- package/scripts/cm-efficiency-checks.test.mjs +37 -0
- package/scripts/cm-efficiency-diagnostics.test.mjs +74 -0
- package/scripts/cm-efficiency-offline.mjs +35 -0
- package/scripts/cm-efficiency-policy.test.mjs +48 -0
- package/scripts/cm-efficiency-presentation.test.mjs +35 -0
- package/scripts/cm-efficiency-response.test.mjs +117 -0
- package/scripts/cm-efficiency-usage.test.mjs +148 -0
- package/scripts/cm-external-batch-host.test.mjs +157 -0
- package/scripts/cm-external-fix-host.test.mjs +281 -0
- package/scripts/cm-external-fix-reconciliation.test.mjs +105 -0
- package/scripts/cm-external-group-models.test.mjs +60 -0
- package/scripts/cm-external-model-host.test.mjs +180 -0
- package/scripts/cm-external-model-recovery.test.mjs +108 -0
- package/scripts/cm-external-models.test.mjs +89 -0
- package/scripts/cm-external-process-cleanup.test.mjs +71 -0
- package/scripts/cm-external-qa-fix.test.mjs +170 -0
- package/scripts/cm-external-review-reconciliation.test.mjs +314 -0
- package/scripts/cm-fix-drive.mjs +28 -13
- package/scripts/cm-fix-final-review.test.mjs +11 -6
- package/scripts/cm-fix-host.mjs +17 -10
- package/scripts/cm-fix-large-log.test.mjs +113 -0
- package/scripts/cm-fix-protected-edits.test.mjs +12 -0
- package/scripts/cm-fix-rediagnosis.test.mjs +168 -0
- package/scripts/cm-fix-review-budget.test.mjs +7 -1
- package/scripts/cm-host-qa-executor.test.mjs +329 -3
- package/scripts/cm-knowledge-closeout.test.mjs +160 -0
- package/scripts/cm-live-evidence.test.mjs +64 -0
- package/scripts/cm-log-event.mjs +34 -7
- package/scripts/cm-log-event.py +15 -0
- package/scripts/cm-model-setup.mjs +79 -0
- package/scripts/cm-prd-drive.mjs +32 -11
- package/scripts/cm-prd-drive.test.mjs +15 -0
- package/scripts/cm-prd-host.mjs +26 -6
- package/scripts/cm-prd-host.test.mjs +4 -0
- package/scripts/cm-prd-review-host.test.mjs +17 -0
- package/scripts/cm-prd-session-recovery.test.mjs +44 -2
- package/scripts/cm-prd-task-grouping.test.mjs +206 -0
- package/scripts/cm-release-smoke.sh +5 -1
- package/scripts/cm-review-scope-recovery.test.mjs +5 -3
- package/scripts/cm-runtime-i18n.mjs +15 -4
- package/scripts/cm-runtime-install.mjs +8 -4
- package/scripts/cm-runtime.mjs +116 -23
- package/scripts/cm-runtime.test.mjs +121 -12
- package/scripts/cm-security.test.mjs +32 -0
- package/scripts/cm-task-gate-correction.test.mjs +117 -0
- package/scripts/cm-task-gate.mjs +146 -10
- package/scripts/cm-task-gate.py +1 -0
- package/scripts/cm-test-branch-impact.test.mjs +11 -0
- package/scripts/cm-test-drive.mjs +10 -4
- package/scripts/cm-test-drive.test.mjs +14 -1
- package/scripts/cm-tool-preview-context.test.mjs +12 -0
- package/scripts/cm-usage-report.py +22 -3
- package/scripts/cm-workflow-config.mjs +10 -1
- package/scripts/fixtures/bootstrap-review-runner.mjs +102 -0
- package/scripts/fixtures/live-evidence-driver.mjs +35 -0
- package/scripts/fixtures/process-cleanup.mjs +3 -1
- package/scripts/test-cm-native-usage.py +62 -0
- package/scripts/test-external-model-setup.py +91 -0
- package/scripts/test-model-configuration-write.py +201 -0
- package/scripts/test-npm-install.py +10 -1
- package/skills/cm-ai/SKILL.md +2 -2
- package/skills/cm-ai/references/N1-init.md +1 -1
- package/skills/cm-ai/references/N8-finish.md +5 -0
- package/skills/cm-ai/references/js-host.md +16 -7
- package/skills/cm-ai/references/knowledge-closeout.md +90 -0
- package/skills/cm-fix/SKILL.md +1 -1
- package/skills/cm-fix/references/js-host.md +30 -2
- package/skills/cm-prd/SKILL.md +5 -4
- package/skills/cm-prd/references/spec-self-check.md +3 -1
- package/skills/cm-runtime/SKILL.md +29 -6
- package/skills/cm-security/SKILL.md +4 -2
- package/skills/cm-security/references/scan-contract.md +1 -0
- package/templates/cm-workflow.yml +1 -1
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""POSIX publication only: pinned directories, cooperative lock, byte CAS.
|
|
3
|
+
|
|
4
|
+
The containing directory must be owned by the caller and not group/world writable.
|
|
5
|
+
This does not sandbox a same-UID actor that can move that directory or ignore locks.
|
|
6
|
+
"""
|
|
7
|
+
import base64
|
|
8
|
+
import errno
|
|
9
|
+
import hashlib
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import stat
|
|
13
|
+
import sys
|
|
14
|
+
import uuid
|
|
15
|
+
|
|
16
|
+
LIMIT = 64 * 1024
|
|
17
|
+
RUN_DIRECTORIES = {'.cm-external-models-v1', '.reviews', '.cm-model-runtime-v1', '.cm-model-reviews-v1',
|
|
18
|
+
'.cm-model-runtime-v2', '.cm-model-reviews-v2', '.cm-model-fix-runtime-v1'}
|
|
19
|
+
RUN_FILES = {'.cm-task-owner.json', '.cm-model-code-owner-v1.json',
|
|
20
|
+
'.cm-model-project-owner-v2.json', '.cm-model-snapshot-v1.json',
|
|
21
|
+
'.cm-model-fix-owner-v1.json'}
|
|
22
|
+
LOCK = '.cm-model-config.lock'
|
|
23
|
+
SECURE_PLATFORM = (os.name == 'posix' and hasattr(os, 'O_NOFOLLOW') and hasattr(os, 'O_DIRECTORY')
|
|
24
|
+
and all(function in os.supports_dir_fd for function in
|
|
25
|
+
(os.open, os.mkdir, os.stat, os.link, os.unlink, os.rename)))
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Refusal(Exception):
|
|
29
|
+
pass
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def require(condition, code):
|
|
33
|
+
if not condition:
|
|
34
|
+
raise Refusal(code)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def validate_target(target):
|
|
38
|
+
require(isinstance(target, str) and os.path.isabs(target)
|
|
39
|
+
and os.path.normpath(target) == target, 'unsupported_model_path')
|
|
40
|
+
require(not any(part.lower() in RUN_DIRECTORIES for part in target.split(os.sep))
|
|
41
|
+
and os.path.basename(target).lower() not in RUN_FILES | {LOCK},
|
|
42
|
+
'model_output_run_path_forbidden')
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def open_parent(target, create):
|
|
46
|
+
"""Never resolve an ancestor through a symlink, including during mkdir."""
|
|
47
|
+
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
|
48
|
+
current = os.open(os.sep, flags)
|
|
49
|
+
try:
|
|
50
|
+
for part in os.path.dirname(target).split(os.sep)[1:]:
|
|
51
|
+
try:
|
|
52
|
+
child = os.open(part, flags, dir_fd=current)
|
|
53
|
+
except FileNotFoundError:
|
|
54
|
+
require(create, 'unsupported_model_path')
|
|
55
|
+
try:
|
|
56
|
+
os.mkdir(part, 0o700, dir_fd=current)
|
|
57
|
+
os.fsync(current)
|
|
58
|
+
except FileExistsError:
|
|
59
|
+
pass
|
|
60
|
+
child = os.open(part, flags, dir_fd=current)
|
|
61
|
+
os.close(current)
|
|
62
|
+
current = child
|
|
63
|
+
info = os.fstat(current)
|
|
64
|
+
require(info.st_uid == os.geteuid() and not info.st_mode & 0o022,
|
|
65
|
+
'model_configuration_untrusted_directory')
|
|
66
|
+
return current
|
|
67
|
+
except BaseException:
|
|
68
|
+
os.close(current)
|
|
69
|
+
raise
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def file_hash(parent, name):
|
|
73
|
+
try:
|
|
74
|
+
fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent)
|
|
75
|
+
except FileNotFoundError:
|
|
76
|
+
return None
|
|
77
|
+
try:
|
|
78
|
+
before = os.fstat(fd)
|
|
79
|
+
require(stat.S_ISREG(before.st_mode) and before.st_nlink == 1
|
|
80
|
+
and before.st_size <= LIMIT, 'invalid_model_configuration_file')
|
|
81
|
+
with os.fdopen(os.dup(fd), 'rb') as stream:
|
|
82
|
+
content = stream.read(LIMIT + 1)
|
|
83
|
+
after = os.stat(name, dir_fd=parent, follow_symlinks=False)
|
|
84
|
+
identity = lambda info: (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns,
|
|
85
|
+
info.st_ctime_ns, info.st_nlink)
|
|
86
|
+
require(len(content) <= LIMIT and identity(before) == identity(os.fstat(fd)) and identity(before) == identity(after),
|
|
87
|
+
'model_configuration_changed')
|
|
88
|
+
return hashlib.sha256(content).hexdigest()
|
|
89
|
+
finally:
|
|
90
|
+
os.close(fd)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def publish(request):
|
|
94
|
+
require(SECURE_PLATFORM, 'model_secure_write_unavailable')
|
|
95
|
+
import fcntl
|
|
96
|
+
require(set(request) == {'target', 'bytes', 'expectedSha256', 'replace', 'createParents', 'sourceGuard'},
|
|
97
|
+
'invalid_model_write_request')
|
|
98
|
+
target = request['target']
|
|
99
|
+
validate_target(target)
|
|
100
|
+
require(type(request['replace']) is bool and type(request['createParents']) is bool,
|
|
101
|
+
'invalid_model_write_request')
|
|
102
|
+
content = base64.b64decode(request['bytes'], validate=True)
|
|
103
|
+
require(len(content) <= LIMIT, 'model_configuration_too_large')
|
|
104
|
+
expected = request['expectedSha256']
|
|
105
|
+
require(expected is None or isinstance(expected, str) and len(expected) == 64
|
|
106
|
+
and all(c in '0123456789abcdef' for c in expected), 'invalid_model_write_request')
|
|
107
|
+
guard = request['sourceGuard']
|
|
108
|
+
if guard is not None:
|
|
109
|
+
require(isinstance(guard, dict) and set(guard) == {'file', 'sha256'}
|
|
110
|
+
and isinstance(guard['file'], str)
|
|
111
|
+
and isinstance(guard['sha256'], str) and len(guard['sha256']) == 64
|
|
112
|
+
and all(c in '0123456789abcdef' for c in guard['sha256'])
|
|
113
|
+
and os.path.dirname(guard['file']) == os.path.dirname(target),
|
|
114
|
+
'invalid_model_write_request')
|
|
115
|
+
validate_target(guard['file'])
|
|
116
|
+
parent = open_parent(target, request['createParents'])
|
|
117
|
+
lock = None
|
|
118
|
+
temporary = None
|
|
119
|
+
published = False
|
|
120
|
+
try:
|
|
121
|
+
try:
|
|
122
|
+
lock = os.open(LOCK, os.O_RDWR | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=parent)
|
|
123
|
+
except FileExistsError:
|
|
124
|
+
try:
|
|
125
|
+
lock = os.open(LOCK, os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent)
|
|
126
|
+
except FileNotFoundError:
|
|
127
|
+
raise Refusal('model_configuration_busy')
|
|
128
|
+
info = os.fstat(lock)
|
|
129
|
+
require(stat.S_ISREG(info.st_mode) and info.st_nlink == 1 and info.st_uid == os.geteuid()
|
|
130
|
+
and not info.st_mode & 0o077, 'invalid_model_configuration_lock')
|
|
131
|
+
try:
|
|
132
|
+
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
133
|
+
except BlockingIOError:
|
|
134
|
+
raise Refusal('model_configuration_busy')
|
|
135
|
+
# Persistent lock inode: never unlink it, including after crash or success.
|
|
136
|
+
require(os.stat(LOCK, dir_fd=parent, follow_symlinks=False).st_ino == info.st_ino,
|
|
137
|
+
'invalid_model_configuration_lock')
|
|
138
|
+
name = os.path.basename(target)
|
|
139
|
+
actual = file_hash(parent, name)
|
|
140
|
+
require(request['replace'] or actual is None, 'model_configuration_exists')
|
|
141
|
+
require(actual == expected, 'model_configuration_changed')
|
|
142
|
+
if guard is not None:
|
|
143
|
+
require(file_hash(parent, os.path.basename(guard['file'])) == guard['sha256'],
|
|
144
|
+
'model_configuration_changed')
|
|
145
|
+
temporary = '.cm-model-' + uuid.uuid4().hex + '.tmp'
|
|
146
|
+
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=parent)
|
|
147
|
+
with os.fdopen(fd, 'wb') as stream:
|
|
148
|
+
stream.write(content)
|
|
149
|
+
stream.flush()
|
|
150
|
+
os.fsync(stream.fileno())
|
|
151
|
+
require(file_hash(parent, name) == expected, 'model_configuration_changed')
|
|
152
|
+
if actual is None:
|
|
153
|
+
try:
|
|
154
|
+
os.link(temporary, name, src_dir_fd=parent, dst_dir_fd=parent, follow_symlinks=False)
|
|
155
|
+
except FileExistsError:
|
|
156
|
+
raise Refusal('model_configuration_changed')
|
|
157
|
+
published = True
|
|
158
|
+
os.unlink(temporary, dir_fd=parent)
|
|
159
|
+
else:
|
|
160
|
+
os.replace(temporary, name, src_dir_fd=parent, dst_dir_fd=parent)
|
|
161
|
+
published = True
|
|
162
|
+
temporary = None
|
|
163
|
+
os.fsync(parent)
|
|
164
|
+
# A renamed pinned directory cannot redirect the write, but the named
|
|
165
|
+
# configuration may no longer refer to it. Do not report success then.
|
|
166
|
+
named_parent = open_parent(target, False)
|
|
167
|
+
try:
|
|
168
|
+
pinned, named = os.fstat(parent), os.fstat(named_parent)
|
|
169
|
+
require((pinned.st_dev, pinned.st_ino) == (named.st_dev, named.st_ino),
|
|
170
|
+
'model_configuration_write_unknown')
|
|
171
|
+
finally:
|
|
172
|
+
os.close(named_parent)
|
|
173
|
+
except BaseException:
|
|
174
|
+
if published:
|
|
175
|
+
raise Refusal('model_configuration_write_unknown')
|
|
176
|
+
raise
|
|
177
|
+
finally:
|
|
178
|
+
cleanup_error = None
|
|
179
|
+
if temporary is not None:
|
|
180
|
+
try:
|
|
181
|
+
os.unlink(temporary, dir_fd=parent)
|
|
182
|
+
except FileNotFoundError:
|
|
183
|
+
pass
|
|
184
|
+
except OSError as error:
|
|
185
|
+
cleanup_error = error
|
|
186
|
+
for descriptor in (lock, parent):
|
|
187
|
+
if descriptor is not None:
|
|
188
|
+
try:
|
|
189
|
+
os.close(descriptor)
|
|
190
|
+
except OSError as error:
|
|
191
|
+
cleanup_error = error
|
|
192
|
+
if cleanup_error is not None:
|
|
193
|
+
if published:
|
|
194
|
+
raise Refusal('model_configuration_write_unknown')
|
|
195
|
+
raise cleanup_error
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def main():
|
|
199
|
+
try:
|
|
200
|
+
data = sys.stdin.buffer.read(192 * 1024 + 1)
|
|
201
|
+
require(len(data) <= 192 * 1024, 'model_configuration_too_large')
|
|
202
|
+
publish(json.loads(data))
|
|
203
|
+
print(json.dumps({'ok': True}))
|
|
204
|
+
except Exception as error:
|
|
205
|
+
code = str(error) if isinstance(error, Refusal) else (
|
|
206
|
+
'unsupported_model_path' if isinstance(error, OSError) and error.errno in (errno.ELOOP, errno.ENOTDIR)
|
|
207
|
+
else 'model_configuration_write_failed')
|
|
208
|
+
print(json.dumps({'ok': False, 'code': code}))
|
|
209
|
+
return 1
|
|
210
|
+
return 0
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
if __name__ == '__main__':
|
|
214
|
+
sys.exit(main())
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// Existing authoritative logger/lock adapter, no telemetry or execution authority.
|
|
2
|
+
import {spawnSync} from 'node:child_process';
|
|
3
|
+
import {fileURLToPath} from 'node:url';
|
|
4
|
+
const writer=fileURLToPath(new URL('../../../scripts/cm-log-event.py',import.meta.url));
|
|
5
|
+
export function createNativeUsageLog({definition,request,provider,role,workflow='cm-ai'}){
|
|
6
|
+
const identity={call_id:request.invocationId,stage:role==='developer'?'develop':'review',role,
|
|
7
|
+
adapter:provider+'-cli',requested_model:request.requestedModel,source:'native-cli-terminal',purpose:'workflow-execution'};
|
|
8
|
+
let claimed=false,completed=false;
|
|
9
|
+
const write=(event,phase,data)=>{
|
|
10
|
+
try{
|
|
11
|
+
const result=spawnSync('python3',[writer,'--workflow',workflow,'--event',event,'--phase',phase,
|
|
12
|
+
'--runtime',provider,'--project-root',definition.codeProject,...(definition.specsDir?['--specs-dir',definition.specsDir]:[]),
|
|
13
|
+
'--run-id',request.identity.runId,'--detail','Native CLI usage accounting','--data-json',JSON.stringify(data)],
|
|
14
|
+
{encoding:'utf8',timeout:10000,maxBuffer:1024*1024});
|
|
15
|
+
if(result.error||result.status!==0)throw Error('unavailable');return true;
|
|
16
|
+
}catch{try{process.stderr.write('[usage] usage_record_unavailable\n');}catch{}return false;}
|
|
17
|
+
};
|
|
18
|
+
return {
|
|
19
|
+
claimed(){if(claimed)return;claimed=true;write('model_call','claimed',identity);},
|
|
20
|
+
complete(usage,outcome){
|
|
21
|
+
if(completed||!claimed)return;completed=true;
|
|
22
|
+
write('model_usage','complete',{...identity,provider,...usage,outcome,
|
|
23
|
+
feature:definition.feature,task:request.identity.taskId,attempt:request.identity.attempt});
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// Presentation only. Native pendingAction decides the available path; guidance
|
|
2
|
+
// never grants permission, changes retryability, or writes execution history.
|
|
3
|
+
const deliveryMessages={
|
|
4
|
+
develop_checks_not_passed:['开发检查未通过,尚未进入独立审查。','根据 reason 中的检查编号和证据修复代码或环境'],
|
|
5
|
+
develop_package_too_large:['审查材料或运行存档记录超过大小限制,交付暂时受阻。','缩小 reason 指出的文件或材料;若要改变任务范围,先走规格变更'],
|
|
6
|
+
developer_result_invalid:['开发答复不符合交付合同。','修正开发答复格式及 Learning 记录'],
|
|
7
|
+
verification_precheck_failed:['交付未满足任务的验证要求。','根据验证证据补齐交付'],
|
|
8
|
+
check_output_out_of_scope:['检查产生了任务范围外的改动。','核对并处理检查产物;保留用户改动,不擅自扩大范围'],
|
|
9
|
+
develop_empty_changes:['交付没有产生可审查的实际改动。','核对任务要求并提供实际修改'],
|
|
10
|
+
develop_unchanged_after_review:['交付没有处理上一轮审查要求。','处理原审查 findings 后提供本轮修改'],
|
|
11
|
+
develop_requirement_missing:['交付后缺少要求保留的文件。','恢复 reason 指出的必要文件'],
|
|
12
|
+
bootstrap_verification_failed:['项目规则验证未通过。','根据规则验证证据修正草稿或检查环境'],
|
|
13
|
+
};
|
|
14
|
+
const explain=(summary,nextStep,operation=null,prerequisites=[])=>Object.freeze({
|
|
15
|
+
summary,nextStep,recoveryOperation:operation,prerequisites:Object.freeze(prerequisites),authorizationGranted:false,
|
|
16
|
+
});
|
|
17
|
+
export function operatorGuidance(result,{executionActive=false}={}){
|
|
18
|
+
if(result?.workflow!=='cm-ai'||!result.state||!result.identity)return null;
|
|
19
|
+
const {state,code,pendingAction:action,outcome}=result;
|
|
20
|
+
if(outcome==='rejected'||outcome==='denied')return explain('本次操作被拒绝,运行状态没有因此获得新的执行权限。',
|
|
21
|
+
'先核对 code 与 reason,修正请求或取得所需授权;不要据此重复开发或审查。');
|
|
22
|
+
if(executionActive)return explain('原运行仍有操作在执行。','等待原操作结果;可读取状态,不重复派发。');
|
|
23
|
+
if(code==='spec_drift')return explain('已批准规格发生变化,后续执行被阻止。',
|
|
24
|
+
action==='spec_rebind'?'先核对重新批准的规格;符合原任务内容未变的条件时,在原运行显式换绑规格。'
|
|
25
|
+
:'先核对规格变更与原任务绑定;当前没有可直接继续的恢复动作。',null,['保留原运行身份与历史','不得绕过规格审批']);
|
|
26
|
+
if(action==='bootstrap_review_recover')return explain('项目规则交付已记录,但规则审查包尚未恢复。',
|
|
27
|
+
'核对当前规则文件、handoff 和原证据;恢复原运行后发送 bootstrap_review_recover。此路径不重新派发开发。',
|
|
28
|
+
'bootstrap_review_recover',['使用原配置与 runId,以 --mode resume 启动','显式 --allow-bootstrap-review-recovery,并提供单行 reason','由原宿主重新核对恢复条件']);
|
|
29
|
+
if(state==='unknown'){
|
|
30
|
+
if(action==='abandon_effect'||action==='abandon_review'){
|
|
31
|
+
const review=action==='abandon_review';
|
|
32
|
+
return explain(review?'独立审查结果尚未确认。':'开发或完成操作的结果尚未确认。',
|
|
33
|
+
'先核对原操作与磁盘结果,确认旧宿主及相关子进程已退出;符合原宿主条件时,再审计放弃这次操作。放弃不代表成功。',
|
|
34
|
+
action,['保留原配置、runId 和失败历史,以 --mode resume 启动',
|
|
35
|
+
review?'显式 --allow-abandon-review,并提供单行 reason':'显式 --allow-abandon-effect,并提供单行 reason',
|
|
36
|
+
'由原宿主核对可放弃条件;不得直接重跑或改写完成记录']);
|
|
37
|
+
}
|
|
38
|
+
return explain('执行结果尚未确认,不能判断这一步成功或失败。',
|
|
39
|
+
'只读核对原运行记录、进程及实际文件;当前没有已确认的直接重试入口,不新建运行绕过历史。');
|
|
40
|
+
}
|
|
41
|
+
if(state==='blocked'&&action==='resume'&&Object.hasOwn(deliveryMessages,code)){
|
|
42
|
+
const [summary,repair]=deliveryMessages[code];
|
|
43
|
+
return explain(summary,`${repair};然后恢复原运行并发送 advance,重做本轮交付和检查。`,
|
|
44
|
+
'advance',['保留原配置、runId 与历史,以 --mode resume 启动','确认原宿主已关闭,且本轮开发有原合同要求的授权','不会自动完成任务或消耗新的独立审查轮次']);
|
|
45
|
+
}
|
|
46
|
+
if(state==='pending_review'&&action==='resume')return explain('本轮独立审查未取得可接受的结论。',
|
|
47
|
+
'核对 code 与原审查证据;恢复原运行后,取得本轮绑定的独立审查授权,再发送 advance。',
|
|
48
|
+
'advance',['原 run、配置和审查包绑定不变','原宿主仍须核对重派次数、进程和独立审查权限']);
|
|
49
|
+
if(state==='blocked'&&action==='complete')return explain('完成前复核受阻,已有审查结论不能直接当作任务完成。',
|
|
50
|
+
'核对 reason 中的检查或文件变化;满足原完成条件后,在原运行发送 complete,不重新开发。',
|
|
51
|
+
'complete',['原 run 与已审交接、范围和包绑定不变','使用当前 packageDigest;由宿主重新核对完成条件']);
|
|
52
|
+
if(code==='protected_scope')return explain('任务 scope 含项目规则或工作流文件,开发在派发前被拒绝,未写入任何文件。',
|
|
53
|
+
'本运行到此结束,原记录保留。从 scope 移除 reason 列出的路径,按原门禁用新 runId 新建运行;规则文件改动走 docs/js-workflow-control.md「项目规则文件的修改通道」。',
|
|
54
|
+
null,['不放宽受保护路径,开发者不能写这些文件','不改写原运行记录']);
|
|
55
|
+
if(code==='bootstrap_instruction_conflict')return explain('已有项目规则与本次允许的写入基准冲突,规则生成被阻止。',
|
|
56
|
+
'核对前序规则任务、提交基准和当前文件;当前没有可直接重派的动作,不覆盖已有规则。');
|
|
57
|
+
if(code==='checks_not_passed')return explain('旧完成阶段的检查未通过,当前不是可重做开发的阻塞。',
|
|
58
|
+
'保留原检查与审查证据,核对原完成恢复合同;不要使用开发重试或新建运行绕过。');
|
|
59
|
+
if(state==='blocked'||code==='correction_review_required'||code==='review_package_changed')return explain('当前流程受阻,尚未确认可执行的恢复步骤。',
|
|
60
|
+
'核对 code、reason 和原运行证据;保留已有文件与历史,不把通用阻塞当作重试许可。');
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
// Only bounded static guidance is rendered, never raw provider output.
|
|
64
|
+
export function guidanceText(result){
|
|
65
|
+
if(result?.workflow!=='cm-ai')return null;
|
|
66
|
+
const guidance=result?.guidance;
|
|
67
|
+
const bounded=value=>typeof value==='string'&&Buffer.byteLength(value,'utf8')<=2000&&!/[\r\n\0]/.test(value);
|
|
68
|
+
if(!guidance||guidance.authorizationGranted!==false||!bounded(guidance.summary)||!bounded(guidance.nextStep)
|
|
69
|
+
||!Array.isArray(guidance.prerequisites)||guidance.prerequisites.length>8||!guidance.prerequisites.every(bounded))return null;
|
|
70
|
+
return `${guidance.summary} ${guidance.nextStep} ${guidance.prerequisites.join(';')}`.trim();
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// A member result is not a batch control surface. Keep unsupported single-run
|
|
74
|
+
// recovery operations out of batch instructions without changing pendingAction.
|
|
75
|
+
export function batchOperatorGuidance(result){
|
|
76
|
+
const g=result?.guidance;if(!g)return null;
|
|
77
|
+
if(result.code==='spec_drift')return explain(g.summary,
|
|
78
|
+
'批次成员不能换绑规格;先按 reason 核对原批次可用出口,不直接重派。');
|
|
79
|
+
if(g.recoveryOperation==='advance')return explain(g.summary,
|
|
80
|
+
g.nextStep.replace('然后恢复原运行并发送 advance,重做本轮交付和检查。','然后从原批次入口发送 advance,重做本轮交付和检查。')
|
|
81
|
+
.replace('恢复原运行后,取得本轮绑定的独立审查授权,再发送 advance。','沿原批次续接,取得本轮绑定的独立审查授权,再发送 advance。'),
|
|
82
|
+
'advance',['保持原批次配置、身份和 PLAN;成员运行由批次宿主选择恢复','先确认原批次宿主已关闭;开发与审查仍需原合同授权']);
|
|
83
|
+
if(g.recoveryOperation==='complete')return explain(g.summary,
|
|
84
|
+
'核对 reason 中的检查或文件变化;满足原完成条件后,从原批次入口发送 advance,由成员宿主继续完成复核。',
|
|
85
|
+
'advance',['保留原批次配置与已审证据;不重新开发','成员宿主重新核对完成条件']);
|
|
86
|
+
if(g.recoveryOperation)return explain(g.summary,
|
|
87
|
+
'批次入口不支持此成员恢复操作;先核对原成员运行与 reason,不通过 advance 重派或新建运行绕过。');
|
|
88
|
+
return g;
|
|
89
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// POSIX children must be spawned detached. Own only that child's process group.
|
|
2
|
+
// A leader closing its pipes does not cancel escalation for its descendants.
|
|
3
|
+
export function ownedProcessCleanup(child,{graceMs=250,killWaitMs=750,killProcess=process.kill.bind(process)}={}) {
|
|
4
|
+
let cleanup;
|
|
5
|
+
const error=()=>Object.assign(new Error('process_cleanup_unknown'),{code:'process_cleanup_unknown'});
|
|
6
|
+
const signal=value=>{
|
|
7
|
+
try{killProcess(-child.pid,value);return true;}
|
|
8
|
+
catch(e){if(e.code==='ESRCH')return false;throw error();}
|
|
9
|
+
};
|
|
10
|
+
const pause=ms=>new Promise(resolve=>setTimeout(resolve,ms));
|
|
11
|
+
return ()=>cleanup??=(async()=>{
|
|
12
|
+
// Preserve the legacy Windows leader termination, without claiming tree cleanup.
|
|
13
|
+
if(process.platform==='win32'){child.kill('SIGTERM');throw error();}
|
|
14
|
+
// A failed spawn has no PID; in-memory test transports also have none.
|
|
15
|
+
if(!Number.isInteger(child.pid)||child.pid<=0){child.kill('SIGTERM');return;}
|
|
16
|
+
if(!signal('SIGTERM'))return;
|
|
17
|
+
await pause(graceMs);
|
|
18
|
+
if(!signal('SIGKILL'))return;
|
|
19
|
+
const until=Date.now()+killWaitMs;
|
|
20
|
+
while(signal(0)){if(Date.now()>=until)throw error();await pause(25);}
|
|
21
|
+
})();
|
|
22
|
+
}
|
|
@@ -132,3 +132,18 @@ export function inspectProviderReviewFailure(observationText,expectationText){
|
|
|
132
132
|
provider:expected.request.provider,requestedModel:expected.request.requestedModel,providerThreadId:thread,
|
|
133
133
|
category,failure,completionEligible:false});
|
|
134
134
|
}
|
|
135
|
+
|
|
136
|
+
export function inspectProviderReviewReconciliation(observationText,expectationText,cause=false){
|
|
137
|
+
const {observation,expected,thread,terminal,close,r}=readObservation(observationText,expectationText,cause);
|
|
138
|
+
need(thread!==null&&close!==null,'review_reconciliation_evidence_required');
|
|
139
|
+
if(terminal==='turn.completed'&&r.status==='succeeded'){
|
|
140
|
+
const review=cause?reviewResultForPaths(r.value,expected.pkg,causeReviewPaths(expected.pkg)):reviewResult(r.value,expected.pkg);
|
|
141
|
+
return json({...inspect(observationText,expectationText,cause),observationStatus:'completed',code:null,review});
|
|
142
|
+
}
|
|
143
|
+
need(['error','turn.failed'].includes(terminal)&&r.status==='failed'&&r.code==='provider_failed',
|
|
144
|
+
'review_reconciliation_evidence_required');
|
|
145
|
+
return json({version:1,kind:'cm-provider-review-failure',requestDigest:expected.request.requestDigest,
|
|
146
|
+
observationDigest:digest(observation),identity:expected.request.identity,logicalContextId:expected.request.contextId,
|
|
147
|
+
provider:expected.request.provider,requestedModel:expected.request.requestedModel,providerThreadId:thread,
|
|
148
|
+
category:'provider',failure:'reviewer_provider_failed',completionEligible:false});
|
|
149
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import {types} from 'node:util';
|
|
2
|
+
// Accept only actual CLI terminal usage, never answer text, estimates or heartbeats.
|
|
3
|
+
const record=value=>value!==null&&typeof value==='object'&&!Array.isArray(value);
|
|
4
|
+
const count=value=>Number.isSafeInteger(value)&&value>=0;
|
|
5
|
+
export function readProviderUsage(provider,raw){
|
|
6
|
+
if(!record(raw)||!count(raw.input_tokens)||!count(raw.output_tokens))return {usage_state:'unavailable'};
|
|
7
|
+
const result={usage_state:'observed',input_tokens:raw.input_tokens,output_tokens:raw.output_tokens};
|
|
8
|
+
const fields=provider==='codex'?{cached_input_tokens:'cache_read_tokens',cache_write_input_tokens:'cache_write_tokens',reasoning_output_tokens:'reasoning_tokens'}:
|
|
9
|
+
provider==='claude'?{cache_read_input_tokens:'cache_read_tokens',cache_creation_input_tokens:'cache_write_tokens'}:null;
|
|
10
|
+
if(fields===null)return {usage_state:'unavailable'};
|
|
11
|
+
for(const [source,target] of Object.entries(fields))if(Object.hasOwn(raw,source)){
|
|
12
|
+
if(!count(raw[source]))return {usage_state:'unavailable'};result[target]=raw[source];
|
|
13
|
+
}
|
|
14
|
+
if(record(raw.output_tokens_details)&&Object.hasOwn(raw.output_tokens_details,'reasoning_tokens')){
|
|
15
|
+
const reasoning=raw.output_tokens_details.reasoning_tokens;
|
|
16
|
+
if(!count(reasoning)||reasoning>raw.output_tokens)return {usage_state:'unavailable'};
|
|
17
|
+
if(Object.hasOwn(result,'reasoning_tokens')&&result.reasoning_tokens!==reasoning)return {usage_state:'unavailable'};
|
|
18
|
+
result.reasoning_tokens=reasoning; // A subset annotation: NEVER added to output_tokens.
|
|
19
|
+
}
|
|
20
|
+
if(provider==='codex'&&result.cache_read_tokens>result.input_tokens)return {usage_state:'unavailable'};
|
|
21
|
+
if(result.reasoning_tokens>result.output_tokens)return {usage_state:'unavailable'};
|
|
22
|
+
return result;
|
|
23
|
+
}
|
|
24
|
+
export function createProviderUsageCapture(provider,onUsage){
|
|
25
|
+
let value=null,conflict=false,completed=false;
|
|
26
|
+
return {
|
|
27
|
+
terminal(usage){
|
|
28
|
+
const next=readProviderUsage(provider,usage);
|
|
29
|
+
if(value!==null&&JSON.stringify(value)!==JSON.stringify(next))conflict=true;
|
|
30
|
+
value??=next;
|
|
31
|
+
},
|
|
32
|
+
complete(){
|
|
33
|
+
if(completed)return;completed=true;
|
|
34
|
+
try{const returned=onUsage?.(conflict?{usage_state:'unavailable'}:value??{usage_state:'unavailable'});
|
|
35
|
+
if(types.isPromise(returned))Promise.prototype.then.call(returned,()=>{},()=>{});
|
|
36
|
+
}catch{/* accounting cannot retry or decide execution */}
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
}
|
|
@@ -211,6 +211,17 @@ function policyDifferencePaths(current,expected){
|
|
|
211
211
|
const diagnostic=(code,p,detail='')=>{
|
|
212
212
|
const error=new Error(`${code}: ${p}${detail?` (${detail})`:''}`);error.code=code;error.paths=[p];return error;
|
|
213
213
|
};
|
|
214
|
+
// Historical runner checkpoints did not carry a typed failure origin. Accept
|
|
215
|
+
// only messages produced by this snapshot builder when recovering an old
|
|
216
|
+
// unknown/limit_exceeded; a generic JSON/provider limit is not package evidence.
|
|
217
|
+
export function reviewMaterialLimitReason(reason){
|
|
218
|
+
if(typeof reason!=='string'||!reason.startsWith('limit_exceeded: '))return false;
|
|
219
|
+
const suffixes=[`file bytes > ${FILE_LIMIT}`,`file count > ${FILE_COUNT}`,
|
|
220
|
+
`file count > ${INVENTORY_COUNT}`,`inventory bytes > ${INVENTORY_LIMIT}`,
|
|
221
|
+
`material file count > ${FILE_COUNT}`,'instruction search depth > 32','directory depth > 32'];
|
|
222
|
+
return suffixes.some(detail=>reason.endsWith(` (${detail})`))
|
|
223
|
+
||new RegExp(` \\(material bytes \\d+\\+\\d+ > ${SNAPSHOT_LIMIT}; scope, requirements and AGENTS\\.md content count\\)$`).test(reason);
|
|
224
|
+
}
|
|
214
225
|
const fail = code => { const error=new Error(code); error.code=code; throw error; };
|
|
215
226
|
const need = (condition,code='invalid_input') => { if(!condition) fail(code); };
|
|
216
227
|
const record = v => v!==null && typeof v==='object' && !Array.isArray(v);
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// Lossless presentation inside the same no-tools prompt. Canonical evidence stays unchanged.
|
|
2
|
+
import {createHash} from 'node:crypto';
|
|
3
|
+
import {json,need} from './effect-contract.mjs';
|
|
4
|
+
export function compactReviewData(raw){
|
|
5
|
+
const input=json(raw,10*1024*1024),contents={},keys=new Map();
|
|
6
|
+
need(!Object.hasOwn(input,'presentation')&&!Object.hasOwn(input,'contents')&&input.reviewPackage?.packageDigest,'review_presentation_invalid');
|
|
7
|
+
const visit=value=>{
|
|
8
|
+
if(Array.isArray(value))return value.map(visit);
|
|
9
|
+
if(value===null||typeof value!=='object')return value;
|
|
10
|
+
need(!Object.hasOwn(value,'contentRef'),'review_presentation_invalid');
|
|
11
|
+
const out=Object.fromEntries(Object.entries(value).map(([key,item])=>[key,visit(item)]));
|
|
12
|
+
if(typeof value.contentBase64!=='string')return out;
|
|
13
|
+
const bytes=Buffer.from(value.contentBase64,'base64');
|
|
14
|
+
need(bytes.toString('base64')===value.contentBase64,'review_presentation_invalid');
|
|
15
|
+
const hash=createHash('sha256').update(bytes).digest('hex');
|
|
16
|
+
if(Object.hasOwn(value,'sha256'))need(hash===value.sha256,'review_presentation_invalid');
|
|
17
|
+
if(Object.hasOwn(value,'size'))need(bytes.length===value.size,'review_presentation_invalid');
|
|
18
|
+
const key=hash+':'+bytes.length;let ref=keys.get(key);
|
|
19
|
+
if(!ref){
|
|
20
|
+
ref='content-'+(keys.size+1);keys.set(key,ref);
|
|
21
|
+
let text;try{text=new TextDecoder('utf8',{fatal:true}).decode(bytes);}catch{}
|
|
22
|
+
// Byte-exact decoding: BOM or invalid UTF-8 retains the original base64.
|
|
23
|
+
const utf8=text!==undefined&&Buffer.from(text,'utf8').equals(bytes);
|
|
24
|
+
contents[ref]={sha256:hash,size:bytes.length,encoding:utf8?'utf8':'base64',content:utf8?text:value.contentBase64};
|
|
25
|
+
}
|
|
26
|
+
delete out.contentBase64;out.contentRef=ref;return out;
|
|
27
|
+
};
|
|
28
|
+
return {presentation:{version:1,kind:'complete-inline-content-table',
|
|
29
|
+
packageDigest:input.reviewPackage.packageDigest},...visit(input),contents};
|
|
30
|
+
}
|
|
31
|
+
export function expandReviewData(raw){
|
|
32
|
+
const {presentation,contents,...data}=raw;
|
|
33
|
+
need(presentation?.version===1&&presentation.kind==='complete-inline-content-table','review_presentation_invalid');
|
|
34
|
+
const visit=value=>{
|
|
35
|
+
if(Array.isArray(value))return value.map(visit);
|
|
36
|
+
if(value===null||typeof value!=='object')return value;
|
|
37
|
+
const out=Object.fromEntries(Object.entries(value).map(([key,item])=>[key,visit(item)]));
|
|
38
|
+
if(!Object.hasOwn(value,'contentRef'))return out;
|
|
39
|
+
const content=contents[value.contentRef];need(content,'review_presentation_invalid');
|
|
40
|
+
const bytes=Buffer.from(content.content,content.encoding==='utf8'?'utf8':'base64');
|
|
41
|
+
need(bytes.length===content.size&&createHash('sha256').update(bytes).digest('hex')===content.sha256,'review_presentation_invalid');
|
|
42
|
+
delete out.contentRef;out.contentBase64=bytes.toString('base64');return out;
|
|
43
|
+
};
|
|
44
|
+
return visit(data);
|
|
45
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Trusted adapter-side capture, separate from the host's sealed observation.
|
|
2
|
+
// No timers, files, provider queries or dispatch authority live here.
|
|
3
|
+
import {json,need,shape} from './effect-contract.mjs';
|
|
4
|
+
export function reconciliationControl(control) {
|
|
5
|
+
if(typeof control.onReconciliation!=='function')return {signal:control.signal,onEvent:control.onEvent};
|
|
6
|
+
const events=[];let invalid=false,closed=false;
|
|
7
|
+
return {signal:control.signal,onEvent:event=>{
|
|
8
|
+
try{need(!closed&&events.length<64);events.push(json(event,64*1024));}catch{invalid=true;}
|
|
9
|
+
return control.onEvent(event);
|
|
10
|
+
},onTerminal:result=>{
|
|
11
|
+
if(closed)return;closed=true;
|
|
12
|
+
if(invalid)return;
|
|
13
|
+
try{control.onReconciliation(json({events,result,cleanup:'owned_process_group_closed'},512*1024));}catch{}
|
|
14
|
+
}};
|
|
15
|
+
}
|
|
16
|
+
export function readReconciliationReceipt(raw){
|
|
17
|
+
const value=json(raw,512*1024);shape(value,['events','result','cleanup']);
|
|
18
|
+
need(value.cleanup==='owned_process_group_closed','review_reconciliation_evidence_required');
|
|
19
|
+
return value;
|
|
20
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// Advisory display only. The existing log lock serializes ownership checks and
|
|
2
|
+
// replacement across processes; neither this file nor its token grants work.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import {randomUUID} from 'node:crypto';
|
|
6
|
+
import {spawnSync} from 'node:child_process';
|
|
7
|
+
import {fileURLToPath} from 'node:url';
|
|
8
|
+
import {json,need,shape,text,validIdentity} from './effect-contract.mjs';
|
|
9
|
+
|
|
10
|
+
const writer=fileURLToPath(new URL('../../../scripts/cm-log-event.py',import.meta.url));
|
|
11
|
+
const LIMIT=64*1024;
|
|
12
|
+
export function statusTarget(specsDir){
|
|
13
|
+
need(typeof specsDir==='string'&&path.isAbsolute(specsDir),'status_invalid');
|
|
14
|
+
const specs=fs.realpathSync(specsDir),target=path.join(specs,'.cm-status.json');
|
|
15
|
+
need(fs.lstatSync(specs).isDirectory(),'status_invalid');
|
|
16
|
+
try{
|
|
17
|
+
const stat=fs.lstatSync(target);
|
|
18
|
+
need(stat.isFile()&&!stat.isSymbolicLink()&&stat.nlink===1&&stat.size<=LIMIT,'status_invalid');
|
|
19
|
+
}catch(error){if(error.code!=='ENOENT')throw error;}
|
|
20
|
+
return {specs,target};
|
|
21
|
+
}
|
|
22
|
+
export function readStatusProjection(specsDir){
|
|
23
|
+
const {target}=statusTarget(specsDir);
|
|
24
|
+
try{
|
|
25
|
+
const value=json(JSON.parse(fs.readFileSync(target,'utf8')),LIMIT);
|
|
26
|
+
need(value&&typeof value==='object'&&!Array.isArray(value),'status_invalid');return value;
|
|
27
|
+
}catch(error){if(error.code==='ENOENT')return null;throw error;}
|
|
28
|
+
}
|
|
29
|
+
function readInput(raw){
|
|
30
|
+
const value=json(raw,LIMIT);
|
|
31
|
+
shape(value,['feature','identity','node','state','detail','claim','expectedToken',
|
|
32
|
+
...['code','caseId','allowedNodes','previousAttempt'].filter(key=>Object.hasOwn(value,key))]);
|
|
33
|
+
validIdentity(value.identity);
|
|
34
|
+
for(const key of ['feature','node','state','detail']){
|
|
35
|
+
text(value[key]);need(Buffer.byteLength(value[key])<=2000&&!/[\r\n\0]/.test(value[key]),'status_invalid');
|
|
36
|
+
}
|
|
37
|
+
need(typeof value.claim==='boolean'&&(value.expectedToken===null||typeof value.expectedToken==='string'),'status_invalid');
|
|
38
|
+
need(!Object.hasOwn(value,'code')||value.code===null||/^[a-z][a-z0-9_]{0,63}$/.test(value.code),'status_invalid');
|
|
39
|
+
need(!Object.hasOwn(value,'caseId')||typeof value.caseId==='string','status_invalid');
|
|
40
|
+
need(!Object.hasOwn(value,'allowedNodes')||Array.isArray(value.allowedNodes)
|
|
41
|
+
&&value.allowedNodes.length<=8&&value.allowedNodes.every(node=>typeof node==='string'),'status_invalid');
|
|
42
|
+
need(!Object.hasOwn(value,'previousAttempt')||value.state==='changes_requested'
|
|
43
|
+
&&Number.isSafeInteger(value.previousAttempt)&&value.previousAttempt>0
|
|
44
|
+
&&value.previousAttempt===value.identity.attempt-1,'status_invalid');
|
|
45
|
+
return value;
|
|
46
|
+
}
|
|
47
|
+
const owns=(previous,value)=>previous.feature===value.feature&&previous.task===value.identity.taskId
|
|
48
|
+
&&(previous.run_id===undefined||previous.run_id===value.identity.runId)
|
|
49
|
+
&&(previous.attempt===undefined||previous.attempt===value.identity.attempt||previous.attempt===value.previousAttempt);
|
|
50
|
+
|
|
51
|
+
// Invoked only by cm-log-event under its Python platform lock. Validation and
|
|
52
|
+
// rename are deliberately in the SAME critical section, not two lock calls.
|
|
53
|
+
export function statusProjectionCommand(argv,environment){
|
|
54
|
+
need(argv.length===5&&argv[0]==='--status-only'&&argv[1]==='--specs-dir'
|
|
55
|
+
&&argv[3]==='--status-json','status_invalid');
|
|
56
|
+
const {specs,target}=statusTarget(argv[2]),value=readInput(JSON.parse(argv[4]));
|
|
57
|
+
if(environment.CM_LOG_PREFLIGHT==='1')return null;
|
|
58
|
+
need(environment.CM_LOG_LOCK_ADAPTER==='1'&&Number(environment.CM_LOG_LOCK_PARENT_PID)===process.ppid
|
|
59
|
+
&&environment.CM_LOG_PROJECT_LOCK===path.join(specs,'.cm-run.lock'),'status_lock_required');
|
|
60
|
+
const previous=readStatusProjection(specs);
|
|
61
|
+
if(!value.claim&&previous&&(!owns(previous,value)
|
|
62
|
+
||value.allowedNodes&&!value.allowedNodes.includes(previous.node)
|
|
63
|
+
||value.caseId&&previous.case_id&&previous.case_id!==value.caseId))return {written:false,token:null};
|
|
64
|
+
if(value.expectedToken!==null&&previous?.progress_id!==value.expectedToken)return {written:false,token:null};
|
|
65
|
+
const token=randomUUID(),projection={node:value.node,feature:value.feature,task:value.identity.taskId,
|
|
66
|
+
run_id:value.identity.runId,attempt:value.identity.attempt,state:value.state,detail:value.detail,
|
|
67
|
+
at:new Date().toTimeString().slice(0,8),progress_id:token,
|
|
68
|
+
...(value.code?{code:value.code}:{}),...(value.caseId?{case_id:value.caseId}:{})};
|
|
69
|
+
const temporary=path.join(specs,`.cm-status.json.tmp.${process.pid}.${token}`);
|
|
70
|
+
let descriptor;
|
|
71
|
+
try{
|
|
72
|
+
descriptor=fs.openSync(temporary,fs.constants.O_WRONLY|fs.constants.O_CREAT|fs.constants.O_EXCL|(fs.constants.O_NOFOLLOW??0),0o644);
|
|
73
|
+
fs.writeFileSync(descriptor,JSON.stringify(projection)+'\n');fs.fsyncSync(descriptor);fs.closeSync(descriptor);descriptor=undefined;
|
|
74
|
+
fs.renameSync(temporary,target);
|
|
75
|
+
if(process.platform!=='win32'){
|
|
76
|
+
const directory=fs.openSync(specs,fs.constants.O_RDONLY|(fs.constants.O_NOFOLLOW??0));
|
|
77
|
+
try{fs.fsyncSync(directory);}finally{fs.closeSync(directory);}
|
|
78
|
+
}
|
|
79
|
+
}finally{
|
|
80
|
+
if(descriptor!==undefined)fs.closeSync(descriptor);
|
|
81
|
+
try{fs.unlinkSync(temporary);}catch(error){if(error.code!=='ENOENT')throw error;}
|
|
82
|
+
}
|
|
83
|
+
return {written:true,token};
|
|
84
|
+
}
|
|
85
|
+
export function writeStatusProjection({specsDir,...raw}){
|
|
86
|
+
const {specs}=statusTarget(specsDir),value=readInput({claim:false,expectedToken:null,...raw});
|
|
87
|
+
const result=spawnSync('python3',[writer,'--status-only','--specs-dir',specs,'--status-json',JSON.stringify(value)],
|
|
88
|
+
{timeout:12000,maxBuffer:LIMIT,encoding:'utf8'});
|
|
89
|
+
need(!result.error&&result.status===0&&result.signal===null,'status_write_failed');
|
|
90
|
+
const receipt=JSON.parse(result.stdout);shape(receipt,['written','token']);
|
|
91
|
+
need(typeof receipt.written==='boolean'&&(receipt.token===null||typeof receipt.token==='string'),'status_write_failed');
|
|
92
|
+
return receipt;
|
|
93
|
+
}
|