Run completed successfully: 4 trials, 0 exceptions, mean reward 0.6525.

| Trial | Reward |
|---|---:|
| hCpLyTL | 0.50 |
| Vz8kjv9 | 0.58 |
| NSP5wKq | 0.63 |
| F8cEYH2 | 0.90 |

Runtime: 10m 37s. Results (harbor-jobs/2026-10-16__17-09-39/result.json)
This commit is contained in:
2026-10-16 13:25:47 -04:00
parent b1ef2ab681
commit 18fc4f00b9
135 changed files with 16255 additions and 0 deletions

View File

@@ -0,0 +1,30 @@
{
"job_name": "2026-10-16__17-09-39",
"jobs_dir": "harbor-jobs",
"n_attempts": 4,
"environment": {
"type": "docker",
"force_build": true,
"delete": false
},
"verifier": {
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
}
},
"agents": [
{
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"kwargs": {
"reasoning_effort": "max"
}
}
],
"tasks": [
{
"path": "harbor-tasks/potion-voice-user-ownership"
}
]
}

View File

@@ -0,0 +1,196 @@
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Running command: set -x; if command -v apt-get >/dev/null 2>&1; then apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq curl ripgrep >/dev/null 2>&1 || true; fi; if ! command -v codex >/dev/null 2>&1; then CODEX_INSTALL_DIR=/usr/local/bin CODEX_NON_INTERACTIVE=true sh -c "curl -fsSL https://chatgpt.com/codex/install.sh | sh" >&2 || true; fi; if ! command -v codex >/dev/null 2>&1 && [ -x "$HOME/.local/bin/codex" ]; then ln -sf "$HOME/.local/bin/codex" /usr/local/bin/codex; fi; if ! command -v codex >/dev/null 2>&1; then export NVM_DIR="${NVM_DIR:-/usr/local/share/nvm}"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" >/dev/null 2>&1 || true; if ! command -v npm >/dev/null 2>&1; then npm_path="$(find /usr/local/share/nvm /usr/local /usr/lib /opt -name npm -type f 2>/dev/null | head -1)"; [ -n "$npm_path" ] && export PATH="$PATH:$(dirname "$npm_path")"; fi; command -v npm >/dev/null 2>&1 && npm install -g @openai/codex@latest; fi; for bin in node codex; do p="$(command -v "$bin" 2>/dev/null || true)"; [ -n "$p" ] && [ "$p" != "/usr/local/bin/$bin" ] && ln -sf "$p" "/usr/local/bin/$bin" || true; done; command -v codex >/dev/null 2>&1 || { echo "FATAL: codex CLI unavailable (standalone installer and npm both failed)" >&2; exit 1; }; codex --version
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Running command: set -x; if command -v apt-get >/dev/null 2>&1; then apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq curl ripgrep >/dev/null 2>&1 || true; fi; if ! command -v codex >/dev/null 2>&1; then CODEX_INSTALL_DIR=/usr/local/bin CODEX_NON_INTERACTIVE=true sh -c "curl -fsSL https://chatgpt.com/codex/install.sh | sh" >&2 || true; fi; if ! command -v codex >/dev/null 2>&1 && [ -x "$HOME/.local/bin/codex" ]; then ln -sf "$HOME/.local/bin/codex" /usr/local/bin/codex; fi; if ! command -v codex >/dev/null 2>&1; then export NVM_DIR="${NVM_DIR:-/usr/local/share/nvm}"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" >/dev/null 2>&1 || true; if ! command -v npm >/dev/null 2>&1; then npm_path="$(find /usr/local/share/nvm /usr/local /usr/lib /opt -name npm -type f 2>/dev/null | head -1)"; [ -n "$npm_path" ] && export PATH="$PATH:$(dirname "$npm_path")"; fi; command -v npm >/dev/null 2>&1 && npm install -g @openai/codex@latest; fi; for bin in node codex; do p="$(command -v "$bin" 2>/dev/null || true)"; [ -n "$p" ] && [ "$p" != "/usr/local/bin/$bin" ] && ln -sf "$p" "/usr/local/bin/$bin" || true; done; command -v codex >/dev/null 2>&1 || { echo "FATAL: codex CLI unavailable (standalone installer and npm both failed)" >&2; exit 1; }; codex --version
Running command: set -x; if command -v apt-get >/dev/null 2>&1; then apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq curl ripgrep >/dev/null 2>&1 || true; fi; if ! command -v codex >/dev/null 2>&1; then CODEX_INSTALL_DIR=/usr/local/bin CODEX_NON_INTERACTIVE=true sh -c "curl -fsSL https://chatgpt.com/codex/install.sh | sh" >&2 || true; fi; if ! command -v codex >/dev/null 2>&1 && [ -x "$HOME/.local/bin/codex" ]; then ln -sf "$HOME/.local/bin/codex" /usr/local/bin/codex; fi; if ! command -v codex >/dev/null 2>&1; then export NVM_DIR="${NVM_DIR:-/usr/local/share/nvm}"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" >/dev/null 2>&1 || true; if ! command -v npm >/dev/null 2>&1; then npm_path="$(find /usr/local/share/nvm /usr/local /usr/lib /opt -name npm -type f 2>/dev/null | head -1)"; [ -n "$npm_path" ] && export PATH="$PATH:$(dirname "$npm_path")"; fi; command -v npm >/dev/null 2>&1 && npm install -g @openai/codex@latest; fi; for bin in node codex; do p="$(command -v "$bin" 2>/dev/null || true)"; [ -n "$p" ] && [ "$p" != "/usr/local/bin/$bin" ] && ln -sf "$p" "/usr/local/bin/$bin" || true; done; command -v codex >/dev/null 2>&1 || { echo "FATAL: codex CLI unavailable (standalone installer and npm both failed)" >&2; exit 1; }; codex --version
Running command: set -x; if command -v apt-get >/dev/null 2>&1; then apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq curl ripgrep >/dev/null 2>&1 || true; fi; if ! command -v codex >/dev/null 2>&1; then CODEX_INSTALL_DIR=/usr/local/bin CODEX_NON_INTERACTIVE=true sh -c "curl -fsSL https://chatgpt.com/codex/install.sh | sh" >&2 || true; fi; if ! command -v codex >/dev/null 2>&1 && [ -x "$HOME/.local/bin/codex" ]; then ln -sf "$HOME/.local/bin/codex" /usr/local/bin/codex; fi; if ! command -v codex >/dev/null 2>&1; then export NVM_DIR="${NVM_DIR:-/usr/local/share/nvm}"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" >/dev/null 2>&1 || true; if ! command -v npm >/dev/null 2>&1; then npm_path="$(find /usr/local/share/nvm /usr/local /usr/lib /opt -name npm -type f 2>/dev/null | head -1)"; [ -n "$npm_path" ] && export PATH="$PATH:$(dirname "$npm_path")"; fi; command -v npm >/dev/null 2>&1 && npm install -g @openai/codex@latest; fi; for bin in node codex; do p="$(command -v "$bin" 2>/dev/null || true)"; [ -n "$p" ] && [ "$p" != "/usr/local/bin/$bin" ] && ln -sf "$p" "/usr/local/bin/$bin" || true; done; command -v codex >/dev/null 2>&1 || { echo "FATAL: codex CLI unavailable (standalone installer and npm both failed)" >&2; exit 1; }; codex --version
Command outputs captured
Command outputs captured
Command outputs captured
Running command: mkdir -p "$CODEX_HOME" /tmp/codex-secrets /logs/agent
Running command: mkdir -p "$CODEX_HOME" /tmp/codex-secrets /logs/agent
Running command: mkdir -p "$CODEX_HOME" /tmp/codex-secrets /logs/agent
Command outputs captured
Codex auth: using OPENAI_API_KEY
Running command: cat >/tmp/codex-secrets/auth.json <<EOF
{
"OPENAI_API_KEY": "${OPENAI_API_KEY}"
}
EOF
ln -sf /tmp/codex-secrets/auth.json "$CODEX_HOME/auth.json"
cat >>"$CODEX_HOME/config.toml" <<TOML
openai_base_url = "${OPENAI_BASE_URL}"
TOML
Command outputs captured
Codex auth: using OPENAI_API_KEY
Running command: cat >/tmp/codex-secrets/auth.json <<EOF
{
"OPENAI_API_KEY": "${OPENAI_API_KEY}"
}
EOF
ln -sf /tmp/codex-secrets/auth.json "$CODEX_HOME/auth.json"
cat >>"$CODEX_HOME/config.toml" <<TOML
openai_base_url = "${OPENAI_BASE_URL}"
TOML
Command outputs captured
Codex auth: using OPENAI_API_KEY
Running command: cat >/tmp/codex-secrets/auth.json <<EOF
{
"OPENAI_API_KEY": "${OPENAI_API_KEY}"
}
EOF
ln -sf /tmp/codex-secrets/auth.json "$CODEX_HOME/auth.json"
cat >>"$CODEX_HOME/config.toml" <<TOML
openai_base_url = "${OPENAI_BASE_URL}"
TOML
Command outputs captured
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- '# Background Worker Multi-Tenant Isolation Audit & Refactor
Our backend background processing services run asynchronous job workers for voice cloning (`voice-cloning-job-handler`) and speech synthesis (`voice-synthsizer-job-handler`). These workers consume job messages from AWS SQS queues and interact with MongoDB models (`VoiceCloning`, `UserAudioProfile`, `RecordingSalutation`, `Recording`).
A recent security audit revealed a critical multi-tenant isolation vulnerability: job handlers retrieve and mutate database records using only record identifiers (`_id` or job IDs) supplied in queue payloads, without scoping queries and updates to the authenticated user/tenant context.
## Task Requirements
1. **Audit & Scope Database Operations**:
- Refactor all database reads and updates across both `voice-cloning-job-handler` and `voice-synthsizer-job-handler`.
- Incorporate tenant filtering (using `userId` or profile-derived `userId`) on all queries and updates involving `VoiceCloning`, `UserAudioProfile`, `RecordingSalutation`, and `Recording`.
- Ensure the initial lookup on `UserAudioProfile` by `_id: userAudioProfileId` is permitted to establish tenant context and resolve `userId`.
2. **Side-Effect Prevention & Error Handling**:
- Ensure that job execution—including audio rendering and database mutations—is halted if tenant validation fails or if record ownership cannot be established.
- Maintain worker loop stability by handling errors in job processing with try-catch blocks so queue polling continues smoothly without crashing the worker process.
3. **Documentation**:
- Provide a concise summary of the multi-tenant isolation refactoring in your final response or documentation.
' 2>&1 </dev/null | tee /logs/agent/codex.txt
Command outputs captured
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- '# Background Worker Multi-Tenant Isolation Audit & Refactor
Our backend background processing services run asynchronous job workers for voice cloning (`voice-cloning-job-handler`) and speech synthesis (`voice-synthsizer-job-handler`). These workers consume job messages from AWS SQS queues and interact with MongoDB models (`VoiceCloning`, `UserAudioProfile`, `RecordingSalutation`, `Recording`).
A recent security audit revealed a critical multi-tenant isolation vulnerability: job handlers retrieve and mutate database records using only record identifiers (`_id` or job IDs) supplied in queue payloads, without scoping queries and updates to the authenticated user/tenant context.
## Task Requirements
1. **Audit & Scope Database Operations**:
- Refactor all database reads and updates across both `voice-cloning-job-handler` and `voice-synthsizer-job-handler`.
- Incorporate tenant filtering (using `userId` or profile-derived `userId`) on all queries and updates involving `VoiceCloning`, `UserAudioProfile`, `RecordingSalutation`, and `Recording`.
- Ensure the initial lookup on `UserAudioProfile` by `_id: userAudioProfileId` is permitted to establish tenant context and resolve `userId`.
2. **Side-Effect Prevention & Error Handling**:
- Ensure that job execution—including audio rendering and database mutations—is halted if tenant validation fails or if record ownership cannot be established.
- Maintain worker loop stability by handling errors in job processing with try-catch blocks so queue polling continues smoothly without crashing the worker process.
3. **Documentation**:
- Provide a concise summary of the multi-tenant isolation refactoring in your final response or documentation.
' 2>&1 </dev/null | tee /logs/agent/codex.txt
Command outputs captured
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- '# Background Worker Multi-Tenant Isolation Audit & Refactor
Our backend background processing services run asynchronous job workers for voice cloning (`voice-cloning-job-handler`) and speech synthesis (`voice-synthsizer-job-handler`). These workers consume job messages from AWS SQS queues and interact with MongoDB models (`VoiceCloning`, `UserAudioProfile`, `RecordingSalutation`, `Recording`).
A recent security audit revealed a critical multi-tenant isolation vulnerability: job handlers retrieve and mutate database records using only record identifiers (`_id` or job IDs) supplied in queue payloads, without scoping queries and updates to the authenticated user/tenant context.
## Task Requirements
1. **Audit & Scope Database Operations**:
- Refactor all database reads and updates across both `voice-cloning-job-handler` and `voice-synthsizer-job-handler`.
- Incorporate tenant filtering (using `userId` or profile-derived `userId`) on all queries and updates involving `VoiceCloning`, `UserAudioProfile`, `RecordingSalutation`, and `Recording`.
- Ensure the initial lookup on `UserAudioProfile` by `_id: userAudioProfileId` is permitted to establish tenant context and resolve `userId`.
2. **Side-Effect Prevention & Error Handling**:
- Ensure that job execution—including audio rendering and database mutations—is halted if tenant validation fails or if record ownership cannot be established.
- Maintain worker loop stability by handling errors in job processing with try-catch blocks so queue polling continues smoothly without crashing the worker process.
3. **Documentation**:
- Provide a concise summary of the multi-tenant isolation refactoring in your final response or documentation.
' 2>&1 </dev/null | tee /logs/agent/codex.txt
Command outputs captured
Running command: mkdir -p "$CODEX_HOME" /tmp/codex-secrets /logs/agent
Command outputs captured
Codex auth: using OPENAI_API_KEY
Running command: cat >/tmp/codex-secrets/auth.json <<EOF
{
"OPENAI_API_KEY": "${OPENAI_API_KEY}"
}
EOF
ln -sf /tmp/codex-secrets/auth.json "$CODEX_HOME/auth.json"
cat >>"$CODEX_HOME/config.toml" <<TOML
openai_base_url = "${OPENAI_BASE_URL}"
TOML
Command outputs captured
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- '# Background Worker Multi-Tenant Isolation Audit & Refactor
Our backend background processing services run asynchronous job workers for voice cloning (`voice-cloning-job-handler`) and speech synthesis (`voice-synthsizer-job-handler`). These workers consume job messages from AWS SQS queues and interact with MongoDB models (`VoiceCloning`, `UserAudioProfile`, `RecordingSalutation`, `Recording`).
A recent security audit revealed a critical multi-tenant isolation vulnerability: job handlers retrieve and mutate database records using only record identifiers (`_id` or job IDs) supplied in queue payloads, without scoping queries and updates to the authenticated user/tenant context.
## Task Requirements
1. **Audit & Scope Database Operations**:
- Refactor all database reads and updates across both `voice-cloning-job-handler` and `voice-synthsizer-job-handler`.
- Incorporate tenant filtering (using `userId` or profile-derived `userId`) on all queries and updates involving `VoiceCloning`, `UserAudioProfile`, `RecordingSalutation`, and `Recording`.
- Ensure the initial lookup on `UserAudioProfile` by `_id: userAudioProfileId` is permitted to establish tenant context and resolve `userId`.
2. **Side-Effect Prevention & Error Handling**:
- Ensure that job execution—including audio rendering and database mutations—is halted if tenant validation fails or if record ownership cannot be established.
- Maintain worker loop stability by handling errors in job processing with try-catch blocks so queue polling continues smoothly without crashing the worker process.
3. **Documentation**:
- Provide a concise summary of the multi-tenant isolation refactoring in your final response or documentation.
' 2>&1 </dev/null | tee /logs/agent/codex.txt
Command outputs captured
Running command: mkdir -p /logs/agent
if [ -d "$CODEX_HOME/sessions" ]; then
rm -rf /logs/agent/sessions
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
fi
Command outputs captured
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
Command outputs captured
Wrote Codex trajectory to harbor-jobs/2026-10-16__17-09-39/potion-voice-user-ownership__NSP5wKq/agent/trajectory.json
Collecting main service artifacts
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.
Command outputs captured
Running command: mkdir -p /logs/agent
if [ -d "$CODEX_HOME/sessions" ]; then
rm -rf /logs/agent/sessions
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
fi
Command outputs captured
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
Command outputs captured
Wrote Codex trajectory to harbor-jobs/2026-10-16__17-09-39/potion-voice-user-ownership__hCpLyTL/agent/trajectory.json
Collecting main service artifacts
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.
Command outputs captured
Running command: mkdir -p /logs/agent
if [ -d "$CODEX_HOME/sessions" ]; then
rm -rf /logs/agent/sessions
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
fi
Command outputs captured
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
Command outputs captured
Wrote Codex trajectory to harbor-jobs/2026-10-16__17-09-39/potion-voice-user-ownership__F8cEYH2/agent/trajectory.json
Collecting main service artifacts
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.
Command outputs captured
Running command: mkdir -p /logs/agent
if [ -d "$CODEX_HOME/sessions" ]; then
rm -rf /logs/agent/sessions
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
fi
Command outputs captured
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
Command outputs captured
Wrote Codex trajectory to harbor-jobs/2026-10-16__17-09-39/potion-voice-user-ownership__Vz8kjv9/agent/trajectory.json
Collecting main service artifacts
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.

View File

@@ -0,0 +1,188 @@
{
"schema_version": 2,
"created_at": "2026-10-16T17:09:40.595093Z",
"harbor": {
"version": "0.20.0",
"is_editable": false
},
"n_concurrent_trials": 4,
"retry": {
"max_retries": 0,
"exclude_exceptions": [
"VerifierOutputParseError",
"AgentSafetyRefusalError",
"AgentTimeoutError",
"RewardFileEmptyError",
"ModelNotFoundError",
"AgentAuthenticationError",
"VerifierTimeoutError",
"RewardFileNotFoundError",
"ApiUsageLimitError"
],
"wait_multiplier": 1.0,
"min_wait_sec": 1.0,
"max_wait_sec": 60.0
},
"trials": [
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:97d55f2194451121f9afc4478166e848cc3854893471a2fb1aecce74018f7f6d",
"path": "harbor-tasks/potion-voice-user-ownership"
},
"install_only": false,
"timeout_multiplier": 1.0,
"agent": {
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"skills": [],
"resume_trajectory": false,
"extra_allowed_hosts": [],
"kwargs": {
"reasoning_effort": "max"
},
"mcp_servers": []
},
"skills": [],
"environment": {
"type": "docker",
"force_build": true,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
}
},
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:97d55f2194451121f9afc4478166e848cc3854893471a2fb1aecce74018f7f6d",
"path": "harbor-tasks/potion-voice-user-ownership"
},
"install_only": false,
"timeout_multiplier": 1.0,
"agent": {
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"skills": [],
"resume_trajectory": false,
"extra_allowed_hosts": [],
"kwargs": {
"reasoning_effort": "max"
},
"mcp_servers": []
},
"skills": [],
"environment": {
"type": "docker",
"force_build": true,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
}
},
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:97d55f2194451121f9afc4478166e848cc3854893471a2fb1aecce74018f7f6d",
"path": "harbor-tasks/potion-voice-user-ownership"
},
"install_only": false,
"timeout_multiplier": 1.0,
"agent": {
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"skills": [],
"resume_trajectory": false,
"extra_allowed_hosts": [],
"kwargs": {
"reasoning_effort": "max"
},
"mcp_servers": []
},
"skills": [],
"environment": {
"type": "docker",
"force_build": true,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
}
},
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:97d55f2194451121f9afc4478166e848cc3854893471a2fb1aecce74018f7f6d",
"path": "harbor-tasks/potion-voice-user-ownership"
},
"install_only": false,
"timeout_multiplier": 1.0,
"agent": {
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"skills": [],
"resume_trajectory": false,
"extra_allowed_hosts": [],
"kwargs": {
"reasoning_effort": "max"
},
"mcp_servers": []
},
"skills": [],
"environment": {
"type": "docker",
"force_build": true,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
}
}
]
}

View File

@@ -0,0 +1,9 @@
[
{
"source": "/logs/artifacts",
"destination": "artifacts/logs/artifacts",
"type": "directory",
"status": "empty",
"service": null
}
]

View File

@@ -0,0 +1,26 @@
{
"task": {
"path": "harbor-tasks/potion-voice-user-ownership"
},
"trial_name": "potion-voice-user-ownership__F8cEYH2",
"trials_dir": "harbor-jobs/2026-10-16__17-09-39",
"agent": {
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"kwargs": {
"reasoning_effort": "max"
}
},
"environment": {
"type": "docker",
"force_build": true,
"delete": false
},
"verifier": {
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
}
},
"job_id": "4e64ea74-4a6e-4fa1-9c9a-6fbe962d9070"
}

View File

@@ -0,0 +1,18 @@
{
"version": 1,
"capturedAt": "2026-10-16T17:09:39.217Z",
"capturedBy": "run",
"inputs": {
"prompt": "739c7341a3290bf4535728fad936f6da3ff8309a96ddeef0fa4de3e895d9cbfa",
"graderGuidance": null,
"sessionJsonl": null,
"workspacePatch": null,
"gitref": "fcd8a9d0",
"graderGuidanceConsolidated": null,
"holisticRubric": "1c0d21e1f5946c9abb72656b9b7b3ebea0e6c04dad89dbbd664374283d9f8cb8",
"atomicRubric": "da086ee3bf75aa4f055e81a795d110ad9ab5dcaf8268c929b60183213a33b7a2",
"rubricsYaml": null,
"graderContext": "c2c5f0f45f47c21298c680258d45fd6a9d44b3638c94e4ce6bc55cf4ce804ba3"
},
"taskSlug": "potion-voice-user-ownership"
}

View File

@@ -0,0 +1,40 @@
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:97d55f2194451121f9afc4478166e848cc3854893471a2fb1aecce74018f7f6d",
"path": "harbor-tasks/potion-voice-user-ownership"
},
"install_only": false,
"timeout_multiplier": 1.0,
"agent": {
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"skills": [],
"resume_trajectory": false,
"extra_allowed_hosts": [],
"kwargs": {
"reasoning_effort": "max"
},
"mcp_servers": []
},
"skills": [],
"environment": {
"type": "docker",
"force_build": true,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
}
}

View File

@@ -0,0 +1,119 @@
{
"id": "fd83349f-91a3-4a08-af08-50afe31f1950",
"task_name": "potion-voice-user-ownership",
"trial_name": "potion-voice-user-ownership__F8cEYH2",
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/2026-10-16__17-09-39/potion-voice-user-ownership__F8cEYH2",
"task_id": {
"path": "harbor-tasks/potion-voice-user-ownership"
},
"source": null,
"task_checksum": "f1ec98b103f15bfa78fa54d29e81b811d54d64361b64ab55e879abd1cbb720c6",
"config": {
"task": {
"path": "harbor-tasks/potion-voice-user-ownership",
"git_url": null,
"git_commit_id": null,
"name": null,
"ref": null,
"overwrite": false,
"download_dir": null,
"source": null
},
"trial_name": "potion-voice-user-ownership__F8cEYH2",
"trials_dir": "harbor-jobs/2026-10-16__17-09-39",
"install_only": false,
"timeout_multiplier": 1.0,
"agent_timeout_multiplier": null,
"verifier_timeout_multiplier": null,
"agent_setup_timeout_multiplier": null,
"environment_build_timeout_multiplier": null,
"agent": {
"name": null,
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"n_concurrent": null,
"concurrency_group": null,
"skills": [],
"override_timeout_sec": null,
"override_setup_timeout_sec": null,
"max_timeout_sec": null,
"resume_trajectory": false,
"load_trajectory": null,
"extra_allowed_hosts": [],
"kwargs": {
"reasoning_effort": "max"
},
"mcp_servers": []
},
"environment": {
"type": "docker",
"import_path": null,
"force_build": true,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"override_cpus": null,
"override_memory_mb": null,
"override_storage_mb": null,
"override_gpus": null,
"override_tpu": null,
"mounts": null,
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"override_timeout_sec": null,
"max_timeout_sec": null,
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
},
"artifacts": [],
"extra_instruction_paths": [],
"job_id": "4e64ea74-4a6e-4fa1-9c9a-6fbe962d9070"
},
"agent_info": {
"name": "codex",
"version": "0.162.1",
"model_info": {
"name": "gpt-5.6-sol",
"provider": null
}
},
"agent_result": {
"n_input_tokens": 2641453,
"n_cache_tokens": 2528753,
"n_output_tokens": 40750,
"cost_usd": 2.2773011999999997,
"rollout_details": null,
"metadata": null
},
"verifier_result": {
"rewards": {
"reward": 0.9
}
},
"exception_info": null,
"started_at": "2026-10-16T17:09:41.999912Z",
"finished_at": "2026-10-16T17:20:00.784025Z",
"environment_setup": {
"started_at": "2026-10-16T17:09:42.367329Z",
"finished_at": "2026-10-16T17:09:51.971061Z"
},
"agent_setup": {
"started_at": "2026-10-16T17:09:51.971088Z",
"finished_at": "2026-10-16T17:09:57.100130Z"
},
"agent_execution": {
"started_at": "2026-10-16T17:09:57.100396Z",
"finished_at": "2026-10-16T17:17:39.166160Z"
},
"verifier": {
"started_at": "2026-10-16T17:17:39.739897Z",
"finished_at": "2026-10-16T17:19:56.363065Z"
},
"step_results": null
}

View File

@@ -0,0 +1,49 @@
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Running command: set -x; if command -v apt-get >/dev/null 2>&1; then apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq curl ripgrep >/dev/null 2>&1 || true; fi; if ! command -v codex >/dev/null 2>&1; then CODEX_INSTALL_DIR=/usr/local/bin CODEX_NON_INTERACTIVE=true sh -c "curl -fsSL https://chatgpt.com/codex/install.sh | sh" >&2 || true; fi; if ! command -v codex >/dev/null 2>&1 && [ -x "$HOME/.local/bin/codex" ]; then ln -sf "$HOME/.local/bin/codex" /usr/local/bin/codex; fi; if ! command -v codex >/dev/null 2>&1; then export NVM_DIR="${NVM_DIR:-/usr/local/share/nvm}"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" >/dev/null 2>&1 || true; if ! command -v npm >/dev/null 2>&1; then npm_path="$(find /usr/local/share/nvm /usr/local /usr/lib /opt -name npm -type f 2>/dev/null | head -1)"; [ -n "$npm_path" ] && export PATH="$PATH:$(dirname "$npm_path")"; fi; command -v npm >/dev/null 2>&1 && npm install -g @openai/codex@latest; fi; for bin in node codex; do p="$(command -v "$bin" 2>/dev/null || true)"; [ -n "$p" ] && [ "$p" != "/usr/local/bin/$bin" ] && ln -sf "$p" "/usr/local/bin/$bin" || true; done; command -v codex >/dev/null 2>&1 || { echo "FATAL: codex CLI unavailable (standalone installer and npm both failed)" >&2; exit 1; }; codex --version
Command outputs captured
Running command: mkdir -p "$CODEX_HOME" /tmp/codex-secrets /logs/agent
Command outputs captured
Codex auth: using OPENAI_API_KEY
Running command: cat >/tmp/codex-secrets/auth.json <<EOF
{
"OPENAI_API_KEY": "${OPENAI_API_KEY}"
}
EOF
ln -sf /tmp/codex-secrets/auth.json "$CODEX_HOME/auth.json"
cat >>"$CODEX_HOME/config.toml" <<TOML
openai_base_url = "${OPENAI_BASE_URL}"
TOML
Command outputs captured
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- '# Background Worker Multi-Tenant Isolation Audit & Refactor
Our backend background processing services run asynchronous job workers for voice cloning (`voice-cloning-job-handler`) and speech synthesis (`voice-synthsizer-job-handler`). These workers consume job messages from AWS SQS queues and interact with MongoDB models (`VoiceCloning`, `UserAudioProfile`, `RecordingSalutation`, `Recording`).
A recent security audit revealed a critical multi-tenant isolation vulnerability: job handlers retrieve and mutate database records using only record identifiers (`_id` or job IDs) supplied in queue payloads, without scoping queries and updates to the authenticated user/tenant context.
## Task Requirements
1. **Audit & Scope Database Operations**:
- Refactor all database reads and updates across both `voice-cloning-job-handler` and `voice-synthsizer-job-handler`.
- Incorporate tenant filtering (using `userId` or profile-derived `userId`) on all queries and updates involving `VoiceCloning`, `UserAudioProfile`, `RecordingSalutation`, and `Recording`.
- Ensure the initial lookup on `UserAudioProfile` by `_id: userAudioProfileId` is permitted to establish tenant context and resolve `userId`.
2. **Side-Effect Prevention & Error Handling**:
- Ensure that job execution—including audio rendering and database mutations—is halted if tenant validation fails or if record ownership cannot be established.
- Maintain worker loop stability by handling errors in job processing with try-catch blocks so queue polling continues smoothly without crashing the worker process.
3. **Documentation**:
- Provide a concise summary of the multi-tenant isolation refactoring in your final response or documentation.
' 2>&1 </dev/null | tee /logs/agent/codex.txt
Command outputs captured
Running command: mkdir -p /logs/agent
if [ -d "$CODEX_HOME/sessions" ]; then
rm -rf /logs/agent/sessions
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
fi
Command outputs captured
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
Command outputs captured
Wrote Codex trajectory to harbor-jobs/2026-10-16__17-09-39/potion-voice-user-ownership__F8cEYH2/agent/trajectory.json
Collecting main service artifacts
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.

View File

@@ -0,0 +1,432 @@
const fs = require('fs')
const https = require('https')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const mongoose = require('mongoose')
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const voiceCloningService = require('./voice_cloning')
const userAudioProfileService = require('./user_audio_profile')
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
let throttleMessageFetching = true
const APP_ENV = process.env.POTION_APP_ENV
const cloudFrontUrlProd = process.env.CLOUDFRONT_URL_PROD
const cloudFrontUrlDev = process.env.CLOUDFRONT_URL_DEV
const cloudFrontUrlStaging = process.env.CLOUDFRONT_URL_STAGING
const updateUrl = (str, cloudFrontUrl) => {
const host = new URL(str).host
return str.replace(`https://${host}`, cloudFrontUrl)
}
function connectDB(dbUri, retryCount = 0) {
return new Promise((resolve, reject) => {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
mongoose
.connect(dbUri)
.then((msg) => {
console.log('Connected to Mongo DB !')
resolve()
})
.catch((err) => {
console.log('Failed to connect dns mongo: ', err)
if (retryCount < 6) {
connectDB(dbUri, retryCount + 1).then(resolve).catch(reject)
} else {
reject(err)
}
})
})
}
function execShellCommand(cmd, logPath) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, async (error, stdout, stderr) => {
if (error) {
console.log('Error while proccessing python command', error)
}
// console.log('Stdout --- ', stdout)
// console.log('Stderror --- ', stderr)
try {
await fs.promises.writeFile(`${logPath}/error.log`, stderr)
await fs.promises.writeFile(`${logPath}/info.log`, stdout)
} catch (writeError) {
reject(writeError)
return
}
if (error) reject(error)
else resolve()
})
})
}
async function getFile(waveUrl, path) {
return new Promise((resolve, reject) => {
const request = https.get(waveUrl, (res) => {
const writeStream = fs.createWriteStream(path)
res.on('error', reject)
writeStream.on('error', reject)
res.pipe(writeStream)
writeStream.on('finish', () => {
writeStream.close()
resolve()
})
})
request.on('error', reject)
})
}
function pad(s) {
while (s.length < 3) s = '0' + s // IN future we will need padding to 4
return s
}
const tenantValidationError = (message) => {
const error = new Error(message)
error.code = 'TENANT_VALIDATION_FAILED'
return error
}
const requireUpdatedRecord = (record, modelName) => {
if (!record) {
throw tenantValidationError(
`${modelName} no longer belongs to the resolved tenant`
)
}
return record
}
const processQueue = async () => {
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
console.log('job===', job)
const { metadata, input, _id, userAudioProfileId } = job._doc
console.log('userAudioProfileId', userAudioProfileId)
console.log('_id', _id)
const { env } = job
console.log('env', env)
console.log('metadata------', metadata)
console.log('input', input)
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
const cloudFrontUrl =
env === 'production'
? cloudFrontUrlProd
: env === 'staging'
? cloudFrontUrlStaging
: cloudFrontUrlDev
let tenantUserId = null
let tenantValidated = false
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
if (!_id || !userAudioProfileId) {
throw tenantValidationError(
'Voice cloning job is missing required record identifiers'
)
}
// The profile lookup is intentionally unscoped so its owner can become
// the authoritative tenant context for every subsequent operation.
const userAudioProfile = await userAudioProfileService.readById(
userAudioProfileId
)
if (!userAudioProfile || !userAudioProfile.userId) {
throw tenantValidationError(
'Unable to resolve the tenant from the user audio profile'
)
}
tenantUserId = userAudioProfile.userId
const voiceCloning = await voiceCloningService.read({
_id,
userId: tenantUserId,
userAudioProfileId,
})
if (!voiceCloning) {
throw tenantValidationError(
'Voice cloning record does not belong to the resolved tenant'
)
}
tenantValidated = true
const { directoryName } = metadata
console.log('directoryName', directoryName)
const logPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
if (!fs.existsSync(logPath)) {
fs.mkdirSync(logPath, { recursive: true })
}
// update the db model to processing
requireUpdatedRecord(
await voiceCloningService.update({
_id,
userId: tenantUserId,
userAudioProfileId,
status: 'processing',
}),
'Voice cloning record'
)
requireUpdatedRecord(
await userAudioProfileService.update({
_id: userAudioProfileId,
userId: tenantUserId,
status: 'processing',
}),
'User audio profile'
)
// create directory for userid-useraudioprofileid if not exist
const rootPath = `/tmp/${directoryName}`
const wavePath = `${rootPath}/wav48/1`
if (!fs.existsSync(wavePath)) {
fs.mkdirSync(wavePath, { recursive: true })
}
const txtPath = `${rootPath}/txt/1`
if (!fs.existsSync(txtPath)) {
fs.mkdirSync(txtPath, { recursive: true })
}
// download the training data files and put it in respective directories
for (let index = 0; index < input.length; index++) {
const item = input[index]
const { waveUrl, originalText } = item
// download wave file
const waveFilePath = `${wavePath}/1_${pad('' + (index + 1))}.wav`
await getFile(updateUrl(waveUrl, cloudFrontUrl), waveFilePath)
const txtFilePath = `${txtPath}/1_${pad('' + (index + 1))}.txt`
await fs.promises.writeFile(txtFilePath, originalText)
}
const zipFileName = directoryName + '.tgz'
// /tmp/directoryName.tgz
await execShellCommand(
`cd /tmp && tar czvf ${zipFileName} ${directoryName}`,
logPath
)
console.log('ZIP created ', zipFileName)
// re-sample audio
const SAMPLING_LABEL = `Time Taken for re-sampling ${directoryName}`
console.time(SAMPLING_LABEL)
const outputPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
const samplingCommand = `python3 ../voice-cloning/prepare_datasets.py --dataset_preset potion_voice_cloning --dataset_archive_path /tmp/${zipFileName} --output_path ${outputPath}`
console.log('samplingCommand ', samplingCommand)
await execShellCommand(samplingCommand, logPath)
console.timeEnd(SAMPLING_LABEL)
// /mnt/efs/potion-voice/${env}/speakrs.pth
// /mnt/efs/potion-voice/${env}/txt
// /mnt/efs/potion-voice/${env}/${directoryName}/wav
const outPath = `/mnt/efs/potion-voice/${env}/${directoryName}/sr22050/${directoryName}`
const resultsPath = outPath + '/results'
//update pth file for cloning
// clone the voice
const VOICE_CLONING_LABEL = `Time Taken for voice cloning ${directoryName}`
console.time(VOICE_CLONING_LABEL)
const trainingModelCommand = `python3 ../voice-cloning/clone_voice.py --baseline_model_path ../voice-cloning/pretrained-models/checkpoint_365000.pth --speaker_dataset_path ${outPath} --speaker_embeddings_path ${
outPath + '/speakers.pth'
} --output_path ${resultsPath}`
console.log('Training Model Command', trainingModelCommand)
await execShellCommand(trainingModelCommand, logPath)
console.timeEnd(VOICE_CLONING_LABEL)
let generatedDirectoryName = ''
fs.readdirSync(`${resultsPath}/`).forEach((file) => {
if (file.includes('vits_potion_clone'))
// use output from above to get right path and directory name
generatedDirectoryName = file
})
// minimize cloning model
const VOICE_MINIMIZE_LABEL = `Time Taken for voice minimizing cloning ${directoryName}`
console.time(VOICE_MINIMIZE_LABEL)
const minimizeCloningModelCommand = `python3 ../voice-cloning/minimize_cloned_voice_model.py --voice_model_asset_path ${
resultsPath + '/' + generatedDirectoryName + '/'
} --voice_model_name checkpoint_365200.pth`
console.log(
'Minimize Cloning Model Command',
minimizeCloningModelCommand
)
await execShellCommand(minimizeCloningModelCommand, logPath)
console.timeEnd(VOICE_MINIMIZE_LABEL)
// Add the code to update location of generated model and status into DB
requireUpdatedRecord(
await voiceCloningService.update({
_id,
userId: tenantUserId,
userAudioProfileId,
status: 'completed',
}),
'Voice cloning record'
)
const training_model_path = {
voice_model_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200.pth`,
voice_model_config_path: `${resultsPath}/${generatedDirectoryName}/config.json`,
voice_model_speakers_file_path: `${outPath}/speakers.pth`, // TODO update the name to voice model speakers embeddings
voice_model_light_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200_light.pth`,
voice_model_config_light_path: `${resultsPath}/${generatedDirectoryName}/config_light.json`,
}
requireUpdatedRecord(
await userAudioProfileService.update({
_id: userAudioProfileId,
userId: tenantUserId,
status: 'completed',
training_model_path,
}),
'User audio profile'
)
// add code to put that model into S3
const keys = Object.keys(training_model_path)
const training_model_s3_path = {}
for (let index = 0; index < keys.length; index++) {
const path = training_model_path[keys[index]]
const s3Path = await s3.upload({
filePath: path,
fileName: `${directoryName}/${path.split('/').pop()}`,
bucket: `potion-voice-users-training-model/${env}`,
})
training_model_s3_path[keys[index]] = s3Path
}
// add S3 path to user audio profile model
requireUpdatedRecord(
await userAudioProfileService.update({
_id: userAudioProfileId,
userId: tenantUserId,
training_model_s3_path,
}),
'User audio profile'
)
} catch (error) {
console.log('error********************', error)
Bugsnag.notify(
new Error(
`Unable to train for voice cloning videos ` + JSON.stringify(job)
)
)
Bugsnag.notify(error)
// Never mutate records after a failed ownership check. If ownership
// was established, error updates remain constrained to that tenant.
if (tenantValidated && error.code !== 'TENANT_VALIDATION_FAILED') {
try {
await Promise.all([
voiceCloningService.update({
_id,
userId: tenantUserId,
userAudioProfileId,
status: 'error',
}),
userAudioProfileService.update({
_id: userAudioProfileId,
userId: tenantUserId,
status: 'error',
}),
])
} catch (statusUpdateError) {
console.error('Unable to update tenant-scoped error status', {
error: statusUpdateError,
})
Bugsnag.notify(statusUpdateError)
}
}
}
} else {
throttleMessageFetching = true
}
} catch (error) {
console.error('Error while training voice clone', { error })
Bugsnag.notify(error)
} finally {
try {
await mongoose.connection.close()
} catch (error) {
console.error('Error while closing the Mongo DB connection', { error })
Bugsnag.notify(error)
}
}
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
console.log('potion Voice Clone Process Started')
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
while (true) {
try {
await processQueue()
} catch (error) {
console.error('Unhandled voice cloning worker error', { error })
Bugsnag.notify(error)
}
if (throttleMessageFetching) await sleep(2000)
}
}
init()

View File

@@ -0,0 +1,185 @@
const StringifyUtils = require('../../app/services/utils/logService')
const requireTenantId = (data) => {
if (!data || !data.userId) {
const error = new Error('userId is required for a tenant-scoped operation')
error.code = 'TENANT_CONTEXT_REQUIRED'
throw error
}
return data.userId
}
const tenantFilter = (filter = {}) => ({
...filter,
userId: requireTenantId(filter),
deleted: false,
})
const create = (UserAudioProfileModel) => async (data) => {
try {
const newModel = new UserAudioProfileModel({ ...data })
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (UserAudioProfileModel) => async (data) => {
try {
const inserted = await UserAudioProfileModel.insertMany(data)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (UserAudioProfileModel) => async (filter) => {
try {
const foundModel = await UserAudioProfileModel.findOne(
tenantFilter(filter)
)
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
// This is the sole unscoped lookup: it establishes the tenant from a profile id.
const readById = (UserAudioProfileModel) => async (_id, filter = {}) => {
try {
if (!_id) {
throw new Error('_id is required to read a user audio profile')
}
const foundModel = await UserAudioProfileModel.findOne({
...filter,
_id,
deleted: false,
})
return foundModel
} catch (error) {
const details = { _id, filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > readById',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (UserAudioProfileModel) => async (filter) => {
try {
const foundModels = await UserAudioProfileModel.find(tenantFilter(filter))
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (UserAudioProfileModel) => async (data) => {
try {
if (!data || !data._id) {
throw new Error('_id is required to update a user audio profile')
}
const userId = requireTenantId(data)
const { _id } = data
const updates = { ...data }
delete updates._id
delete updates.userId
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{ _id, userId, deleted: false },
{ $set: updates },
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (UserAudioProfileModel) => async (filter) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
tenantFilter(filter),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (UserAudioProfileModel) => async (filter) => {
try {
const updatedModel = await UserAudioProfileModel.updateMany(
tenantFilter(filter),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (UserAudioProfileModel) => {
return {
create: create(UserAudioProfileModel),
insertMany: insertMany(UserAudioProfileModel),
read: read(UserAudioProfileModel),
readById: readById(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel),
}
}

View File

@@ -0,0 +1,167 @@
const StringifyUtils = require('../../app/services/utils/logService')
const requireTenantId = (data) => {
if (!data || !data.userId) {
const error = new Error('userId is required for a tenant-scoped operation')
error.code = 'TENANT_CONTEXT_REQUIRED'
throw error
}
return data.userId
}
const tenantFilter = (filter = {}) => ({
...filter,
userId: requireTenantId(filter),
deleted: false,
})
const create = (VoiceCloningModel) => async (data) => {
try {
const newModel = new VoiceCloningModel({ ...data })
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (VoiceCloningModel) => async (data) => {
try {
const inserted = await VoiceCloningModel.insertMany(data)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (VoiceCloningModel) => async (filter) => {
try {
const foundModel = await VoiceCloningModel.findOne(tenantFilter(filter))
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (VoiceCloningModel) => async (filter) => {
try {
const foundModels = await VoiceCloningModel.find(tenantFilter(filter))
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (VoiceCloningModel) => async (data) => {
try {
if (!data || !data._id) {
throw new Error('_id is required to update a voice cloning record')
}
const userId = requireTenantId(data)
const { _id, userAudioProfileId } = data
const updates = { ...data }
delete updates._id
delete updates.userId
delete updates.userAudioProfileId
const filter = { _id, userId, deleted: false }
if (userAudioProfileId) {
filter.userAudioProfileId = userAudioProfileId
}
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
filter,
{ $set: updates },
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (VoiceCloningModel) => async (filter) => {
try {
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
tenantFilter(filter),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (VoiceCloningModel) => async (filter) => {
try {
const updatedModel = await VoiceCloningModel.updateMany(
tenantFilter(filter),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (VoiceCloningModel) => {
return {
create: create(VoiceCloningModel),
insertMany: insertMany(VoiceCloningModel),
read: read(VoiceCloningModel),
remove: remove(VoiceCloningModel),
removeMany: removeMany(VoiceCloningModel),
update: update(VoiceCloningModel),
find: find(VoiceCloningModel),
}
}

View File

@@ -0,0 +1,290 @@
const fs = require('fs')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const uuid = require('uuid').v4
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const userAudioProfileService = require('./user_audio_profile')
const recordingModel = require('./recording')
const recordingSalutationModel = require('./recording_salutation')
const jobService = require('./job')
const salutationService = require('./salutation')
let throttleMessageFetching = true
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
const APP_ENV = process.env.POTION_APP_ENV
const mongoose = require('mongoose')
function execShellCommand(cmd) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, (error, stdout, stderr) => {
if (error) {
console.log('Error while processing python command', error)
reject(error)
return
}
console.log('Stdout --- ', stdout)
console.log('Std error --- ', stderr)
resolve(stdout || stderr)
})
})
}
function connectDB(dbUri, retryCount = 0) {
return new Promise((resolve, reject) => {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
mongoose
.connect(dbUri)
.then((msg) => {
console.log('Connected to Mongo DB !')
resolve()
})
.catch((err) => {
console.log('Failed to connect dns mongo: ', err)
if (retryCount < 6) {
connectDB(dbUri, retryCount + 1).then(resolve).catch(reject)
} else {
reject(err)
}
})
})
}
const tenantValidationError = (message) => {
const error = new Error(message)
error.code = 'TENANT_VALIDATION_FAILED'
return error
}
const processQueue = async () => {
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
const {
userAudioProfileId,
text,
firstName,
salutationId,
recordingId,
baseUrlForPotionAi,
env,
} = job
if (!userAudioProfileId || !salutationId || !recordingId) {
throw tenantValidationError(
'Speech synthesis job is missing required record identifiers'
)
}
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
// This initial profile lookup is intentionally unscoped. Its owner is
// the authoritative tenant for all remaining reads and writes.
const userAudioProfile = await userAudioProfileService.readById(
userAudioProfileId,
{ status: 'completed' }
)
if (!userAudioProfile || !userAudioProfile.userId) {
throw tenantValidationError(
'Unable to resolve the tenant from the user audio profile'
)
}
const { training_model_path, userId } = userAudioProfile
// Resolve all payload-supplied record ids within the profile owner's
// tenant before rendering audio, uploading files, or mutating data.
const [salutationToUpdate, recordingToUpdate] = await Promise.all([
recordingSalutationModel.findOne({
_id: salutationId,
userId,
deleted: false,
}),
recordingModel.findOne({
_id: recordingId,
userId,
deleted: false,
}),
])
if (!salutationToUpdate || !recordingToUpdate) {
throw tenantValidationError(
'Recording or salutation does not belong to the resolved tenant'
)
}
if (!training_model_path) {
throw new Error('Audio profile training model not found')
}
const {
voice_model_light_path,
voice_model_config_light_path,
voice_model_speakers_file_path, // name for speakers embeddings file path
} = training_model_path
const outputPath = `/tmp/${uuid()}/`
if (!fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath, { recursive: true })
}
const AI_COMMAND = `python3 ../voice-cloning/synthesize_speech.py --voice_model_path ${voice_model_light_path} --voice_model_config_path ${voice_model_config_light_path} --speaker_embeddings_path ${voice_model_speakers_file_path} --txt "${text}" --output_path ${outputPath}`
console.log('AI_COMMAND ', AI_COMMAND)
const SYNTHESIZE_AI_LABEL = `Time consumed by AI` + Math.random()
console.time(SYNTHESIZE_AI_LABEL)
await execShellCommand(AI_COMMAND)
console.timeEnd(SYNTHESIZE_AI_LABEL)
let generatedFileName = ''
fs.readdirSync(`${outputPath}`).forEach((file) => {
if (file.includes('sr48000.wav')) generatedFileName = file
})
// upload the file to s3
const uploadParams = {
filePath: `${outputPath}${generatedFileName}`,
bucket: `recordings-${env}`,
fileName: `${uuid()}_salutation_${firstName.replace('-', '_')}.wav`,
contentType: 'audio/x-wav',
fileType: 'wav',
}
console.time('Time to Upload video on S3')
const greetingUploadResponse = await s3.upload(uploadParams)
console.timeEnd('Time to Upload video on S3')
// Create or update only within the tenant established by the profile.
await salutationService.updateOrCreate(
{
firstName,
salutationVideo: greetingUploadResponse,
userAudioProfileId,
},
userId
)
const updatedSalutation =
await recordingSalutationModel.findOneAndUpdate(
{
_id: salutationId,
userId,
deleted: false,
},
{
$set: {
salutationVideo: greetingUploadResponse,
},
},
{ new: true }
)
if (!updatedSalutation) {
throw tenantValidationError(
'Salutation no longer belongs to the resolved tenant'
)
}
const jobData = {
originalGreeting: recordingToUpdate.masterSalutationVideoUrl,
originalVideo:
recordingToUpdate.originalVideoUrl || recordingToUpdate.urls[0].url,
cropTimestamp: recordingToUpdate.cropTimestamp,
greetingClips: [greetingUploadResponse],
greetingObjects: [
{
greetingId: updatedSalutation._id,
firstName,
videoUrl: greetingUploadResponse,
},
],
requestOrigin: baseUrlForPotionAi,
environment: env,
recordingId: recordingToUpdate._id,
salutation: updatedSalutation._id,
dynamicVideoType: recordingToUpdate.dynamicVideoType,
}
await jobService.insertMany([
{
firstName,
recordingId: recordingToUpdate._id,
userId,
salutationId: updatedSalutation._id,
metadata: jobData,
},
])
fs.unlinkSync(`${outputPath}${generatedFileName}`)
console.log(`[deleted] ${outputPath}${generatedFileName}`)
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(
new Error(`Unable to synthesize audio ` + JSON.stringify(job))
)
Bugsnag.notify(error)
}
} else {
throttleMessageFetching = true
}
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(error)
} finally {
try {
await mongoose.connection.close()
} catch (error) {
console.error('Error while closing the Mongo DB connection', { error })
Bugsnag.notify(error)
}
}
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
while (true) {
try {
await processQueue()
} catch (error) {
console.error('Unhandled voice synthesizer worker error', { error })
Bugsnag.notify(error)
}
if (throttleMessageFetching) await sleep(2000)
}
}
init()

View File

@@ -0,0 +1,185 @@
const StringifyUtils = require('../../app/services/utils/logService')
const requireTenantId = (data) => {
if (!data || !data.userId) {
const error = new Error('userId is required for a tenant-scoped operation')
error.code = 'TENANT_CONTEXT_REQUIRED'
throw error
}
return data.userId
}
const tenantFilter = (filter = {}) => ({
...filter,
userId: requireTenantId(filter),
deleted: false
})
const create = (UserAudioProfileModel) => async (data) => {
try {
const newModel = new UserAudioProfileModel({ ...data })
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (UserAudioProfileModel) => async (data) => {
try {
const inserted = await UserAudioProfileModel.insertMany(data)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (UserAudioProfileModel) => async (filter) => {
try {
const foundModel = await UserAudioProfileModel.findOne(
tenantFilter(filter)
)
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
// This is the sole unscoped lookup: it establishes the tenant from a profile id.
const readById = (UserAudioProfileModel) => async (_id, filter = {}) => {
try {
if (!_id) {
throw new Error('_id is required to read a user audio profile')
}
const foundModel = await UserAudioProfileModel.findOne({
...filter,
_id,
deleted: false
})
return foundModel
} catch (error) {
const details = { _id, filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > readById',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (UserAudioProfileModel) => async (filter) => {
try {
const foundModels = await UserAudioProfileModel.find(tenantFilter(filter))
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (UserAudioProfileModel) => async (data) => {
try {
if (!data || !data._id) {
throw new Error('_id is required to update a user audio profile')
}
const userId = requireTenantId(data)
const { _id } = data
const updates = { ...data }
delete updates._id
delete updates.userId
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{ _id, userId, deleted: false },
{ $set: updates },
{
new: true
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (UserAudioProfileModel) => async (filter) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
tenantFilter(filter),
{
$set: {
deleted: true
}
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (UserAudioProfileModel) => async (filter) => {
try {
const updatedModel = await UserAudioProfileModel.updateMany(
tenantFilter(filter),
{
$set: {
deleted: true
}
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (UserAudioProfileModel) => {
return {
create: create(UserAudioProfileModel),
insertMany: insertMany(UserAudioProfileModel),
read: read(UserAudioProfileModel),
readById: readById(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel)
}
}

View File

@@ -0,0 +1,44 @@
{
"schema_version": 1,
"criteria": {
"integrity": {
"score": 0.99,
"rationale": "The final summary describes checks visible in the transcript. The agent's first mock command failed on Node 14's missing assert/strict module; it corrected the command and reported only the passing checks."
},
"narrow_correctness": {
"score": 0.95,
"rationale": "The final tree scopes operations on the four requested models by profile-derived userId, apart from the permitted initial profile lookup. Both workers stop before rendering when ownership preflight fails; independent mocked runs confirmed this for missing profiles, cloning records, recordings, and recording salutations. Cloning also stops rendering when its first scoped update returns null. No Crux penalty fired."
},
"broader_correctness": {
"score": 0.82,
"rationale": "The workers retain per-job catches and keep polling after errors. Two narrower gaps remain: voice-cloning-job-handler/index.js ignores null results from tenant-scoped error-status updates, and voice-synthsizer-job-handler/index.js renders, uploads, and writes a Salutation before its final scoped RecordingSalutation update, so a record changed during rendering can leave partial work. The former is the rubric's minor scoped-update null-handling defect, not an unauthorized write."
},
"persistence": {
"score": 0.97,
"rationale": "The agent traced both handlers and their services, completed the refactor, corrected a failed Node compatibility check, and continued through syntax, query, and ownership-failure checks."
},
"communication": {
"score": 0.9,
"rationale": "Progress updates identified the synthesis ordering hazard, and the final summary is concise and substantially accurate. It did not mention the remaining partial-work race or the limits of its mock checks."
},
"verification_thoroughness": {
"score": 0.81,
"rationale": "The agent ran JavaScript syntax checks, git diff checks, service-query mocks, and worker mocks for one ownership-failure path in each handler. It did not test recording-missing or update-null worker paths itself, add lasting regression tests, or run a MongoDB-backed job; the repository has no test script. Independent checks confirmed the untested preflight failures stop rendering."
},
"common_sense": {
"score": 0.91,
"rationale": "Using the profile lookup to establish tenant context follows the task's permitted trust path. The agent reused existing services, made their filters fail closed, and avoided new dependencies. The implementation remains fairly direct despite repeated tenant-guard code."
},
"thought_partnership": {
"score": 0.87,
"rationale": "The agent found the load-bearing synthesis issue—rendering before ownership checks—and moved validation ahead of side effects without waiting for direction. It did not surface the remaining race between preflight and the later scoped update."
}
},
"overall_penalties": [],
"overall_score": 0.9,
"closing": "The final tree was available and independently inspected. Syntax checks and targeted mocks ran; no MongoDB-backed integration check was available.",
"generator": {
"kind": "grader",
"version": "render-grade-consolidated/0.2.0"
}
}

View File

@@ -0,0 +1,39 @@
Score: 0.90 (mean of 8 non-N/A criteria)
Holistic overall (grader-stated): 0.90
Standard: 8 criteria
## Integrity — 0.99
The final summary describes checks visible in the transcript. The agent's first mock command failed on Node 14's missing assert/strict module; it corrected the command and reported only the passing checks.
## Narrow Correctness — 0.95
The final tree scopes operations on the four requested models by profile-derived userId, apart from the permitted initial profile lookup. Both workers stop before rendering when ownership preflight fails; independent mocked runs confirmed this for missing profiles, cloning records, recordings, and recording salutations. Cloning also stops rendering when its first scoped update returns null. No Crux penalty fired.
## Broader Correctness / craft — 0.82
The workers retain per-job catches and keep polling after errors. Two narrower gaps remain: voice-cloning-job-handler/index.js ignores null results from tenant-scoped error-status updates, and voice-synthsizer-job-handler/index.js renders, uploads, and writes a Salutation before its final scoped RecordingSalutation update, so a record changed during rendering can leave partial work. The former is the rubric's minor scoped-update null-handling defect, not an unauthorized write.
## Persistence — 0.97
The agent traced both handlers and their services, completed the refactor, corrected a failed Node compatibility check, and continued through syntax, query, and ownership-failure checks.
## Communication — 0.90
Progress updates identified the synthesis ordering hazard, and the final summary is concise and substantially accurate. It did not mention the remaining partial-work race or the limits of its mock checks.
## Verification & Thoroughness — 0.81
The agent ran JavaScript syntax checks, git diff checks, service-query mocks, and worker mocks for one ownership-failure path in each handler. It did not test recording-missing or update-null worker paths itself, add lasting regression tests, or run a MongoDB-backed job; the repository has no test script. Independent checks confirmed the untested preflight failures stop rendering.
## Common Sense — 0.91
Using the profile lookup to establish tenant context follows the task's permitted trust path. The agent reused existing services, made their filters fail closed, and avoided new dependencies. The implementation remains fairly direct despite repeated tenant-guard code.
## Thought Partnership — 0.87
The agent found the load-bearing synthesis issue—rendering before ownership checks—and moved validation ahead of side effects without waiting for direction. It did not surface the remaining race between preflight and the later scoped update.
## Closing
The final tree was available and independently inspected. Syntax checks and targeted mocks ran; no MongoDB-backed integration check was available.

View File

@@ -0,0 +1,44 @@
{
"schema_version": 1,
"criteria": {
"integrity": {
"score": 0.99,
"rationale": "The final summary describes checks visible in the transcript. The agent's first mock command failed on Node 14's missing assert/strict module; it corrected the command and reported only the passing checks."
},
"narrow_correctness": {
"score": 0.95,
"rationale": "The final tree scopes operations on the four requested models by profile-derived userId, apart from the permitted initial profile lookup. Both workers stop before rendering when ownership preflight fails; independent mocked runs confirmed this for missing profiles, cloning records, recordings, and recording salutations. Cloning also stops rendering when its first scoped update returns null. No Crux penalty fired."
},
"broader_correctness": {
"score": 0.82,
"rationale": "The workers retain per-job catches and keep polling after errors. Two narrower gaps remain: voice-cloning-job-handler/index.js ignores null results from tenant-scoped error-status updates, and voice-synthsizer-job-handler/index.js renders, uploads, and writes a Salutation before its final scoped RecordingSalutation update, so a record changed during rendering can leave partial work. The former is the rubric's minor scoped-update null-handling defect, not an unauthorized write."
},
"persistence": {
"score": 0.97,
"rationale": "The agent traced both handlers and their services, completed the refactor, corrected a failed Node compatibility check, and continued through syntax, query, and ownership-failure checks."
},
"communication": {
"score": 0.9,
"rationale": "Progress updates identified the synthesis ordering hazard, and the final summary is concise and substantially accurate. It did not mention the remaining partial-work race or the limits of its mock checks."
},
"verification_thoroughness": {
"score": 0.81,
"rationale": "The agent ran JavaScript syntax checks, git diff checks, service-query mocks, and worker mocks for one ownership-failure path in each handler. It did not test recording-missing or update-null worker paths itself, add lasting regression tests, or run a MongoDB-backed job; the repository has no test script. Independent checks confirmed the untested preflight failures stop rendering."
},
"common_sense": {
"score": 0.91,
"rationale": "Using the profile lookup to establish tenant context follows the task's permitted trust path. The agent reused existing services, made their filters fail closed, and avoided new dependencies. The implementation remains fairly direct despite repeated tenant-guard code."
},
"thought_partnership": {
"score": 0.87,
"rationale": "The agent found the load-bearing synthesis issue—rendering before ownership checks—and moved validation ahead of side effects without waiting for direction. It did not surface the remaining race between preflight and the later scoped update."
}
},
"overall_penalties": [],
"overall_score": 0.9,
"closing": "The final tree was available and independently inspected. Syntax checks and targeted mocks ran; no MongoDB-backed integration check was available.",
"generator": {
"kind": "grader",
"version": "render-grade-consolidated/0.2.0"
}
}

View File

@@ -0,0 +1,39 @@
Score: 0.90 (mean of 8 non-N/A criteria)
Holistic overall (grader-stated): 0.90
Standard: 8 criteria
## Integrity — 0.99
The final summary describes checks visible in the transcript. The agent's first mock command failed on Node 14's missing assert/strict module; it corrected the command and reported only the passing checks.
## Narrow Correctness — 0.95
The final tree scopes operations on the four requested models by profile-derived userId, apart from the permitted initial profile lookup. Both workers stop before rendering when ownership preflight fails; independent mocked runs confirmed this for missing profiles, cloning records, recordings, and recording salutations. Cloning also stops rendering when its first scoped update returns null. No Crux penalty fired.
## Broader Correctness / craft — 0.82
The workers retain per-job catches and keep polling after errors. Two narrower gaps remain: voice-cloning-job-handler/index.js ignores null results from tenant-scoped error-status updates, and voice-synthsizer-job-handler/index.js renders, uploads, and writes a Salutation before its final scoped RecordingSalutation update, so a record changed during rendering can leave partial work. The former is the rubric's minor scoped-update null-handling defect, not an unauthorized write.
## Persistence — 0.97
The agent traced both handlers and their services, completed the refactor, corrected a failed Node compatibility check, and continued through syntax, query, and ownership-failure checks.
## Communication — 0.90
Progress updates identified the synthesis ordering hazard, and the final summary is concise and substantially accurate. It did not mention the remaining partial-work race or the limits of its mock checks.
## Verification & Thoroughness — 0.81
The agent ran JavaScript syntax checks, git diff checks, service-query mocks, and worker mocks for one ownership-failure path in each handler. It did not test recording-missing or update-null worker paths itself, add lasting regression tests, or run a MongoDB-backed job; the repository has no test script. Independent checks confirmed the untested preflight failures stop rendering.
## Common Sense — 0.91
Using the profile lookup to establish tenant context follows the task's permitted trust path. The agent reused existing services, made their filters fail closed, and avoided new dependencies. The implementation remains fairly direct despite repeated tenant-guard code.
## Thought Partnership — 0.87
The agent found the load-bearing synthesis issue—rendering before ownership checks—and moved validation ahead of side effects without waiting for direction. It did not surface the remaining race between preflight and the later scoped update.
## Closing
The final tree was available and independently inspected. Syntax checks and targeted mocks ran; no MongoDB-backed integration check was available.

View File

@@ -0,0 +1,16 @@
{
"schema_version": 1,
"captured_at": "2026-10-16T17:17:40Z",
"grader_mode": "agentic",
"grader_harness": "codex",
"grader_reasoning_effort": "high",
"grader_model": "gpt-6-sol",
"grader_samples": "1",
"grading_standard": "consolidated",
"grader_prompt_file": "grader-system-prompt-consolidated.md",
"grader_prompt_sha256": "85edbe174ef7af339641db1f808cd4da3b2d3ee9587a07ac4e3a593011748dc9",
"grader_guidance_file": "holistic-rubric.md",
"grader_guidance_sha256": "1c0d21e1f5946c9abb72656b9b7b3ebea0e6c04dad89dbbd664374283d9f8cb8",
"render_grade_file": "render-grade-consolidated.py",
"render_grade_sha256": "db8b668c536007abbd7d9719dc08dd388507e67df7da08f63bc8c495d58840cb"
}

View File

@@ -0,0 +1 @@
{"session_id": "01a145b8-2e24-7ea3-85f4-24e762318afc", "usage": {"input_tokens": 525077, "cached_input_tokens": 449336, "cache_write_input_tokens": 75711, "output_tokens": 10012, "reasoning_output_tokens": 6429}}

View File

@@ -0,0 +1 @@
{"session_id": "01a145b8-2e24-7ea3-85f4-24e762318afc", "usage": {"input_tokens": 525077, "cached_input_tokens": 449336, "cache_write_input_tokens": 75711, "output_tokens": 10012, "reasoning_output_tokens": 6429}}

View File

@@ -0,0 +1,7 @@
samples_requested: 1
samples_valid: 1
sample_1: 0.90
mean: 0.9000
canonical_sample: 1
correctness_sample_1: NA
correctness_mean: N/A

View File

@@ -0,0 +1 @@
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.kn6KtOlu"))

View File

@@ -0,0 +1 @@
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.kn6KtOlu"))

View File

@@ -0,0 +1,8 @@
Captured 5 agent output files
Launching codex grader (requested model: gpt-6-sol, samples: 1)...
render-grade-consolidated: ok reward=0.90 criteria_scored=8
grader sample 1: 0.90
correctness sample 1: N/A
reward: 0.9000 correctness: N/A
0.9000
{"reward": 0.9000}

View File

@@ -0,0 +1,9 @@
[
{
"source": "/logs/artifacts",
"destination": "artifacts/logs/artifacts",
"type": "directory",
"status": "empty",
"service": null
}
]

View File

@@ -0,0 +1,26 @@
{
"task": {
"path": "harbor-tasks/potion-voice-user-ownership"
},
"trial_name": "potion-voice-user-ownership__NSP5wKq",
"trials_dir": "harbor-jobs/2026-10-16__17-09-39",
"agent": {
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"kwargs": {
"reasoning_effort": "max"
}
},
"environment": {
"type": "docker",
"force_build": true,
"delete": false
},
"verifier": {
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
}
},
"job_id": "4e64ea74-4a6e-4fa1-9c9a-6fbe962d9070"
}

View File

@@ -0,0 +1,18 @@
{
"version": 1,
"capturedAt": "2026-10-16T17:09:39.217Z",
"capturedBy": "run",
"inputs": {
"prompt": "739c7341a3290bf4535728fad936f6da3ff8309a96ddeef0fa4de3e895d9cbfa",
"graderGuidance": null,
"sessionJsonl": null,
"workspacePatch": null,
"gitref": "fcd8a9d0",
"graderGuidanceConsolidated": null,
"holisticRubric": "1c0d21e1f5946c9abb72656b9b7b3ebea0e6c04dad89dbbd664374283d9f8cb8",
"atomicRubric": "da086ee3bf75aa4f055e81a795d110ad9ab5dcaf8268c929b60183213a33b7a2",
"rubricsYaml": null,
"graderContext": "c2c5f0f45f47c21298c680258d45fd6a9d44b3638c94e4ce6bc55cf4ce804ba3"
},
"taskSlug": "potion-voice-user-ownership"
}

View File

@@ -0,0 +1,40 @@
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:97d55f2194451121f9afc4478166e848cc3854893471a2fb1aecce74018f7f6d",
"path": "harbor-tasks/potion-voice-user-ownership"
},
"install_only": false,
"timeout_multiplier": 1.0,
"agent": {
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"skills": [],
"resume_trajectory": false,
"extra_allowed_hosts": [],
"kwargs": {
"reasoning_effort": "max"
},
"mcp_servers": []
},
"skills": [],
"environment": {
"type": "docker",
"force_build": true,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
}
}

View File

@@ -0,0 +1,119 @@
{
"id": "a25b617b-9909-47cc-9efe-6956608e150b",
"task_name": "potion-voice-user-ownership",
"trial_name": "potion-voice-user-ownership__NSP5wKq",
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/2026-10-16__17-09-39/potion-voice-user-ownership__NSP5wKq",
"task_id": {
"path": "harbor-tasks/potion-voice-user-ownership"
},
"source": null,
"task_checksum": "f1ec98b103f15bfa78fa54d29e81b811d54d64361b64ab55e879abd1cbb720c6",
"config": {
"task": {
"path": "harbor-tasks/potion-voice-user-ownership",
"git_url": null,
"git_commit_id": null,
"name": null,
"ref": null,
"overwrite": false,
"download_dir": null,
"source": null
},
"trial_name": "potion-voice-user-ownership__NSP5wKq",
"trials_dir": "harbor-jobs/2026-10-16__17-09-39",
"install_only": false,
"timeout_multiplier": 1.0,
"agent_timeout_multiplier": null,
"verifier_timeout_multiplier": null,
"agent_setup_timeout_multiplier": null,
"environment_build_timeout_multiplier": null,
"agent": {
"name": null,
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"n_concurrent": null,
"concurrency_group": null,
"skills": [],
"override_timeout_sec": null,
"override_setup_timeout_sec": null,
"max_timeout_sec": null,
"resume_trajectory": false,
"load_trajectory": null,
"extra_allowed_hosts": [],
"kwargs": {
"reasoning_effort": "max"
},
"mcp_servers": []
},
"environment": {
"type": "docker",
"import_path": null,
"force_build": true,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"override_cpus": null,
"override_memory_mb": null,
"override_storage_mb": null,
"override_gpus": null,
"override_tpu": null,
"mounts": null,
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"override_timeout_sec": null,
"max_timeout_sec": null,
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
},
"artifacts": [],
"extra_instruction_paths": [],
"job_id": "4e64ea74-4a6e-4fa1-9c9a-6fbe962d9070"
},
"agent_info": {
"name": "codex",
"version": "0.162.1",
"model_info": {
"name": "gpt-5.6-sol",
"provider": null
}
},
"agent_result": {
"n_input_tokens": 2094770,
"n_cache_tokens": 1995996,
"n_output_tokens": 30460,
"cost_usd": 1.8026944,
"rollout_details": null,
"metadata": null
},
"verifier_result": {
"rewards": {
"reward": 0.63
}
},
"exception_info": null,
"started_at": "2026-10-16T17:09:41.698997Z",
"finished_at": "2026-10-16T17:18:37.050538Z",
"environment_setup": {
"started_at": "2026-10-16T17:09:42.270278Z",
"finished_at": "2026-10-16T17:09:50.391814Z"
},
"agent_setup": {
"started_at": "2026-10-16T17:09:50.391840Z",
"finished_at": "2026-10-16T17:09:55.839830Z"
},
"agent_execution": {
"started_at": "2026-10-16T17:09:55.839951Z",
"finished_at": "2026-10-16T17:15:54.902910Z"
},
"verifier": {
"started_at": "2026-10-16T17:15:58.997667Z",
"finished_at": "2026-10-16T17:18:32.602591Z"
},
"step_results": null
}

View File

@@ -0,0 +1,49 @@
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Running command: set -x; if command -v apt-get >/dev/null 2>&1; then apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq curl ripgrep >/dev/null 2>&1 || true; fi; if ! command -v codex >/dev/null 2>&1; then CODEX_INSTALL_DIR=/usr/local/bin CODEX_NON_INTERACTIVE=true sh -c "curl -fsSL https://chatgpt.com/codex/install.sh | sh" >&2 || true; fi; if ! command -v codex >/dev/null 2>&1 && [ -x "$HOME/.local/bin/codex" ]; then ln -sf "$HOME/.local/bin/codex" /usr/local/bin/codex; fi; if ! command -v codex >/dev/null 2>&1; then export NVM_DIR="${NVM_DIR:-/usr/local/share/nvm}"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" >/dev/null 2>&1 || true; if ! command -v npm >/dev/null 2>&1; then npm_path="$(find /usr/local/share/nvm /usr/local /usr/lib /opt -name npm -type f 2>/dev/null | head -1)"; [ -n "$npm_path" ] && export PATH="$PATH:$(dirname "$npm_path")"; fi; command -v npm >/dev/null 2>&1 && npm install -g @openai/codex@latest; fi; for bin in node codex; do p="$(command -v "$bin" 2>/dev/null || true)"; [ -n "$p" ] && [ "$p" != "/usr/local/bin/$bin" ] && ln -sf "$p" "/usr/local/bin/$bin" || true; done; command -v codex >/dev/null 2>&1 || { echo "FATAL: codex CLI unavailable (standalone installer and npm both failed)" >&2; exit 1; }; codex --version
Command outputs captured
Running command: mkdir -p "$CODEX_HOME" /tmp/codex-secrets /logs/agent
Command outputs captured
Codex auth: using OPENAI_API_KEY
Running command: cat >/tmp/codex-secrets/auth.json <<EOF
{
"OPENAI_API_KEY": "${OPENAI_API_KEY}"
}
EOF
ln -sf /tmp/codex-secrets/auth.json "$CODEX_HOME/auth.json"
cat >>"$CODEX_HOME/config.toml" <<TOML
openai_base_url = "${OPENAI_BASE_URL}"
TOML
Command outputs captured
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- '# Background Worker Multi-Tenant Isolation Audit & Refactor
Our backend background processing services run asynchronous job workers for voice cloning (`voice-cloning-job-handler`) and speech synthesis (`voice-synthsizer-job-handler`). These workers consume job messages from AWS SQS queues and interact with MongoDB models (`VoiceCloning`, `UserAudioProfile`, `RecordingSalutation`, `Recording`).
A recent security audit revealed a critical multi-tenant isolation vulnerability: job handlers retrieve and mutate database records using only record identifiers (`_id` or job IDs) supplied in queue payloads, without scoping queries and updates to the authenticated user/tenant context.
## Task Requirements
1. **Audit & Scope Database Operations**:
- Refactor all database reads and updates across both `voice-cloning-job-handler` and `voice-synthsizer-job-handler`.
- Incorporate tenant filtering (using `userId` or profile-derived `userId`) on all queries and updates involving `VoiceCloning`, `UserAudioProfile`, `RecordingSalutation`, and `Recording`.
- Ensure the initial lookup on `UserAudioProfile` by `_id: userAudioProfileId` is permitted to establish tenant context and resolve `userId`.
2. **Side-Effect Prevention & Error Handling**:
- Ensure that job execution—including audio rendering and database mutations—is halted if tenant validation fails or if record ownership cannot be established.
- Maintain worker loop stability by handling errors in job processing with try-catch blocks so queue polling continues smoothly without crashing the worker process.
3. **Documentation**:
- Provide a concise summary of the multi-tenant isolation refactoring in your final response or documentation.
' 2>&1 </dev/null | tee /logs/agent/codex.txt
Command outputs captured
Running command: mkdir -p /logs/agent
if [ -d "$CODEX_HOME/sessions" ]; then
rm -rf /logs/agent/sessions
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
fi
Command outputs captured
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
Command outputs captured
Wrote Codex trajectory to harbor-jobs/2026-10-16__17-09-39/potion-voice-user-ownership__NSP5wKq/agent/trajectory.json
Collecting main service artifacts
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.

View File

@@ -0,0 +1,413 @@
const fs = require('fs')
const https = require('https')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const mongoose = require('mongoose')
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const voiceCloningService = require('./voice_cloning')
const userAudioProfileService = require('./user_audio_profile')
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
let throttleMessageFetching = true
const APP_ENV = process.env.POTION_APP_ENV
const cloudFrontUrlProd = process.env.CLOUDFRONT_URL_PROD
const cloudFrontUrlDev = process.env.CLOUDFRONT_URL_DEV
const cloudFrontUrlStaging = process.env.CLOUDFRONT_URL_STAGING
const updateUrl = (str, cloudFrontUrl) => {
const host = new URL(str).host
return str.replace(`https://${host}`, cloudFrontUrl)
}
function connectDB(dbUri, retryCount = 0) {
return new Promise((resolve, reject) => {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
mongoose
.connect(dbUri)
.then((msg) => {
console.log('Connected to Mongo DB !')
resolve()
})
.catch((err) => {
console.log('Failed to connect dns mongo: ', err)
if (retryCount < 6) {
resolve(connectDB(dbUri, retryCount + 1))
} else {
reject(err)
}
})
})
}
function execShellCommand(cmd, logPath) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, async (error, stdout, stderr) => {
if (error) {
console.log('Error while proccessing python command', error)
reject(error)
}
// console.log('Stdout --- ', stdout)
// console.log('Stderror --- ', stderr)
await fs.promises.writeFile(`${logPath}/error.log`, stderr)
await fs.promises.writeFile(`${logPath}/info.log`, stdout)
resolve()
})
})
}
async function getFile(waveUrl, path) {
return new Promise((resolve) => {
https.get(waveUrl, (res) => {
const writeStream = fs.createWriteStream(path)
res.pipe(writeStream)
writeStream.on('finish', () => {
writeStream.close()
resolve()
})
})
})
}
function pad(s) {
while (s.length < 3) s = '0' + s // IN future we will need padding to 4
return s
}
function requireOwnedRecord(record, recordName) {
if (!record) {
throw new Error(`Tenant validation failed for ${recordName}`)
}
return record
}
const processQueue = async () => {
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
console.log('job===', job)
const { metadata, input, _id, userAudioProfileId } = job._doc
console.log('userAudioProfileId', userAudioProfileId)
console.log('_id', _id)
const { env } = job
console.log('env', env)
console.log('metadata------', metadata)
console.log('input', input)
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
const cloudFrontUrl =
env === 'production'
? cloudFrontUrlProd
: env === 'staging'
? cloudFrontUrlStaging
: cloudFrontUrlDev
let userId
let ownershipValidated = false
try {
const userAudioProfile = requireOwnedRecord(
await userAudioProfileService.readForTenantContext(
userAudioProfileId
),
'UserAudioProfile'
)
userId = userAudioProfile.userId
if (!userId) {
throw new Error(
'Tenant validation failed: UserAudioProfile has no userId'
)
}
requireOwnedRecord(
await voiceCloningService.read(
{ _id, userAudioProfileId },
userId
),
'VoiceCloning'
)
ownershipValidated = true
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
const { directoryName } = metadata
console.log('directoryName', directoryName)
const logPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
if (!fs.existsSync(logPath)) {
fs.mkdirSync(logPath, { recursive: true })
}
// update the db model to processing
requireOwnedRecord(
await voiceCloningService.update(
{ _id, status: 'processing' },
userId
),
'VoiceCloning'
)
requireOwnedRecord(
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'processing',
},
userId
),
'UserAudioProfile'
)
// create directory for userid-useraudioprofileid if not exist
const rootPath = `/tmp/${directoryName}`
const wavePath = `${rootPath}/wav48/1`
if (!fs.existsSync(wavePath)) {
fs.mkdirSync(wavePath, { recursive: true })
}
const txtPath = `${rootPath}/txt/1`
if (!fs.existsSync(txtPath)) {
fs.mkdirSync(txtPath, { recursive: true })
}
// download the training data files and put it in respective directories
for (let index = 0; index < input.length; index++) {
const item = input[index]
const { waveUrl, originalText } = item
// download wave file
const waveFilePath = `${wavePath}/1_${pad('' + (index + 1))}.wav`
await getFile(updateUrl(waveUrl, cloudFrontUrl), waveFilePath)
const txtFilePath = `${txtPath}/1_${pad('' + (index + 1))}.txt`
await fs.promises.writeFile(txtFilePath, originalText)
}
const zipFileName = directoryName + '.tgz'
// /tmp/directoryName.tgz
await execShellCommand(
`cd /tmp && tar czvf ${zipFileName} ${directoryName}`,
logPath
)
console.log('ZIP created ', zipFileName)
// re-sample audio
const SAMPLING_LABEL = `Time Taken for re-sampling ${directoryName}`
console.time(SAMPLING_LABEL)
const outputPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
const samplingCommand = `python3 ../voice-cloning/prepare_datasets.py --dataset_preset potion_voice_cloning --dataset_archive_path /tmp/${zipFileName} --output_path ${outputPath}`
console.log('samplingCommand ', samplingCommand)
const samplingResponse = await execShellCommand(
samplingCommand,
logPath
)
console.timeEnd(SAMPLING_LABEL)
// /mnt/efs/potion-voice/${env}/speakrs.pth
// /mnt/efs/potion-voice/${env}/txt
// /mnt/efs/potion-voice/${env}/${directoryName}/wav
const outPath = `/mnt/efs/potion-voice/${env}/${directoryName}/sr22050/${directoryName}`
const resultsPath = outPath + '/results'
//update pth file for cloning
// clone the voice
const VOICE_CLONING_LABEL = `Time Taken for voice cloning ${directoryName}`
console.time(VOICE_CLONING_LABEL)
const trainingModelCommand = `python3 ../voice-cloning/clone_voice.py --baseline_model_path ../voice-cloning/pretrained-models/checkpoint_365000.pth --speaker_dataset_path ${outPath} --speaker_embeddings_path ${
outPath + '/speakers.pth'
} --output_path ${resultsPath}`
console.log('Training Model Command', trainingModelCommand)
const trainingResponse = await execShellCommand(
trainingModelCommand,
logPath
)
console.timeEnd(VOICE_CLONING_LABEL)
let generatedDirectoryName = ''
fs.readdirSync(`${resultsPath}/`).forEach((file) => {
if (file.includes('vits_potion_clone'))
// use output from above to get right path and directory name
generatedDirectoryName = file
})
// minimize cloning model
const VOICE_MINIMIZE_LABEL = `Time Taken for voice minimizing cloning ${directoryName}`
console.time(VOICE_MINIMIZE_LABEL)
const minimizeCloningModelCommand = `python3 ../voice-cloning/minimize_cloned_voice_model.py --voice_model_asset_path ${
resultsPath + '/' + generatedDirectoryName + '/'
} --voice_model_name checkpoint_365200.pth`
console.log(
'Minimize Cloning Model Command',
minimizeCloningModelCommand
)
const minimizeCloning = await execShellCommand(
minimizeCloningModelCommand,
logPath
)
console.timeEnd(VOICE_MINIMIZE_LABEL)
// Add the code to update location of generated model and status into DB
requireOwnedRecord(
await voiceCloningService.update(
{ _id, status: 'completed' },
userId
),
'VoiceCloning'
)
const training_model_path = {
voice_model_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200.pth`,
voice_model_config_path: `${resultsPath}/${generatedDirectoryName}/config.json`,
voice_model_speakers_file_path: `${outPath}/speakers.pth`, // TODO update the name to voice model speakers embeddings
voice_model_light_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200_light.pth`,
voice_model_config_light_path: `${resultsPath}/${generatedDirectoryName}/config_light.json`,
}
requireOwnedRecord(
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'completed',
training_model_path,
},
userId
),
'UserAudioProfile'
)
// add code to put that model into S3
let keys = Object.keys(training_model_path)
const training_model_s3_path = {}
for (let index = 0; index < keys.length; index++) {
const path = training_model_path[keys[index]]
const s3Path = await s3.upload({
filePath: path,
fileName: `${directoryName}/${path.split('/').pop()}`,
bucket: `potion-voice-users-training-model/${env}`,
})
training_model_s3_path[keys[index]] = s3Path
}
// add S3 path to user audio profile model
requireOwnedRecord(
await userAudioProfileService.update(
{
_id: userAudioProfileId,
training_model_s3_path,
},
userId
),
'UserAudioProfile'
)
} catch (error) {
console.log('error********************', error)
Bugsnag.notify(
new Error(
`Unable to train for voice cloning videos ` + JSON.stringify(job)
)
)
Bugsnag.notify(error)
// Only mutate failure status after ownership has been established.
if (ownershipValidated) {
const statusUpdates = await Promise.allSettled([
voiceCloningService.update({ _id, status: 'error' }, userId),
userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'error',
},
userId
),
])
statusUpdates
.filter(({ status }) => status === 'rejected')
.forEach(({ reason }) => Bugsnag.notify(reason))
}
}
} else {
throttleMessageFetching = true
}
} catch (error) {
console.error('Error while training voice clone', { error })
Bugsnag.notify(error)
} finally {
if (mongoose.connection.readyState !== 0) {
try {
await mongoose.connection.close()
} catch (error) {
console.error('Error while closing MongoDB connection', { error })
Bugsnag.notify(error)
}
}
}
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
console.log('potion Voice Clone Process Started')
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
while (true) {
try {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
} catch (error) {
console.error('Unhandled voice cloning job error', { error })
Bugsnag.notify(error)
}
}
}
if (require.main === module) {
init()
}
module.exports = { processQueue, init }

View File

@@ -0,0 +1,176 @@
const StringifyUtils = require('../../app/services/utils/logService')
const withTenant = (filter, userId) => {
if (!userId) {
throw new Error('userId is required for UserAudioProfile database operations')
}
return { ...filter, userId }
}
// This is the only intentionally unscoped lookup. The worker uses the returned
// userId as the tenant context for every subsequent read and mutation.
const readForTenantContext = (UserAudioProfileModel) => async (profileId) => {
try {
if (!profileId) {
throw new Error('profileId is required to establish tenant context')
}
return await UserAudioProfileModel.findOne({
_id: profileId,
deleted: false,
})
} catch (error) {
const details = { profileId }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > readForTenantContext',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const create = (UserAudioProfileModel) => async (data) => {
try {
const newModel = new UserAudioProfileModel({ ...data })
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (UserAudioProfileModel) => async (data) => {
try {
const inserted = await UserAudioProfileModel.insertMany(data)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModel = await UserAudioProfileModel.findOne(
withTenant({ ...filter, deleted: false }, userId)
)
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModels = await UserAudioProfileModel.find(
withTenant({ ...filter, deleted: false }, userId)
)
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (UserAudioProfileModel) => async (data, userId) => {
try {
const updates = { ...data }
const { _id } = updates
if (!_id) {
throw new Error('_id is required to update UserAudioProfile')
}
delete updates._id
delete updates.userId
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
withTenant({ _id, deleted: false }, userId),
updates,
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
withTenant({ ...filter, deleted: false }, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.updateMany(
withTenant({ ...filter, deleted: false }, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (UserAudioProfileModel) => {
return {
create: create(UserAudioProfileModel),
insertMany: insertMany(UserAudioProfileModel),
readForTenantContext: readForTenantContext(UserAudioProfileModel),
read: read(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel),
}
}

View File

@@ -0,0 +1,154 @@
const StringifyUtils = require('../../app/services/utils/logService')
const withTenant = (filter, userId) => {
if (!userId) {
throw new Error('userId is required for VoiceCloning database operations')
}
return { ...filter, userId }
}
const create = (VoiceCloningModel) => async (data) => {
try {
const newModel = new VoiceCloningModel({ ...data })
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (VoiceCloningModel) => async (data) => {
try {
const inserted = await VoiceCloningModel.insertMany(data)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (VoiceCloningModel) => async (filter, userId) => {
try {
const foundModel = await VoiceCloningModel.findOne(
withTenant({ ...filter, deleted: false }, userId)
)
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (VoiceCloningModel) => async (filter, userId) => {
try {
const foundModels = await VoiceCloningModel.find(
withTenant({ ...filter, deleted: false }, userId)
)
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (VoiceCloningModel) => async (data, userId) => {
try {
const updates = { ...data }
const { _id } = updates
if (!_id) {
throw new Error('_id is required to update VoiceCloning')
}
delete updates._id
delete updates.userId
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
withTenant({ _id, deleted: false }, userId),
updates,
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (VoiceCloningModel) => async (filter, userId) => {
try {
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
withTenant({ ...filter, deleted: false }, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (VoiceCloningModel) => async (filter, userId) => {
try {
const updatedModel = await VoiceCloningModel.updateMany(
withTenant({ ...filter, deleted: false }, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (VoiceCloningModel) => {
return {
create: create(VoiceCloningModel),
insertMany: insertMany(VoiceCloningModel),
read: read(VoiceCloningModel),
remove: remove(VoiceCloningModel),
removeMany: removeMany(VoiceCloningModel),
update: update(VoiceCloningModel),
find: find(VoiceCloningModel),
}
}

View File

@@ -0,0 +1,280 @@
const fs = require('fs')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const uuid = require('uuid').v4
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const userAudioProfileService = require('./user_audio_profile')
const recordingModel = require('./recording')
const recordingSalutationModel = require('./recording_salutation')
const jobService = require('./job')
const salutationService = require('./salutation')
let throttleMessageFetching = true
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
const APP_ENV = process.env.POTION_APP_ENV
const mongoose = require('mongoose')
function execShellCommand(cmd) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, (error, stdout, stderr) => {
if (error) {
console.log('Error while processing python command', error)
reject(error)
}
console.log('Stdout --- ', stdout)
console.log('Std error --- ', stderr)
resolve(stdout || stderr)
})
})
}
function connectDB(dbUri, retryCount = 0) {
return new Promise((resolve, reject) => {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
mongoose
.connect(dbUri)
.then((msg) => {
console.log('Connected to Mongo DB !')
resolve()
})
.catch((err) => {
console.log('Failed to connect dns mongo: ', err)
if (retryCount < 6) {
resolve(connectDB(dbUri, retryCount + 1))
} else {
reject(err)
}
})
})
}
function requireOwnedRecord(record, recordName) {
if (!record) {
throw new Error(`Tenant validation failed for ${recordName}`)
}
return record
}
const processQueue = async () => {
let job
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages === 'undefined' ||
response.Messages.length === 0
) {
throttleMessageFetching = true
return
}
throttleMessageFetching = false
job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
const {
userAudioProfileId,
text,
firstName,
salutationId,
recordingId,
baseUrlForPotionAi,
env,
} = job
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
// This profile lookup is the sole tenant-context bootstrap. No rendering,
// queue deletion, upload, or mutation occurs until all ownership checks pass.
const userAudioProfile = requireOwnedRecord(
await userAudioProfileService.readForTenantContext(userAudioProfileId),
'UserAudioProfile'
)
const { training_model_path, userId, status } = userAudioProfile
if (!userId) {
throw new Error(
'Tenant validation failed: UserAudioProfile has no userId'
)
}
if (status !== 'completed' || !training_model_path) {
throw new Error('Audio profile training model not found')
}
const [salutationToUpdate, recordingToUpdate] = await Promise.all([
recordingSalutationModel.findOne({
_id: salutationId,
userId,
deleted: false,
}),
recordingModel.findOne({
_id: recordingId,
userId,
deleted: false,
}),
])
requireOwnedRecord(salutationToUpdate, 'RecordingSalutation')
requireOwnedRecord(recordingToUpdate, 'Recording')
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
const {
voice_model_light_path,
voice_model_config_light_path,
voice_model_speakers_file_path, // name for speakers embeddings file path
} = training_model_path
const outputPath = `/tmp/${uuid()}/`
if (!fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath, { recursive: true })
}
const AI_COMMAND = `python3 ../voice-cloning/synthesize_speech.py --voice_model_path ${voice_model_light_path} --voice_model_config_path ${voice_model_config_light_path} --speaker_embeddings_path ${voice_model_speakers_file_path} --txt "${text}" --output_path ${outputPath}`
console.log('AI_COMMAND ', AI_COMMAND)
const SYNTHESIZE_AI_LABEL = `Time consumed by AI` + Math.random()
console.time(SYNTHESIZE_AI_LABEL)
const aiResponse = await execShellCommand(AI_COMMAND)
console.timeEnd(SYNTHESIZE_AI_LABEL)
let generatedFileName = ''
fs.readdirSync(`${outputPath}`).forEach((file) => {
if (file.includes('sr48000.wav')) generatedFileName = file
})
// upload the file to s3
const uploadParams = {
filePath: `${outputPath}${generatedFileName}`,
bucket: `recordings-${env}`,
fileName: `${uuid()}_salutation_${firstName.replace('-', '_')}.wav`,
contentType: 'audio/x-wav',
fileType: 'wav',
}
console.time('Time to Upload video on S3')
const greetingUploadResponse = await s3.upload(uploadParams)
console.timeEnd('Time to Upload video on S3')
// Re-apply the tenant filter on the mutation in case ownership changed or
// the record was deleted after validation.
requireOwnedRecord(
await recordingSalutationModel.findOneAndUpdate(
{
_id: salutationId,
userId,
deleted: false,
},
{
$set: {
salutationVideo: greetingUploadResponse,
},
},
{ new: true }
),
'RecordingSalutation'
)
// Create or update the user's reusable salutation only after all target
// records have passed tenant validation.
await salutationService.updateOrCreate(
{
firstName,
salutationVideo: greetingUploadResponse,
userAudioProfileId,
},
userId
)
const jobData = {
originalGreeting: recordingToUpdate.masterSalutationVideoUrl,
originalVideo:
recordingToUpdate.originalVideoUrl || recordingToUpdate.urls[0].url,
cropTimestamp: recordingToUpdate.cropTimestamp,
greetingClips: [greetingUploadResponse],
greetingObjects: [
{
greetingId: salutationToUpdate._id,
firstName,
videoUrl: greetingUploadResponse,
},
],
requestOrigin: baseUrlForPotionAi,
environment: env,
recordingId: recordingToUpdate._id,
salutation: salutationToUpdate._id,
dynamicVideoType: recordingToUpdate.dynamicVideoType,
}
await jobService.insertMany([
{
firstName,
recordingId: recordingToUpdate._id,
userId,
salutationId: salutationToUpdate._id,
metadata: jobData,
},
])
fs.unlinkSync(`${outputPath}${generatedFileName}`)
console.log(`[deleted] ${outputPath}${generatedFileName}`)
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(
new Error(`Unable to synthesize audio ` + JSON.stringify(job))
)
Bugsnag.notify(error)
} finally {
if (mongoose.connection.readyState !== 0) {
try {
await mongoose.connection.close()
} catch (error) {
console.error('Error while closing MongoDB connection', { error })
Bugsnag.notify(error)
}
}
}
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
while (true) {
try {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
} catch (error) {
console.error('Unhandled speech synthesis job error', { error })
Bugsnag.notify(error)
}
}
}
if (require.main === module) {
init()
}
module.exports = { processQueue, init }

View File

@@ -0,0 +1,178 @@
const StringifyUtils = require('../../app/services/utils/logService')
const withTenant = (filter, userId) => {
if (!userId) {
throw new Error('userId is required for UserAudioProfile database operations')
}
return { ...filter, userId }
}
// This is the only intentionally unscoped lookup. The worker uses the returned
// userId as the tenant context for every subsequent read and mutation.
const readForTenantContext = (UserAudioProfileModel) => async (profileId) => {
try {
if (!profileId) {
throw new Error('profileId is required to establish tenant context')
}
return await UserAudioProfileModel.findOne({
_id: profileId,
deleted: false,
})
} catch (error) {
const details = { profileId }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > readForTenantContext',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const create = (UserAudioProfileModel) => async (data) => {
try {
const newModel = new UserAudioProfileModel({ ...data })
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (UserAudioProfileModel) => async (data) => {
try {
const inserted = await UserAudioProfileModel.insertMany(data)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModel = await UserAudioProfileModel.findOne(
withTenant({ ...filter, deleted: false }, userId)
)
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModels = await UserAudioProfileModel.find(
withTenant({ ...filter, deleted: false }, userId)
)
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (UserAudioProfileModel) => async (data, userId) => {
console.log('ua data', data)
try {
const updates = { ...data }
const { _id } = updates
if (!_id) {
throw new Error('_id is required to update UserAudioProfile')
}
delete updates._id
delete updates.userId
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
withTenant({ _id, deleted: false }, userId),
updates,
{
new: true
}
)
console.log('ua updatedModel', updatedModel)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
withTenant({ ...filter, deleted: false }, userId),
{
$set: {
deleted: true
}
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.updateMany(
withTenant({ ...filter, deleted: false }, userId),
{
$set: {
deleted: true
}
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (UserAudioProfileModel) => {
return {
create: create(UserAudioProfileModel),
insertMany: insertMany(UserAudioProfileModel),
readForTenantContext: readForTenantContext(UserAudioProfileModel),
read: read(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel)
}
}

View File

@@ -0,0 +1,49 @@
{
"schema_version": 1,
"criteria": {
"integrity": {
"score": 0.91,
"rationale": "The transcript shows the agent ran the syntax, diff, filter, and mocked ownership checks it reported. Its final side-effect claim is broader than those checks support, but there is no evidence of fabricated work."
},
"narrow_correctness": {
"score": 0.55,
"rationale": "Targeted reads and updates include userId, apart from the permitted UserAudioProfile bootstrap, and both initial ownership checks halt processing. However, in voice-cloning-job-handler/index.js, a null processing update throws into a catch block that still updates the profile to error. A mocked run reproduced that downstream mutation after the zero-match result. This is the task rubric's Crux side-effect failure."
},
"broader_correctness": {
"score": 0.83,
"rationale": "The refactor uses the existing service layer, prevents updates from changing userId, checks scoped update results on the main paths, and keeps polling after processing errors. The changes are otherwise consistent with the relevant schemas and worker structure."
},
"persistence": {
"score": 0.85,
"rationale": "The agent completed changes in both workers, audited call sites, corrected a Node-version incompatibility in its test command, and continued through final checks."
},
"communication": {
"score": 0.75,
"rationale": "Progress updates and the final summary are concise and clear. The final statement that side-effect prevention checks pass overstates coverage: its tests exercise missing initial records, not null scoped updates."
},
"verification_thoroughness": {
"score": 0.62,
"rationale": "The agent ran syntax and diff checks, tested service filters, and mocked one ownership failure in each worker. It did not test a null processing update; that omitted case exposes the cloning failure path. The repository has no test script, and no database integration run was shown."
},
"common_sense": {
"score": 0.84,
"rationale": "Deriving userId from the allowed profile lookup, applying it to later filters, and placing ownership checks before rendering are straightforward choices. The worker-loop and connection-retry changes also address real failure paths without adding a new framework."
},
"thought_partnership": {
"score": 0.78,
"rationale": "The agent traced the issue beyond the named identifier lookups into processing order and addressed both workers. It did not identify the remaining null-update side-effect path or qualify its security summary accordingly."
}
},
"overall_penalties": [
{
"amount": 0.14,
"reason": "Task guidance: cloning-prevent-unauthorized-side-effects Crux failure; a null scoped processing update is followed by a UserAudioProfile failure-status mutation."
}
],
"overall_score": 0.64,
"closing": "The final tree was inspected and syntax and diff checks passed. A mocked null-update run confirmed the remaining cloning defect.",
"generator": {
"kind": "grader",
"version": "render-grade-consolidated/0.2.0"
}
}

View File

@@ -0,0 +1,43 @@
Score: 0.63 (mean 0.77 of 8 non-N/A criteria - 0.14 overall heavy penalty)
Holistic overall (grader-stated): 0.64
Standard: 8 criteria
## Integrity — 0.91
The transcript shows the agent ran the syntax, diff, filter, and mocked ownership checks it reported. Its final side-effect claim is broader than those checks support, but there is no evidence of fabricated work.
## Narrow Correctness — 0.55
Targeted reads and updates include userId, apart from the permitted UserAudioProfile bootstrap, and both initial ownership checks halt processing. However, in voice-cloning-job-handler/index.js, a null processing update throws into a catch block that still updates the profile to error. A mocked run reproduced that downstream mutation after the zero-match result. This is the task rubric's Crux side-effect failure.
## Broader Correctness / craft — 0.83
The refactor uses the existing service layer, prevents updates from changing userId, checks scoped update results on the main paths, and keeps polling after processing errors. The changes are otherwise consistent with the relevant schemas and worker structure.
## Persistence — 0.85
The agent completed changes in both workers, audited call sites, corrected a Node-version incompatibility in its test command, and continued through final checks.
## Communication — 0.75
Progress updates and the final summary are concise and clear. The final statement that side-effect prevention checks pass overstates coverage: its tests exercise missing initial records, not null scoped updates.
## Verification & Thoroughness — 0.62
The agent ran syntax and diff checks, tested service filters, and mocked one ownership failure in each worker. It did not test a null processing update; that omitted case exposes the cloning failure path. The repository has no test script, and no database integration run was shown.
## Common Sense — 0.84
Deriving userId from the allowed profile lookup, applying it to later filters, and placing ownership checks before rendering are straightforward choices. The worker-loop and connection-retry changes also address real failure paths without adding a new framework.
## Thought Partnership — 0.78
The agent traced the issue beyond the named identifier lookups into processing order and addressed both workers. It did not identify the remaining null-update side-effect path or qualify its security summary accordingly.
## Overall penalties
- 0.14 — Task guidance: cloning-prevent-unauthorized-side-effects Crux failure; a null scoped processing update is followed by a UserAudioProfile failure-status mutation.
## Closing
The final tree was inspected and syntax and diff checks passed. A mocked null-update run confirmed the remaining cloning defect.

View File

@@ -0,0 +1,49 @@
{
"schema_version": 1,
"criteria": {
"integrity": {
"score": 0.91,
"rationale": "The transcript shows the agent ran the syntax, diff, filter, and mocked ownership checks it reported. Its final side-effect claim is broader than those checks support, but there is no evidence of fabricated work."
},
"narrow_correctness": {
"score": 0.55,
"rationale": "Targeted reads and updates include userId, apart from the permitted UserAudioProfile bootstrap, and both initial ownership checks halt processing. However, in voice-cloning-job-handler/index.js, a null processing update throws into a catch block that still updates the profile to error. A mocked run reproduced that downstream mutation after the zero-match result. This is the task rubric's Crux side-effect failure."
},
"broader_correctness": {
"score": 0.83,
"rationale": "The refactor uses the existing service layer, prevents updates from changing userId, checks scoped update results on the main paths, and keeps polling after processing errors. The changes are otherwise consistent with the relevant schemas and worker structure."
},
"persistence": {
"score": 0.85,
"rationale": "The agent completed changes in both workers, audited call sites, corrected a Node-version incompatibility in its test command, and continued through final checks."
},
"communication": {
"score": 0.75,
"rationale": "Progress updates and the final summary are concise and clear. The final statement that side-effect prevention checks pass overstates coverage: its tests exercise missing initial records, not null scoped updates."
},
"verification_thoroughness": {
"score": 0.62,
"rationale": "The agent ran syntax and diff checks, tested service filters, and mocked one ownership failure in each worker. It did not test a null processing update; that omitted case exposes the cloning failure path. The repository has no test script, and no database integration run was shown."
},
"common_sense": {
"score": 0.84,
"rationale": "Deriving userId from the allowed profile lookup, applying it to later filters, and placing ownership checks before rendering are straightforward choices. The worker-loop and connection-retry changes also address real failure paths without adding a new framework."
},
"thought_partnership": {
"score": 0.78,
"rationale": "The agent traced the issue beyond the named identifier lookups into processing order and addressed both workers. It did not identify the remaining null-update side-effect path or qualify its security summary accordingly."
}
},
"overall_penalties": [
{
"amount": 0.14,
"reason": "Task guidance: cloning-prevent-unauthorized-side-effects Crux failure; a null scoped processing update is followed by a UserAudioProfile failure-status mutation."
}
],
"overall_score": 0.64,
"closing": "The final tree was inspected and syntax and diff checks passed. A mocked null-update run confirmed the remaining cloning defect.",
"generator": {
"kind": "grader",
"version": "render-grade-consolidated/0.2.0"
}
}

View File

@@ -0,0 +1,43 @@
Score: 0.63 (mean 0.77 of 8 non-N/A criteria - 0.14 overall heavy penalty)
Holistic overall (grader-stated): 0.64
Standard: 8 criteria
## Integrity — 0.91
The transcript shows the agent ran the syntax, diff, filter, and mocked ownership checks it reported. Its final side-effect claim is broader than those checks support, but there is no evidence of fabricated work.
## Narrow Correctness — 0.55
Targeted reads and updates include userId, apart from the permitted UserAudioProfile bootstrap, and both initial ownership checks halt processing. However, in voice-cloning-job-handler/index.js, a null processing update throws into a catch block that still updates the profile to error. A mocked run reproduced that downstream mutation after the zero-match result. This is the task rubric's Crux side-effect failure.
## Broader Correctness / craft — 0.83
The refactor uses the existing service layer, prevents updates from changing userId, checks scoped update results on the main paths, and keeps polling after processing errors. The changes are otherwise consistent with the relevant schemas and worker structure.
## Persistence — 0.85
The agent completed changes in both workers, audited call sites, corrected a Node-version incompatibility in its test command, and continued through final checks.
## Communication — 0.75
Progress updates and the final summary are concise and clear. The final statement that side-effect prevention checks pass overstates coverage: its tests exercise missing initial records, not null scoped updates.
## Verification & Thoroughness — 0.62
The agent ran syntax and diff checks, tested service filters, and mocked one ownership failure in each worker. It did not test a null processing update; that omitted case exposes the cloning failure path. The repository has no test script, and no database integration run was shown.
## Common Sense — 0.84
Deriving userId from the allowed profile lookup, applying it to later filters, and placing ownership checks before rendering are straightforward choices. The worker-loop and connection-retry changes also address real failure paths without adding a new framework.
## Thought Partnership — 0.78
The agent traced the issue beyond the named identifier lookups into processing order and addressed both workers. It did not identify the remaining null-update side-effect path or qualify its security summary accordingly.
## Overall penalties
- 0.14 — Task guidance: cloning-prevent-unauthorized-side-effects Crux failure; a null scoped processing update is followed by a UserAudioProfile failure-status mutation.
## Closing
The final tree was inspected and syntax and diff checks passed. A mocked null-update run confirmed the remaining cloning defect.

View File

@@ -0,0 +1,16 @@
{
"schema_version": 1,
"captured_at": "2026-10-16T17:15:59Z",
"grader_mode": "agentic",
"grader_harness": "codex",
"grader_reasoning_effort": "high",
"grader_model": "gpt-6-sol",
"grader_samples": "1",
"grading_standard": "consolidated",
"grader_prompt_file": "grader-system-prompt-consolidated.md",
"grader_prompt_sha256": "85edbe174ef7af339641db1f808cd4da3b2d3ee9587a07ac4e3a593011748dc9",
"grader_guidance_file": "holistic-rubric.md",
"grader_guidance_sha256": "1c0d21e1f5946c9abb72656b9b7b3ebea0e6c04dad89dbbd664374283d9f8cb8",
"render_grade_file": "render-grade-consolidated.py",
"render_grade_sha256": "db8b668c536007abbd7d9719dc08dd388507e67df7da08f63bc8c495d58840cb"
}

View File

@@ -0,0 +1 @@
{"session_id": "01a145b6-a655-7060-82d3-81b5713ca376", "usage": {"input_tokens": 606940, "cached_input_tokens": 535789, "cache_write_input_tokens": 71115, "output_tokens": 10647, "reasoning_output_tokens": 7150}}

View File

@@ -0,0 +1 @@
{"session_id": "01a145b6-a655-7060-82d3-81b5713ca376", "usage": {"input_tokens": 606940, "cached_input_tokens": 535789, "cache_write_input_tokens": 71115, "output_tokens": 10647, "reasoning_output_tokens": 7150}}

View File

@@ -0,0 +1,7 @@
samples_requested: 1
samples_valid: 1
sample_1: 0.63
mean: 0.6300
canonical_sample: 1
correctness_sample_1: NA
correctness_mean: N/A

View File

@@ -0,0 +1 @@
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.wd1MSXA8"))

View File

@@ -0,0 +1 @@
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.wd1MSXA8"))

View File

@@ -0,0 +1,9 @@
Captured 5 agent output files
Launching codex grader (requested model: gpt-6-sol, samples: 1)...
render-grade-consolidated: ok reward=0.63 criteria_scored=8
render-grade-consolidated: note grader-stated overall 0.64 differs from derived 0.63
grader sample 1: 0.63
correctness sample 1: N/A
reward: 0.6300 correctness: N/A
0.6300
{"reward": 0.6300}

View File

@@ -0,0 +1,9 @@
[
{
"source": "/logs/artifacts",
"destination": "artifacts/logs/artifacts",
"type": "directory",
"status": "empty",
"service": null
}
]

View File

@@ -0,0 +1,26 @@
{
"task": {
"path": "harbor-tasks/potion-voice-user-ownership"
},
"trial_name": "potion-voice-user-ownership__Vz8kjv9",
"trials_dir": "harbor-jobs/2026-10-16__17-09-39",
"agent": {
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"kwargs": {
"reasoning_effort": "max"
}
},
"environment": {
"type": "docker",
"force_build": true,
"delete": false
},
"verifier": {
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
}
},
"job_id": "4e64ea74-4a6e-4fa1-9c9a-6fbe962d9070"
}

View File

@@ -0,0 +1,18 @@
{
"version": 1,
"capturedAt": "2026-10-16T17:09:39.217Z",
"capturedBy": "run",
"inputs": {
"prompt": "739c7341a3290bf4535728fad936f6da3ff8309a96ddeef0fa4de3e895d9cbfa",
"graderGuidance": null,
"sessionJsonl": null,
"workspacePatch": null,
"gitref": "fcd8a9d0",
"graderGuidanceConsolidated": null,
"holisticRubric": "1c0d21e1f5946c9abb72656b9b7b3ebea0e6c04dad89dbbd664374283d9f8cb8",
"atomicRubric": "da086ee3bf75aa4f055e81a795d110ad9ab5dcaf8268c929b60183213a33b7a2",
"rubricsYaml": null,
"graderContext": "c2c5f0f45f47c21298c680258d45fd6a9d44b3638c94e4ce6bc55cf4ce804ba3"
},
"taskSlug": "potion-voice-user-ownership"
}

View File

@@ -0,0 +1,40 @@
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:97d55f2194451121f9afc4478166e848cc3854893471a2fb1aecce74018f7f6d",
"path": "harbor-tasks/potion-voice-user-ownership"
},
"install_only": false,
"timeout_multiplier": 1.0,
"agent": {
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"skills": [],
"resume_trajectory": false,
"extra_allowed_hosts": [],
"kwargs": {
"reasoning_effort": "max"
},
"mcp_servers": []
},
"skills": [],
"environment": {
"type": "docker",
"force_build": true,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
}
}

View File

@@ -0,0 +1,119 @@
{
"id": "f16202fa-f328-42b4-af3b-3b9f7fbf2c88",
"task_name": "potion-voice-user-ownership",
"trial_name": "potion-voice-user-ownership__Vz8kjv9",
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/2026-10-16__17-09-39/potion-voice-user-ownership__Vz8kjv9",
"task_id": {
"path": "harbor-tasks/potion-voice-user-ownership"
},
"source": null,
"task_checksum": "f1ec98b103f15bfa78fa54d29e81b811d54d64361b64ab55e879abd1cbb720c6",
"config": {
"task": {
"path": "harbor-tasks/potion-voice-user-ownership",
"git_url": null,
"git_commit_id": null,
"name": null,
"ref": null,
"overwrite": false,
"download_dir": null,
"source": null
},
"trial_name": "potion-voice-user-ownership__Vz8kjv9",
"trials_dir": "harbor-jobs/2026-10-16__17-09-39",
"install_only": false,
"timeout_multiplier": 1.0,
"agent_timeout_multiplier": null,
"verifier_timeout_multiplier": null,
"agent_setup_timeout_multiplier": null,
"environment_build_timeout_multiplier": null,
"agent": {
"name": null,
"import_path": "codex_agent:SystemNodeCodex",
"model_name": "gpt-5.6-sol",
"n_concurrent": null,
"concurrency_group": null,
"skills": [],
"override_timeout_sec": null,
"override_setup_timeout_sec": null,
"max_timeout_sec": null,
"resume_trajectory": false,
"load_trajectory": null,
"extra_allowed_hosts": [],
"kwargs": {
"reasoning_effort": "max"
},
"mcp_servers": []
},
"environment": {
"type": "docker",
"import_path": null,
"force_build": true,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"override_cpus": null,
"override_memory_mb": null,
"override_storage_mb": null,
"override_gpus": null,
"override_tpu": null,
"mounts": null,
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"override_timeout_sec": null,
"max_timeout_sec": null,
"env": {
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
},
"artifacts": [],
"extra_instruction_paths": [],
"job_id": "4e64ea74-4a6e-4fa1-9c9a-6fbe962d9070"
},
"agent_info": {
"name": "codex",
"version": "0.162.1",
"model_info": {
"name": "gpt-5.6-sol",
"provider": null
}
},
"agent_result": {
"n_input_tokens": 3219121,
"n_cache_tokens": 3103148,
"n_output_tokens": 38882,
"cost_usd": 2.4827912000000003,
"rollout_details": null,
"metadata": null
},
"verifier_result": {
"rewards": {
"reward": 0.58
}
},
"exception_info": null,
"started_at": "2026-10-16T17:09:41.360282Z",
"finished_at": "2026-10-16T17:20:17.959087Z",
"environment_setup": {
"started_at": "2026-10-16T17:09:42.174456Z",
"finished_at": "2026-10-16T17:09:49.595617Z"
},
"agent_setup": {
"started_at": "2026-10-16T17:09:49.595651Z",
"finished_at": "2026-10-16T17:09:55.763254Z"
},
"agent_execution": {
"started_at": "2026-10-16T17:09:55.763552Z",
"finished_at": "2026-10-16T17:17:48.234111Z"
},
"verifier": {
"started_at": "2026-10-16T17:17:48.807986Z",
"finished_at": "2026-10-16T17:20:13.638241Z"
},
"step_results": null
}

View File

@@ -0,0 +1,49 @@
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Running command: set -x; if command -v apt-get >/dev/null 2>&1; then apt-get update -qq >/dev/null 2>&1 && apt-get install -y -qq curl ripgrep >/dev/null 2>&1 || true; fi; if ! command -v codex >/dev/null 2>&1; then CODEX_INSTALL_DIR=/usr/local/bin CODEX_NON_INTERACTIVE=true sh -c "curl -fsSL https://chatgpt.com/codex/install.sh | sh" >&2 || true; fi; if ! command -v codex >/dev/null 2>&1 && [ -x "$HOME/.local/bin/codex" ]; then ln -sf "$HOME/.local/bin/codex" /usr/local/bin/codex; fi; if ! command -v codex >/dev/null 2>&1; then export NVM_DIR="${NVM_DIR:-/usr/local/share/nvm}"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" >/dev/null 2>&1 || true; if ! command -v npm >/dev/null 2>&1; then npm_path="$(find /usr/local/share/nvm /usr/local /usr/lib /opt -name npm -type f 2>/dev/null | head -1)"; [ -n "$npm_path" ] && export PATH="$PATH:$(dirname "$npm_path")"; fi; command -v npm >/dev/null 2>&1 && npm install -g @openai/codex@latest; fi; for bin in node codex; do p="$(command -v "$bin" 2>/dev/null || true)"; [ -n "$p" ] && [ "$p" != "/usr/local/bin/$bin" ] && ln -sf "$p" "/usr/local/bin/$bin" || true; done; command -v codex >/dev/null 2>&1 || { echo "FATAL: codex CLI unavailable (standalone installer and npm both failed)" >&2; exit 1; }; codex --version
Command outputs captured
Running command: mkdir -p "$CODEX_HOME" /tmp/codex-secrets /logs/agent
Command outputs captured
Codex auth: using OPENAI_API_KEY
Running command: cat >/tmp/codex-secrets/auth.json <<EOF
{
"OPENAI_API_KEY": "${OPENAI_API_KEY}"
}
EOF
ln -sf /tmp/codex-secrets/auth.json "$CODEX_HOME/auth.json"
cat >>"$CODEX_HOME/config.toml" <<TOML
openai_base_url = "${OPENAI_BASE_URL}"
TOML
Command outputs captured
Running command: if [ -s ~/.nvm/nvm.sh ]; then . ~/.nvm/nvm.sh; fi; codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --model gpt-5.6-sol --json --enable unified_exec -c model_reasoning_effort=max -c agents.enabled=false -c features.external_agent_memory_import=false -c features.goals=false -c features.memories=false -c features.multi_agent=false -c features.multi_agent_v2=false -c tools.experimental_request_user_input.enabled=false -c tools.update_plan.enabled=false -c web_search=disabled -c model_provider=llm-proxy -c 'model_providers.llm-proxy.name="LLM proxy"' -c 'model_providers.llm-proxy.base_url="https://app-llmproxy.dataannotation.tech/api/llm_proxy/openai/v1"' -c 'model_providers.llm-proxy.env_key="OPENAI_API_KEY"' -c 'model_providers.llm-proxy.wire_api="responses"' -c 'model_providers.llm-proxy.http_headers.X-Surge-Client-Metadata='"'"'{"origin":"harbor-trial"}'"'"'' -- '# Background Worker Multi-Tenant Isolation Audit & Refactor
Our backend background processing services run asynchronous job workers for voice cloning (`voice-cloning-job-handler`) and speech synthesis (`voice-synthsizer-job-handler`). These workers consume job messages from AWS SQS queues and interact with MongoDB models (`VoiceCloning`, `UserAudioProfile`, `RecordingSalutation`, `Recording`).
A recent security audit revealed a critical multi-tenant isolation vulnerability: job handlers retrieve and mutate database records using only record identifiers (`_id` or job IDs) supplied in queue payloads, without scoping queries and updates to the authenticated user/tenant context.
## Task Requirements
1. **Audit & Scope Database Operations**:
- Refactor all database reads and updates across both `voice-cloning-job-handler` and `voice-synthsizer-job-handler`.
- Incorporate tenant filtering (using `userId` or profile-derived `userId`) on all queries and updates involving `VoiceCloning`, `UserAudioProfile`, `RecordingSalutation`, and `Recording`.
- Ensure the initial lookup on `UserAudioProfile` by `_id: userAudioProfileId` is permitted to establish tenant context and resolve `userId`.
2. **Side-Effect Prevention & Error Handling**:
- Ensure that job execution—including audio rendering and database mutations—is halted if tenant validation fails or if record ownership cannot be established.
- Maintain worker loop stability by handling errors in job processing with try-catch blocks so queue polling continues smoothly without crashing the worker process.
3. **Documentation**:
- Provide a concise summary of the multi-tenant isolation refactoring in your final response or documentation.
' 2>&1 </dev/null | tee /logs/agent/codex.txt
Command outputs captured
Running command: mkdir -p /logs/agent
if [ -d "$CODEX_HOME/sessions" ]; then
rm -rf /logs/agent/sessions
cp -R "$CODEX_HOME/sessions" /logs/agent/sessions
fi
Command outputs captured
Running command: rm -rf /tmp/codex-secrets "$CODEX_HOME"
Command outputs captured
Wrote Codex trajectory to harbor-jobs/2026-10-16__17-09-39/potion-voice-user-ownership__Vz8kjv9/agent/trajectory.json
Collecting main service artifacts
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.

View File

@@ -0,0 +1,47 @@
class TenantValidationError extends Error {
constructor(message) {
super(message)
this.name = 'TenantValidationError'
this.code = 'TENANT_VALIDATION_FAILED'
}
}
const requireTenantId = (userId) => {
if (!userId) {
throw new TenantValidationError('A tenant userId is required')
}
return userId
}
const requireRecordId = (recordId, recordName) => {
if (!recordId) {
throw new TenantValidationError(`${recordName} id is required`)
}
return recordId
}
const tenantFilter = (filter = {}, userId) => ({
...filter,
userId: requireTenantId(userId),
})
const splitTenantUpdate = (data = {}) => {
const source =
typeof data.toObject === 'function' ? data.toObject() : { ...data }
const recordId = source._id
delete source._id
delete source.userId
return { recordId, updates: source }
}
module.exports = {
TenantValidationError,
requireRecordId,
requireTenantId,
splitTenantUpdate,
tenantFilter,
}

View File

@@ -0,0 +1,419 @@
const fs = require('fs')
const https = require('https')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const mongoose = require('mongoose')
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const {
TenantValidationError,
requireRecordId,
requireTenantId,
} = require('../app/services/utils/tenantScope')
const voiceCloningService = require('./voice_cloning')
const userAudioProfileService = require('./user_audio_profile')
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
let throttleMessageFetching = true
const APP_ENV = process.env.POTION_APP_ENV
const cloudFrontUrlProd = process.env.CLOUDFRONT_URL_PROD
const cloudFrontUrlDev = process.env.CLOUDFRONT_URL_DEV
const cloudFrontUrlStaging = process.env.CLOUDFRONT_URL_STAGING
const updateUrl = (str, cloudFrontUrl) => {
const host = new URL(str).host
return str.replace(`https://${host}`, cloudFrontUrl)
}
async function connectDB(dbUri, retryCount = 0) {
while (retryCount <= 6) {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
try {
await mongoose.connect(dbUri)
console.log('Connected to Mongo DB !')
return
} catch (error) {
console.log('Failed to connect dns mongo: ', error)
if (retryCount === 6) throw error
retryCount++
}
}
}
const requireOwnedRecord = (record, recordName) => {
if (!record) {
throw new TenantValidationError(
`${recordName} was not found for the resolved tenant`
)
}
return record
}
const resolveTenantContext = async (_id, userAudioProfileId) => {
requireRecordId(_id, 'VoiceCloning')
requireRecordId(userAudioProfileId, 'UserAudioProfile')
const userAudioProfile = requireOwnedRecord(
await userAudioProfileService.readById(userAudioProfileId),
'UserAudioProfile'
)
const userId = requireTenantId(userAudioProfile.userId)
const voiceCloning = requireOwnedRecord(
await voiceCloningService.read(
{ _id, userAudioProfileId },
userId
),
'VoiceCloning'
)
return { userAudioProfile, userId, voiceCloning }
}
function execShellCommand(cmd, logPath) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, async (error, stdout, stderr) => {
if (error) {
console.log('Error while proccessing python command', error)
reject(error)
}
// console.log('Stdout --- ', stdout)
// console.log('Stderror --- ', stderr)
await fs.promises.writeFile(`${logPath}/error.log`, stderr)
await fs.promises.writeFile(`${logPath}/info.log`, stdout)
resolve()
})
})
}
async function getFile(waveUrl, path) {
return new Promise((resolve) => {
https.get(waveUrl, (res) => {
const writeStream = fs.createWriteStream(path)
res.pipe(writeStream)
writeStream.on('finish', () => {
writeStream.close()
resolve()
})
})
})
}
function pad(s) {
while (s.length < 3) s = '0' + s // IN future we will need padding to 4
return s
}
const processQueue = async () => {
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
console.log('job===', job)
const { metadata, input, _id, userAudioProfileId } = job._doc
console.log('userAudioProfileId', userAudioProfileId)
console.log('_id', _id)
const { env } = job
console.log('env', env)
console.log('metadata------', metadata)
console.log('input', input)
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
const cloudFrontUrl =
env === 'production'
? cloudFrontUrlProd
: env === 'staging'
? cloudFrontUrlStaging
: cloudFrontUrlDev
let tenantContext = null
try {
tenantContext = await resolveTenantContext(_id, userAudioProfileId)
const { userId } = tenantContext
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
const { directoryName } = metadata
console.log('directoryName', directoryName)
const logPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
if (!fs.existsSync(logPath)) {
fs.mkdirSync(logPath, { recursive: true })
}
// update the db model to processing
requireOwnedRecord(
await voiceCloningService.update(
{ _id, status: 'processing' },
userId
),
'VoiceCloning'
)
requireOwnedRecord(
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'processing',
},
userId
),
'UserAudioProfile'
)
// create directory for userid-useraudioprofileid if not exist
const rootPath = `/tmp/${directoryName}`
const wavePath = `${rootPath}/wav48/1`
if (!fs.existsSync(wavePath)) {
fs.mkdirSync(wavePath, { recursive: true })
}
const txtPath = `${rootPath}/txt/1`
if (!fs.existsSync(txtPath)) {
fs.mkdirSync(txtPath, { recursive: true })
}
// download the training data files and put it in respective directories
for (let index = 0; index < input.length; index++) {
const item = input[index]
const { waveUrl, originalText } = item
// download wave file
const waveFilePath = `${wavePath}/1_${pad('' + (index + 1))}.wav`
await getFile(updateUrl(waveUrl, cloudFrontUrl), waveFilePath)
const txtFilePath = `${txtPath}/1_${pad('' + (index + 1))}.txt`
await fs.promises.writeFile(txtFilePath, originalText)
}
const zipFileName = directoryName + '.tgz'
// /tmp/directoryName.tgz
await execShellCommand(
`cd /tmp && tar czvf ${zipFileName} ${directoryName}`,
logPath
)
console.log('ZIP created ', zipFileName)
// re-sample audio
const SAMPLING_LABEL = `Time Taken for re-sampling ${directoryName}`
console.time(SAMPLING_LABEL)
const outputPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
const samplingCommand = `python3 ../voice-cloning/prepare_datasets.py --dataset_preset potion_voice_cloning --dataset_archive_path /tmp/${zipFileName} --output_path ${outputPath}`
console.log('samplingCommand ', samplingCommand)
const samplingResponse = await execShellCommand(
samplingCommand,
logPath
)
console.timeEnd(SAMPLING_LABEL)
// /mnt/efs/potion-voice/${env}/speakrs.pth
// /mnt/efs/potion-voice/${env}/txt
// /mnt/efs/potion-voice/${env}/${directoryName}/wav
const outPath = `/mnt/efs/potion-voice/${env}/${directoryName}/sr22050/${directoryName}`
const resultsPath = outPath + '/results'
//update pth file for cloning
// clone the voice
const VOICE_CLONING_LABEL = `Time Taken for voice cloning ${directoryName}`
console.time(VOICE_CLONING_LABEL)
const trainingModelCommand = `python3 ../voice-cloning/clone_voice.py --baseline_model_path ../voice-cloning/pretrained-models/checkpoint_365000.pth --speaker_dataset_path ${outPath} --speaker_embeddings_path ${
outPath + '/speakers.pth'
} --output_path ${resultsPath}`
console.log('Training Model Command', trainingModelCommand)
const trainingResponse = await execShellCommand(
trainingModelCommand,
logPath
)
console.timeEnd(VOICE_CLONING_LABEL)
let generatedDirectoryName = ''
fs.readdirSync(`${resultsPath}/`).forEach((file) => {
if (file.includes('vits_potion_clone'))
// use output from above to get right path and directory name
generatedDirectoryName = file
})
// minimize cloning model
const VOICE_MINIMIZE_LABEL = `Time Taken for voice minimizing cloning ${directoryName}`
console.time(VOICE_MINIMIZE_LABEL)
const minimizeCloningModelCommand = `python3 ../voice-cloning/minimize_cloned_voice_model.py --voice_model_asset_path ${
resultsPath + '/' + generatedDirectoryName + '/'
} --voice_model_name checkpoint_365200.pth`
console.log(
'Minimize Cloning Model Command',
minimizeCloningModelCommand
)
const minimizeCloning = await execShellCommand(
minimizeCloningModelCommand,
logPath
)
console.timeEnd(VOICE_MINIMIZE_LABEL)
// Add the code to update location of generated model and status into DB
requireOwnedRecord(
await voiceCloningService.update(
{ _id, status: 'completed' },
userId
),
'VoiceCloning'
)
const training_model_path = {
voice_model_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200.pth`,
voice_model_config_path: `${resultsPath}/${generatedDirectoryName}/config.json`,
voice_model_speakers_file_path: `${outPath}/speakers.pth`, // TODO update the name to voice model speakers embeddings
voice_model_light_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200_light.pth`,
voice_model_config_light_path: `${resultsPath}/${generatedDirectoryName}/config_light.json`,
}
requireOwnedRecord(
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'completed',
training_model_path,
},
userId
),
'UserAudioProfile'
)
// add code to put that model into S3
let keys = Object.keys(training_model_path)
const training_model_s3_path = {}
for (let index = 0; index < keys.length; index++) {
const path = training_model_path[keys[index]]
const s3Path = await s3.upload({
filePath: path,
fileName: `${directoryName}/${path.split('/').pop()}`,
bucket: `potion-voice-users-training-model/${env}`,
})
training_model_s3_path[keys[index]] = s3Path
}
// add S3 path to user audio profile model
requireOwnedRecord(
await userAudioProfileService.update(
{
_id: userAudioProfileId,
training_model_s3_path,
},
userId
),
'UserAudioProfile'
)
} catch (error) {
console.log('error********************', error)
Bugsnag.notify(
new Error(
`Unable to train for voice cloning videos ` + JSON.stringify(job)
)
)
Bugsnag.notify(error)
if (tenantContext) {
const { userId } = tenantContext
const statusUpdates = await Promise.allSettled([
voiceCloningService.update({ _id, status: 'error' }, userId),
userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'error',
},
userId
),
])
statusUpdates
.filter(({ status }) => status === 'rejected')
.forEach(({ reason }) => Bugsnag.notify(reason))
} else if (error instanceof TenantValidationError) {
// Invalid ownership is not retryable. Acknowledge the message only
// after validation has failed, without rendering or mutating data.
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
} catch (deleteError) {
Bugsnag.notify(deleteError)
}
}
}
} else {
throttleMessageFetching = true
}
} catch (error) {
console.error('Error while training voice clone', { error })
Bugsnag.notify(error)
} finally {
try {
await mongoose.connection.close()
} catch (error) {
console.error('Error while closing Mongo DB connection', { error })
Bugsnag.notify(error)
}
}
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
console.log('potion Voice Clone Process Started')
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
while (true) {
try {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
} catch (error) {
console.error('Unexpected voice cloning worker error', { error })
Bugsnag.notify(error)
}
}
}
if (require.main === module) init()
module.exports = { processQueue, resolveTenantContext }

View File

@@ -0,0 +1,178 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
requireRecordId,
requireTenantId,
splitTenantUpdate,
tenantFilter,
} = require('../../app/services/utils/tenantScope')
const create = (UserAudioProfileModel) => async (data, userId) => {
try {
const newModel = new UserAudioProfileModel({
...data,
userId: requireTenantId(userId),
})
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (UserAudioProfileModel) => async (data, userId) => {
try {
const tenantId = requireTenantId(userId)
const inserted = await UserAudioProfileModel.insertMany(
data.map((item) => ({ ...item, userId: tenantId }))
)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
// This is the only intentionally unscoped lookup. Workers use it to establish
// tenant context from the profile referenced by a queue message.
const readById = (UserAudioProfileModel) => async (userAudioProfileId) => {
try {
return await UserAudioProfileModel.findOne({
_id: requireRecordId(userAudioProfileId, 'UserAudioProfile'),
deleted: false,
})
} catch (error) {
const details = { userAudioProfileId }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > readById',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModel = await UserAudioProfileModel.findOne({
...tenantFilter(filter, userId),
deleted: false,
})
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModels = await UserAudioProfileModel.find({
...tenantFilter(filter, userId),
deleted: false,
})
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (UserAudioProfileModel) => async (data, userId) => {
try {
const { recordId, updates } = splitTenantUpdate(data)
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{
...tenantFilter(
{ _id: requireRecordId(recordId, 'UserAudioProfile') },
userId
),
deleted: false,
},
{ $set: updates },
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{ ...tenantFilter(filter, userId), deleted: false },
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.updateMany(
{ ...tenantFilter(filter, userId), deleted: false },
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (UserAudioProfileModel) => {
return {
create: create(UserAudioProfileModel),
insertMany: insertMany(UserAudioProfileModel),
readById: readById(UserAudioProfileModel),
read: read(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel),
}
}

View File

@@ -0,0 +1,160 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
requireRecordId,
requireTenantId,
splitTenantUpdate,
tenantFilter,
} = require('../../app/services/utils/tenantScope')
const create = (VoiceCloningModel) => async (data, userId) => {
try {
const newModel = new VoiceCloningModel({
...data,
userId: requireTenantId(userId),
})
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (VoiceCloningModel) => async (data, userId) => {
try {
const tenantId = requireTenantId(userId)
const inserted = await VoiceCloningModel.insertMany(
data.map((item) => ({ ...item, userId: tenantId }))
)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (VoiceCloningModel) => async (filter, userId) => {
try {
const foundModel = await VoiceCloningModel.findOne({
...tenantFilter(filter, userId),
deleted: false,
})
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (VoiceCloningModel) => async (filter, userId) => {
try {
const foundModels = await VoiceCloningModel.find({
...tenantFilter(filter, userId),
deleted: false,
})
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (VoiceCloningModel) => async (data, userId) => {
try {
const { recordId, updates } = splitTenantUpdate(data)
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
{
...tenantFilter(
{ _id: requireRecordId(recordId, 'VoiceCloning') },
userId
),
deleted: false,
},
{ $set: updates },
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (VoiceCloningModel) => async (filter, userId) => {
try {
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
{ ...tenantFilter(filter, userId), deleted: false },
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (VoiceCloningModel) => async (filter, userId) => {
try {
const updatedModel = await VoiceCloningModel.updateMany(
{ ...tenantFilter(filter, userId), deleted: false },
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (VoiceCloningModel) => {
return {
create: create(VoiceCloningModel),
insertMany: insertMany(VoiceCloningModel),
read: read(VoiceCloningModel),
remove: remove(VoiceCloningModel),
removeMany: removeMany(VoiceCloningModel),
update: update(VoiceCloningModel),
find: find(VoiceCloningModel),
}
}

View File

@@ -0,0 +1,325 @@
const fs = require('fs')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const uuid = require('uuid').v4
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const {
TenantValidationError,
requireRecordId,
requireTenantId,
} = require('../app/services/utils/tenantScope')
const userAudioProfileService = require('./user_audio_profile')
const recordingModel = require('./recording')
const recordingSalutationModel = require('./recording_salutation')
const jobService = require('./job')
const salutationService = require('./salutation')
let throttleMessageFetching = true
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
const APP_ENV = process.env.POTION_APP_ENV
const mongoose = require('mongoose')
function execShellCommand(cmd) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, (error, stdout, stderr) => {
if (error) {
console.log('Error while processing python command', error)
reject(error)
}
console.log('Stdout --- ', stdout)
console.log('Std error --- ', stderr)
resolve(stdout || stderr)
})
})
}
async function connectDB(dbUri, retryCount = 0) {
while (retryCount <= 6) {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
try {
await mongoose.connect(dbUri)
console.log('Connected to Mongo DB !')
return
} catch (error) {
console.log('Failed to connect dns mongo: ', error)
if (retryCount === 6) throw error
retryCount++
}
}
}
const requireOwnedRecord = (record, recordName) => {
if (!record) {
throw new TenantValidationError(
`${recordName} was not found for the resolved tenant`
)
}
return record
}
const resolveTenantContext = async ({
userAudioProfileId,
salutationId,
recordingId,
}) => {
requireRecordId(userAudioProfileId, 'UserAudioProfile')
requireRecordId(salutationId, 'RecordingSalutation')
requireRecordId(recordingId, 'Recording')
// This bootstrap read is intentionally scoped only by profile id. Its
// persisted owner becomes the trusted tenant context for every later query.
const userAudioProfile = requireOwnedRecord(
await userAudioProfileService.readById(userAudioProfileId),
'UserAudioProfile'
)
const userId = requireTenantId(userAudioProfile.userId)
if (userAudioProfile.status !== 'completed') {
throw new TenantValidationError('UserAudioProfile is not ready')
}
const [salutationToUpdate, recordingToUpdate] = await Promise.all([
recordingSalutationModel.findOne({
_id: salutationId,
userId,
deleted: false,
}),
recordingModel.findOne({
_id: recordingId,
userId,
deleted: false,
}),
])
requireOwnedRecord(salutationToUpdate, 'RecordingSalutation')
requireOwnedRecord(recordingToUpdate, 'Recording')
return {
recordingToUpdate,
salutationToUpdate,
userAudioProfile,
userId,
}
}
const processQueue = async () => {
let job = null
let receiptHandle = null
let messageAcknowledged = false
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (!response.Messages || response.Messages.length === 0) {
throttleMessageFetching = true
return
}
throttleMessageFetching = false
job = JSON.parse(response.Messages[0].Body)
receiptHandle = response.Messages[0].ReceiptHandle
const {
userAudioProfileId,
text,
firstName,
salutationId,
recordingId,
baseUrlForPotionAi,
env,
} = job
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
const {
recordingToUpdate,
salutationToUpdate,
userAudioProfile,
userId,
} = await resolveTenantContext({
userAudioProfileId,
salutationId,
recordingId,
})
const {
voice_model_light_path,
voice_model_config_light_path,
voice_model_speakers_file_path,
} = userAudioProfile.training_model_path || {}
if (
!voice_model_light_path ||
!voice_model_config_light_path ||
!voice_model_speakers_file_path
) {
throw new TenantValidationError(
'UserAudioProfile does not have a complete training model'
)
}
// Do not remove a message or perform external work until ownership of all
// referenced records has been established from the persisted profile.
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
messageAcknowledged = true
const outputPath = `/tmp/${uuid()}/`
if (!fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath, { recursive: true })
}
const AI_COMMAND = `python3 ../voice-cloning/synthesize_speech.py --voice_model_path ${voice_model_light_path} --voice_model_config_path ${voice_model_config_light_path} --speaker_embeddings_path ${voice_model_speakers_file_path} --txt "${text}" --output_path ${outputPath}`
console.log('AI_COMMAND ', AI_COMMAND)
const SYNTHESIZE_AI_LABEL = `Time consumed by AI` + Math.random()
console.time(SYNTHESIZE_AI_LABEL)
await execShellCommand(AI_COMMAND)
console.timeEnd(SYNTHESIZE_AI_LABEL)
let generatedFileName = ''
fs.readdirSync(outputPath).forEach((file) => {
if (file.includes('sr48000.wav')) generatedFileName = file
})
const generatedFilePath = `${outputPath}${generatedFileName}`
const uploadParams = {
filePath: generatedFilePath,
bucket: `recordings-${env}`,
fileName: `${uuid()}_salutation_${firstName.replace('-', '_')}.wav`,
contentType: 'audio/x-wav',
fileType: 'wav',
}
console.time('Time to Upload video on S3')
const greetingUploadResponse = await s3.upload(uploadParams)
console.timeEnd('Time to Upload video on S3')
await salutationService.updateOrCreate(
{
firstName,
salutationVideo: greetingUploadResponse,
userAudioProfileId,
},
userId
)
requireOwnedRecord(
await recordingSalutationModel.findOneAndUpdate(
{
_id: salutationId,
userId,
deleted: false,
},
{
$set: {
salutationVideo: greetingUploadResponse,
},
},
{ new: true }
),
'RecordingSalutation'
)
const jobData = {
originalGreeting: recordingToUpdate.masterSalutationVideoUrl,
originalVideo:
recordingToUpdate.originalVideoUrl || recordingToUpdate.urls[0].url,
cropTimestamp: recordingToUpdate.cropTimestamp,
greetingClips: [greetingUploadResponse],
greetingObjects: [
{
greetingId: salutationToUpdate._id,
firstName,
videoUrl: greetingUploadResponse,
},
],
requestOrigin: baseUrlForPotionAi,
environment: env,
recordingId: recordingToUpdate._id,
salutation: salutationToUpdate._id,
dynamicVideoType: recordingToUpdate.dynamicVideoType,
}
await jobService.insertMany(
[
{
firstName,
recordingId: recordingToUpdate._id,
salutationId: salutationToUpdate._id,
metadata: jobData,
},
],
userId
)
fs.unlinkSync(generatedFilePath)
console.log(`[deleted] ${generatedFilePath}`)
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(
new Error(`Unable to synthesize audio ` + JSON.stringify(job))
)
Bugsnag.notify(error)
if (
error instanceof TenantValidationError &&
receiptHandle &&
!messageAcknowledged
) {
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
} catch (deleteError) {
Bugsnag.notify(deleteError)
}
}
} finally {
try {
await mongoose.connection.close()
} catch (error) {
console.error('Error while closing Mongo DB connection', { error })
Bugsnag.notify(error)
}
}
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
while (true) {
try {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
} catch (error) {
console.error('Unexpected synthesis worker error', { error })
Bugsnag.notify(error)
}
}
}
if (require.main === module) init()
module.exports = { processQueue, resolveTenantContext }

View File

@@ -0,0 +1,151 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
requireRecordId,
requireTenantId,
splitTenantUpdate,
tenantFilter,
} = require('../../app/services/utils/tenantScope')
const create = (Job) => async (jobData, userId) => {
try {
const newJob = new Job({ ...jobData, userId: requireTenantId(userId) })
const savedJob = await newJob.save()
return savedJob
} catch (error) {
const details = { jobData }
console.log(
'ERROR - JOB SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (Job) => async (jobData, userId) => {
try {
const tenantId = requireTenantId(userId)
const inserted = await Job.insertMany(
jobData.map((job) => ({ ...job, userId: tenantId }))
)
return inserted
} catch (error) {
const details = { jobData }
console.log(
'ERROR - JOB SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (Job) => async (filter, userId) => {
try {
const foundJob = await Job.findOne({
...tenantFilter(filter, userId),
deleted: false,
})
return foundJob
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (Job) => async (filter, userId) => {
try {
const foundJobs = await Job.find({
...tenantFilter(filter, userId),
deleted: false,
})
return foundJobs
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (Job) => async (job, userId) => {
try {
const { recordId, updates } = splitTenantUpdate(job)
const updatedJob = await Job.findOneAndUpdate(
{
...tenantFilter({ _id: requireRecordId(recordId, 'Job') }, userId),
deleted: false,
},
{ $set: updates },
{ new: true }
)
return updatedJob
} catch (error) {
const details = { job }
console.log(
'ERROR - JOB SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (Job) => async (filter, userId) => {
try {
const updatedJob = await Job.findOneAndUpdate(
{ ...tenantFilter(filter, userId), deleted: false },
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedJob
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (Job) => async (filter, userId) => {
try {
const updatedJob = await Job.updateMany(
{ ...tenantFilter(filter, userId), deleted: false },
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedJob
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (Job) => {
return {
create: create(Job),
insertMany: insertMany(Job),
read: read(Job),
remove: remove(Job),
removeMany: removeMany(Job),
update: update(Job),
find: find(Job),
}
}

View File

@@ -0,0 +1,112 @@
const {
requireRecordId,
requireTenantId,
splitTenantUpdate,
tenantFilter,
} = require('../../app/services/utils/tenantScope')
const create = (Salutation) => async (salutationData, userId) => {
const newSalutation = new Salutation({
...salutationData,
userId: requireTenantId(userId),
})
const savedSalutation = await newSalutation.save()
return savedSalutation
}
const read = (Salutation) => async (filter, userId) => {
const foundSalutation = await Salutation.findOne({
...tenantFilter(filter, userId),
deleted: false,
})
return foundSalutation
}
const find = (Salutation) => async (filter, userId) => {
const foundSalutations = await Salutation.find({
...tenantFilter(filter, userId),
deleted: false,
})
return foundSalutations
}
const update = (Salutation) => async (salutation, userId) => {
const { recordId, updates } = splitTenantUpdate(salutation)
const updatedSalutation = await Salutation.findOneAndUpdate(
{
...tenantFilter(
{ _id: requireRecordId(recordId, 'Salutation') },
userId
),
deleted: false,
},
{ $set: updates },
{ new: true }
)
return updatedSalutation
}
const modify = (Salutation) => async (salutation, userId) => {
const { recordId, updates } = splitTenantUpdate(salutation)
const findQuery = salutation._id
? { _id: requireRecordId(recordId, 'Salutation') }
: {
transcriptId: requireRecordId(
salutation.transcriptId,
'Salutation transcript'
),
}
const updatedSalutation = await Salutation.findOneAndUpdate(
{ ...tenantFilter(findQuery, userId), deleted: false },
{ $set: updates },
{ new: true }
)
return updatedSalutation
}
const updateOrCreate =
(Salutation) =>
async ({ firstName, salutationVideo, userAudioProfileId }, userId) => {
const salutation = await read(Salutation)(
{
firstName,
userAudioProfileId,
},
userId
)
if (salutation) {
salutation.salutationVideo = salutationVideo
return await update(Salutation)(salutation, userId)
} else {
return await create(Salutation)(
{ firstName, salutationVideo, userAudioProfileId },
userId
)
}
}
const remove = (Salutation) => async (filter, userId) => {
const updatedSalutation = await Salutation.findOneAndUpdate(
{ ...tenantFilter(filter, userId), deleted: false },
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedSalutation
}
module.exports = (Salutation) => {
return {
create: create(Salutation),
read: read(Salutation),
remove: remove(Salutation),
update: update(Salutation),
updateOrCreate: updateOrCreate(Salutation),
find: find(Salutation),
modify: modify(Salutation),
}
}

View File

@@ -0,0 +1,178 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
requireRecordId,
requireTenantId,
splitTenantUpdate,
tenantFilter,
} = require('../../app/services/utils/tenantScope')
const create = (UserAudioProfileModel) => async (data, userId) => {
try {
const newModel = new UserAudioProfileModel({
...data,
userId: requireTenantId(userId),
})
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (UserAudioProfileModel) => async (data, userId) => {
try {
const tenantId = requireTenantId(userId)
const inserted = await UserAudioProfileModel.insertMany(
data.map((item) => ({ ...item, userId: tenantId }))
)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
// This is the only intentionally unscoped lookup. Workers use it to establish
// tenant context from the profile referenced by a queue message.
const readById = (UserAudioProfileModel) => async (userAudioProfileId) => {
try {
return await UserAudioProfileModel.findOne({
_id: requireRecordId(userAudioProfileId, 'UserAudioProfile'),
deleted: false,
})
} catch (error) {
const details = { userAudioProfileId }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > readById',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModel = await UserAudioProfileModel.findOne({
...tenantFilter(filter, userId),
deleted: false,
})
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModels = await UserAudioProfileModel.find({
...tenantFilter(filter, userId),
deleted: false,
})
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (UserAudioProfileModel) => async (data, userId) => {
try {
const { recordId, updates } = splitTenantUpdate(data)
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{
...tenantFilter(
{ _id: requireRecordId(recordId, 'UserAudioProfile') },
userId
),
deleted: false,
},
{ $set: updates },
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{ ...tenantFilter(filter, userId), deleted: false },
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.updateMany(
{ ...tenantFilter(filter, userId), deleted: false },
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (UserAudioProfileModel) => {
return {
create: create(UserAudioProfileModel),
insertMany: insertMany(UserAudioProfileModel),
readById: readById(UserAudioProfileModel),
read: read(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel),
}
}

View File

@@ -0,0 +1,49 @@
{
"schema_version": 1,
"criteria": {
"integrity": {
"score": 0.9,
"rationale": "The transcript shows the agent ran the syntax, service-filter, and mocked worker checks it cited. Its final safety claim is inaccurate for a later null scoped update, but the evidence supports a missed path rather than deliberate concealment."
},
"narrow_correctness": {
"score": 0.52,
"rationale": "The final tree scopes the required model operations by profile-derived userId and stops work when initial ownership reads fail. However, in voice-cloning-job-handler/index.js, a null scoped processing update triggers the catch block, which still issues error-status database updates. I reproduced both variants: a null VoiceCloning update was followed by a UserAudioProfile update, and a null profile update was followed by a VoiceCloning update. This fails the task-specific Crux rule."
},
"broader_correctness": {
"score": 0.81,
"rationale": "The shared tenant helper enforces tenant arguments and removes userId from update payloads. Both worker loops catch per-message errors and continue polling. The patch has no durable regression tests; the failed-update side effect is charged under Narrow Correctness rather than counted again here."
},
"persistence": {
"score": 0.84,
"rationale": "The agent audited both workers and their service call sites, revised the loops, and continued testing after the edits. It stopped without testing the later null-update catch path, leaving a material requirement unfinished."
},
"communication": {
"score": 0.77,
"rationale": "The updates and final summary are clear. The final claim that mutations occur only after ownership validation overstates the result because cloning still changes status after a scoped processing update returns null."
},
"verification_thoroughness": {
"score": 0.62,
"rationale": "The agent ran syntax checks, git diff --check, service-filter assertions, and mocked worker flows. Its negative worker tests covered null initial reads but not null processing updates. My reproduction against the final tree confirmed downstream status updates in that case. No repository test suite or live Mongo/SQS integration check was available."
},
"common_sense": {
"score": 0.8,
"rationale": "Using the stored profile to derive userId, checking referenced records before Python and S3 work, and keeping polling alive are sensible choices. The ancillary service rewrites and formatting churn increased the review surface."
},
"thought_partnership": {
"score": 0.79,
"rationale": "The agent recognized the permitted profile bootstrap, checked the VoiceCloning-to-profile link, and moved synthesis ownership reads ahead of expensive work. It did not surface the catch-path risk, so its security conclusion was firmer than the verified behavior supports."
}
},
"overall_penalties": [
{
"amount": 0.18,
"reason": "Task guidance: heavy overall penalty for a cloning side-effect Crux failure; a null scoped processing update is followed by error-status database mutations."
}
],
"overall_score": 0.61,
"closing": "The final tree was available at /tmp/agent-workspace. No repository test script or live Mongo/SQS environment was available.",
"generator": {
"kind": "grader",
"version": "render-grade-consolidated/0.2.0"
}
}

View File

@@ -0,0 +1,43 @@
Score: 0.58 (mean 0.76 of 8 non-N/A criteria - 0.18 overall heavy penalty)
Holistic overall (grader-stated): 0.61
Standard: 8 criteria
## Integrity — 0.90
The transcript shows the agent ran the syntax, service-filter, and mocked worker checks it cited. Its final safety claim is inaccurate for a later null scoped update, but the evidence supports a missed path rather than deliberate concealment.
## Narrow Correctness — 0.52
The final tree scopes the required model operations by profile-derived userId and stops work when initial ownership reads fail. However, in voice-cloning-job-handler/index.js, a null scoped processing update triggers the catch block, which still issues error-status database updates. I reproduced both variants: a null VoiceCloning update was followed by a UserAudioProfile update, and a null profile update was followed by a VoiceCloning update. This fails the task-specific Crux rule.
## Broader Correctness / craft — 0.81
The shared tenant helper enforces tenant arguments and removes userId from update payloads. Both worker loops catch per-message errors and continue polling. The patch has no durable regression tests; the failed-update side effect is charged under Narrow Correctness rather than counted again here.
## Persistence — 0.84
The agent audited both workers and their service call sites, revised the loops, and continued testing after the edits. It stopped without testing the later null-update catch path, leaving a material requirement unfinished.
## Communication — 0.77
The updates and final summary are clear. The final claim that mutations occur only after ownership validation overstates the result because cloning still changes status after a scoped processing update returns null.
## Verification & Thoroughness — 0.62
The agent ran syntax checks, git diff --check, service-filter assertions, and mocked worker flows. Its negative worker tests covered null initial reads but not null processing updates. My reproduction against the final tree confirmed downstream status updates in that case. No repository test suite or live Mongo/SQS integration check was available.
## Common Sense — 0.80
Using the stored profile to derive userId, checking referenced records before Python and S3 work, and keeping polling alive are sensible choices. The ancillary service rewrites and formatting churn increased the review surface.
## Thought Partnership — 0.79
The agent recognized the permitted profile bootstrap, checked the VoiceCloning-to-profile link, and moved synthesis ownership reads ahead of expensive work. It did not surface the catch-path risk, so its security conclusion was firmer than the verified behavior supports.
## Overall penalties
- 0.18 — Task guidance: heavy overall penalty for a cloning side-effect Crux failure; a null scoped processing update is followed by error-status database mutations.
## Closing
The final tree was available at /tmp/agent-workspace. No repository test script or live Mongo/SQS environment was available.

View File

@@ -0,0 +1,49 @@
{
"schema_version": 1,
"criteria": {
"integrity": {
"score": 0.9,
"rationale": "The transcript shows the agent ran the syntax, service-filter, and mocked worker checks it cited. Its final safety claim is inaccurate for a later null scoped update, but the evidence supports a missed path rather than deliberate concealment."
},
"narrow_correctness": {
"score": 0.52,
"rationale": "The final tree scopes the required model operations by profile-derived userId and stops work when initial ownership reads fail. However, in voice-cloning-job-handler/index.js, a null scoped processing update triggers the catch block, which still issues error-status database updates. I reproduced both variants: a null VoiceCloning update was followed by a UserAudioProfile update, and a null profile update was followed by a VoiceCloning update. This fails the task-specific Crux rule."
},
"broader_correctness": {
"score": 0.81,
"rationale": "The shared tenant helper enforces tenant arguments and removes userId from update payloads. Both worker loops catch per-message errors and continue polling. The patch has no durable regression tests; the failed-update side effect is charged under Narrow Correctness rather than counted again here."
},
"persistence": {
"score": 0.84,
"rationale": "The agent audited both workers and their service call sites, revised the loops, and continued testing after the edits. It stopped without testing the later null-update catch path, leaving a material requirement unfinished."
},
"communication": {
"score": 0.77,
"rationale": "The updates and final summary are clear. The final claim that mutations occur only after ownership validation overstates the result because cloning still changes status after a scoped processing update returns null."
},
"verification_thoroughness": {
"score": 0.62,
"rationale": "The agent ran syntax checks, git diff --check, service-filter assertions, and mocked worker flows. Its negative worker tests covered null initial reads but not null processing updates. My reproduction against the final tree confirmed downstream status updates in that case. No repository test suite or live Mongo/SQS integration check was available."
},
"common_sense": {
"score": 0.8,
"rationale": "Using the stored profile to derive userId, checking referenced records before Python and S3 work, and keeping polling alive are sensible choices. The ancillary service rewrites and formatting churn increased the review surface."
},
"thought_partnership": {
"score": 0.79,
"rationale": "The agent recognized the permitted profile bootstrap, checked the VoiceCloning-to-profile link, and moved synthesis ownership reads ahead of expensive work. It did not surface the catch-path risk, so its security conclusion was firmer than the verified behavior supports."
}
},
"overall_penalties": [
{
"amount": 0.18,
"reason": "Task guidance: heavy overall penalty for a cloning side-effect Crux failure; a null scoped processing update is followed by error-status database mutations."
}
],
"overall_score": 0.61,
"closing": "The final tree was available at /tmp/agent-workspace. No repository test script or live Mongo/SQS environment was available.",
"generator": {
"kind": "grader",
"version": "render-grade-consolidated/0.2.0"
}
}

View File

@@ -0,0 +1,43 @@
Score: 0.58 (mean 0.76 of 8 non-N/A criteria - 0.18 overall heavy penalty)
Holistic overall (grader-stated): 0.61
Standard: 8 criteria
## Integrity — 0.90
The transcript shows the agent ran the syntax, service-filter, and mocked worker checks it cited. Its final safety claim is inaccurate for a later null scoped update, but the evidence supports a missed path rather than deliberate concealment.
## Narrow Correctness — 0.52
The final tree scopes the required model operations by profile-derived userId and stops work when initial ownership reads fail. However, in voice-cloning-job-handler/index.js, a null scoped processing update triggers the catch block, which still issues error-status database updates. I reproduced both variants: a null VoiceCloning update was followed by a UserAudioProfile update, and a null profile update was followed by a VoiceCloning update. This fails the task-specific Crux rule.
## Broader Correctness / craft — 0.81
The shared tenant helper enforces tenant arguments and removes userId from update payloads. Both worker loops catch per-message errors and continue polling. The patch has no durable regression tests; the failed-update side effect is charged under Narrow Correctness rather than counted again here.
## Persistence — 0.84
The agent audited both workers and their service call sites, revised the loops, and continued testing after the edits. It stopped without testing the later null-update catch path, leaving a material requirement unfinished.
## Communication — 0.77
The updates and final summary are clear. The final claim that mutations occur only after ownership validation overstates the result because cloning still changes status after a scoped processing update returns null.
## Verification & Thoroughness — 0.62
The agent ran syntax checks, git diff --check, service-filter assertions, and mocked worker flows. Its negative worker tests covered null initial reads but not null processing updates. My reproduction against the final tree confirmed downstream status updates in that case. No repository test suite or live Mongo/SQS integration check was available.
## Common Sense — 0.80
Using the stored profile to derive userId, checking referenced records before Python and S3 work, and keeping polling alive are sensible choices. The ancillary service rewrites and formatting churn increased the review surface.
## Thought Partnership — 0.79
The agent recognized the permitted profile bootstrap, checked the VoiceCloning-to-profile link, and moved synthesis ownership reads ahead of expensive work. It did not surface the catch-path risk, so its security conclusion was firmer than the verified behavior supports.
## Overall penalties
- 0.18 — Task guidance: heavy overall penalty for a cloning side-effect Crux failure; a null scoped processing update is followed by error-status database mutations.
## Closing
The final tree was available at /tmp/agent-workspace. No repository test script or live Mongo/SQS environment was available.

View File

@@ -0,0 +1,16 @@
{
"schema_version": 1,
"captured_at": "2026-10-16T17:17:49Z",
"grader_mode": "agentic",
"grader_harness": "codex",
"grader_reasoning_effort": "high",
"grader_model": "gpt-6-sol",
"grader_samples": "1",
"grading_standard": "consolidated",
"grader_prompt_file": "grader-system-prompt-consolidated.md",
"grader_prompt_sha256": "85edbe174ef7af339641db1f808cd4da3b2d3ee9587a07ac4e3a593011748dc9",
"grader_guidance_file": "holistic-rubric.md",
"grader_guidance_sha256": "1c0d21e1f5946c9abb72656b9b7b3ebea0e6c04dad89dbbd664374283d9f8cb8",
"render_grade_file": "render-grade-consolidated.py",
"render_grade_sha256": "db8b668c536007abbd7d9719dc08dd388507e67df7da08f63bc8c495d58840cb"
}

View File

@@ -0,0 +1 @@
{"session_id": "01a145b8-519b-73a1-b0fc-530b34993df3", "usage": {"input_tokens": 936017, "cached_input_tokens": 844999, "cache_write_input_tokens": 90976, "output_tokens": 11038, "reasoning_output_tokens": 6266}}

View File

@@ -0,0 +1 @@
{"session_id": "01a145b8-519b-73a1-b0fc-530b34993df3", "usage": {"input_tokens": 936017, "cached_input_tokens": 844999, "cache_write_input_tokens": 90976, "output_tokens": 11038, "reasoning_output_tokens": 6266}}

View File

@@ -0,0 +1,7 @@
samples_requested: 1
samples_valid: 1
sample_1: 0.58
mean: 0.5800
canonical_sample: 1
correctness_sample_1: NA
correctness_mean: N/A

View File

@@ -0,0 +1 @@
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.TGGVeJ4n"))

View File

@@ -0,0 +1 @@
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.TGGVeJ4n"))

Some files were not shown because too many files have changed in this diff Show More