@openai/codex-security 0.1.4 → 0.1.6

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.
Files changed (106) hide show
  1. package/README.md +127 -13
  2. package/_bundled_plugin/.codex-plugin/plugin.json +1 -1
  3. package/_bundled_plugin/.mcp.json +8 -1
  4. package/_bundled_plugin/examples/completed-scan/findings.json +6 -0
  5. package/_bundled_plugin/examples/completed-scan/scan-manifest.json +1 -1
  6. package/_bundled_plugin/mcp/mcp-app.html.br +0 -0
  7. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  8. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  9. package/_bundled_plugin/preflight/capability-profiles.toml +0 -57
  10. package/_bundled_plugin/references/config-preflight.md +1 -1
  11. package/_bundled_plugin/references/final-report.md +15 -7
  12. package/_bundled_plugin/references/finding-detail-fields.md +10 -2
  13. package/_bundled_plugin/references/scan-artifacts.md +11 -9
  14. package/_bundled_plugin/references/scan-contract.md +3 -1
  15. package/_bundled_plugin/schemas/definitions/artifact-common.schema.json +42 -0
  16. package/_bundled_plugin/schemas/definitions/discovery-candidate.schema.json +100 -0
  17. package/_bundled_plugin/schemas/tools/candidate-attack-paths.schema.json +181 -0
  18. package/_bundled_plugin/schemas/tools/candidate-validations.schema.json +166 -0
  19. package/_bundled_plugin/schemas/tools/deep-reducer.schema.json +120 -0
  20. package/_bundled_plugin/schemas/tools/discovery-candidates.schema.json +83 -0
  21. package/_bundled_plugin/schemas/tools/review-items.schema.json +80 -0
  22. package/_bundled_plugin/schemas/tools/scan-draft.schema.json +572 -0
  23. package/_bundled_plugin/schemas/tools/worker-threat-model.schema.json +18 -0
  24. package/_bundled_plugin/scripts/deep_scan_config.py +11 -3
  25. package/_bundled_plugin/scripts/deep_scan_workbench.py +153 -133
  26. package/_bundled_plugin/scripts/finalize_scan_contract.py +39 -0
  27. package/_bundled_plugin/scripts/generate_in_scope_files.py +134 -0
  28. package/_bundled_plugin/scripts/workbench_cli.py +33 -1
  29. package/_bundled_plugin/scripts/workbench_db.py +181 -118
  30. package/_bundled_plugin/scripts/workbench_feedback.py +2 -0
  31. package/_bundled_plugin/scripts/workbench_native_indexes.py +5 -49
  32. package/_bundled_plugin/scripts/workbench_progress.py +86 -3
  33. package/_bundled_plugin/scripts/workbench_remediation.py +19 -1
  34. package/_bundled_plugin/scripts/workbench_scan_history.py +7 -1
  35. package/_bundled_plugin/scripts/workbench_scan_start.py +11 -5
  36. package/_bundled_plugin/scripts/workbench_scan_usage.py +557 -0
  37. package/_bundled_plugin/scripts/workbench_schema.py +501 -0
  38. package/_bundled_plugin/scripts/workbench_target.py +14 -1
  39. package/_bundled_plugin/scripts/workbench_validation.py +117 -13
  40. package/_bundled_plugin/skills/attack-path-analysis/SKILL.md +4 -4
  41. package/_bundled_plugin/skills/deep-security-scan/SKILL.md +34 -28
  42. package/_bundled_plugin/skills/finding-discovery/SKILL.md +1 -1
  43. package/_bundled_plugin/skills/security-diff-scan/SKILL.md +11 -8
  44. package/_bundled_plugin/skills/security-scan/SKILL.md +16 -9
  45. package/_bundled_plugin/skills/security-scan/references/repository-wide-scan.md +26 -14
  46. package/_bundled_plugin/skills/security-scan/references/scan-artifacts-and-ledger.md +1 -1
  47. package/_bundled_plugin/skills/threat-model/SKILL.md +2 -2
  48. package/_bundled_plugin/skills/validation/SKILL.md +5 -5
  49. package/_bundled_plugin/skills/vulnerability-writeup/SKILL.md +145 -227
  50. package/_bundled_plugin/skills/vulnerability-writeup/references/report-format.md +53 -68
  51. package/dist/api.d.ts +30 -8
  52. package/dist/api.d.ts.map +1 -1
  53. package/dist/api.js +438 -66
  54. package/dist/api.js.map +1 -1
  55. package/dist/auth.d.ts.map +1 -1
  56. package/dist/auth.js +262 -44
  57. package/dist/auth.js.map +1 -1
  58. package/dist/cli.d.ts +4 -3
  59. package/dist/cli.d.ts.map +1 -1
  60. package/dist/cli.js +713 -148
  61. package/dist/cli.js.map +1 -1
  62. package/dist/config.d.ts +28 -0
  63. package/dist/config.d.ts.map +1 -1
  64. package/dist/config.js +39 -2
  65. package/dist/config.js.map +1 -1
  66. package/dist/contract.d.ts.map +1 -1
  67. package/dist/contract.js +14 -0
  68. package/dist/contract.js.map +1 -1
  69. package/dist/cost.d.ts +7 -0
  70. package/dist/cost.d.ts.map +1 -1
  71. package/dist/cost.js +397 -26
  72. package/dist/cost.js.map +1 -1
  73. package/dist/errors.d.ts +2 -0
  74. package/dist/errors.d.ts.map +1 -1
  75. package/dist/errors.js +48 -0
  76. package/dist/errors.js.map +1 -1
  77. package/dist/index.d.ts +3 -2
  78. package/dist/index.d.ts.map +1 -1
  79. package/dist/index.js.map +1 -1
  80. package/dist/multiscan.d.ts +1 -0
  81. package/dist/multiscan.d.ts.map +1 -1
  82. package/dist/multiscan.js +5 -7
  83. package/dist/multiscan.js.map +1 -1
  84. package/dist/runtime.d.ts +40 -1
  85. package/dist/runtime.d.ts.map +1 -1
  86. package/dist/runtime.js +742 -46
  87. package/dist/runtime.js.map +1 -1
  88. package/dist/scan-activity.d.ts +13 -0
  89. package/dist/scan-activity.d.ts.map +1 -0
  90. package/dist/scan-activity.js +319 -0
  91. package/dist/scan-activity.js.map +1 -0
  92. package/dist/scan-dashboard.d.ts +47 -0
  93. package/dist/scan-dashboard.d.ts.map +1 -0
  94. package/dist/scan-dashboard.js +444 -0
  95. package/dist/scan-dashboard.js.map +1 -0
  96. package/dist/scan-history-renderer.d.ts.map +1 -1
  97. package/dist/scan-history-renderer.js +4 -1
  98. package/dist/scan-history-renderer.js.map +1 -1
  99. package/dist/version.d.ts +1 -1
  100. package/dist/version.js +1 -1
  101. package/dist/version.js.map +1 -1
  102. package/dist/worker-progress.d.ts +7 -0
  103. package/dist/worker-progress.d.ts.map +1 -1
  104. package/dist/worker-progress.js +68 -0
  105. package/dist/worker-progress.js.map +1 -1
  106. package/package.json +3 -3
@@ -24,21 +24,21 @@ from typing import Any
24
24
 
25
25
  try:
26
26
  import fcntl as posix_file_lock
27
- except ModuleNotFoundError: # pragma: no cover - exercised through the Windows lock test.
27
+ except ModuleNotFoundError: # pragma: no cover
28
28
  posix_file_lock = None
29
29
 
30
30
  try:
31
31
  import msvcrt as windows_file_lock
32
- except ModuleNotFoundError: # pragma: no cover - msvcrt is only available on Windows.
32
+ except ModuleNotFoundError: # pragma: no cover
33
33
  windows_file_lock = None
34
34
 
35
- # Plugin hosts may enable safe-path isolation.
36
35
  sys.path.insert(0, str(Path(__file__).resolve().parent))
37
36
  import deep_scan_workbench as deep_scan
38
37
  import workbench_native_indexes as native_indexes
39
38
  import workbench_progress as progress
40
39
  import workbench_remediation as remediation
41
40
  import workbench_scan_history as scan_history
41
+ import workbench_scan_usage as scan_usage
42
42
  from filesystem_identity import serialize_filesystem_identity as serialize_filesystem_identity
43
43
  from filesystem_identity import (
44
44
  stored_filesystem_identity_matches as stored_filesystem_identity_matches,
@@ -79,6 +79,7 @@ from workbench_constants import (
79
79
  SQLITE_RETRY_ATTEMPTS,
80
80
  )
81
81
  from workbench_feedback import get_scan_feedback
82
+ from workbench_remediation import remediation_claim_is_active
82
83
  from workbench_scan_start import (
83
84
  archive_scan,
84
85
  compact_timestamp,
@@ -88,7 +89,15 @@ from workbench_scan_start import (
88
89
  scan_target_identity,
89
90
  stored_diff_target,
90
91
  )
91
- from workbench_schema import MIGRATIONS, normalize_pre_release_migrations, sql_statements
92
+ from workbench_schema import (
93
+ MIGRATIONS,
94
+ )
95
+ from workbench_schema import (
96
+ apply_migrations as apply_schema_migrations,
97
+ )
98
+ from workbench_schema import (
99
+ sql_statements as sql_statements,
100
+ )
92
101
  from workbench_source_excerpt import finding_source_excerpt
93
102
  from workbench_target import (
94
103
  clean_worktree_content_digest,
@@ -116,9 +125,12 @@ from workbench_validation import (
116
125
  capability_preflight_json,
117
126
  optional_text,
118
127
  parse_scan_cost,
119
- require_close_reason,
128
+ path_within_scope,
129
+ require_close_note,
120
130
  require_occurrence,
121
131
  require_uuid,
132
+ sqlite_busy,
133
+ user_text,
122
134
  )
123
135
 
124
136
  FINDING_ARTIFACT_DIRECTORIES_LIMIT = 80
@@ -137,23 +149,6 @@ def stale_claim_before(seconds: int = CLAIM_LEASE_SECONDS) -> str:
137
149
  )
138
150
 
139
151
 
140
- def remediation_claim_is_active(remediation: sqlite3.Row) -> bool:
141
- if remediation["pending_action_claim_token"] is None:
142
- return False
143
- delivered_at = remediation["pending_action_delivered_at"]
144
- claimed_at = delivered_at or remediation["pending_action_claimed_at"]
145
- if not isinstance(claimed_at, str):
146
- return True
147
- try:
148
- parsed = datetime.fromisoformat(claimed_at)
149
- if parsed.tzinfo is None:
150
- return True
151
- except ValueError:
152
- return True
153
- lease_seconds = DELIVERED_ACTION_LEASE_SECONDS if delivered_at else CLAIM_LEASE_SECONDS
154
- return parsed > datetime.now(timezone.utc) - timedelta(seconds=lease_seconds)
155
-
156
-
157
152
  def state_dir() -> Path:
158
153
  state_dir = os.environ.get("CODEX_SECURITY_STATE_DIR")
159
154
  if state_dir:
@@ -200,7 +195,6 @@ def acquire_completion_file_lock(descriptor: int) -> None:
200
195
  if windows_file_lock is None:
201
196
  raise SystemExit("Scan completion requires operating-system file locking support.")
202
197
 
203
- # Retry seeding and locking the first byte.
204
198
  while os.fstat(descriptor).st_size == 0:
205
199
  os.lseek(descriptor, 0, os.SEEK_SET)
206
200
  try:
@@ -252,10 +246,6 @@ def connect() -> sqlite3.Connection:
252
246
  raise AssertionError("SQLite retry loop exhausted unexpectedly.")
253
247
 
254
248
 
255
- def sqlite_busy(error: sqlite3.OperationalError) -> bool:
256
- return "locked" in str(error).lower() or "busy" in str(error).lower()
257
-
258
-
259
249
  def setup_preference(connection: sqlite3.Connection) -> dict[str, bool]:
260
250
  row = connection.execute(
261
251
  "SELECT skip_setup_ui FROM setup_preferences WHERE singleton = 1"
@@ -290,37 +280,7 @@ def disable_setup_ui(connection: sqlite3.Connection, args: argparse.Namespace) -
290
280
 
291
281
 
292
282
  def apply_migrations(connection: sqlite3.Connection) -> None:
293
- connection.commit()
294
- connection.execute("BEGIN IMMEDIATE")
295
- try:
296
- connection.execute(
297
- """
298
- CREATE TABLE IF NOT EXISTS schema_migrations (
299
- version INTEGER PRIMARY KEY,
300
- name TEXT NOT NULL,
301
- applied_at TEXT NOT NULL
302
- )
303
- """
304
- )
305
- normalize_pre_release_migrations(connection, now())
306
- applied = {
307
- row["version"] for row in connection.execute("SELECT version FROM schema_migrations")
308
- }
309
- for version, name, sql in MIGRATIONS:
310
- if version in applied:
311
- continue
312
- for statement in sql_statements(sql):
313
- connection.execute(statement)
314
- connection.execute(
315
- "INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)",
316
- (version, name, now()),
317
- )
318
- if 16 not in applied:
319
- backfill_security_targets(connection)
320
- connection.commit()
321
- except BaseException:
322
- connection.rollback()
323
- raise
283
+ apply_schema_migrations(connection, MIGRATIONS, now, backfill_security_targets)
324
284
 
325
285
 
326
286
  def require_target(value: str) -> Path:
@@ -565,8 +525,6 @@ def expected_coverage_mode(scan: sqlite3.Row) -> str:
565
525
 
566
526
 
567
527
  def workbench_completion_binding(scan: sqlite3.Row, completed_at: str) -> dict[str, Any]:
568
- """Return deterministic draft fields owned by the selected workbench scan."""
569
-
570
528
  contract = scan_contract(scan)
571
529
  target_contract = contract["target"]
572
530
  plugin_manifest = read_json_object(
@@ -678,16 +636,6 @@ def verify_manifest_binding(scan: sqlite3.Row, manifest: dict[str, Any]) -> None
678
636
  raise SystemExit("scan-manifest.json scope must stay inside the workbench scan scope.")
679
637
 
680
638
 
681
- def path_within_scope(path: str, scope: str) -> bool:
682
- candidate = PurePosixPath(path)
683
- requested = PurePosixPath(scope)
684
- if candidate.is_absolute() or ".." in candidate.parts:
685
- return False
686
- if requested == PurePosixPath("."):
687
- return True
688
- return candidate == requested or requested in candidate.parents
689
-
690
-
691
639
  def require_scope(scope: str, mode: str, target: Path) -> str:
692
640
  value = scope.strip() or "."
693
641
  if "\\" in value:
@@ -811,7 +759,7 @@ def create_workspace(connection: sqlite3.Connection, args: argparse.Namespace) -
811
759
  optional_text(args.target_summary, maximum=2400),
812
760
  default_scope,
813
761
  args.mode,
814
- optional_text(args.user_context),
762
+ user_text(args.user_context),
815
763
  diff_target_kind,
816
764
  diff_base_revision,
817
765
  diff_head_revision,
@@ -920,7 +868,7 @@ def save_workspace(connection: sqlite3.Connection, args: argparse.Namespace) ->
920
868
  target_summary,
921
869
  scope,
922
870
  args.mode,
923
- optional_text(args.user_context),
871
+ user_text(args.user_context),
924
872
  diff_target["kind"] if diff_target else None,
925
873
  diff_target["baseRevision"] if diff_target else None,
926
874
  diff_target["headRevision"] if diff_target else None,
@@ -994,7 +942,7 @@ def begin_diff_resolution(
994
942
  target_id,
995
943
  str(target),
996
944
  target_title,
997
- optional_text(args.user_context),
945
+ user_text(args.user_context),
998
946
  request_id,
999
947
  timestamp,
1000
948
  workspace["id"],
@@ -1172,6 +1120,8 @@ def start_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dict
1172
1120
  target_summary=target_summary,
1173
1121
  scope_file_count=scope_file_count,
1174
1122
  timestamp=timestamp,
1123
+ model=args.model,
1124
+ reasoning_effort=args.reasoning_effort,
1175
1125
  )
1176
1126
  if manages_transaction:
1177
1127
  connection.commit()
@@ -1184,6 +1134,18 @@ def start_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dict
1184
1134
 
1185
1135
  def start_prompt_only_scan(
1186
1136
  connection: sqlite3.Connection, args: argparse.Namespace
1137
+ ) -> dict[str, Any]:
1138
+ return _start_prompt_driven_scan(connection, args, headless_standard=False)
1139
+
1140
+
1141
+ def start_headless_standard_scan(
1142
+ connection: sqlite3.Connection, args: argparse.Namespace
1143
+ ) -> dict[str, Any]:
1144
+ return _start_prompt_driven_scan(connection, args, headless_standard=True)
1145
+
1146
+
1147
+ def _start_prompt_driven_scan(
1148
+ connection: sqlite3.Connection, args: argparse.Namespace, *, headless_standard: bool
1187
1149
  ) -> dict[str, Any]:
1188
1150
  thread_id = optional_text(args.thread_id, maximum=512)
1189
1151
  if thread_id is None:
@@ -1201,7 +1163,7 @@ def start_prompt_only_scan(
1201
1163
  target_path = str(target)
1202
1164
  scope = inspected["scope"]
1203
1165
  diff_target = inspected["diffTarget"]
1204
- user_context = optional_text(args.user_context)
1166
+ user_context = user_text(args.user_context)
1205
1167
  target_summary = optional_text(args.target_summary, maximum=2400)
1206
1168
  if diff_target is not None and not target_summary:
1207
1169
  target_summary = diff_target_summary(diff_target)
@@ -1214,7 +1176,7 @@ def start_prompt_only_scan(
1214
1176
 
1215
1177
  connection.execute("BEGIN IMMEDIATE")
1216
1178
  try:
1217
- if not setup_preference(connection)["skipSetupUi"]:
1179
+ if not headless_standard and not setup_preference(connection)["skipSetupUi"]:
1218
1180
  raise SystemExit(
1219
1181
  "Prompt-only scanning requires the persisted setup UI opt-out preference."
1220
1182
  )
@@ -1250,7 +1212,13 @@ def start_prompt_only_scan(
1250
1212
  AND scans.target_snapshot_digest IS ? AND scans.target_device = ?
1251
1213
  AND scans.target_inode = ? AND scans.status = 'running'
1252
1214
  AND scans.handoff_status = 'delivered'
1253
- AND scans.handoff_claim_token IS NULL
1215
+ AND (
1216
+ (? = 0 AND scans.handoff_claim_token IS NULL)
1217
+ OR (
1218
+ ? = 1 AND scans.handoff_claim_token IS NOT NULL
1219
+ AND scans.continuation_thread_id = ?
1220
+ )
1221
+ )
1254
1222
  ORDER BY scans.updated_at DESC, scans.started_at DESC, scans.id LIMIT 1
1255
1223
  """,
1256
1224
  (
@@ -1262,11 +1230,28 @@ def start_prompt_only_scan(
1262
1230
  target_summary,
1263
1231
  *diff_identity,
1264
1232
  *target_identity,
1233
+ int(headless_standard),
1234
+ int(headless_standard),
1235
+ thread_id,
1265
1236
  ),
1266
1237
  ).fetchone()
1267
1238
  if existing is not None:
1268
1239
  connection.commit()
1269
1240
  return {**scan_context(connection, existing["id"]), "startDisposition": "joined"}
1241
+ if headless_standard and not setup_preference(connection)["skipSetupUi"]:
1242
+ pending = connection.execute(
1243
+ """
1244
+ SELECT 1 FROM workspaces
1245
+ WHERE thread_id = ? AND target_path = ? AND default_scope = ?
1246
+ AND default_mode = 'standard' AND active_scan_id IS NULL LIMIT 1
1247
+ """,
1248
+ (thread_id, target_path, scope),
1249
+ ).fetchone()
1250
+ if pending is not None:
1251
+ raise SystemExit(
1252
+ "A matching Codex Security setup workspace is waiting for Start scan. "
1253
+ "Finish that setup and retry with its scanId."
1254
+ )
1270
1255
  target_root.mkdir(parents=True, exist_ok=True)
1271
1256
  workspace_id = str(uuid.uuid4())
1272
1257
  scan_id = str(uuid.uuid4())
@@ -1309,7 +1294,21 @@ def start_prompt_only_scan(
1309
1294
  scope_file_count=scope_file_count,
1310
1295
  timestamp=timestamp,
1311
1296
  handoff_status="delivered",
1297
+ model=args.model,
1298
+ reasoning_effort=args.reasoning_effort,
1312
1299
  )
1300
+ if headless_standard:
1301
+ claimed = connection.execute(
1302
+ """
1303
+ UPDATE scans
1304
+ SET handoff_claim_token = ?, continuation_thread_id = ?
1305
+ WHERE id = ? AND status = 'running' AND handoff_status = 'delivered'
1306
+ AND handoff_claim_token IS NULL AND continuation_thread_id IS NULL
1307
+ """,
1308
+ (str(uuid.uuid4()), thread_id, scan_id),
1309
+ )
1310
+ if claimed.rowcount != 1:
1311
+ raise SystemExit("Codex Security headless scan ownership could not be recorded.")
1313
1312
  connection.commit()
1314
1313
  except BaseException:
1315
1314
  connection.rollback()
@@ -1369,7 +1368,12 @@ def complete_scan(
1369
1368
  cost_json = None if prepare_only else parse_scan_cost(args.cost_json)
1370
1369
  with scan_completion_lock(scan_id):
1371
1370
  return complete_scan_locked(
1372
- connection, scan_id, args.claim_token, cost_json, prepare_only=prepare_only
1371
+ connection,
1372
+ scan_id,
1373
+ args.claim_token,
1374
+ cost_json,
1375
+ prepare_only=prepare_only,
1376
+ thread_id=getattr(args, "thread_id", None),
1373
1377
  )
1374
1378
 
1375
1379
 
@@ -1380,6 +1384,7 @@ def complete_scan_locked(
1380
1384
  cost_json: str | None,
1381
1385
  *,
1382
1386
  prepare_only: bool = False,
1387
+ thread_id: str | None = None,
1383
1388
  ) -> dict[str, Any]:
1384
1389
  scan = require_scan(connection, scan_id)
1385
1390
  if scan["status"] == "complete":
@@ -1407,14 +1412,38 @@ def complete_scan_locked(
1407
1412
  if scan["recipe_json"] is None:
1408
1413
  deep_scan.require_deep_scan_ready_for_parent_completion(connection, scan)
1409
1414
  warnings = json.loads(scan["completion_warnings_json"])
1415
+ target_warnings: list[str] = []
1410
1416
  warning = scan_target_warning(scan)
1411
- if warning is not None and warning not in warnings:
1412
- warnings.append(warning)
1417
+ if warning is not None:
1418
+ target_warnings.append(warning)
1419
+ if warning not in warnings:
1420
+ warnings.append(warning)
1413
1421
  scan_dir = require_canonical_scan_directory(Path(scan["scan_dir"]))
1414
1422
  completion_timestamp = now()
1415
1423
  completion_binding = workbench_completion_binding(scan, completion_timestamp)
1416
1424
  if scan["recipe_json"] is not None:
1417
- manifest = read_json_object(artifact_path(scan_dir, ARTIFACTS["manifest"], required=True))
1425
+ draft_artifacts: dict[str, Path] = {}
1426
+ missing_drafts = []
1427
+ for file_name in (
1428
+ ARTIFACTS["manifest"],
1429
+ ARTIFACTS["findings"],
1430
+ ARTIFACTS["coverage"],
1431
+ ):
1432
+ try:
1433
+ (scan_dir / file_name).lstat()
1434
+ except FileNotFoundError:
1435
+ missing_drafts.append(file_name)
1436
+ continue
1437
+ draft_path = artifact_path(scan_dir, file_name, required=True)
1438
+ if draft_path is not None:
1439
+ draft_artifacts[file_name] = draft_path
1440
+ if missing_drafts:
1441
+ raise SystemExit(
1442
+ "Scan agent did not create required draft artifacts: "
1443
+ f"{', '.join(missing_drafts)}. Check that the scan agent can run shell "
1444
+ "commands and write to the scan directory before retrying."
1445
+ )
1446
+ manifest = read_json_object(draft_artifacts[ARTIFACTS["manifest"]])
1418
1447
  manifest_scan = manifest.get("scan")
1419
1448
  if isinstance(manifest_scan, dict) and manifest_scan.get("sealedAt") is not None:
1420
1449
  completion_binding["startedAt"] = manifest_scan.get("startedAt")
@@ -1427,8 +1456,11 @@ def complete_scan_locked(
1427
1456
  completion_warnings=warnings,
1428
1457
  )
1429
1458
  warning = scan_target_warning(scan)
1430
- if warning is not None and warning not in warnings:
1431
- warnings.append(warning)
1459
+ if warning is not None:
1460
+ if warning not in target_warnings:
1461
+ target_warnings.append(warning)
1462
+ if warning not in warnings:
1463
+ warnings.append(warning)
1432
1464
  manifest, findings, _ = _write_prepared_scan_finalization(prepared)
1433
1465
  except ContractError as exc:
1434
1466
  raise SystemExit(str(exc)) from exc
@@ -1450,7 +1482,18 @@ def complete_scan_locked(
1450
1482
  except BaseException:
1451
1483
  connection.rollback()
1452
1484
  raise
1453
- return scan_context(connection, scan["id"])
1485
+ context = scan_context(connection, scan["id"])
1486
+ context["targetWarnings"] = target_warnings
1487
+ return context
1488
+
1489
+ if cost_json is None:
1490
+ measured_usage = scan_usage.collect_scan_usage(
1491
+ connection,
1492
+ scan,
1493
+ thread_id=thread_id,
1494
+ completed_at=completion_timestamp,
1495
+ )
1496
+ cost_json = parse_scan_cost(scan_usage.measured_scan_cost_json(measured_usage))
1454
1497
  connection.execute("BEGIN IMMEDIATE")
1455
1498
  try:
1456
1499
  timestamp = manifest["scan"]["completedAt"]
@@ -1509,7 +1552,9 @@ def complete_scan_locked(
1509
1552
  except BaseException:
1510
1553
  connection.rollback()
1511
1554
  raise
1512
- return scan_context(connection, scan["id"])
1555
+ context = scan_context(connection, scan["id"])
1556
+ context["targetWarnings"] = target_warnings
1557
+ return context
1513
1558
 
1514
1559
 
1515
1560
  def register_cli_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[str, Any]:
@@ -1622,6 +1667,7 @@ def register_cli_scan(connection: sqlite3.Connection, args: argparse.Namespace)
1622
1667
  "contract": scan_contract(scan),
1623
1668
  "scanDir": str(scan_dir),
1624
1669
  "scanId": scan_id,
1670
+ "scopeFileCount": scope_file_count,
1625
1671
  "targetId": target_id,
1626
1672
  "targetRevision": scan["target_revision"],
1627
1673
  }
@@ -1720,6 +1766,7 @@ def fail_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[
1720
1766
  args.claim_token,
1721
1767
  error_message="Scan failure is owned by another continuation.",
1722
1768
  )
1769
+ message = optional_text(args.message, maximum=2400)
1723
1770
  updated = connection.execute(
1724
1771
  """
1725
1772
  UPDATE scans
@@ -1727,22 +1774,11 @@ def fail_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[
1727
1774
  cost_json = ?
1728
1775
  WHERE id = ? AND status = 'running'
1729
1776
  """,
1730
- (
1731
- optional_text(args.message, maximum=2400),
1732
- timestamp,
1733
- timestamp,
1734
- cost_json,
1735
- scan["id"],
1736
- ),
1777
+ (message, timestamp, timestamp, cost_json, scan["id"]),
1737
1778
  )
1738
1779
  if updated.rowcount != 1:
1739
1780
  raise SystemExit("Only a running scan can be marked failed.")
1740
- deep_scan.fail_from_parent_scan(
1741
- connection,
1742
- scan["id"],
1743
- optional_text(args.message, maximum=2400),
1744
- timestamp,
1745
- )
1781
+ deep_scan.fail_from_parent_scan(connection, scan["id"], message, timestamp)
1746
1782
  progress_updated = connection.execute(
1747
1783
  "UPDATE scan_progress SET updated_at = ? WHERE scan_id = ?",
1748
1784
  (timestamp, scan["id"]),
@@ -1803,7 +1839,7 @@ def set_finding_triage(connection: sqlite3.Connection, args: argparse.Namespace)
1803
1839
  if args.status == "closed" and close_reason is None:
1804
1840
  raise SystemExit("Choose why this finding is being closed.")
1805
1841
  note = optional_text(args.note, maximum=2400)
1806
- require_close_reason(close_reason, note)
1842
+ require_close_note(close_reason, note)
1807
1843
  connection.execute("BEGIN IMMEDIATE")
1808
1844
  try:
1809
1845
  timestamp = now()
@@ -2789,7 +2825,9 @@ def workspace_state(
2789
2825
  result["capabilityPreflight"] = json.loads(workspace["capability_preflight_json"])
2790
2826
  selected_scan_id = result_scan_id or workspace["active_scan_id"]
2791
2827
  if selected_scan_id:
2792
- result["results"] = scan_result(connection, require_scan(connection, selected_scan_id))
2828
+ selected_scan = require_scan(connection, selected_scan_id)
2829
+ result["userContext"] = selected_scan["user_context"]
2830
+ result["results"] = scan_result(connection, selected_scan)
2793
2831
  return result
2794
2832
 
2795
2833
  target_metadata = None
@@ -2983,15 +3021,12 @@ def scan_result(
2983
3021
  progress_result["independentReviews"] = {
2984
3022
  "active": independent_reviews["active"],
2985
3023
  "completed": independent_reviews["completed"],
3024
+ "consolidating": independent_reviews["consolidating"],
2986
3025
  }
2987
3026
  return {
2988
3027
  "artifacts": artifacts,
2989
3028
  "canceledAt": scan["canceled_at"],
2990
- **(
2991
- {"cost": json.loads(scan["cost_json"], parse_constant=reject_non_finite_json)}
2992
- if scan["cost_json"] is not None
2993
- else {}
2994
- ),
3029
+ **scan_usage.stored_scan_cost_fields(scan["cost_json"]),
2995
3030
  "contract": scan_contract(scan),
2996
3031
  "continuationThreadId": scan["continuation_thread_id"],
2997
3032
  "failureMessage": scan["failure_message"],
@@ -3003,8 +3038,10 @@ def scan_result(
3003
3038
  "handoffClaimToken": scan["handoff_claim_token"],
3004
3039
  "handoffStatus": scan["handoff_status"],
3005
3040
  "mode": scan["mode"],
3041
+ "model": scan["model"],
3006
3042
  "diffTarget": stored_diff_target(scan),
3007
3043
  "progress": progress_result,
3044
+ "reasoningEffort": scan["reasoning_effort"],
3008
3045
  "remediationAvailable": remediation_available,
3009
3046
  "remediationUnavailableReason": remediation_unavailable_reason,
3010
3047
  "reportAvailable": "markdownReport" in artifacts,
@@ -3434,7 +3471,7 @@ def available_artifact_path(scan_dir: Path, candidate: Path) -> Path | None:
3434
3471
  resolved.relative_to(resolved_scan_dir)
3435
3472
  except (FileNotFoundError, RuntimeError, SystemExit, ValueError):
3436
3473
  return None
3437
- if resolved != candidate or not candidate.is_file():
3474
+ if os.path.normcase(resolved) != os.path.normcase(candidate) or not candidate.is_file():
3438
3475
  return None
3439
3476
  return resolved
3440
3477
 
@@ -3469,6 +3506,38 @@ def require_canonical_scan_directory(scan_dir: Path) -> Path:
3469
3506
  scan_dir
3470
3507
  ):
3471
3508
  raise SystemExit("Scan directory must be an existing canonical non-symlink directory.")
3509
+ # Re-check privacy on every resolution so a mid-scan rename/replace under a
3510
+ # shared parent cannot substitute another user's forged artifact tree.
3511
+ if os.name != "nt":
3512
+ if stat.S_IMODE(metadata.st_mode) & 0o077:
3513
+ raise SystemExit(
3514
+ "Scan directory must not be accessible to other users (chmod 700)."
3515
+ )
3516
+ geteuid = getattr(os, "geteuid", None)
3517
+ effective_uid = geteuid() if geteuid is not None else None
3518
+ if effective_uid is not None and metadata.st_uid != effective_uid:
3519
+ raise SystemExit("Scan directory must be owned by the current user.")
3520
+ for parent in scan_dir.parents:
3521
+ try:
3522
+ parent_metadata = parent.lstat()
3523
+ except OSError as exc:
3524
+ raise SystemExit("Scan output parent could not be inspected.") from exc
3525
+ if not stat.S_ISDIR(parent_metadata.st_mode) or stat.S_ISLNK(
3526
+ parent_metadata.st_mode
3527
+ ):
3528
+ raise SystemExit("Scan output parent must be a non-symlink directory.")
3529
+ if effective_uid is not None and parent_metadata.st_uid not in {
3530
+ 0,
3531
+ effective_uid,
3532
+ }:
3533
+ raise SystemExit("Scan output parent must have a trusted owner.")
3534
+ if (
3535
+ stat.S_IMODE(parent_metadata.st_mode) & 0o022
3536
+ and not parent_metadata.st_mode & stat.S_ISVTX
3537
+ ):
3538
+ raise SystemExit(
3539
+ "Scan output parent must not be group- or world-writable without the sticky bit."
3540
+ )
3472
3541
  return scan_dir
3473
3542
 
3474
3543
 
@@ -3544,6 +3613,8 @@ def main() -> None:
3544
3613
  result = start_scan(connection, args)
3545
3614
  elif args.command == "start-prompt-only-scan":
3546
3615
  result = start_prompt_only_scan(connection, args)
3616
+ elif args.command == "start-headless-standard-scan":
3617
+ result = start_headless_standard_scan(connection, args)
3547
3618
  elif args.command == "begin-deep-scan":
3548
3619
  result = deep_scan.begin_deep_scan(connection, args)
3549
3620
  elif args.command == "get-deep-scan":
@@ -3594,22 +3665,14 @@ def main() -> None:
3594
3665
  read_coverage=coverage_for_comparison,
3595
3666
  )
3596
3667
  elif args.command == "list-global-findings":
3597
- result = native_indexes.list_global_findings(
3598
- connection, args, read_coverage=coverage_for_comparison
3599
- )
3668
+ result = native_indexes.list_global_findings(connection, args)
3600
3669
  elif args.command == "list-repositories":
3601
- result = native_indexes.list_repositories(
3602
- connection, args, read_coverage=coverage_for_comparison
3603
- )
3670
+ result = native_indexes.list_repositories(connection, args)
3604
3671
  elif args.command == "list-findings":
3605
3672
  result = list_findings(connection, args)
3606
- elif args.command == "update-progress":
3607
- result = progress.update_progress(
3608
- connection,
3609
- args,
3610
- now=now,
3611
- require_scan=require_scan,
3612
- scan_context=scan_context,
3673
+ elif args.command in {"update-progress", "update-scan-context"}:
3674
+ result = progress.update(
3675
+ connection, args, now, require_scan, require_workspace, scan_context
3613
3676
  )
3614
3677
  elif args.command in {"prepare-scan-completion", "complete-scan"}:
3615
3678
  result = complete_scan(
@@ -8,7 +8,9 @@ import sys
8
8
  from pathlib import Path
9
9
  from typing import Any
10
10
 
11
+ # Some plugin hosts launch Python with safe-path isolation enabled.
11
12
  sys.path.insert(0, str(Path(__file__).resolve().parent))
13
+
12
14
  from workbench_constants import (
13
15
  FINDING_LOCATION_PATH_BYTES,
14
16
  FINDING_SUMMARY_BYTES,